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