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