diff --git a/lib/IPRScan5_Axis1.jar b/lib/IPRScan5_Axis1.jar new file mode 100644 index 0000000..6ad95ac Binary files /dev/null and b/lib/IPRScan5_Axis1.jar differ diff --git a/lib/IPRScan_JAXWS.jar b/lib/IPRScan_JAXWS.jar deleted file mode 100644 index cbbb544..0000000 Binary files a/lib/IPRScan_JAXWS.jar and /dev/null differ diff --git a/lib/ebiws-lib/activation-1.1.1.jar b/lib/ebiws-lib/activation-1.1.1.jar new file mode 100644 index 0000000..1b703ab Binary files /dev/null and b/lib/ebiws-lib/activation-1.1.1.jar differ diff --git a/lib/ebiws-lib/axis-1.4.jar b/lib/ebiws-lib/axis-1.4.jar new file mode 100644 index 0000000..20b09a5 Binary files /dev/null and b/lib/ebiws-lib/axis-1.4.jar differ diff --git a/lib/ebiws-lib/axis-jaxrpc-1.4.jar b/lib/ebiws-lib/axis-jaxrpc-1.4.jar new file mode 100644 index 0000000..a2c13d9 Binary files /dev/null and b/lib/ebiws-lib/axis-jaxrpc-1.4.jar differ diff --git a/lib/ebiws-lib/axis-saaj-1.4.jar b/lib/ebiws-lib/axis-saaj-1.4.jar new file mode 100644 index 0000000..4ea696e Binary files /dev/null and b/lib/ebiws-lib/axis-saaj-1.4.jar differ diff --git a/lib/ebiws-lib/axis-wsdl4j-1.5.1.jar b/lib/ebiws-lib/axis-wsdl4j-1.5.1.jar new file mode 100644 index 0000000..c6254ee Binary files /dev/null and b/lib/ebiws-lib/axis-wsdl4j-1.5.1.jar differ diff --git a/lib/commons-cli-1.2.jar b/lib/ebiws-lib/commons-cli-1.2.jar similarity index 100% rename from lib/commons-cli-1.2.jar rename to lib/ebiws-lib/commons-cli-1.2.jar diff --git a/lib/ebiws-lib/commons-codec-1.2.jar b/lib/ebiws-lib/commons-codec-1.2.jar new file mode 100644 index 0000000..67cb720 Binary files /dev/null and b/lib/ebiws-lib/commons-codec-1.2.jar differ diff --git a/lib/ebiws-lib/commons-discovery-0.2.jar b/lib/ebiws-lib/commons-discovery-0.2.jar new file mode 100644 index 0000000..b885548 Binary files /dev/null and b/lib/ebiws-lib/commons-discovery-0.2.jar differ diff --git a/lib/ebiws-lib/commons-httpclient-3.1.jar b/lib/ebiws-lib/commons-httpclient-3.1.jar new file mode 100644 index 0000000..7c59774 Binary files /dev/null and b/lib/ebiws-lib/commons-httpclient-3.1.jar differ diff --git a/lib/ebiws-lib/commons-logging-1.0.4.jar b/lib/ebiws-lib/commons-logging-1.0.4.jar new file mode 100644 index 0000000..b73a80f Binary files /dev/null and b/lib/ebiws-lib/commons-logging-1.0.4.jar differ diff --git a/lib/ebiws-lib/mail-1.4.1.jar b/lib/ebiws-lib/mail-1.4.1.jar new file mode 100644 index 0000000..1d15e79 Binary files /dev/null and b/lib/ebiws-lib/mail-1.4.1.jar differ diff --git a/src/ipr/AbstractWsToolClient.java b/src/ipr/AbstractWsToolClient.java new file mode 100644 index 0000000..1ea0b17 --- /dev/null +++ b/src/ipr/AbstractWsToolClient.java @@ -0,0 +1,880 @@ +/* $Id: AbstractWsToolClient.java 2718 2014-01-21 12:55:10Z hpm $ + * ====================================================================== + * + * Copyright 2008-2014 EMBL - European Bioinformatics Institute + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ====================================================================== + * Abstract jDispatcher web services Java client. + * ====================================================================== */ +package ipr; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.Reader; +import java.lang.reflect.InvocationTargetException; +import java.rmi.RemoteException; +import java.util.ArrayList; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.xml.rpc.ServiceException; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.Options; + +/** Abstract class defining common methods to all jDispatcher SOAP web + * service clients. + * + * See: + * http://www.ebi.ac.uk/Tools/webservices/ + * http://www.ebi.ac.uk/Tools/webservices/tutorials/java + */ +public abstract class AbstractWsToolClient { + /** Maximum number of errors to mark job as failed. */ + private static final int MAX_ERROR_STATUS_COUNT = 3; + /** Pattern to extract entry identifier from fasta format sequence data. */ + private static final Pattern FASTA_SEQID_PATTERN = Pattern.compile(">\\s*(\\S+)"); + /** Output level. Controlled by the --verbose and --quiet options. */ + protected int outputLevel = 1; + /** Debug level. Controlled by the --debugLevel option. */ + private int debugLevel = 0; + /** Maximum interval between polling events (ms). */ + private int maxCheckInterval = 60000; + /** Temporary line for fasta sequence parsing. */ + private String tmpFastaLine = null; + /** Buffered reader for fasta sequence input. */ + private BufferedReader fastaInputReader = null; + /** Buffered reader for identifier list input. */ + private BufferedReader identifierListReader = null; + /** URL for service endpoint. */ + private String serviceEndPoint = null; + /** Generic options message. */ + private static final String genericOptsStr = "[General]\n" + + "\n" + + " --params : : list tool parameters\n" + + " --paramDetail : str : information about a parameter\n" + + " --email : str : e-mail address, required to submit job\n" + + " --title : str : title for the job\n" + + " --async : : perform an asynchronous submission\n" + + " --jobid : str : job identifier\n" + + " --status : : get status of a job\n" + + " --resultTypes : : get list of result formats for a job\n" + + " --polljob : : get results for a job\n" + + " --outfile : str : name of the file results should be written to\n" + + " (default is based on the jobid; \"-\" for STDOUT)\n" + + " --outformat : str : output format, see --resultTypes\n" + + " --help : : prints this help text\n" + + " --quiet : : decrease output\n" + + " --verbose : : increase output\n" + + " --debugLevel : int : set debug output level\n" + + "\n" + + "Synchronous job:\n" + + "\n" + + " The results/errors are returned as soon as the job is finished.\n" + + " Usage: java -jar --email [options...] seqFile\n" + + " Returns: results as an attachment\n" + + "\n" + + "Asynchronous job:\n" + + "\n" + + " Use this if you want to retrieve the results at a later time. The results \n" + + " are stored for up to 7 days.\n" + + " Usage: java -jar --async --email [options...] seqFile\n" + + " Returns: jobid\n" + + "\n" + + " Use the jobid to query for the status of the job.\n" + + " Usage: java -jar --status --jobid \n" + + " Returns: string indicating the status of the job.\n" + + "\n" + + " If the job is finished, get the available result types.\n" + + " Usage: java -jar --resultTypes --jobid \n" + + " Returns: details of the available results for the job.\n" + + "\n" + + " If the job is finished get the results.\n" + + " Usage:\n" + + " java -jar --polljob --jobid \n" + + " java -jar --polljob --jobid --outformat \n" + + " Returns: results in the requested format, or if not specified all \n" + + " formats. By default the output file(s) are named after the job, to \n" + + " specify a name for the file(s) use the --outfile option.\n"; + + /** Add genetic option to command-line parser. + * + * @param options Command-line parser. + */ + protected static void addGenericOptions(Options options) { + options.addOption("help", "help", false, "help on using this client"); + options.addOption("async", "async", false, "perform an asynchronous job"); + options.addOption("polljob", "polljob", false, "poll for the status of an asynchronous job and get the results"); + options.addOption("status", "status", false, "poll for the status of an asynchronous job"); + options.addOption("email", "email", true, "Your email address"); + options.addOption("jobid", "jobid", true, "Job identifier of an asynchronous job"); + options.addOption("stdout", "stdout", false, "print to standard output"); + options.addOption("outfile", "outfile", true, "file name to save the results"); + options.addOption("outformat", "outformat", true, "Output format (txt or xml)"); + options.addOption("quiet", "quiet", false, "Decrease output messages"); + options.addOption("verbose", "verbose", false, "Increase output messages"); + options.addOption("params", "params", false, "List parameters"); + options.addOption("paramDetail", "paramDetail", true, "List parameter information"); + options.addOption("resultTypes", "resultTypes", false, "List result types for job"); + options.addOption("debugLevel", "debugLevel", true, "Debug output"); + options.addOption("endpoint", "endpoint", true, "Service endpoint URL"); + } + + /** Print the generic options usage message to STDOUT. */ + protected static void printGenericOptsUsage() { + System.out.println(genericOptsStr); + } + + /** Set debug level. + * + * @param level Debug level. 0 = off. + */ + public void setDebugLevel(int level) { + printDebugMessage("setDebugLevel", "Begin " + level, 1); + if(level > -1) { + debugLevel = level; + } + printDebugMessage("setDebugLevel", "End", 1); + } + + /** Get current debug level. + * + * @return Debug level. + */ + public int getDebugLevel() { + printDebugMessage("getDebugLevel", new Integer(debugLevel).toString(), 1); + return debugLevel; + } + + /** Output debug message at specified level + * + * @param methodName Name of the method to appear in the message + * @param message The message + * @param level Level at which to output message + */ + protected void printDebugMessage(String methodName, String message, int level) { + if(level <= debugLevel) { + System.err.println("[" + methodName + "()] " + message); + } + } + + /**

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:

+ *
    + *
  • a filename
  • + *
  • an entry identifier (e.g. UNIPROT:WAP_RAT)
  • + *
  • raw data (e.g. "MRCSISLVLG")
  • + *
  • data from standard input (STDIN)
  • + *
+ *

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 jobInfoList = new ArrayList(); + this.setFastaInputFile(dataOption); + // Loop over input sequences, submitting each one. + String fastaSeq = null; + fastaSeq = this.nextFastaSequence(); + while (fastaSeq != null) { + this.printDebugMessage("multifastaSubmitCli", "fastaSeq: " + fastaSeq, 12); + jobNumber++; + String entryId = ""; + Matcher fastaSeqIdMatch = FASTA_SEQID_PATTERN.matcher(fastaSeq); + if(fastaSeqIdMatch.find()) { + entryId = fastaSeqIdMatch.group(1); + } + this.printProgressMessage("ID: " + entryId, 1); + String jobId = this.submitJobFromCli(cli, fastaSeq); + // JobId, EntryId, errorCount, jobNumber + String[] jobInfo = {jobId, entryId, "0", String.valueOf(jobNumber)}; + jobInfoList.add(jobInfo); + // Parallel mode... wait for job(s) to finish to free slots. + while(maxJobs > 1 && jobInfoList.size() >= maxJobs) { + pollJobList(jobInfoList, cli); + this.printDebugMessage("multifastaSubmitCli", "Remaining jobs: " + jobInfoList.size(), 11); + } + fastaSeq = this.nextFastaSequence(); + } + this.closeFastaFile(); + // Parallel mode... poll remaining jobs. + while(maxJobs > 1 && jobInfoList.size() > 0) { + pollJobList(jobInfoList, cli); + this.printDebugMessage("multifastaSubmitCli", "Remaining jobs: " + jobInfoList.size(), 11); + } + this.printProgressMessage("Processed " + jobNumber + + " input sequences", 2); + this.printDebugMessage("multifastaSubmitCli", "End", 11); + } + + /** Set the identifier list input file. + * + * @param fileName Name of the identifier list file. + * @throws FileNotFoundException + */ + public void setIdentifierListFile(String fileName) throws FileNotFoundException { + Reader inputReader = null; + if(fileName.equals("-")) { // STDIN + inputReader = new InputStreamReader(System.in); + } + else { // File + inputReader = new FileReader(fileName); + } + this.identifierListReader = new BufferedReader(inputReader); + } + + /** Get the next identifier from the identifier list file. + * + * NB: Assumes identifiers are in DB:ID format. + * + * @return An identifier. + * @throws IOException + */ + public String nextIdentifier() throws IOException { + String retVal = null; + // Read lines until EOF or a line contains a ':'. + String tmpLine = this.identifierListReader.readLine(); + while(this.identifierListReader.ready() && + (tmpLine == null || !(tmpLine.indexOf(':') > 0))) { + this.printDebugMessage("nextIdentifier", "tmpLine: " + tmpLine, 12); + tmpLine = this.identifierListReader.readLine(); + } + this.printDebugMessage("nextIdentifier", "tmpLine: " + tmpLine, 12); + if(tmpLine != null && tmpLine.indexOf(':') > 0) { + retVal = tmpLine; + } + return retVal; + } + + /** Close the identifier list input file. + * + * @throws IOException + */ + public void closeIdentifierListFile() throws IOException { + this.identifierListReader.close(); + this.identifierListReader = null; + } + + /** Submit a set of jobs using input from an identifier list (DB:ID format). + * + * @param dataOption Name of the identifier list file. + * @param cli Command-line options for the jobs. + * @throws IOException + * @throws ServiceException + */ + protected void idlistSubmitCli(String dataOption, CommandLine cli) throws IOException, ServiceException { + this.printDebugMessage("idlistSubmitCli", "Begin", 11); + int maxJobs = 1; + if(cli.hasOption("maxJobs")) { + maxJobs = Integer.parseInt(cli.getOptionValue("maxJobs")); + } + int jobNumber = 0; + ArrayList jobInfoList = new ArrayList(); + // Trim initial '@' from filename. + this.setIdentifierListFile(dataOption.substring(1)); + // Loop over input entries, submitting each one. + String entryId = null; + entryId = this.nextIdentifier(); + while (entryId != null) { + jobNumber++; + this.printProgressMessage("ID: " + entryId, 1); + String jobId = this.submitJobFromCli(cli, entryId); + // JobId, EntryId, errorCount, jobNumber + String[] jobInfo = {jobId, entryId, "0", String.valueOf(jobNumber)}; + jobInfoList.add(jobInfo); + // Parallel mode... wait for job(s) to finish to free slots. + while(maxJobs > 1 && jobInfoList.size() >= maxJobs) { + pollJobList(jobInfoList, cli); + this.printDebugMessage("idlistSubmitCli", "Remaining jobs: " + jobInfoList.size(), 11); + } + entryId = this.nextIdentifier(); + } + this.closeIdentifierListFile(); + // Parallel mode... poll remaining jobs. + while(maxJobs > 1 && jobInfoList.size() > 0) { + pollJobList(jobInfoList, cli); + this.printDebugMessage("idlistSubmitCli", "Remaining jobs: " + jobInfoList.size(), 11); + } + this.printProgressMessage("Processed " + jobNumber + + " input identifiers", 2); + this.printDebugMessage("idlistSubmitCli", "End", 11); + } + + /** Poll the status of a set of jobs and retrieve results for those that have finished. + * + * @param jobInfoList Set of submitted jobs to check status for. For each + * job an array is used to track: job Id, entry Id, error count, job + * number. Completed jobs are removed from the list. + * @param cli Command-line options for controlling output. + * @throws IOException + * @throws ServiceException + */ + private void pollJobList(ArrayList jobInfoList, CommandLine cli) throws IOException, ServiceException { + this.printDebugMessage("pollJobList", "Begin", 21); + // Poll a list of jobs. + for(int jobNum = 0; jobNum < jobInfoList.size(); jobNum++) { + long startTime = System.currentTimeMillis(); + String jobId = jobInfoList.get(jobNum)[0]; + String jobStatus = this.checkStatus(jobId); + int jobErrorCount = Integer.parseInt(jobInfoList.get(jobNum)[2]); + if(!(jobStatus.equals("RUNNING") || jobStatus.equals("PENDING") + || (jobStatus.equals("ERROR") && jobErrorCount < MAX_ERROR_STATUS_COUNT))) { + // Report job failure. + if(jobStatus.equals("ERROR") || jobStatus.equals("FAILURE")) { + this.printProgressMessage("Warning: job " + jobId + " failed for sequence " + jobInfoList.get(jobNum)[3] + ": " + jobInfoList.get(jobNum)[1], 0); + } + // Get results for finished job. + this.getResults(jobId, cli, jobInfoList.get(jobNum)[1]); + // Remove job from tracking list. + jobInfoList.remove(jobNum); + } + else { + // Track error status count. + if(jobStatus.equals("ERROR")) { + jobErrorCount++; + } + else if(jobErrorCount > 0) { + jobErrorCount--; + } + jobInfoList.get(jobNum)[2] = String.valueOf(jobErrorCount); + } + // Ensure each poll takes a minimum of 1s. + long endTime = System.currentTimeMillis(); + long duration = endTime - startTime; + if(duration < 1000) + try { + Thread.sleep((1000 - duration)); + } catch (InterruptedException e) { + // Ignore interrupted sleep. + } + } + this.printDebugMessage("pollJobList", "End", 21); + } +} diff --git a/src/ipr/IPRScan5Client.java b/src/ipr/IPRScan5Client.java new file mode 100644 index 0000000..c03ea2b --- /dev/null +++ b/src/ipr/IPRScan5Client.java @@ -0,0 +1,625 @@ +package ipr; + +/* $Id: IPRScan5Client.java 2754 2014-04-10 14:58:21Z hpm $ + * ====================================================================== + * + * Copyright 2010-2014 EMBL - European Bioinformatics Institute + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * ====================================================================== + * JDispatcher InterProScan 5 (SOAP) web service Java client using Axis 1.x. + * ---------------------------------------------------------------------- + * Tested with: + * Sun Java 1.5.0_17 with Apache Axis 1.4 on CentOS 5.2. + * ====================================================================== */ + +import java.io.File; +import java.io.IOException; +import java.rmi.RemoteException; +import javax.xml.rpc.Call; +import javax.xml.rpc.ServiceException; +import org.apache.axis.transport.http.HTTPConstants; +import org.apache.commons.cli.*; +import uk.ac.ebi.webservices.axis1.stubs.iprscan5.*; + +/** + *

+ * JDispatcher InterProScan 5 (SOAP) web service Java client using Apache Axis + * 1.x. + *

+ * + *

+ * See: + *

+ * + */ +public class IPRScan5Client extends AbstractWsToolClient { + /** Service proxy */ + private JDispatcherService_PortType srvProxy = null; + /** Client version/revision */ + private String revision = "$Revision: 2754 $"; + /** Tool specific usage message */ + private static final String usageMsg = "InterProScan 5\n" + + "==============\n" + + "\n" + + "Identify protein family, domain and signal signatures in a protein sequence.\n" + + "\n" + + "For information see:\n" + + "- http://www.ebi.ac.uk/interpro/\n" + + "- http://www.ebi.ac.uk/Tools/webservices/services/pfa/iprscan5_soap\n" + + "\n" + + "[Required]\n" + + "\n" + + " seqFile : file : query sequence (\"-\" for STDIN, @filename for\n" + + " identifier list file)\n" + + "\n" + + "[Optional]\n" + + "\n" + + " --appl : str : list of signature methods to run, comma, space or\n" + + " plus sign separated: see --paramDetail appl. \n" + + " --goterms : : enable retrieval of GO terms\n" + + " --nogoterms : : disable retrieval of GO terms\n" + + " --pathways : : enable retrieval of pathway terms\n" + + " --nopathways : : disable retrieval of pathway terms\n" + + " --multifasta : : treat input as a set of fasta formatted sequences\n" + + "\n"; + + /** + * Default constructor. + */ + public IPRScan5Client() { + // Set the HTTP user agent string for (java.net) requests. + this.setUserAgent(); + } + + /**

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 getSeq2DomainMap(List IPRoutput, B Map seq2domain = new HashMap(); for (int i=0; i < IPRoutput.size(); i++) { - String[] domain_entry = IPRoutput.get(i); + if (domain_entry.length < 12) continue; String sequence_id = domain_entry[0].trim(); String domain_id = domain_entry[11].trim(); int domain_start = Integer.parseInt(domain_entry[6]); int domain_end = Integer.parseInt(domain_entry[7]); int curr_domain_length = domain_end - domain_start + 1; - String domain_interval = domain_id + " " + domain_start + "\t" + domain_end; // skip domains for which no InterPro-ID is given if (domain_id.equals("NULL")) { - continue; + System.out.println("WARNING: Skipped domain " + domain_id + " with missing InterPro-ID"); + continue; } IprEntry curr_entry; @@ -146,11 +146,11 @@ public static Map parseIPRoutput(List IPRoutput) { String[] domain_entry = IPRoutput.get(i); + if (domain_entry.length < 13) { + continue; + } String domain_id = domain_entry[11].trim(); // skip domains for which no InterPro-ID is given - if (domain_id.equals("NULL")) { - continue; - } // skip domain IDs which were already added if (ipr_domains.containsKey(domain_id)) { continue; @@ -174,15 +174,8 @@ public static Map parseIPRoutput(List IPRoutput) { // parse GO terms for current InterPro domain entry domain_GOterms = new ArrayList(); - for (String go_entry : domain_go.split(",")) { - - if (go_entry.contains("GO:")) { - int start_pos = go_entry.indexOf("(GO:")+1; - int end_pos = go_entry.indexOf(")", start_pos); - - go_entry = go_entry.substring(start_pos, end_pos); - domain_GOterms.add(go_entry); - } + for (String go_entry : domain_go.split("\\|")) { + domain_GOterms.add(go_entry); } } IprRaw ipr_domain = new IprRaw(domain_id, domain_names, domain_GOterms); diff --git a/src/ipr/IPRrun.java b/src/ipr/IPRrun.java index 45e3ae5..ff8084f 100644 --- a/src/ipr/IPRrun.java +++ b/src/ipr/IPRrun.java @@ -44,7 +44,7 @@ import javax.xml.rpc.ServiceException; -import uk.ac.ebi.webservices.jaxws.IPRScanClient; +import uk.ac.ebi.webservices.axis1.stubs.iprscan5.WsResultType; /** * @@ -54,7 +54,7 @@ */ public class IPRrun { - public static boolean addSpacerLine = true; + public static boolean addSpacerLine = false; // fixes bug in current version of InterProScan which removes first line of sequence if header is given private static void addSpacerLine(String seqfile) { @@ -134,7 +134,7 @@ public ArrayList run(String seqfile, String iprpath, String basedir, b // submit job try { - IPRScanClient.main(param); + IPRScan5Client.main(param); } catch (Exception e) { } // restore System.exit @@ -146,14 +146,15 @@ public ArrayList run(String seqfile, String iprpath, String basedir, b // restore System.out System.setOut(orig_stdout); - IPRScanClient webIPR = new IPRScanClient(); + IPRScan5Client webIPR = new IPRScan5Client(); if (!silent) System.out.println("Waiting for " + jobs.size() + " job(s) to finish ..."); for (String jobid : jobs) { if (!silent) System.out.println("Polling job \"" + jobid + "\" ..."); try { - webIPR.getResults(jobid, basedir + jobid, "out"); - webIPR.getResults(jobid, basedir + jobid, "visual-png"); + new File(basedir).mkdirs(); + webIPR.getResults(jobid, basedir + jobid, "tsv"); + webIPR.getResults(jobid, basedir + jobid, "svg"); } catch (IOException e) { e.printStackTrace(); } catch (ServiceException e) { @@ -166,6 +167,7 @@ public ArrayList run(String seqfile, String iprpath, String basedir, b if (silent) { System.setErr(orig_stderr); } + IPRoutput = readIPROutput(basedir, jobs); } else { // local @@ -199,7 +201,7 @@ private static ArrayList readIPROutput(String basedir, ArrayList\n"); - bw.write(" " + "\n"); + bw.write(" " + "\n"); bw.write(" Illustration generated by InterProScan \n"); bw.write("\n\n"); bw.write("
\n\n");