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