Webservice Updated for scoremanager but I think I broke something on the way.
[jabaws.git] / webservices / compbio / ws / client / Jws2Client.java
index 5c7a879..18424f6 100644 (file)
@@ -1,6 +1,6 @@
-/* Copyright (c) 2009 Peter Troshin\r
+/* Copyright (c) 2011 Peter Troshin\r
  *  \r
- *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 1.0     \r
+ *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0     \r
  * \r
  *  This library is free software; you can redistribute it and/or modify it under the terms of the\r
  *  Apache License version 2 as published by the Apache Software Foundation\r
 \r
 package compbio.ws.client;\r
 \r
-import static compbio.ws.client.Constraints.hostkey;\r
 import static compbio.ws.client.Constraints.inputkey;\r
-import static compbio.ws.client.Constraints.limitList;\r
 import static compbio.ws.client.Constraints.outputkey;\r
 import static compbio.ws.client.Constraints.paramFile;\r
-import static compbio.ws.client.Constraints.paramList;\r
-import static compbio.ws.client.Constraints.presetList;\r
-import static compbio.ws.client.Constraints.presetkey;\r
-import static compbio.ws.client.Constraints.pseparator;\r
-import static compbio.ws.client.Constraints.servicekey;\r
 \r
 import java.io.Closeable;\r
 import java.io.File;\r
 import java.io.FileInputStream;\r
 import java.io.IOException;\r
-import java.io.OutputStream;\r
+import java.io.PrintWriter;\r
+import java.io.Writer;\r
+import java.net.ConnectException;\r
 import java.net.MalformedURLException;\r
 import java.net.URL;\r
 import java.util.Arrays;\r
+import java.util.Collections;\r
 import java.util.List;\r
+import java.util.Set;\r
 import java.util.logging.Level;\r
 import java.util.logging.Logger;\r
 \r
+import javax.xml.namespace.QName;\r
 import javax.xml.ws.Service;\r
 import javax.xml.ws.WebServiceException;\r
 \r
 import compbio.data.msa.JABAService;\r
+import compbio.data.msa.FoldWS;\r
 import compbio.data.msa.Metadata;\r
 import compbio.data.msa.MsaWS;\r
+import compbio.data.msa.RegistryWS;\r
+import compbio.data.msa.SequenceAnnotation;\r
 import compbio.data.sequence.Alignment;\r
 import compbio.data.sequence.FastaSequence;\r
+import compbio.data.sequence.RNAStruct;\r
+import compbio.data.sequence.ScoreManager;\r
+import compbio.data.sequence.ClustalAlignmentUtil;\r
 import compbio.data.sequence.SequenceUtil;\r
+import compbio.data.sequence.UnknownFileFormatException;\r
 import compbio.metadata.JobSubmissionException;\r
 import compbio.metadata.Option;\r
 import compbio.metadata.Preset;\r
 import compbio.metadata.ResultNotAvailableException;\r
 import compbio.metadata.WrongParameterException;\r
+import compbio.util.FileUtil;\r
 \r
 /**\r
  * A command line client for JAva Bioinformatics Analysis Web Services\r
@@ -71,12 +77,6 @@ public class Jws2Client {
        private static final Logger log = Logger.getLogger(Jws2Client.class\r
                        .getCanonicalName());\r
 \r
-       // JABAWS version 1.0 service name\r
-       static final String QUALIFIED_SERVICE_NAME = "http://msa.data.compbio/01/01/2010/";\r
-\r
-       // JABAWS version 2.0 service name\r
-       static final String V2_QUALIFIED_SERVICE_NAME = "http://msa.data.compbio/01/12/2010/";\r
-\r
        /**\r
         * Attempt to construct the URL object from the string\r
         * \r
@@ -106,29 +106,44 @@ public class Jws2Client {
         * @throws IOException\r
         */\r
        <T> Jws2Client(String[] cmd) throws IOException {\r
+               \r
 \r
                String hostname = CmdHelper.getHost(cmd);\r
                if (hostname == null) {\r
-                       System.out.println("Host name is not provided!");\r
+                       System.err.println("Host name is not provided!");\r
                        printUsage(1);\r
                }\r
 \r
                if (!validURL(hostname)) {\r
-                       System.out.println("Host name is not valid!");\r
+                       System.err.println("Host name is not valid!");\r
                        printUsage(1);\r
                }\r
+               // Just list available services and quit\r
+               boolean listServices = CmdHelper.listServices(cmd);\r
+               if (listServices) {\r
+                       listServices(hostname);\r
+                       System.exit(0);\r
+               }\r
+\r
                String serviceName = CmdHelper.getServiceName(cmd);\r
                if (serviceName == null) {\r
-                       System.out.println("Service name is no provided!");\r
+                       System.err.println("Service name is no provided!");\r
                        printUsage(1);\r
                }\r
                Services service = Services.getService(serviceName);\r
                if (service == null) {\r
-                       System.out.println("Service " + serviceName\r
-                                       + " is no supported! Valid values are: "\r
+                       System.err.println("Service " + serviceName\r
+                                       + " is no recognized! Valid values are: "\r
                                        + Arrays.toString(Services.values()));\r
                        printUsage(1);\r
                }\r
+               // Test service and quit\r
+               boolean testService = CmdHelper.testService(cmd);\r
+               if (testService) {\r
+                       testService(hostname, service, new PrintWriter(System.out, true));\r
+                       System.exit(0);\r
+               }\r
+\r
                File inputFile = IOHelper.getFile(cmd, inputkey, true);\r
                File outFile = IOHelper.getFile(cmd, outputkey, false);\r
                File parametersFile = IOHelper.getFile(cmd, paramFile, true);\r
@@ -145,25 +160,29 @@ public class Jws2Client {
                        customOptions = MetadataHelper.processParameters(prms,\r
                                        msaws.getRunnerOptions());\r
                }\r
+//             System.out.println("The Options read from the command line: " + customOptions);\r
+               \r
                Alignment alignment = null;\r
                if (inputFile != null) {\r
-                       if (service == Services.AAConWS) {\r
-                               System.out.println("calc conserv!");\r
+                       Writer writer = null;\r
+                       if (outFile != null) {\r
+                               writer = IOHelper.getWriter(outFile);\r
                        } else {\r
+                               // this stream is going to be closed later which is fine as\r
+                               // std.out will not be\r
+                               writer = new PrintWriter(System.out, true);\r
+                       }\r
+                       if (service.getServiceType() == SequenceAnnotation.class) {\r
+                               ScoreManager result = analize(inputFile,\r
+                                               ((SequenceAnnotation<T>) msaws), preset, customOptions);\r
 \r
+                               IOHelper.writeOut(writer, result);\r
+                       } else if (service.getServiceType() == MsaWS.class) {\r
                                alignment = align(inputFile, (MsaWS<T>) msaws, preset,\r
                                                customOptions);\r
-                               OutputStream outStream = null;\r
-                               if (outFile != null) {\r
-                                       outStream = IOHelper.getOutStream(outFile);\r
-                               } else {\r
-                                       // this stream is going to be closed later which is fine as\r
-                                       // std.out will not be\r
-                                       outStream = System.out;\r
-                               }\r
-                               IOHelper.writeOut(outStream, alignment);\r
-                               // stream is closed in the method no need to close it here\r
+                               IOHelper.writeOut(writer, alignment);\r
                        }\r
+                       writer.close();\r
                }\r
 \r
                boolean listParameters = CmdHelper.listParameters(cmd);\r
@@ -184,17 +203,162 @@ public class Jws2Client {
        }\r
 \r
        /**\r
-        * Connects to a web service by the host and the service name\r
+        * Asks registry to test the service on the host hostname\r
+        * \r
+        * @param hostname\r
+        * @param service\r
+        * @param writer\r
+        * @throws ConnectException\r
+        * @throws WebServiceException\r
+        */\r
+       public static void testService(String hostname, Services service,\r
+                       PrintWriter writer) throws ConnectException, WebServiceException {\r
+               RegistryWS registry = connectToRegistry(hostname);\r
+               if (registry != null) {\r
+                       String message = registry.testService(service);\r
+                       writer.println("Service " + service + " testing results: ");\r
+                       writer.println(message);\r
+                       FileUtil.closeSilently(((Closeable) registry));\r
+               }\r
+               writer.flush();\r
+       }\r
+\r
+       public static Set<Services> getServices(String hostname)\r
+                       throws WebServiceException, ConnectException {\r
+               RegistryWS registry = connectToRegistry(hostname);\r
+               Set<Services> services = Collections.EMPTY_SET;\r
+               if (registry != null) {\r
+                       services = registry.getSupportedServices();\r
+                       FileUtil.closeSilently(((Closeable) registry));\r
+               }\r
+               return services;\r
+       }\r
+\r
+       private static void listServices(String hostname)\r
+                       throws WebServiceException, IOException {\r
+               Set<Services> services = Jws2Client.getServices(hostname);\r
+               if (!services.isEmpty()) {\r
+                       System.out.println("Supported services are: "\r
+                                       + Services.toString(services));\r
+               } else {\r
+                       System.out.println("Failed to connect to the registry! ");\r
+               }\r
+       }\r
+\r
+       /**\r
+        * Calculate conservation for sequences loaded from the file\r
+        * \r
+        * @param wsproxy\r
+        *            a web service proxy\r
+        * @param file\r
+        *            the file to read the results from\r
+        * @param preset\r
+        *            Preset to use optional\r
+        * @param customOptions\r
+        *            the list of options\r
+        * @return Set<Score> the conservation scores\r
+        * @throws UnknownFileFormatException\r
+        */\r
+       static <T> ScoreManager analize(List<FastaSequence> fastalist,\r
+                       SequenceAnnotation<T> wsproxy, Preset<T> preset,\r
+                       List<Option<T>> customOptions) {\r
+\r
+               ScoreManager scores = null;\r
+               try {\r
+                       String jobId = null;\r
+                       if (customOptions != null && preset != null) {\r
+                               System.out\r
+                                               .println("WARN: Parameters (-f) are defined together with a preset (-r) ignoring preset!");\r
+                       }\r
+                       if (customOptions != null) {\r
+                               jobId = wsproxy.customAnalize(fastalist, customOptions);\r
+                       } else if (preset != null) {\r
+                               jobId = wsproxy.presetAnalize(fastalist, preset);\r
+                       } else {\r
+                               jobId = wsproxy.analize(fastalist);\r
+                       }\r
+                       System.out.println("\n\ncalling analise.........");\r
+                       Thread.sleep(1000);\r
+                       scores = wsproxy.getAnnotation(jobId);\r
+\r
+               } catch (JobSubmissionException e) {\r
+                       System.err\r
+                                       .println("Exception while submitting job to a web server. "\r
+                                                       + "Exception details are below:");\r
+                       e.printStackTrace();\r
+               } catch (ResultNotAvailableException e) {\r
+                       System.err.println("Exception while waiting for results. "\r
+                                       + "Exception details are below:");\r
+                       e.printStackTrace();\r
+               } catch (InterruptedException e) {\r
+                       // ignore and propagate an interruption\r
+                       Thread.currentThread().interrupt();\r
+                       System.err.println("Exception while waiting for results. "\r
+                                       + "Exception details are below:");\r
+                       e.printStackTrace();\r
+               } catch (WrongParameterException e) {\r
+                       System.err\r
+                                       .println("Exception while parsing the web method input parameters. "\r
+                                                       + "Exception details are below:");\r
+                       e.printStackTrace();\r
+               }\r
+               return scores;\r
+\r
+       }\r
+\r
+       /**\r
+        * Calculate conservation for sequences loaded from the file\r
+        * \r
+        * @param wsproxy\r
+        *            a web service proxy\r
+        * @param file\r
+        *            the file to read the results from\r
+        * @param preset\r
+        *            Preset to use optional\r
+        * @param customOptions\r
+        *            the list of options\r
+        * @return Set<Score> the conservation scores\r
+        * @throws IOException\r
+        * @throws UnknownFileFormatException\r
+        */\r
+       static <T> ScoreManager analize(File file, SequenceAnnotation<T> wsproxy,\r
+                       Preset<T> preset, List<Option<T>> customOptions) {\r
+               List<FastaSequence> fastalist = null;\r
+               try {\r
+                       fastalist = SequenceUtil.openInputStream(file.getAbsolutePath());\r
+                       assert !fastalist.isEmpty() : "Input is empty!";\r
+               } catch (IOException e) {\r
+                       System.err\r
+                                       .println("Exception while reading the input file. "\r
+                                                       + "Check that the input file contains a list of fasta formatted sequences! "\r
+                                                       + "Exception details are below:");\r
+                       e.printStackTrace();\r
+               } catch (UnknownFileFormatException e) {\r
+                       System.err\r
+                                       .println("Exception while attempting to read the input file "\r
+                                                       + "Exception details are below:");\r
+                       System.out.println(e.getMessage());\r
+                       e.printStackTrace();\r
+               }\r
+               return analize(fastalist, wsproxy, preset, customOptions);\r
+       }\r
+       /**\r
+        * Connects to a web service by the host and the service name web service\r
+        * type\r
         * \r
-        * @param <T>\r
-        *            web service type\r
         * @param host\r
+        *            the fully qualified name of JABAWS server including JABAWS\r
+        *            context name e.g\r
+        *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
         * @param service\r
-        * @return MsaWS<T>\r
+        *            the name of the JABAWS service to connect to\r
+        * @return JABAService<T>\r
         * @throws WebServiceException\r
+        * @throws ConnectException\r
+        *             if fails to connect to the service on the host\r
         */\r
        public static JABAService connect(String host, Services service)\r
-                       throws WebServiceException {\r
+                       throws WebServiceException, ConnectException {\r
                URL url = null;\r
                log.log(Level.FINE, "Attempting to connect...");\r
                try {\r
@@ -205,15 +369,20 @@ public class Jws2Client {
                }\r
                Service serv = null;\r
                try {\r
-                       serv = service.getService(url, QUALIFIED_SERVICE_NAME);\r
+                       serv = service.getService(url, JABAService.SERVICE_NAMESPACE);\r
                } catch (WebServiceException wse) {\r
-                       System.out.println("Conecting to JABAWS version 2 service");\r
+                       System.out.println("Connecting to JABAWS version 2 service");\r
                        if (isV2service(wse)) {\r
-                               serv = service.getService(url, V2_QUALIFIED_SERVICE_NAME);\r
+                               serv = service\r
+                                               .getService(url, JABAService.V2_SERVICE_NAMESPACE);\r
                        }\r
                }\r
+               if (serv == null) {\r
+                       throw new ConnectException("Could not connect to " + url\r
+                                       + " the server is down?");\r
+               }\r
                JABAService serviceIF = service.getInterface(serv);\r
-               log.log(Level.FINE, "Connected successfully!");\r
+               log.log(Level.INFO, "Connected successfully!");\r
 \r
                return serviceIF;\r
        }\r
@@ -222,7 +391,8 @@ public class Jws2Client {
                String message = wse.getMessage();\r
                int idx = message.indexOf("not a valid service");\r
                if (idx > 0) {\r
-                       if (message.substring(idx).contains(V2_QUALIFIED_SERVICE_NAME)) {\r
+                       if (message.substring(idx).contains(\r
+                                       JABAService.V2_SERVICE_NAMESPACE)) {\r
                                return true;\r
                        }\r
                }\r
@@ -230,6 +400,48 @@ public class Jws2Client {
        }\r
 \r
        /**\r
+        * Get a connection of JABAWS registry\r
+        * \r
+        * @param host\r
+        *            the fully qualified name of JABAWS server including JABAWS\r
+        *            context name e.g\r
+        *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
+        * @return compbio.data.msa.RegistryWS - instance of a RegistryWS web\r
+        *         service\r
+        * @throws WebServiceException\r
+        * @throws ConnectException\r
+        */\r
+       public static compbio.data.msa.RegistryWS connectToRegistry(String host)\r
+                       throws WebServiceException, ConnectException {\r
+               URL url = null;\r
+               String service = "RegistryWS";\r
+               log.log(Level.FINE, "Attempting to connect...");\r
+\r
+               try {\r
+                       url = new URL(host + "/" + service + "?wsdl");\r
+               } catch (MalformedURLException e) {\r
+                       e.printStackTrace();\r
+                       // ignore as the host name is already verified\r
+               }\r
+               QName qname = new QName(JABAService.V2_SERVICE_NAMESPACE, service);\r
+               Service serv = Service.create(url, qname);\r
+\r
+               if (serv == null) {\r
+                       throw new ConnectException("Could not connect to " + url\r
+                                       + " the server is down?");\r
+               }\r
+\r
+               QName portName = new QName(serv.getServiceName().getNamespaceURI(),\r
+                               service + "Port");\r
+               compbio.data.msa.RegistryWS serviceIF = serv.getPort(portName,\r
+                               compbio.data.msa.RegistryWS.class);\r
+\r
+               log.log(Level.INFO, "Connected to " + service + " successfully!");\r
+\r
+               return serviceIF;\r
+       }\r
+\r
+       /**\r
         * Align sequences from the file using MsaWS\r
         * \r
         * @param <T>\r
@@ -265,6 +477,7 @@ public class Jws2Client {
                        } else {\r
                                jobId = msaws.align(fastalist);\r
                        }\r
+                       System.out.println("\n\ncalling align.........");\r
                        Thread.sleep(1000);\r
                        alignment = msaws.getResult(jobId);\r
 \r
@@ -299,59 +512,90 @@ public class Jws2Client {
                }\r
                return alignment;\r
        }\r
-\r
+       \r
+       /**\r
+        * Return RNA secondary structure from a file using FoldWS\r
+        * \r
+        * @param <T>\r
+        *            web service type e.g. Clustal\r
+        * @param file\r
+        *            to read the results from\r
+        * @param foldws\r
+        *            FoldWS required\r
+        * @param preset\r
+        *            Preset to use optional\r
+        * @param customOptions\r
+        *            file which contains new line separated list of options\r
+        * @return String\r
+        */\r
+       \r
+       static <T> String fold(File file, FoldWS<T> foldws, Preset<T> preset,\r
+                       List<Option<T>> customOptions) {\r
+               FileInputStream instream = null;\r
+               Alignment alignment = null;\r
+               String rnastruct = null;\r
+               try {\r
+                       instream = new FileInputStream(file);\r
+                       alignment = ClustalAlignmentUtil.readClustalFile(instream);\r
+                       instream.close();\r
+                       String jobId = null;\r
+                       if (customOptions != null && preset != null) {\r
+                               System.out.println("WARN: Parameters (-f) are defined together"\r
+                                               + "with a preset (-r), ignoring preset! ");\r
+                       }\r
+                       if (customOptions != null) {\r
+                               jobId = foldws.customFold(alignment, customOptions);\r
+                       } else if (preset != null) {\r
+                               jobId = foldws.presetFold(alignment, preset);\r
+                       } else {\r
+                               jobId = foldws.fold(alignment);\r
+                       }\r
+                       System.out.println("\n\ncalling fold.........");\r
+                       Thread.sleep(1000);\r
+                       rnastruct = foldws.getResult(jobId);\r
+                               \r
+               } catch (IOException e) {\r
+                       System.err.println("Exception while reading the input file. Exception details: ");\r
+                       e.printStackTrace();\r
+               } catch (UnknownFileFormatException e) {\r
+                       System.err.println("Exception while reading input file. Doesnt look like a Clustal format file");\r
+                       e.printStackTrace();\r
+               } catch (JobSubmissionException e) {\r
+                       System.err.println("Exception while submitting job to the web server. ");\r
+                       e.printStackTrace();\r
+               } catch (ResultNotAvailableException e) {\r
+                       System.err.println("Exception while waiting for results. Exception details: ");\r
+                       e.printStackTrace();\r
+               } catch (InterruptedException ignored) {\r
+                       // ignore and propagate an interruption\r
+                       Thread.currentThread().interrupt();\r
+               } catch (WrongParameterException e) {\r
+                       e.printStackTrace();\r
+               } finally {\r
+                       if (instream != null) {\r
+                               try {\r
+                                       instream.close();\r
+                               } catch (IOException ignored) {\r
+                                       // ignore\r
+                               }\r
+                       }\r
+               }\r
+               return rnastruct;\r
+       }\r
+               \r
        /**\r
         * Prints Jws2Client usage information to standard out\r
         * \r
         * @param exitStatus\r
         */\r
        static void printUsage(int exitStatus) {\r
-               System.out.println();\r
-               System.out.println("Usage: <Class or Jar file name> " + hostkey\r
-                               + pseparator + "host_and_context " + servicekey + pseparator\r
-                               + "serviceName ACTION [OPTIONS] ");\r
-               System.out.println();\r
-               System.out\r
-                               .println(hostkey\r
-                                               + pseparator\r
-                                               + "<host_and_context> - a full URL to the JWS2 web server including context path e.g. http://10.31.1.159:8080/ws");\r
-               System.out.println(servicekey + pseparator + "<ServiceName> - one of "\r
-                               + Arrays.toString(Services.values()));\r
-               System.out.println();\r
-               System.out.println("ACTIONS: ");\r
-               System.out\r
-                               .println(inputkey\r
-                                               + pseparator\r
-                                               + "<inputFile> - full path to fasta formatted sequence file, from which to align sequences");\r
-               System.out.println(paramList\r
-                               + " - lists parameters supported by web service");\r
-               System.out.println(presetList\r
-                               + " - lists presets supported by web service");\r
-               System.out.println(limitList + " - lists web services limits");\r
-               System.out\r
-                               .println("Please note that if input file is specified other actions are ignored");\r
-\r
-               System.out.println();\r
-               System.out.println("OPTIONS (only for use with -i action):");\r
-\r
-               System.out.println(presetkey + pseparator\r
-                               + "<presetName> - name of the preset to use");\r
-               System.out\r
-                               .println(outputkey\r
-                                               + pseparator\r
-                                               + "<outputFile> - full path to the file where to write an alignment");\r
-               System.out\r
-                               .println("-f=<parameterInputFile> - the name of the file with the list of parameters to use.");\r
-               System.out\r
-                               .println("Please note that -r and -f options cannot be used together. "\r
-                                               + "Alignment is done with either preset or a parameters from the file, but not both!");\r
-\r
+               System.out.println(Constraints.help_text);\r
                System.exit(exitStatus);\r
        }\r
 \r
        /**\r
         * Starts command line client, if no parameter are supported print help. Two\r
-        * parameters are required for successfull call the JWS2 host name and a\r
+        * parameters are required for successful call the JWS2 host name and a\r
         * service name.\r
         * \r
         * @param args\r
@@ -391,7 +635,7 @@ public class Jws2Client {
                        printUsage(1);\r
                }\r
                if (args.length < 2) {\r
-                       System.out.println("Host and service names are required!");\r
+                       System.err.println("Host and service names are required!");\r
                        printUsage(1);\r
                }\r
 \r