5a728020a33f2cdf982811ffad06c99c97c80bfd
[jabaws.git] / webservices / compbio / ws / client / Jws2Client.java
1 /* Copyright (c) 2011 Peter Troshin\r
2  *  \r
3  *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 2.0     \r
4  * \r
5  *  This library is free software; you can redistribute it and/or modify it under the terms of the\r
6  *  Apache License version 2 as published by the Apache Software Foundation\r
7  * \r
8  *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r
9  *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache \r
10  *  License for more details.\r
11  * \r
12  *  A copy of the license is in apache_license.txt. It is also available here:\r
13  * @see: http://www.apache.org/licenses/LICENSE-2.0.txt\r
14  * \r
15  * Any republication or derived work distributed in source code form\r
16  * must include this copyright and license notice.\r
17  */\r
18 \r
19 package compbio.ws.client;\r
20 \r
21 import static compbio.ws.client.Constraints.inputkey;\r
22 import static compbio.ws.client.Constraints.outputkey;\r
23 import static compbio.ws.client.Constraints.paramFile;\r
24 \r
25 import java.io.Closeable;\r
26 import java.io.File;\r
27 import java.io.FileInputStream;\r
28 import java.io.IOException;\r
29 import java.io.PrintWriter;\r
30 import java.io.Writer;\r
31 import java.net.ConnectException;\r
32 import java.net.MalformedURLException;\r
33 import java.net.URL;\r
34 import java.util.Arrays;\r
35 import java.util.Collections;\r
36 import java.util.List;\r
37 import java.util.Set;\r
38 import java.util.logging.Level;\r
39 import java.util.logging.Logger;\r
40 \r
41 import javax.xml.namespace.QName;\r
42 import javax.xml.ws.Service;\r
43 import javax.xml.ws.WebServiceException;\r
44 \r
45 import compbio.data.msa.JABAService;\r
46 import compbio.data.msa.Metadata;\r
47 import compbio.data.msa.MsaWS;\r
48 import compbio.data.msa.RegistryWS;\r
49 import compbio.data.msa.SequenceAnnotation;\r
50 import compbio.data.sequence.Alignment;\r
51 import compbio.data.sequence.FastaSequence;\r
52 import compbio.data.sequence.ScoreManager;\r
53 import compbio.data.sequence.SequenceUtil;\r
54 import compbio.data.sequence.UnknownFileFormatException;\r
55 import compbio.metadata.JobSubmissionException;\r
56 import compbio.metadata.Option;\r
57 import compbio.metadata.Preset;\r
58 import compbio.metadata.ResultNotAvailableException;\r
59 import compbio.metadata.WrongParameterException;\r
60 import compbio.util.FileUtil;\r
61 \r
62 /**\r
63  * A command line client for JAva Bioinformatics Analysis Web Services\r
64  * \r
65  * @author pvtroshin\r
66  * @version 1.0\r
67  */\r
68 public class Jws2Client {\r
69 \r
70         /*\r
71          * Use java.util.Logger instead of log4j logger to reduce the size of the\r
72          * client package\r
73          */\r
74         private static final Logger log = Logger.getLogger(Jws2Client.class\r
75                         .getCanonicalName());\r
76 \r
77         /**\r
78          * Attempt to construct the URL object from the string\r
79          * \r
80          * @param urlstr\r
81          * @return true if it succeed false otherwise\r
82          */\r
83         public static boolean validURL(String urlstr) {\r
84                 try {\r
85                         if (urlstr == null || urlstr.trim().length() == 0) {\r
86                                 return false;\r
87                         }\r
88                         new URL(urlstr);\r
89                 } catch (MalformedURLException e) {\r
90                         return false;\r
91                 }\r
92                 return true;\r
93         }\r
94 \r
95         /**\r
96          * Connects to the service and do the job as requested, if something goes\r
97          * wrong reports or/and prints usage help.\r
98          * \r
99          * @param <T>\r
100          *            web service type\r
101          * @param cmd\r
102          *            command line options\r
103          * @throws IOException\r
104          */\r
105         <T> Jws2Client(String[] cmd) throws IOException {\r
106                 \r
107 \r
108                 String hostname = CmdHelper.getHost(cmd);\r
109                 if (hostname == null) {\r
110                         System.err.println("Host name is not provided!");\r
111                         printUsage(1);\r
112                 }\r
113 \r
114                 if (!validURL(hostname)) {\r
115                         System.err.println("Host name is not valid!");\r
116                         printUsage(1);\r
117                 }\r
118                 // Just list available services and quit\r
119                 boolean listServices = CmdHelper.listServices(cmd);\r
120                 if (listServices) {\r
121                         listServices(hostname);\r
122                         System.exit(0);\r
123                 }\r
124 \r
125                 String serviceName = CmdHelper.getServiceName(cmd);\r
126                 if (serviceName == null) {\r
127                         System.err.println("Service name is no provided!");\r
128                         printUsage(1);\r
129                 }\r
130                 Services service = Services.getService(serviceName);\r
131                 if (service == null) {\r
132                         System.err.println("Service " + serviceName\r
133                                         + " is no recognized! Valid values are: "\r
134                                         + Arrays.toString(Services.values()));\r
135                         printUsage(1);\r
136                 }\r
137                 // Test service and quit\r
138                 boolean testService = CmdHelper.testService(cmd);\r
139                 if (testService) {\r
140                         testService(hostname, service, new PrintWriter(System.out, true));\r
141                         System.exit(0);\r
142                 }\r
143 \r
144                 File inputFile = IOHelper.getFile(cmd, inputkey, true);\r
145                 File outFile = IOHelper.getFile(cmd, outputkey, false);\r
146                 File parametersFile = IOHelper.getFile(cmd, paramFile, true);\r
147                 String presetName = CmdHelper.getPresetName(cmd);\r
148 \r
149                 Metadata<T> msaws = (Metadata<T>) connect(hostname, service);\r
150                 Preset<T> preset = null;\r
151                 if (presetName != null) {\r
152                         preset = MetadataHelper.getPreset(msaws, presetName);\r
153                 }\r
154                 List<Option<T>> customOptions = null;\r
155                 if (parametersFile != null) {\r
156                         List<String> prms = IOHelper.loadParameters(parametersFile);\r
157                         customOptions = MetadataHelper.processParameters(prms,\r
158                                         msaws.getRunnerOptions());\r
159                 }\r
160 //              System.out.println("The Options read from the command line: " + customOptions);\r
161                 \r
162                 Alignment alignment = null;\r
163                 if (inputFile != null) {\r
164                         Writer writer = null;\r
165                         if (outFile != null) {\r
166                                 writer = IOHelper.getWriter(outFile);\r
167                         } else {\r
168                                 // this stream is going to be closed later which is fine as\r
169                                 // std.out will not be\r
170                                 writer = new PrintWriter(System.out, true);\r
171                         }\r
172                         if (service.getServiceType() == SequenceAnnotation.class) {\r
173                                 ScoreManager result = analize(inputFile,\r
174                                                 ((SequenceAnnotation<T>) msaws), preset, customOptions);\r
175 \r
176                                 IOHelper.writeOut(writer, result);\r
177                         } else if (service.getServiceType() == MsaWS.class) {\r
178                                 alignment = align(inputFile, (MsaWS<T>) msaws, preset,\r
179                                                 customOptions);\r
180                                 IOHelper.writeOut(writer, alignment);\r
181                         }\r
182                         writer.close();\r
183                 }\r
184 \r
185                 boolean listParameters = CmdHelper.listParameters(cmd);\r
186                 if (listParameters) {\r
187                         System.out.println(MetadataHelper.getParametersList(msaws));\r
188                 }\r
189                 boolean listPreset = CmdHelper.listPresets(cmd);\r
190                 if (listPreset) {\r
191                         System.out.println(MetadataHelper.getPresetList(msaws));\r
192                 }\r
193                 boolean listLimits = CmdHelper.listLimits(cmd);\r
194                 if (listLimits) {\r
195                         System.out.println(MetadataHelper.getLimits(msaws));\r
196                 }\r
197                 log.fine("Disconnecting...");\r
198                 ((Closeable) msaws).close();\r
199                 log.fine("Disconnected successfully!");\r
200         }\r
201 \r
202         /**\r
203          * Asks registry to test the service on the host hostname\r
204          * \r
205          * @param hostname\r
206          * @param service\r
207          * @param writer\r
208          * @throws ConnectException\r
209          * @throws WebServiceException\r
210          */\r
211         public static void testService(String hostname, Services service,\r
212                         PrintWriter writer) throws ConnectException, WebServiceException {\r
213                 RegistryWS registry = connectToRegistry(hostname);\r
214                 if (registry != null) {\r
215                         String message = registry.testService(service);\r
216                         writer.println("Service " + service + " testing results: ");\r
217                         writer.println(message);\r
218                         FileUtil.closeSilently(((Closeable) registry));\r
219                 }\r
220                 writer.flush();\r
221         }\r
222 \r
223         public static Set<Services> getServices(String hostname)\r
224                         throws WebServiceException, ConnectException {\r
225                 RegistryWS registry = connectToRegistry(hostname);\r
226                 Set<Services> services = Collections.EMPTY_SET;\r
227                 if (registry != null) {\r
228                         services = registry.getSupportedServices();\r
229                         FileUtil.closeSilently(((Closeable) registry));\r
230                 }\r
231                 return services;\r
232         }\r
233 \r
234         private static void listServices(String hostname)\r
235                         throws WebServiceException, IOException {\r
236                 Set<Services> services = Jws2Client.getServices(hostname);\r
237                 if (!services.isEmpty()) {\r
238                         System.out.println("Supported services are: "\r
239                                         + Services.toString(services));\r
240                 } else {\r
241                         System.out.println("Failed to connect to the registry! ");\r
242                 }\r
243         }\r
244 \r
245         /**\r
246          * Calculate conservation for sequences loaded from the file\r
247          * \r
248          * @param wsproxy\r
249          *            a web service proxy\r
250          * @param file\r
251          *            the file to read the results from\r
252          * @param preset\r
253          *            Preset to use optional\r
254          * @param customOptions\r
255          *            the list of options\r
256          * @return Set<Score> the conservation scores\r
257          * @throws UnknownFileFormatException\r
258          */\r
259         static <T> ScoreManager analize(List<FastaSequence> fastalist,\r
260                         SequenceAnnotation<T> wsproxy, Preset<T> preset,\r
261                         List<Option<T>> customOptions) {\r
262 \r
263                 ScoreManager scores = null;\r
264                 try {\r
265                         String jobId = null;\r
266                         if (customOptions != null && preset != null) {\r
267                                 System.out\r
268                                                 .println("WARN: Parameters (-f) are defined together with a preset (-r) ignoring preset!");\r
269                         }\r
270                         if (customOptions != null) {\r
271                                 jobId = wsproxy.customAnalize(fastalist, customOptions);\r
272                         } else if (preset != null) {\r
273                                 jobId = wsproxy.presetAnalize(fastalist, preset);\r
274                         } else {\r
275                                 jobId = wsproxy.analize(fastalist);\r
276                         }\r
277                         System.out.println("\n\ncalling analise.........");\r
278                         Thread.sleep(1000);\r
279                         scores = wsproxy.getAnnotation(jobId);\r
280 \r
281                 } catch (JobSubmissionException e) {\r
282                         System.err\r
283                                         .println("Exception while submitting job to a web server. "\r
284                                                         + "Exception details are below:");\r
285                         e.printStackTrace();\r
286                 } catch (ResultNotAvailableException e) {\r
287                         System.err.println("Exception while waiting for results. "\r
288                                         + "Exception details are below:");\r
289                         e.printStackTrace();\r
290                 } catch (InterruptedException e) {\r
291                         // ignore and propagate an interruption\r
292                         Thread.currentThread().interrupt();\r
293                         System.err.println("Exception while waiting for results. "\r
294                                         + "Exception details are below:");\r
295                         e.printStackTrace();\r
296                 } catch (WrongParameterException e) {\r
297                         System.err\r
298                                         .println("Exception while parsing the web method input parameters. "\r
299                                                         + "Exception details are below:");\r
300                         e.printStackTrace();\r
301                 }\r
302                 return scores;\r
303 \r
304         }\r
305 \r
306         /**\r
307          * Calculate conservation for sequences loaded from the file\r
308          * \r
309          * @param wsproxy\r
310          *            a web service proxy\r
311          * @param file\r
312          *            the file to read the results from\r
313          * @param preset\r
314          *            Preset to use optional\r
315          * @param customOptions\r
316          *            the list of options\r
317          * @return Set<Score> the conservation scores\r
318          * @throws IOException\r
319          * @throws UnknownFileFormatException\r
320          */\r
321         static <T> ScoreManager analize(File file, SequenceAnnotation<T> wsproxy,\r
322                         Preset<T> preset, List<Option<T>> customOptions) {\r
323                 List<FastaSequence> fastalist = null;\r
324                 try {\r
325                         fastalist = SequenceUtil.openInputStream(file.getAbsolutePath());\r
326                         assert !fastalist.isEmpty() : "Input is empty!";\r
327                 } catch (IOException e) {\r
328                         System.err\r
329                                         .println("Exception while reading the input file. "\r
330                                                         + "Check that the input file contains a list of fasta formatted sequences! "\r
331                                                         + "Exception details are below:");\r
332                         e.printStackTrace();\r
333                 } catch (UnknownFileFormatException e) {\r
334                         System.err\r
335                                         .println("Exception while attempting to read the input file "\r
336                                                         + "Exception details are below:");\r
337                         System.out.println(e.getMessage());\r
338                         e.printStackTrace();\r
339                 }\r
340                 return analize(fastalist, wsproxy, preset, customOptions);\r
341         }\r
342         /**\r
343          * Connects to a web service by the host and the service name web service\r
344          * type\r
345          * \r
346          * @param host\r
347          *            the fully qualified name of JABAWS server including JABAWS\r
348          *            context name e.g\r
349          *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
350          * @param service\r
351          *            the name of the JABAWS service to connect to\r
352          * @return JABAService<T>\r
353          * @throws WebServiceException\r
354          * @throws ConnectException\r
355          *             if fails to connect to the service on the host\r
356          */\r
357         public static JABAService connect(String host, Services service)\r
358                         throws WebServiceException, ConnectException {\r
359                 URL url = null;\r
360                 log.log(Level.FINE, "Attempting to connect...");\r
361                 try {\r
362                         url = new URL(host + "/" + service.toString() + "?wsdl");\r
363                 } catch (MalformedURLException e) {\r
364                         e.printStackTrace();\r
365                         // ignore as the host name is already verified\r
366                 }\r
367                 Service serv = null;\r
368                 try {\r
369                         serv = service.getService(url, JABAService.SERVICE_NAMESPACE);\r
370                 } catch (WebServiceException wse) {\r
371                         System.out.println("Connecting to JABAWS version 2 service");\r
372                         if (isV2service(wse)) {\r
373                                 serv = service\r
374                                                 .getService(url, JABAService.V2_SERVICE_NAMESPACE);\r
375                         }\r
376                 }\r
377                 if (serv == null) {\r
378                         throw new ConnectException("Could not connect to " + url\r
379                                         + " the server is down?");\r
380                 }\r
381                 JABAService serviceIF = service.getInterface(serv);\r
382                 log.log(Level.INFO, "Connected successfully!");\r
383 \r
384                 return serviceIF;\r
385         }\r
386 \r
387         static boolean isV2service(WebServiceException wse) {\r
388                 String message = wse.getMessage();\r
389                 int idx = message.indexOf("not a valid service");\r
390                 if (idx > 0) {\r
391                         if (message.substring(idx).contains(\r
392                                         JABAService.V2_SERVICE_NAMESPACE)) {\r
393                                 return true;\r
394                         }\r
395                 }\r
396                 return false;\r
397         }\r
398 \r
399         /**\r
400          * Get a connection of JABAWS registry\r
401          * \r
402          * @param host\r
403          *            the fully qualified name of JABAWS server including JABAWS\r
404          *            context name e.g\r
405          *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
406          * @return compbio.data.msa.RegistryWS - instance of a RegistryWS web\r
407          *         service\r
408          * @throws WebServiceException\r
409          * @throws ConnectException\r
410          */\r
411         public static compbio.data.msa.RegistryWS connectToRegistry(String host)\r
412                         throws WebServiceException, ConnectException {\r
413                 URL url = null;\r
414                 String service = "RegistryWS";\r
415                 log.log(Level.FINE, "Attempting to connect...");\r
416 \r
417                 try {\r
418                         url = new URL(host + "/" + service + "?wsdl");\r
419                 } catch (MalformedURLException e) {\r
420                         e.printStackTrace();\r
421                         // ignore as the host name is already verified\r
422                 }\r
423                 QName qname = new QName(JABAService.V2_SERVICE_NAMESPACE, service);\r
424                 Service serv = Service.create(url, qname);\r
425 \r
426                 if (serv == null) {\r
427                         throw new ConnectException("Could not connect to " + url\r
428                                         + " the server is down?");\r
429                 }\r
430 \r
431                 QName portName = new QName(serv.getServiceName().getNamespaceURI(),\r
432                                 service + "Port");\r
433                 compbio.data.msa.RegistryWS serviceIF = serv.getPort(portName,\r
434                                 compbio.data.msa.RegistryWS.class);\r
435 \r
436                 log.log(Level.INFO, "Connected to " + service + " successfully!");\r
437 \r
438                 return serviceIF;\r
439         }\r
440 \r
441         /**\r
442          * Align sequences from the file using MsaWS\r
443          * \r
444          * @param <T>\r
445          *            web service type e.g. Clustal\r
446          * @param file\r
447          *            to write the resulting alignment to\r
448          * @param msaws\r
449          *            MsaWS required\r
450          * @param preset\r
451          *            Preset to use optional\r
452          * @param customOptions\r
453          *            file which contains new line separated list of options\r
454          * @return Alignment\r
455          */\r
456         static <T> Alignment align(File file, MsaWS<T> msaws, Preset<T> preset,\r
457                         List<Option<T>> customOptions) {\r
458                 FileInputStream instream = null;\r
459                 List<FastaSequence> fastalist = null;\r
460                 Alignment alignment = null;\r
461                 try {\r
462                         instream = new FileInputStream(file);\r
463                         fastalist = SequenceUtil.readFasta(instream);\r
464                         instream.close();\r
465                         String jobId = null;\r
466                         if (customOptions != null && preset != null) {\r
467                                 System.out\r
468                                                 .println("WARN: Parameters (-f) are defined together with a preset (-r) ignoring preset!");\r
469                         }\r
470                         if (customOptions != null) {\r
471                                 jobId = msaws.customAlign(fastalist, customOptions);\r
472                         } else if (preset != null) {\r
473                                 jobId = msaws.presetAlign(fastalist, preset);\r
474                         } else {\r
475                                 jobId = msaws.align(fastalist);\r
476                         }\r
477                         System.out.println("\n\ncalling align.........");\r
478                         Thread.sleep(1000);\r
479                         alignment = msaws.getResult(jobId);\r
480 \r
481                 } catch (IOException e) {\r
482                         System.err\r
483                                         .println("Exception while reading the input file. "\r
484                                                         + "Check that the input file contains a list of fasta formatted sequences! "\r
485                                                         + "Exception details are below:");\r
486                         e.printStackTrace();\r
487                 } catch (JobSubmissionException e) {\r
488                         System.err\r
489                                         .println("Exception while submitting job to a web server. "\r
490                                                         + "Exception details are below:");\r
491                         e.printStackTrace();\r
492                 } catch (ResultNotAvailableException e) {\r
493                         System.err.println("Exception while waiting for results. "\r
494                                         + "Exception details are below:");\r
495                         e.printStackTrace();\r
496                 } catch (InterruptedException ignored) {\r
497                         // ignore and propagate an interruption\r
498                         Thread.currentThread().interrupt();\r
499                 } catch (WrongParameterException e) {\r
500                         e.printStackTrace();\r
501                 } finally {\r
502                         if (instream != null) {\r
503                                 try {\r
504                                         instream.close();\r
505                                 } catch (IOException ignored) {\r
506                                         // ignore\r
507                                 }\r
508                         }\r
509                 }\r
510                 return alignment;\r
511         }\r
512         \r
513         /**\r
514          * Prints Jws2Client usage information to standard out\r
515          * \r
516          * @param exitStatus\r
517          */\r
518         static void printUsage(int exitStatus) {\r
519                 System.out.println(Constraints.help_text);\r
520                 System.exit(exitStatus);\r
521         }\r
522 \r
523         /**\r
524          * Starts command line client, if no parameter are supported print help. Two\r
525          * parameters are required for successful call the JWS2 host name and a\r
526          * service name.\r
527          * \r
528          * @param args\r
529          *            Usage: <Class or Jar file name> -h=host_and_context\r
530          *            -s=serviceName ACTION [OPTIONS]\r
531          * \r
532          *            -h=<host_and_context> - a full URL to the JWS2 web server\r
533          *            including context path e.g. http://10.31.1.159:8080/ws\r
534          * \r
535          *            -s=<ServiceName> - one of [MafftWS, MuscleWS, ClustalWS,\r
536          *            TcoffeeWS, ProbconsWS] ACTIONS:\r
537          * \r
538          *            -i=<inputFile> - full path to fasta formatted sequence file,\r
539          *            from which to align sequences\r
540          * \r
541          *            -parameters - lists parameters supported by web service\r
542          * \r
543          *            -presets - lists presets supported by web service\r
544          * \r
545          *            -limits - lists web services limits Please note that if input\r
546          *            file is specified other actions are ignored\r
547          * \r
548          *            OPTIONS: (only for use with -i action):\r
549          * \r
550          *            -r=<presetName> - name of the preset to use\r
551          * \r
552          *            -o=<outputFile> - full path to the file where to write an\r
553          *            alignment -f=<parameterInputFile> - the name of the file with\r
554          *            the list of parameters to use. Please note that -r and -f\r
555          *            options cannot be used together. Alignment is done with either\r
556          *            preset or a parameters from the file, but not both!\r
557          * \r
558          */\r
559         public static void main(String[] args) {\r
560 \r
561                 if (args == null) {\r
562                         printUsage(1);\r
563                 }\r
564                 if (args.length < 2) {\r
565                         System.err.println("Host and service names are required!");\r
566                         printUsage(1);\r
567                 }\r
568 \r
569                 try {\r
570                         new Jws2Client(args);\r
571                 } catch (IOException e) {\r
572                         log.log(Level.SEVERE, "IOException in client! " + e.getMessage(),\r
573                                         e.getCause());\r
574                         System.err.println("Cannot write output file! Stack trace: ");\r
575                         e.printStackTrace();\r
576                 }\r
577         }\r
578 }\r