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