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