Get the HTTP user-agent string used for java.net calls by the + * client (see RFC2616).
+ * + * @return User-agent string. + */ + public String getUserAgent() { + printDebugMessage("getUserAgent", "Begin/End", 1); + return System.getProperty("http.agent"); + } + + /**Set the HTTP user-agent string used for java.net calls by the + * client (see RFC2616).
+ * + * @param userAgent User-agent string to prepend to default client + * user-agent. + */ + public void setUserAgent(String userAgent) { + printDebugMessage("setUserAgent", "Begin", 1); + // Java web calls use the http.agent property as a prefix to the default user-agent. + StringBuffer clientUserAgent = new StringBuffer(); + if(userAgent != null && userAgent.length() > 0) { + clientUserAgent.append(userAgent); + } + clientUserAgent.append(getClientUserAgentString()); + if(System.getProperty("http.agent") != null) { + clientUserAgent.append(" ").append(System.getProperty("http.agent")); + } + System.setProperty("http.agent", clientUserAgent.toString()); + printDebugMessage("setUserAgent", "End", 1); + } + + /**Set the HTTP User-agent header string (see RFC2616) used by the + * client for java.net requests.
+ */ + protected void setUserAgent() { + printDebugMessage("setUserAgent", "Begin", 1); + // Java web calls use the http.agent property as a prefix to the default user-agent. + String clientUserAgent = getClientUserAgentString(); + if(System.getProperty("http.agent") != null) { + System.setProperty("http.agent", clientUserAgent + " " + System.getProperty("http.agent")); + } + else System.setProperty("http.agent", clientUserAgent); + printDebugMessage("setUserAgent", "End", 1); + } + + /** Get client specific user-agent string for addition to client + * user-agent string. + * + * @return Client specific user-agent string. + */ + protected abstract String getClientUserAgentString(); + + /** Generate a string containing the values of the fields with "get" methods. + * + * @param obj Object the get values from + * @return String containing values and method names. + */ + protected String objectFieldsToString(Object obj) { + printDebugMessage("ObjectFieldsToString", "Begin", 31); + StringBuilder strBuilder = new StringBuilder(); + try { + @SuppressWarnings("rawtypes") + Class objType = obj.getClass(); + printDebugMessage("ObjectFieldsToString", "objType: " + objType, 32); + java.lang.reflect.Method[] methods = objType.getMethods(); + for(int i = 0; i < methods.length; i++) { + String methodName = methods[i].getName(); + if(methodName.startsWith("get") && methods[i].getParameterTypes().length == 0 && + !methodName.equals("getClass") && !methodName.equals("getTypeDesc")) { + printDebugMessage("ObjectFieldsToString", "invoke(): " + methodName, 32); + Object tmpObj = methods[i].invoke(obj, new Object[0]); + // Handle any string lists (e.g. database) + if(tmpObj instanceof String[]) { + String[] tmpList = (String[])tmpObj; + strBuilder.append(methodName + ":\n"); + for(int j = 0; j < tmpList.length; j++) { + strBuilder.append("\t" + tmpList[j] + "\n"); + } + } + // Otherwise just use implicit toString(); + else { + strBuilder.append(methodName + ": " + tmpObj + "\n"); + } + } + } + } + catch(SecurityException e) { + System.err.println(e.getMessage()); + } + catch (IllegalArgumentException e) { + System.err.println(e.getMessage()); + } + catch (IllegalAccessException e) { + System.err.println(e.getMessage()); + } + catch (InvocationTargetException e) { + System.err.println(e.getMessage()); + } + printDebugMessage("ObjectFieldsToString", "End", 31); + return strBuilder.toString(); + } + + /** Set the output level. + * + * @param level Output level. 0 = quiet, 1 = normal and 2 = verbose. + */ + public void setOutputLevel(int level) { + printDebugMessage("setOutputLevel", "Begin " + level, 1); + if(level > -1) { + this.outputLevel = level; + } + printDebugMessage("setOutputLevel", "End", 1); + } + + /** Get the current output level. + * + * @return Output level. + */ + public int getOutputLevel() { + printDebugMessage("getOutputLevel", new Integer(this.outputLevel).toString(), 1); + return this.outputLevel; + } + + /** Set the maximum interval between polling events. + * + * @param checkInterval Maximum interval in milliseconds. Must be greater than 1000. + */ + public void setMaxCheckInterval(int checkInterval) { + printDebugMessage("setMaxCheckInterval", "Begin " + checkInterval, 1); + if(checkInterval > 1000) { + this.maxCheckInterval = checkInterval; + } + printDebugMessage("setMaxCheckInterval", "End", 1); + } + + /** Get the maximum interval between polling events. + * + * @return Maximum interval in milliseconds + */ + public int getMaxCheckInterval() { + printDebugMessage("getMaxCheckInterval", new Integer(this.maxCheckInterval).toString(), 1); + return this.maxCheckInterval; + } + + /** Set the service endpoint URL for generating the service connection. + * + * @param urlStr Service endpoint URL as a string. + */ + public void setServiceEndPoint(String urlStr) { + this.serviceEndPoint = urlStr; + } + + /** Get the current service endpoint URL. + * + * @return The service endpoint URL as a string. + */ + public String getServiceEndPoint() { + return this.serviceEndPoint; + } + + /** Print a progress message. + * + * @param msg The message to print. + * @param level The output level at or above which this message should be displayed. + */ + protected void printProgressMessage(String msg, int level) { + if(outputLevel >= level) { + System.err.println(msg); + } + } + + /** Read the contents of a file into a byte array. + * + * @param file the file to read + * @return the contents of the file in a byte array + * @throws IOException if all contents not read + */ + public byte[] readFile(File file) throws IOException, FileNotFoundException { + printDebugMessage("readFile", "Begin", 1); + printDebugMessage("readFile", "file: " + file.getPath() + File.pathSeparator + file.getName(), 2); + if(!file.exists()) { + throw new FileNotFoundException(file.getName() + " does not exist"); + } + InputStream is = new FileInputStream(file); + byte[] bytes = readStream(is); + is.close(); + printDebugMessage("readFile", "End", 1); + return bytes; + } + + /** Read the contents of an input stream into a byte array. + * + * @param inStream the input steam to read + * @return the contents of the stream in a byte array + * @throws IOException if all contents not read + */ + public byte[] readStream(InputStream inStream) throws IOException { + printDebugMessage("readStream", "Begin", 1); + byte[] ret = null; + while(inStream.available()>0) + { + long length = inStream.available(); + byte[] bytes = new byte[(int)length]; + int offset = 0; + int numRead = 0; + while(offset < bytes.length && + (numRead=inStream.read(bytes,offset,bytes.length-offset)) >= 0 ) { + offset += numRead; + } + if (offset < bytes.length) { + throw new IOException("Unable to read to end of stream"); + } + printDebugMessage("readStream", "read " + bytes.length + " bytes", 2); + if(ret==null) + ret = bytes; + else + { + byte[] tmp = ret.clone(); + ret = new byte[ret.length+bytes.length]; + System.arraycopy(tmp,0,ret,0 ,tmp.length); + System.arraycopy(bytes,0,ret,tmp.length,bytes.length); + } + } + printDebugMessage("readStream", "End", 1); + return ret; + } + + /**The input data can be passed as:
+ *This method gets the data to be passed to the service, checking for + * a file and loading it if necessary.
+ * + * @param fileOptionStr Filename or entry identifier. + * @return Data to use as input as a byte array. + * @throws IOException + */ + public byte[] loadData(String fileOptionStr) throws IOException { + printDebugMessage("loadData", "Begin", 1); + printDebugMessage("loadData", "fileOptionStr: " + fileOptionStr, 2); + byte[] retVal = null; + if(fileOptionStr != null) { + if(fileOptionStr.equals("-")) { // STDIN. + // TODO: wait for input from STDIN. + retVal = readStream(System.in); + } + else if(new File(fileOptionStr).exists()) { // File. + retVal = readFile(new File(fileOptionStr)); + } else { // Entry Id or raw data. + retVal = fileOptionStr.getBytes(); + } + } + printDebugMessage("loadData", "End", 1); + return retVal; + } + + /** Write a string to a file. + * + * @param file the file to create/write to + * @param data the string to write + * @return an integer value indicating success/failure + * @throws IOException if there is a problem with the file operations + */ + public int writeFile(File file, String data) throws IOException { + printDebugMessage("writeFile", "Begin", 1); + printDebugMessage("writeFile", "file: " + file.getName(), 2); + printDebugMessage("writeFile", "data: " + data.length() + " characters", 2); + OutputStream os = new FileOutputStream(file); + PrintStream p = new PrintStream( os ); + p.println (data); + p.close(); + printDebugMessage("writeFile", "End", 1); + return 0; + } + + /** Write an array of bytes to a file. + * + * @param file the file to create/write to + * @param data the bytes to write + * @return an integer value indicating success/failure + * @throws IOException if there is a problem with the file operations + */ + public int writeFile(File file, byte[] data) throws IOException { + printDebugMessage("writeFile", "Begin", 1); + printDebugMessage("writeFile", "file: " + file.getName(), 2); + printDebugMessage("writeFile", "data: " + data.length + " bytes", 2); + OutputStream os = new FileOutputStream(file); + os.write (data); + os.close(); + printDebugMessage("writeFile", "End", 1); + return 0; + } + + /** Get an instance of the service proxy to use with other methods. + * + * @throws ServiceException + */ + abstract protected void srvProxyConnect() throws ServiceException; + + /** Get list of tool parameter names. + * + * @return String array containing list of parameter names + * @throws ServiceException + * @throws RemoteException + */ + abstract public String[] getParams() throws ServiceException, RemoteException; + + /** Print list of parameter names for tool. + * + * @throws RemoteException + * @throws ServiceException + */ + protected void printParams() throws RemoteException, ServiceException { + printDebugMessage("printParams", "Begin", 1); + String[] paramList = getParams(); + for(int i = 0; i < paramList.length; i++) { + System.out.println(paramList[i]); + } + printDebugMessage("printParams", "End", 1); + } + + /** Print information about a tool parameter + * + * @param paramName Name of the tool parameter to get information for. + * @throws RemoteException + * @throws ServiceException + */ + abstract protected void printParamDetail(String paramName) throws RemoteException, ServiceException; + + /** Get the status of a submitted job given its job identifier. + * + * @param jobid The job identifier + * @return Job status as a string. + * @throws IOException + * @throws ServiceException + */ + abstract public String checkStatus(String jobid) throws IOException, ServiceException; + + /** Poll the job status until the job completes. + * + * @param jobid The job identifier. + * @throws ServiceException + */ + public void clientPoll(String jobId) throws ServiceException { + printDebugMessage("clientPoll", "Begin", 1); + printDebugMessage("clientPoll", "jobId: " + jobId, 2); + int checkInterval = 1000; + String status = "PENDING"; + // Check status and wait if not finished + while(status.equals("RUNNING") || status.equals("PENDING")) { + try { + status = this.checkStatus(jobId); + printProgressMessage(status, 1); + if(status.equals("RUNNING") || status.equals("PENDING")) { + // Wait before polling again. + printDebugMessage("clientPoll", "checkInterval: " + checkInterval, 2); + Thread.sleep(checkInterval); + checkInterval *= 2; + if(checkInterval > this.maxCheckInterval) checkInterval = this.maxCheckInterval; + } + } + catch(InterruptedException ex) { + // Ignore + } + catch(IOException ex) { + // Report and continue + System.err.println("Warning: " + ex.getMessage()); + } + } + printDebugMessage("clientPoll", "End", 1); + } + + /** Print details of the available result types for a job. + * + * @param jobId Job identifier to check for result types. + * @throws ServiceException + * @throws RemoteException + */ + abstract protected void printResultTypes(String jobId) throws ServiceException, RemoteException; + + /** Get the results for a job and save them to files. + * + * @param jobid The job identifier. + * @param outfile The base name of the file to save the results to. If + * null the jobid will be used. + * @param outformat The name of the data format to save, e.g. toolraw + * or toolxml. If null all available data formats will be saved. + * @return Array of filenames + * @throws IOException + * @throws javax.xml.rpc.ServiceException + */ + abstract public String[] getResults(String jobid, String outfile, String outformat) throws IOException, ServiceException; + + protected boolean getResults(String jobId, CommandLine cli) throws IOException, ServiceException { + this.printDebugMessage("getResults", "Begin", 21); + boolean resultsContainContent = this.getResults(jobId, cli, null); + this.printDebugMessage("getResults", "End", 21); + return resultsContainContent; + } + + private boolean getResults(String jobId, CommandLine cli, String entryId) throws IOException, ServiceException { + this.printDebugMessage("getResults", "Begin", 21); + this.printDebugMessage("getResults", "jobId: " + jobId, 21); + boolean resultsContainContent = false; + String[] resultFilenames; + if(cli.hasOption("outfile")) { + resultFilenames = this.getResults(jobId, cli.getOptionValue("outfile"), cli.getOptionValue("outformat")); + } + else if(cli.hasOption("useSeqId") && entryId != null && entryId.length() > 0) { + String cleanEntryId = entryId.replaceAll("\\W", "_"); + resultFilenames = this.getResults(jobId, cleanEntryId, cli.getOptionValue("outformat")); + } + else { + resultFilenames = this.getResults(jobId, (String)null, cli.getOptionValue("outformat")); + } + for (int i = 0; i < resultFilenames.length; i++) { + if (resultFilenames[i] != null) { + System.out.println("Wrote file: " + resultFilenames[i]); + resultsContainContent = true; + } + } + this.printDebugMessage("getResults", "End", 21); + return resultsContainContent; + } + + /** Set input fasta format sequence data file. + * + * @param fastaFileName Name of the file. + * @throws FileNotFoundException + */ + public void setFastaInputFile(String fastaFileName) throws FileNotFoundException { + Reader inputReader = null; + if(fastaFileName.equals("-")) { // STDIN + inputReader = new InputStreamReader(System.in); + } + else { // File + inputReader = new FileReader(fastaFileName); + } + this.fastaInputReader = new BufferedReader(inputReader); + } + + /** Get next fasta sequence from input sequence file. + * + * NB: Assumes files contains correctly formated input sequences, + * i.e. are in fasta sequence format, and that the file contains only + * fasta formated sequences. For a more generic solution see BioJava. + * + * @return Fasta input sequence from file. + * @throws IOException + */ + public String nextFastaSequence() throws IOException { + String retVal = null; + // Read lines until one begins with '>'. + while(this.fastaInputReader.ready() && + (this.tmpFastaLine == null || !this.tmpFastaLine.startsWith(">"))) { + this.tmpFastaLine = this.fastaInputReader.readLine(); + } + // Read fasta header line. + if(this.tmpFastaLine.startsWith(">")) { + this.printProgressMessage("Sequence: " + tmpFastaLine, 2); + StringBuffer tmpFastaSeq = new StringBuffer(); + tmpFastaSeq.append(tmpFastaLine).append("\n"); + // Read lines until EOF or a line begins with '>'. + this.tmpFastaLine = this.fastaInputReader.readLine(); + while(this.fastaInputReader.ready() && + (this.tmpFastaLine == null || !this.tmpFastaLine.startsWith(">"))) { + this.tmpFastaLine = this.fastaInputReader.readLine(); + if(!tmpFastaLine.startsWith(">")) { + tmpFastaSeq.append(tmpFastaLine).append("\n"); + } + } + retVal = tmpFastaSeq.toString(); + } + return retVal; + } + + /** Close the input fasta sequence file. + * + * @throws IOException + */ + public void closeFastaFile() throws IOException { + this.fastaInputReader.close(); + this.fastaInputReader = null; + } + + /** + * Submit a job using command-line information to construct the input. + * + * @param cli + * Command-line parameters. + * @param inputSeq + * Data input. + * @throws ServiceException + * @throws IOException + */ + abstract public String submitJobFromCli(CommandLine cli, String inputData) + throws ServiceException, IOException; + + /** Submit a set of jobs using input containing multiple fasta format + * sequences. Each sequence corresponds to a job. + * + * NB: services which require multiple input sequences (e.g. multiple + * sequence alignment) or multiple data inputs (e.g. pairwise alignment) + * are not supported by this method. + * + * @param dataOption Input data file name or '-' for STDIN. + * @param cli Command-line options for the jobs. + * @throws IOException + * @throws ServiceException + */ + public void multifastaSubmitCli(String dataOption, CommandLine cli) throws IOException, ServiceException { + this.printDebugMessage("multifastaSubmitCli", "Begin", 11); + int maxJobs = 1; + if(cli.hasOption("maxJobs")) { + maxJobs = Integer.parseInt(cli.getOptionValue("maxJobs")); + } + int jobNumber = 0; + ArrayList+ * JDispatcher InterProScan 5 (SOAP) web service Java client using Apache Axis + * 1.x. + *
+ * + *+ * See: + *
+ *Get a user-agent string for this client.
+ * + *Note: this affects all java.net based requests, but not the + * Axis requests. The user-agent used by Axis is set from the + * /org/apache/axis/i18n/resource.properties file included in the Axis + * JAR.
+ * + * @return Client user-agent string. + */ + protected String getClientUserAgentString() { + printDebugMessage("getClientUserAgent", "Begin", 11); + String clientVersion = this.revision.substring(11, this.revision.length() - 2); + String clientUserAgent = "EBI-Sample-Client/" + clientVersion + + " (" + this.getClass().getName() + "; " + + System.getProperty("os.name") + ")"; + printDebugMessage("getClientUserAgent", "End", 11); + return clientUserAgent; + } + + /** Print usage message. */ + private static void printUsage() { + System.out.println(usageMsg); + printGenericOptsUsage(); + } + + /** Ensure that a service proxy is available to call the web service. + * + * @throws ServiceException + */ + protected void srvProxyConnect() throws ServiceException { + printDebugMessage("srvProxyConnect", "Begin", 11); + if (this.srvProxy == null) { + JDispatcherService_Service service = new JDispatcherService_ServiceLocatorExtended(); + if (this.getServiceEndPoint() != null) { + try { + this.srvProxy = service + .getJDispatcherServiceHttpPort(new java.net.URL( + this.getServiceEndPoint())); + } catch (java.net.MalformedURLException ex) { + System.err.println(ex.getMessage()); + System.err + .println("Warning: problem with specified endpoint URL. Default endpoint used."); + this.srvProxy = service.getJDispatcherServiceHttpPort(); + } + } else { + this.srvProxy = service.getJDispatcherServiceHttpPort(); + } + } + printDebugMessage("srvProxyConnect", "End", 11); + } + + /** Wrapper for JDispatcherService_ServiceLocator to enable HTTP + * compression. + * + * Compression requires Commons HttpClient and a client-config.wsdd which + * specifies that Commons HttpClient should be used as the HTTP transport. + * See http://wiki.apache.org/ws/FrontPage/Axis/GzipCompression. + */ + private class JDispatcherService_ServiceLocatorExtended extends JDispatcherService_ServiceLocator { + private static final long serialVersionUID = 1L; + + public Call createCall() throws ServiceException { + Call call = super.createCall(); + // Enable response compression. + call.setProperty(HTTPConstants.MC_ACCEPT_GZIP, Boolean.TRUE); + return call; + } + } + + /** + * Get the web service proxy so it can be called directly. + * + * @return The web service proxy. + * @throws javax.xml.rpc.ServiceException + */ + public JDispatcherService_PortType getSrvProxy() + throws javax.xml.rpc.ServiceException { + printDebugMessage("getSrvProxy", "", 1); + this.srvProxyConnect(); // Ensure the service proxy exists + return this.srvProxy; + } + + /** + * Get list of tool parameter names. + * + * @return String array containing list of parameter names + * @throws ServiceException + * @throws RemoteException + */ + public String[] getParams() throws ServiceException, RemoteException { + printDebugMessage("getParams", "Begin", 1); + String[] retVal = null; + this.srvProxyConnect(); // Ensure the service proxy exists + retVal = this.srvProxy.getParameters(); + printDebugMessage("getParams", retVal.length + " params", 2); + printDebugMessage("getParams", "End", 1); + return retVal; + } + + /** + * Get detailed information about the specified tool parameter. + * + * @param paramName + * Tool parameter name + * @return Object describing tool parameter + * @throws ServiceException + * @throws RemoteException + */ + public WsParameterDetails getParamDetail(String paramName) + throws ServiceException, RemoteException { + printDebugMessage("getParamDetail", paramName, 1); + this.srvProxyConnect(); // Ensure the service proxy exists + return this.srvProxy.getParameterDetails(paramName); + } + + /** + * Print detailed information about a tool parameter. + * + * @param paramName + * Name of the tool parameter to get information for. + * @throws RemoteException + * @throws ServiceException + */ + protected void printParamDetail(String paramName) throws RemoteException, + ServiceException { + printDebugMessage("printParamDetail", "Begin", 1); + WsParameterDetails paramDetail = getParamDetail(paramName); + // Print object + System.out + .println(paramDetail.getName() + "\t" + paramDetail.getType()); + System.out.println(paramDetail.getDescription()); + WsParameterValue[] valueList = paramDetail.getValues(); + if(valueList!=null) { + for (int i = 0; i < valueList.length; i++) { + System.out.print(valueList[i].getValue()); + if (valueList[i].isDefaultValue()) { + System.out.println("\tdefault"); + } else { + System.out.println(); + } + System.out.println("\t" + valueList[i].getLabel()); + WsProperty[] valuePropertiesList = valueList[i].getProperties(); + if (valuePropertiesList != null) { + for (int j = 0; j < valuePropertiesList.length; j++) { + System.out.println("\t" + valuePropertiesList[j].getKey() + + "\t" + valuePropertiesList[j].getValue()); + } + } + } + } + printDebugMessage("printParamDetail", "End", 1); + } + + /** + * Get the status of a submitted job given its job identifier. + * + * @param jobid + * The job identifier. + * @return Job status as a string. + * @throws IOException + * @throws ServiceException + */ + public String checkStatus(String jobid) throws IOException, + ServiceException { + printDebugMessage("checkStatus", jobid, 1); + this.srvProxyConnect(); // Ensure the service proxy exists + return this.srvProxy.getStatus(jobid); + } + + /** + * Get details of the available result types for a job. + * + * @param jobId + * Job identifier to check for results types. + * @return Array of objects describing result types. + * @throws ServiceException + * @throws RemoteException + */ + public WsResultType[] getResultTypes(String jobId) throws ServiceException, + RemoteException { + printDebugMessage("getResultTypes", "Begin", 1); + printDebugMessage("getResultTypes", "jobId: " + jobId, 2); + WsResultType[] retVal = null; + this.srvProxyConnect(); // Ensure the service proxy exists + clientPoll(jobId); // Wait for job to finish + retVal = this.srvProxy.getResultTypes(jobId); + printDebugMessage("getResultTypes", retVal.length + " result types", 2); + printDebugMessage("getResultTypes", "End", 1); + return retVal; + } + + /** + * Print details of the available result types for a job. + * + * @param jobId + * Job identifier to check for result types. + * @throws ServiceException + * @throws RemoteException + */ + protected void printResultTypes(String jobId) throws ServiceException, + RemoteException { + printDebugMessage("printResultTypes", "Begin", 1); + WsResultType[] typeList = getResultTypes(jobId); + for (int i = 0; i < typeList.length; i++) { + System.out.print(typeList[i].getIdentifier() + "\n\t" + + typeList[i].getLabel() + "\n\t" + + typeList[i].getDescription() + "\n\t" + + typeList[i].getMediaType() + "\n\t" + + typeList[i].getFileSuffix() + "\n"); + } + printDebugMessage("printResultTypes", "End", 1); + } + + /** + * Get the results for a job and save them to files. + * + * @param jobid + * The job identifier. + * @param outfile + * The base name of the file to save the results to. If null the + * jobid will be used. + * @param outformat + * The name of the data format to save, e.g. toolraw or toolxml. + * If null all available data formats will be saved. + * @return Array of filenames + * @throws IOException + * @throws javax.xml.rpc.ServiceException + */ + public String[] getResults(String jobid, String outfile, String outformat) + throws IOException, javax.xml.rpc.ServiceException { + printDebugMessage("getResults", "Begin", 1); + printDebugMessage("getResults", "jobid: " + jobid + " outfile: " + + outfile + " outformat: " + outformat, 2); + String[] retVal = null; + this.srvProxyConnect(); // Ensure the service proxy exists + clientPoll(jobid); // Wait for job to finish + // Set the base name for the output file. + String basename = (outfile != null) ? outfile : jobid; + // Get result types + WsResultType[] resultTypes = getResultTypes(jobid); + int retValN = 0; + if (outformat == null) { + retVal = new String[resultTypes.length]; + } else { + retVal = new String[1]; + } + for (int i = 0; i < resultTypes.length; i++) { + printProgressMessage( + "File type: " + resultTypes[i].getIdentifier(), 2); + // Get the results + if (outformat == null + || outformat.equals(resultTypes[i].getIdentifier())) { + byte[] resultbytes = this.srvProxy.getResult(jobid, + resultTypes[i].getIdentifier(), null); + if (resultbytes == null) { + System.err.println("Null result for " + + resultTypes[i].getIdentifier() + "!"); + } else { + printProgressMessage("Result bytes length: " + + resultbytes.length, 2); + // Write the results to a file + String result = new String(resultbytes); + if (basename.equals("-")) { // STDOUT + if (resultTypes[i].getMediaType().startsWith("text")) { // String + System.out.print(result); + } else { // Binary + System.out.print(resultbytes); + } + } else { // File + String filename = basename + "." + + resultTypes[i].getIdentifier() + "." + + resultTypes[i].getFileSuffix(); + if (resultTypes[i].getMediaType().startsWith("text")) { // String + writeFile(new File(filename), result); + } else { // Binary + writeFile(new File(filename), resultbytes); + } + retVal[retValN] = filename; + retValN++; + } + } + } + } + printDebugMessage("getResults", retVal.length + " file names", 2); + printDebugMessage("getResults", "End", 1); + return retVal; + } + + /** + * Submit a job to the service. + * + * @param params + * Input parameters for the job. + * @param content + * Data to run the job on. + * @return The job identifier. + * @throws RemoteException + * @throws ServiceException + */ + public String runApp(String email, String title, InputParameters params) + throws RemoteException, ServiceException { + printDebugMessage("runApp", "Begin", 1); + printDebugMessage("runApp", "email: " + email + " title: " + title, 2); + printDebugMessage("runApp", "params:\n" + objectFieldsToString(params), + 2); + String jobId = null; + this.srvProxyConnect(); // Ensure the service proxy exists + jobId = srvProxy.run(email, title, params); + printDebugMessage("runApp", "jobId: " + jobId, 2); + printDebugMessage("runApp", "End", 1); + return jobId; + } + + /** + * Populate input parameters structure from command-line options. + * + * @param line + * Command line options + * @return input Input parameters structure for use with runApp(). + * @throws IOException + */ + public InputParameters loadParams(CommandLine line) throws IOException { + printDebugMessage("loadParams", "Begin", 1); + InputParameters params = new InputParameters(); + // Tool specific options + if (line.hasOption("appl")) { + String tmpVal = line.getOptionValue("appl").replace(',', ' ').replace('+', ' ').replaceAll("\\s+", " "); + String[] dbList = tmpVal.split(" "); + params.setAppl(dbList); + } else if (line.hasOption("app")) { + String tmpVal = line.getOptionValue("app").replace(',', ' ').replace('+', ' ').replaceAll("\\s+", " "); + String[] dbList = tmpVal.split(" "); + params.setAppl(dbList); + } + if (line.hasOption("goterms")) + params.setGoterms(new Boolean(true)); + else if (line.hasOption("nogoterms")) + params.setGoterms(new Boolean(false)); + if (line.hasOption("pathways")) + params.setPathways(new Boolean(true)); + else if (line.hasOption("nopathways")) + params.setPathways(new Boolean(false)); + printDebugMessage("loadParams", "End", 1); + return params; + } + + /** + * Submit a job using the command-line information to construct the input. + * + * @param cli + * Command-line parameters. + * @param inputSeq + * Data input. + * @throws ServiceException + * @throws IOException + */ + public String submitJobFromCli(CommandLine cli, String inputSeq) + throws ServiceException, IOException { + this.printDebugMessage("submitJobFromCli", "Begin", 1); + // Create job submission parameters from command-line + InputParameters params = this.loadParams(cli); + params.setSequence(inputSeq); + // Submit the job + String email = null, title = null; + if (cli.hasOption("email")) + email = cli.getOptionValue("email"); + if (cli.hasOption("title")) + title = cli.getOptionValue("title"); + String jobid = this.runApp(email, title, params); + // Asynchronous submission. + if (cli.hasOption("async")) { + System.out.println(jobid); // Output the job id. + System.err + .println("To get status: java -jar IPRScan5_Axis1.jar --status --jobid " + + jobid); + } + // Parallel submission mode. + else if(cli.hasOption("maxJobs") && Integer.parseInt(cli.getOptionValue("maxJobs")) > 1) { + this.printProgressMessage(jobid, 1); + } + // Simulate synchronous submission, serial mode. + else { + this.clientPoll(jobid); + this.getResults(jobid, cli); + } + this.printDebugMessage("submitJobFromCli", "End", 1); + return jobid; + } + + /** + * Entry point for running as an application. + * + * @param args + * list of command-line options + */ + public static void main(String[] args) { + int exitVal = 0; // Exit value + int argsLength = args.length; // Number of command-line arguments + + // Configure the command-line options + Options options = new Options(); + // Common options for EBI clients + addGenericOptions(options); + options.addOption("multifasta", "multifasta", false, + "Multiple fasta sequence input"); + options.addOption("maxJobs", "maxJobs", true, + "Maximum number of concurrent jobs"); + options.addOption("useSeqId", "useSeqId", false, + "Use sequence identifiers for file names"); + // Application specific options + options.addOption("appl", "appl", true, "Signature methods"); + options.addOption("app", "app", true, "Signature methods"); + options.addOption("goterms", "goterms", false, "Enable GO terms"); + options.addOption("nogoterms", "nogoterms", false, "Disable GO terms"); + options.addOption("pathways", "pathways", false, "Enable pathway terms"); + options.addOption("nopathways", "nopathways", false, "Disable pathway terms"); + options.addOption("sequence", true, + "sequence file or datbase entry database:acc.no"); + // Compatibility options. + options.addOption("crc", "crc", false, "Enable CRC look-up (ignored)"); + options.addOption("nocrc", "nocrc", false, "Disable CRC look-up (ignored)"); + + CommandLineParser cliParser = new GnuParser(); // Create the command + // line parser + // Create an instance of the client + IPRScan5Client client = new IPRScan5Client(); + try { + // Parse the command-line + CommandLine cli = cliParser.parse(options, args); + // User asked for usage info + if (argsLength == 0 || cli.hasOption("help")) { + printUsage(); + System.exit(0); + } + // Modify output level according to the quiet and verbose options + if (cli.hasOption("quiet")) { + client.outputLevel--; + } + if (cli.hasOption("verbose")) { + client.outputLevel++; + } + // Set debug level + if (cli.hasOption("debugLevel")) { + client.setDebugLevel(Integer.parseInt(cli + .getOptionValue("debugLevel"))); + } + // Alternative service endpoint + if (cli.hasOption("endpoint")) { + client.setServiceEndPoint(cli.getOptionValue("endpoint")); + } + // Tool meta-data + // List parameters + if (cli.hasOption("params")) { + client.printParams(); + } + // Details of a parameter + else if (cli.hasOption("paramDetail")) { + client.printParamDetail(cli.getOptionValue("paramDetail")); + } + // Job related actions + else if (cli.hasOption("jobid")) { + String jobid = cli.getOptionValue("jobid"); + // Get results for job + if (cli.hasOption("polljob")) { + client.clientPoll(jobid); + boolean resultContainContent = client.getResults(jobid, cli); + if (resultContainContent == false) { + System.err.println("Error: requested result type " + + cli.getOptionValue("outformat") + + " not available!"); + } + } + // Get status of job + else if (cli.hasOption("status")) { + System.out.println(client.checkStatus(jobid)); + } + // Get result types for job + else if (cli.hasOption("resultTypes")) { + client.clientPoll(jobid); + client.printResultTypes(jobid); + } + // Unknown... + else { + System.err + .println("Error: jobid specified without related action option"); + printUsage(); + exitVal = 2; + } + } + // Job submission + else if (cli.hasOption("email") + && (cli.hasOption("sequence") || cli.getArgs().length > 0)) { + // Input sequence, data file or entry identifier. + String dataOption = (cli.hasOption("sequence")) ? cli + .getOptionValue("sequence") : cli.getArgs()[0]; + // Multi-fasta sequence input. + if (cli.hasOption("multifasta")) { + client.multifastaSubmitCli(dataOption, cli); + } + // Entry identifier list. + else if (dataOption.startsWith("@")) { + client.idlistSubmitCli(dataOption, cli); + } + // Submit a job + else { + client.printDebugMessage("main", "Mode: sequence", 11); + client.submitJobFromCli(cli, new String(client + .loadData(dataOption))); + } + } + // Unknown action + else { + System.err + .println("Error: unknown combination of arguments. See --help."); + exitVal = 2; + } + } catch (UnrecognizedOptionException ex) { + System.err.println("ERROR: " + ex.getMessage()); + printUsage(); + exitVal = 1; + } + // Catch all exceptions + catch (Exception e) { + System.err.println("ERROR: " + e.getMessage()); + if (client.getDebugLevel() > 0) { + e.printStackTrace(); + } + exitVal = 3; + } + System.exit(exitVal); + } +} diff --git a/src/ipr/IPRextract.java b/src/ipr/IPRextract.java index e2ff8b2..47eb70f 100644 --- a/src/ipr/IPRextract.java +++ b/src/ipr/IPRextract.java @@ -51,19 +51,19 @@ public static Map