Merge branch 'JABAWS_Release_2_5' into develop
[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 client package\r
72          */\r
73         private static final Logger log = Logger.getLogger(Jws2Client.class.getCanonicalName());\r
74 \r
75         /**\r
76          * Attempt to construct the URL object from the string\r
77          * \r
78          * @param urlstr\r
79          * @return true if it succeed false otherwise\r
80          */\r
81         public static boolean validURL(String urlstr) {\r
82                 try {\r
83                         if (urlstr == null || urlstr.trim().length() == 0) {\r
84                                 return false;\r
85                         }\r
86                         new URL(urlstr);\r
87                 } catch (MalformedURLException e) {\r
88                         return false;\r
89                 }\r
90                 return true;\r
91         }\r
92 \r
93         /**\r
94          * Connects to the service and do the job as requested, if something goes\r
95          * wrong reports or/and prints usage help.\r
96          * \r
97          * @param <T>\r
98          *            web service type\r
99          * @param cmd\r
100          *            command line options\r
101          * @throws IOException\r
102          */\r
103         <T> Jws2Client(String[] cmd) throws IOException {\r
104                 \r
105 \r
106                 String hostname = CmdHelper.getHost(cmd);\r
107                 if (hostname == null) {\r
108                         System.err.println("Host name is not provided!");\r
109                         System.out.println(Constraints.help_text);\r
110                         System.exit(1);\r
111                 }\r
112 \r
113                 if (!validURL(hostname)) {\r
114                         System.err.println("Host name is not valid!");\r
115                         System.out.println(Constraints.help_text);\r
116                         System.exit(1);\r
117                 }\r
118 \r
119                 boolean listServices = CmdHelper.listServices(cmd);\r
120                 if (listServices) {\r
121                         listAllServices(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                         System.out.println(Constraints.help_text);\r
129                         System.exit(1);\r
130                 }\r
131 \r
132                 Services service = Services.getService(serviceName);\r
133                 if (service == null) {\r
134                         String mess = "Service " + serviceName + " is no available! Valid values are: ";\r
135                         System.err.println(mess + Arrays.toString(Services.values()));\r
136                         System.out.println(Constraints.help_text);\r
137                         System.exit(1);\r
138                 }\r
139 \r
140                 if (CmdHelper.testService(cmd)) {\r
141                         testService(hostname, service, new PrintWriter(System.out, true));\r
142                         System.exit(0);\r
143                 }\r
144 \r
145                 Metadata<T> thews = (Metadata<T>) connect(hostname, service);\r
146                 Preset<T> preset = null;\r
147                 if (null != CmdHelper.getPresetName(cmd)) {\r
148                         preset = MetadataHelper.getPreset(thews, CmdHelper.getPresetName(cmd));\r
149                 }\r
150 \r
151                 List<Option<T>> customOptions = null;\r
152                 if (null != IOHelper.getFile(cmd, paramFile, true)) {\r
153                         List<String> prms = IOHelper.loadParameters(IOHelper.getFile(cmd, paramFile, true));\r
154                         customOptions = MetadataHelper.processParameters(prms, thews.getRunnerOptions());\r
155                 }\r
156 \r
157                 if (null != IOHelper.getFile(cmd, inputkey, true)) {\r
158                         File infile = IOHelper.getFile(cmd, inputkey, true);\r
159                         File outfile = IOHelper.getFile(cmd, outputkey, false);\r
160                         Writer writer = null;\r
161                         if (outfile != null) {\r
162                                 writer = IOHelper.getWriter(outfile);\r
163                         } else {\r
164                                 // this stream is going to be closed later which is fine as std.out will not be\r
165                                 writer = new PrintWriter(System.out, true);\r
166                         }\r
167                         if (service.getServiceType() == SequenceAnnotation.class) {\r
168                                 ScoreManager result = analize(infile, ((SequenceAnnotation<T>) thews), preset, customOptions);\r
169                                 IOHelper.writeOut(writer, result);\r
170                         } else if (service.getServiceType() == MsaWS.class) {\r
171                                 Alignment alignment = align(infile, (MsaWS<T>) thews, preset, customOptions);\r
172                                 IOHelper.writeOut(writer, alignment);\r
173                         }\r
174                         writer.close();\r
175                 }\r
176 \r
177                 if (CmdHelper.listParameters(cmd)) {\r
178                         System.out.println(MetadataHelper.getParametersList(thews));\r
179                 }\r
180                 if (CmdHelper.listPresets(cmd)) {\r
181                         System.out.println(MetadataHelper.getPresetList(thews));\r
182                 }\r
183                 if (CmdHelper.listLimits(cmd)) {\r
184                         System.out.println(MetadataHelper.getLimits(thews));\r
185                 }\r
186                 log.fine("Disconnecting...");\r
187                 ((Closeable) thews).close();\r
188                 log.fine("Disconnected successfully!");\r
189         }\r
190 \r
191         /**\r
192          * Connects to a web service by the host and the service name web service type\r
193          * \r
194          * @param host\r
195          *            the fully qualified name of JABAWS server including JABAWS\r
196          *            context name e.g\r
197          *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
198          * @param service\r
199          *            the name of the JABAWS service to connect to\r
200          * @return JABAService<T>\r
201          * @throws WebServiceException\r
202          * @throws ConnectException\r
203          *             if fails to connect to the service on the host\r
204          */\r
205         public static JABAService connect(String host, Services service)\r
206                         throws WebServiceException, ConnectException {\r
207                 URL url = null;\r
208                 log.log(Level.FINE, "Attempting to connect with " + service.toString() + "...");\r
209                 System.out.println ("Attempting to connect with " + service.toString() + "...");\r
210                 try {\r
211                         url = new URL(host + "/" + service.toString() + "?wsdl");\r
212                 } catch (MalformedURLException e) {\r
213                         e.printStackTrace();\r
214                         // ignore as the host name is already verified\r
215                 }\r
216                 Service serv = null;\r
217                 try {\r
218                         serv = service.getService(url, service.getServiceNamespace());\r
219                 } catch (WebServiceException wse) {\r
220                         wse.printStackTrace();\r
221                 }\r
222                 if (serv == null) {\r
223                         throw new ConnectException("Could not connect to " + url + ". Is the server down?");\r
224                 }\r
225                 JABAService serviceIF = service.getInterface(serv);\r
226                 log.log(Level.INFO, "Connected successfully!");\r
227 \r
228                 return serviceIF;\r
229         }\r
230 \r
231         /**\r
232          * Get a connection of JABAWS registry\r
233          * \r
234          * @param host\r
235          *            the fully qualified name of JABAWS server including JABAWS\r
236          *            context name e.g\r
237          *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
238          * @return compbio.data.msa.RegistryWS - instance of a RegistryWS web\r
239          *         service\r
240          * @throws WebServiceException\r
241          * @throws ConnectException\r
242          */\r
243         public static compbio.data.msa.RegistryWS connectToRegistry(String host)\r
244                         throws WebServiceException, ConnectException {\r
245                 URL url = null;\r
246                 String service = "RegistryWS";\r
247                 log.log(Level.FINE, "Attempting to connect...");\r
248 \r
249                 try {\r
250                         url = new URL(host + "/" + service + "?wsdl");\r
251                 } catch (MalformedURLException e) {\r
252                         e.printStackTrace();\r
253                         // ignore as the host name is already verified\r
254                 }\r
255                 QName qname = new QName(JABAService.V2_SERVICE_NAMESPACE, service);\r
256                 Service serv = Service.create(url, qname);\r
257 \r
258                 if (serv == null) {\r
259                         throw new ConnectException("Could not connect to " + url + ". Is the server down?");\r
260                 }\r
261 \r
262                 QName portName = new QName(serv.getServiceName().getNamespaceURI(), service + "Port");\r
263                 compbio.data.msa.RegistryWS serviceIF = serv.getPort(portName, compbio.data.msa.RegistryWS.class);\r
264                 log.log(Level.INFO, "Connected to " + service + " successfully!");\r
265 \r
266                 return serviceIF;\r
267         }\r
268 \r
269         /**\r
270          * Asks registry to test the service on the host hostname\r
271          * \r
272          * @param hostname\r
273          * @param service\r
274          * @param writer\r
275          * @throws ConnectException\r
276          * @throws WebServiceException\r
277          */\r
278         public static void testService(String hostname, Services service, PrintWriter writer)\r
279                         throws ConnectException, WebServiceException {\r
280                 RegistryWS registry = connectToRegistry(hostname);\r
281                 if (registry != null) {\r
282                         String message = registry.testService(service);\r
283                         writer.println("Service " + service + " testing results: ");\r
284                         writer.println(message);\r
285                         FileUtil.closeSilently(((Closeable) registry));\r
286                 }\r
287                 writer.flush();\r
288         }\r
289 \r
290         private static void listAllServices(String hostname) throws WebServiceException, IOException {\r
291                 RegistryWS registry = connectToRegistry(hostname);\r
292                 Set<Services> func_services = Collections.EMPTY_SET;\r
293                 Set<Services> nonfunc_services = Collections.EMPTY_SET;\r
294                 if (registry != null) {\r
295                         func_services = registry.getSupportedServices();\r
296                         nonfunc_services = registry.getNonoperatedServices();\r
297                         FileUtil.closeSilently(((Closeable) registry));\r
298                 } else {\r
299                         System.out.println("Failed to connect to the registry! ");\r
300                         return;\r
301                 }\r
302                 if (!func_services.isEmpty()) {\r
303                         String mess = "\n\rAvailable services: ";\r
304                         System.out.println(mess + Services.toString(func_services));\r
305                 }\r
306                 if (!nonfunc_services.isEmpty()) {\r
307                         String mess = "Non-available services (internal tests failed): ";\r
308                         System.out.println(mess + Services.toString(nonfunc_services));\r
309                 }\r
310         }\r
311 \r
312         /**\r
313          * Calculate conservation for sequences loaded from a FASTA record list structure \r
314          * \r
315          * @param fastalist\r
316          *            the list of FASTA records\r
317          * @param wsproxy\r
318          *            a web service proxy\r
319          * @param preset\r
320          *            Preset to use optional\r
321          * @param customOptions\r
322          *            the list of options\r
323          * @return Set<Score> the conservation scores\r
324          * @throws UnknownFileFormatException\r
325          */\r
326         static <T> ScoreManager analize(List<FastaSequence> fastalist, SequenceAnnotation<T> wsproxy, Preset<T> preset, List<Option<T>> customOptions) {\r
327                 ScoreManager scores = null;\r
328                 try {\r
329                         String jobId = null;\r
330                         if (customOptions != null && preset != null) {\r
331                                 System.out.println("WARN: Parameters (-f) are defined together with a preset (-r) ignoring preset!");\r
332                         }\r
333                         if (customOptions != null) {\r
334                                 jobId = wsproxy.customAnalize(fastalist, customOptions);\r
335                         } else if (preset != null) {\r
336                                 jobId = wsproxy.presetAnalize(fastalist, preset);\r
337                         } else {\r
338                                 jobId = wsproxy.analize(fastalist);\r
339                         }\r
340                         System.out.println("\n\rcalling predictor.........");\r
341                         Thread.sleep(100);\r
342                         scores = wsproxy.getAnnotation(jobId);\r
343                 } catch (JobSubmissionException e) {\r
344                         System.err.println("Exception while submitting job to a web server. Exception details are below:");\r
345                         e.printStackTrace();\r
346                 } catch (ResultNotAvailableException e) {\r
347                         System.err.println("Exception while waiting for results. Exception details are below:");\r
348                         e.printStackTrace();\r
349                 } catch (InterruptedException e) {\r
350                         Thread.currentThread().interrupt();\r
351                         System.err.println("Exception while waiting for results. Exception details are below:");\r
352                         e.printStackTrace();\r
353                 } catch (WrongParameterException e) {\r
354                         String mess = "Parsing the web method input parameters failed Exception details are below:";\r
355                         System.err.println(mess);\r
356                         e.printStackTrace();\r
357                 }\r
358                 return scores;\r
359 \r
360         }\r
361 \r
362         /**\r
363          * Calculate conservation for sequences loaded from the file\r
364          * \r
365          * @param wsproxy\r
366          *            a web service proxy\r
367          * @param file\r
368          *            the file to read the results from\r
369          * @param preset\r
370          *            Preset to use optional\r
371          * @param customOptions\r
372          *            the list of options\r
373          * @return Set<Score> the conservation scores\r
374          * @throws IOException\r
375          * @throws UnknownFileFormatException\r
376          */\r
377         static <T> ScoreManager analize(File file, SequenceAnnotation<T> wsproxy, Preset<T> preset, List<Option<T>> customOptions) {\r
378                 List<FastaSequence> fastalist = null;\r
379                 try {\r
380                         fastalist = SequenceUtil.openInputStream(file.getAbsolutePath());\r
381                         assert !fastalist.isEmpty() : "Input is empty!";\r
382                 } catch (IOException e) {\r
383                         String mess = "Reading the input file failed. Check that the file contains a list of FASTA records!\n";\r
384                         System.err.println(mess + "Exception details are below:");\r
385                         e.printStackTrace();\r
386                 } catch (UnknownFileFormatException e) {\r
387                         String mess = "Reading the input file failed. Exception details are below:";\r
388                         System.err.println(mess);\r
389                         System.out.println(e.getMessage());\r
390                         e.printStackTrace();\r
391                 }\r
392                 return analize(fastalist, wsproxy, preset, customOptions);\r
393         }\r
394 \r
395         /**\r
396          * Align sequences from the file using MsaWS\r
397          * \r
398          * @param <T>\r
399          *            web service type e.g. Clustal\r
400          * @param file\r
401          *            to write the resulting alignment to\r
402          * @param msaws\r
403          *            MsaWS required\r
404          * @param preset\r
405          *            Preset to use optional\r
406          * @param customOptions\r
407          *            file which contains new line separated list of options\r
408          * @return Alignment\r
409          */\r
410         static <T> Alignment align(File file, MsaWS<T> msaws, Preset<T> preset,\r
411                         List<Option<T>> customOptions) {\r
412                 FileInputStream instream = null;\r
413                 List<FastaSequence> fastalist = null;\r
414                 Alignment alignment = null;\r
415                 try {\r
416                         instream = new FileInputStream(file);\r
417                         fastalist = SequenceUtil.readFasta(instream);\r
418                         instream.close();\r
419                         String jobId = null;\r
420                         if (customOptions != null && preset != null) {\r
421                                 System.out.println("WARN: Parameters (-f) are defined together with a preset (-r) ignoring preset!");\r
422                         }\r
423                         if (customOptions != null) {\r
424                                 jobId = msaws.customAlign(fastalist, customOptions);\r
425                         } else if (preset != null) {\r
426                                 jobId = msaws.presetAlign(fastalist, preset);\r
427                         } else {\r
428                                 jobId = msaws.align(fastalist);\r
429                         }\r
430                         System.out.println("\ncalling aligner.........");\r
431                         Thread.sleep(1000);\r
432                         alignment = msaws.getResult(jobId);\r
433 \r
434                 } catch (IOException e) {\r
435                         System.err.println("Exception while reading the input file. "\r
436                                                 + "Check that the input file contains a list of fasta formatted sequences! "\r
437                                                 + "Exception details are below:");\r
438                         e.printStackTrace();\r
439                 } catch (JobSubmissionException e) {\r
440                         System.err.println("Exception while submitting job to a web server. "\r
441                                                 + "Exception details are below:");\r
442                         e.printStackTrace();\r
443                 } catch (ResultNotAvailableException e) {\r
444                         System.err.println("Exception while waiting for results. "\r
445                                         + "Exception details are below:");\r
446                         e.printStackTrace();\r
447                 } catch (InterruptedException ignored) {\r
448                         // ignore and propagate an interruption\r
449                         Thread.currentThread().interrupt();\r
450                 } catch (WrongParameterException e) {\r
451                         e.printStackTrace();\r
452                 } finally {\r
453                         if (instream != null) {\r
454                                 try {\r
455                                         instream.close();\r
456                                 } catch (IOException ignored) {\r
457                                         // ignore\r
458                                 }\r
459                         }\r
460                 }\r
461                 return alignment;\r
462         }\r
463         \r
464         /**\r
465          * Starts command line client, if no parameter are supported print help. Two\r
466          * parameters are required for successful call the JWS2 host name and a\r
467          * service name.\r
468          * \r
469          * @param args\r
470          *            Usage: <Class or Jar file name> -h=host_and_context\r
471          *            -s=serviceName ACTION [OPTIONS]\r
472          * \r
473          *            -h=<host_and_context> - a full URL to the JWS2 web server\r
474          *            including context path e.g. http://10.31.1.159:8080/ws\r
475          * \r
476          *            -s=<ServiceName> - one of [MafftWS, MuscleWS, ClustalWS,\r
477          *            TcoffeeWS, ProbconsWS] ACTIONS:\r
478          * \r
479          *            -i=<inputFile> - full path to fasta formatted sequence file,\r
480          *            from which to align sequences\r
481          * \r
482          *            -parameters - lists parameters supported by web service\r
483          * \r
484          *            -presets - lists presets supported by web service\r
485          * \r
486          *            -limits - lists web services limits Please note that if input\r
487          *            file is specified other actions are ignored\r
488          * \r
489          *            OPTIONS: (only for use with -i action):\r
490          * \r
491          *            -r=<presetName> - name of the preset to use\r
492          * \r
493          *            -o=<outputFile> - full path to the file where to write an\r
494          *            alignment -f=<parameterInputFile> - the name of the file with\r
495          *            the list of parameters to use. Please note that -r and -f\r
496          *            options cannot be used together. Alignment is done with either\r
497          *            preset or a parameters from the file, but not both!\r
498          * \r
499          */\r
500         public static void main(String[] args) {\r
501 \r
502                 if (args == null) {\r
503                         System.out.println(Constraints.help_text);\r
504                         System.exit(1);\r
505                 }\r
506                 if (args.length < 2) {\r
507                         System.err.println("Host (-h=<host>, e.g. -h=http://www.compbio.dundee.ac.uk/jabaws) and service (-s=<ServiceName>, e.g. -s=Jpred) are required!");\r
508                         System.out.println(Constraints.help_text);\r
509                         System.exit(1);\r
510                 }\r
511 \r
512                 try {\r
513                         new Jws2Client(args);\r
514                 } catch (IOException e) {\r
515                         log.log(Level.SEVERE, "IOException in client! " + e.getMessage(), e.getCause());\r
516                         System.err.println("Cannot write output file! Stack trace: ");\r
517                         e.printStackTrace();\r
518                 }\r
519         }\r
520 }\r