Refactored client class to accomodate new WS interface and reduce the complexity
[jabaws.git] / webservices / compbio / ws / client / Jws2Client.java
1 /* Copyright (c) 2009 Peter Troshin\r
2  *  \r
3  *  JAva Bioinformatics Analysis Web Services (JABAWS) @version: 1.0     \r
4  * \r
5  *  This library is free software; you can redistribute it and/or modify it under the terms of the\r
6  *  Apache License version 2 as published by the Apache Software Foundation\r
7  * \r
8  *  This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without\r
9  *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Apache \r
10  *  License for more details.\r
11  * \r
12  *  A copy of the license is in apache_license.txt. It is also available here:\r
13  * @see: http://www.apache.org/licenses/LICENSE-2.0.txt\r
14  * \r
15  * Any republication or derived work distributed in source code form\r
16  * must include this copyright and license notice.\r
17  */\r
18 \r
19 package compbio.ws.client;\r
20 \r
21 import static compbio.ws.client.Constraints.hostkey;\r
22 import static compbio.ws.client.Constraints.inputkey;\r
23 import static compbio.ws.client.Constraints.limitList;\r
24 import static compbio.ws.client.Constraints.outputkey;\r
25 import static compbio.ws.client.Constraints.paramFile;\r
26 import static compbio.ws.client.Constraints.paramList;\r
27 import static compbio.ws.client.Constraints.presetList;\r
28 import static compbio.ws.client.Constraints.presetkey;\r
29 import static compbio.ws.client.Constraints.pseparator;\r
30 import static compbio.ws.client.Constraints.servicekey;\r
31 \r
32 import java.io.Closeable;\r
33 import java.io.File;\r
34 import java.io.FileInputStream;\r
35 import java.io.IOException;\r
36 import java.io.OutputStream;\r
37 import java.net.MalformedURLException;\r
38 import java.net.URL;\r
39 import java.util.Arrays;\r
40 import java.util.List;\r
41 import java.util.logging.Level;\r
42 import java.util.logging.Logger;\r
43 \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.sequence.Alignment;\r
51 import compbio.data.sequence.FastaSequence;\r
52 import compbio.data.sequence.SequenceUtil;\r
53 import compbio.metadata.JobSubmissionException;\r
54 import compbio.metadata.Option;\r
55 import compbio.metadata.Preset;\r
56 import compbio.metadata.ResultNotAvailableException;\r
57 import compbio.metadata.WrongParameterException;\r
58 \r
59 /**\r
60  * A command line client for JAva Bioinformatics Analysis Web Services\r
61  * \r
62  * @author pvtroshin\r
63  * @version 1.0\r
64  */\r
65 public class Jws2Client {\r
66 \r
67         /*\r
68          * Use java.util.Logger instead of log4j logger to reduce the size of the\r
69          * client package\r
70          */\r
71         private static final Logger log = Logger.getLogger(Jws2Client.class\r
72                         .getCanonicalName());\r
73 \r
74         // JABAWS version 1.0 service name\r
75         static final String QUALIFIED_SERVICE_NAME = "http://msa.data.compbio/01/01/2010/";\r
76 \r
77         // JABAWS version 2.0 service name\r
78         static final String V2_QUALIFIED_SERVICE_NAME = "http://msa.data.compbio/01/12/2010/";\r
79 \r
80         /**\r
81          * Attempt to construct the URL object from the string\r
82          * \r
83          * @param urlstr\r
84          * @return true if it succeed false otherwise\r
85          */\r
86         public static boolean validURL(String urlstr) {\r
87                 try {\r
88                         if (urlstr == null || urlstr.trim().length() == 0) {\r
89                                 return false;\r
90                         }\r
91                         new URL(urlstr);\r
92                 } catch (MalformedURLException e) {\r
93                         return false;\r
94                 }\r
95                 return true;\r
96         }\r
97 \r
98         /**\r
99          * Connects to the service and do the job as requested, if something goes\r
100          * wrong reports or/and prints usage help.\r
101          * \r
102          * @param <T>\r
103          *            web service type\r
104          * @param cmd\r
105          *            command line options\r
106          * @throws IOException\r
107          */\r
108         <T> Jws2Client(String[] cmd) throws IOException {\r
109 \r
110                 String hostname = CmdHelper.getHost(cmd);\r
111                 if (hostname == null) {\r
112                         System.out.println("Host name is not provided!");\r
113                         printUsage(1);\r
114                 }\r
115 \r
116                 if (!validURL(hostname)) {\r
117                         System.out.println("Host name is not valid!");\r
118                         printUsage(1);\r
119                 }\r
120                 String serviceName = CmdHelper.getServiceName(cmd);\r
121                 if (serviceName == null) {\r
122                         System.out.println("Service name is no provided!");\r
123                         printUsage(1);\r
124                 }\r
125                 Services service = Services.getService(serviceName);\r
126                 if (service == null) {\r
127                         System.out.println("Service " + serviceName\r
128                                         + " is no supported! Valid values are: "\r
129                                         + Arrays.toString(Services.values()));\r
130                         printUsage(1);\r
131                 }\r
132                 File inputFile = IOHelper.getFile(cmd, inputkey, true);\r
133                 File outFile = IOHelper.getFile(cmd, outputkey, false);\r
134                 File parametersFile = IOHelper.getFile(cmd, paramFile, true);\r
135                 String presetName = CmdHelper.getPresetName(cmd);\r
136 \r
137                 Metadata<T> msaws = (Metadata<T>) connect(hostname, service);\r
138                 Preset<T> preset = null;\r
139                 if (presetName != null) {\r
140                         preset = MetadataHelper.getPreset(msaws, presetName);\r
141                 }\r
142                 List<Option<T>> customOptions = null;\r
143                 if (parametersFile != null) {\r
144                         List<String> prms = IOHelper.loadParameters(parametersFile);\r
145                         customOptions = MetadataHelper.processParameters(prms,\r
146                                         msaws.getRunnerOptions());\r
147                 }\r
148                 Alignment alignment = null;\r
149                 if (inputFile != null) {\r
150                         if (service == Services.AAConWS) {\r
151                                 System.out.println("calc conserv!");\r
152                         } else {\r
153 \r
154                                 alignment = align(inputFile, (MsaWS<T>) msaws, preset,\r
155                                                 customOptions);\r
156                                 OutputStream outStream = null;\r
157                                 if (outFile != null) {\r
158                                         outStream = IOHelper.getOutStream(outFile);\r
159                                 } else {\r
160                                         // this stream is going to be closed later which is fine as\r
161                                         // std.out will not be\r
162                                         outStream = System.out;\r
163                                 }\r
164                                 IOHelper.writeOut(outStream, alignment);\r
165                                 // stream is closed in the method no need to close it here\r
166                         }\r
167                 }\r
168 \r
169                 boolean listParameters = CmdHelper.listParameters(cmd);\r
170                 if (listParameters) {\r
171                         System.out.println(MetadataHelper.getParametersList(msaws));\r
172                 }\r
173                 boolean listPreset = CmdHelper.listPresets(cmd);\r
174                 if (listPreset) {\r
175                         System.out.println(MetadataHelper.getPresetList(msaws));\r
176                 }\r
177                 boolean listLimits = CmdHelper.listLimits(cmd);\r
178                 if (listLimits) {\r
179                         System.out.println(MetadataHelper.getLimits(msaws));\r
180                 }\r
181                 log.fine("Disconnecting...");\r
182                 ((Closeable) msaws).close();\r
183                 log.fine("Disconnected successfully!");\r
184         }\r
185 \r
186         /**\r
187          * Connects to a web service by the host and the service name\r
188          * \r
189          * @param <T>\r
190          *            web service type\r
191          * @param host\r
192          * @param service\r
193          * @return MsaWS<T>\r
194          * @throws WebServiceException\r
195          */\r
196         public static JABAService connect(String host, Services service)\r
197                         throws WebServiceException {\r
198                 URL url = null;\r
199                 log.log(Level.FINE, "Attempting to connect...");\r
200                 try {\r
201                         url = new URL(host + "/" + service.toString() + "?wsdl");\r
202                 } catch (MalformedURLException e) {\r
203                         e.printStackTrace();\r
204                         // ignore as the host name is already verified\r
205                 }\r
206                 Service serv = null;\r
207                 try {\r
208                         serv = service.getService(url, QUALIFIED_SERVICE_NAME);\r
209                 } catch (WebServiceException wse) {\r
210                         System.out.println("Conecting to JABAWS version 2 service");\r
211                         if (isV2service(wse)) {\r
212                                 serv = service.getService(url, V2_QUALIFIED_SERVICE_NAME);\r
213                         }\r
214                 }\r
215                 JABAService serviceIF = service.getInterface(serv);\r
216                 log.log(Level.FINE, "Connected successfully!");\r
217 \r
218                 return serviceIF;\r
219         }\r
220 \r
221         static boolean isV2service(WebServiceException wse) {\r
222                 String message = wse.getMessage();\r
223                 int idx = message.indexOf("not a valid service");\r
224                 if (idx > 0) {\r
225                         if (message.substring(idx).contains(V2_QUALIFIED_SERVICE_NAME)) {\r
226                                 return true;\r
227                         }\r
228                 }\r
229                 return false;\r
230         }\r
231 \r
232         /**\r
233          * Align sequences from the file using MsaWS\r
234          * \r
235          * @param <T>\r
236          *            web service type e.g. Clustal\r
237          * @param file\r
238          *            to write the resulting alignment to\r
239          * @param msaws\r
240          *            MsaWS required\r
241          * @param preset\r
242          *            Preset to use optional\r
243          * @param customOptions\r
244          *            file which contains new line separated list of options\r
245          * @return Alignment\r
246          */\r
247         static <T> Alignment align(File file, MsaWS<T> msaws, Preset<T> preset,\r
248                         List<Option<T>> customOptions) {\r
249                 FileInputStream instream = null;\r
250                 List<FastaSequence> fastalist = null;\r
251                 Alignment alignment = null;\r
252                 try {\r
253                         instream = new FileInputStream(file);\r
254                         fastalist = SequenceUtil.readFasta(instream);\r
255                         instream.close();\r
256                         String jobId = null;\r
257                         if (customOptions != null && preset != null) {\r
258                                 System.out\r
259                                                 .println("WARN: Parameters (-f) are defined together with a preset (-r) ignoring preset!");\r
260                         }\r
261                         if (customOptions != null) {\r
262                                 jobId = msaws.customAlign(fastalist, customOptions);\r
263                         } else if (preset != null) {\r
264                                 jobId = msaws.presetAlign(fastalist, preset);\r
265                         } else {\r
266                                 jobId = msaws.align(fastalist);\r
267                         }\r
268                         Thread.sleep(1000);\r
269                         alignment = msaws.getResult(jobId);\r
270 \r
271                 } catch (IOException e) {\r
272                         System.err\r
273                                         .println("Exception while reading the input file. "\r
274                                                         + "Check that the input file contains a list of fasta formatted sequences! "\r
275                                                         + "Exception details are below:");\r
276                         e.printStackTrace();\r
277                 } catch (JobSubmissionException e) {\r
278                         System.err\r
279                                         .println("Exception while submitting job to a web server. "\r
280                                                         + "Exception details are below:");\r
281                         e.printStackTrace();\r
282                 } catch (ResultNotAvailableException e) {\r
283                         System.err.println("Exception while waiting for results. "\r
284                                         + "Exception details are below:");\r
285                         e.printStackTrace();\r
286                 } catch (InterruptedException ignored) {\r
287                         // ignore and propagate an interruption\r
288                         Thread.currentThread().interrupt();\r
289                 } catch (WrongParameterException e) {\r
290                         e.printStackTrace();\r
291                 } finally {\r
292                         if (instream != null) {\r
293                                 try {\r
294                                         instream.close();\r
295                                 } catch (IOException ignored) {\r
296                                         // ignore\r
297                                 }\r
298                         }\r
299                 }\r
300                 return alignment;\r
301         }\r
302 \r
303         /**\r
304          * Prints Jws2Client usage information to standard out\r
305          * \r
306          * @param exitStatus\r
307          */\r
308         static void printUsage(int exitStatus) {\r
309                 System.out.println();\r
310                 System.out.println("Usage: <Class or Jar file name> " + hostkey\r
311                                 + pseparator + "host_and_context " + servicekey + pseparator\r
312                                 + "serviceName ACTION [OPTIONS] ");\r
313                 System.out.println();\r
314                 System.out\r
315                                 .println(hostkey\r
316                                                 + pseparator\r
317                                                 + "<host_and_context> - a full URL to the JWS2 web server including context path e.g. http://10.31.1.159:8080/ws");\r
318                 System.out.println(servicekey + pseparator + "<ServiceName> - one of "\r
319                                 + Arrays.toString(Services.values()));\r
320                 System.out.println();\r
321                 System.out.println("ACTIONS: ");\r
322                 System.out\r
323                                 .println(inputkey\r
324                                                 + pseparator\r
325                                                 + "<inputFile> - full path to fasta formatted sequence file, from which to align sequences");\r
326                 System.out.println(paramList\r
327                                 + " - lists parameters supported by web service");\r
328                 System.out.println(presetList\r
329                                 + " - lists presets supported by web service");\r
330                 System.out.println(limitList + " - lists web services limits");\r
331                 System.out\r
332                                 .println("Please note that if input file is specified other actions are ignored");\r
333 \r
334                 System.out.println();\r
335                 System.out.println("OPTIONS (only for use with -i action):");\r
336 \r
337                 System.out.println(presetkey + pseparator\r
338                                 + "<presetName> - name of the preset to use");\r
339                 System.out\r
340                                 .println(outputkey\r
341                                                 + pseparator\r
342                                                 + "<outputFile> - full path to the file where to write an alignment");\r
343                 System.out\r
344                                 .println("-f=<parameterInputFile> - the name of the file with the list of parameters to use.");\r
345                 System.out\r
346                                 .println("Please note that -r and -f options cannot be used together. "\r
347                                                 + "Alignment is done with either preset or a parameters from the file, but not both!");\r
348 \r
349                 System.exit(exitStatus);\r
350         }\r
351 \r
352         /**\r
353          * Starts command line client, if no parameter are supported print help. Two\r
354          * parameters are required for successfull call the JWS2 host name and a\r
355          * service name.\r
356          * \r
357          * @param args\r
358          *            Usage: <Class or Jar file name> -h=host_and_context\r
359          *            -s=serviceName ACTION [OPTIONS]\r
360          * \r
361          *            -h=<host_and_context> - a full URL to the JWS2 web server\r
362          *            including context path e.g. http://10.31.1.159:8080/ws\r
363          * \r
364          *            -s=<ServiceName> - one of [MafftWS, MuscleWS, ClustalWS,\r
365          *            TcoffeeWS, ProbconsWS] ACTIONS:\r
366          * \r
367          *            -i=<inputFile> - full path to fasta formatted sequence file,\r
368          *            from which to align sequences\r
369          * \r
370          *            -parameters - lists parameters supported by web service\r
371          * \r
372          *            -presets - lists presets supported by web service\r
373          * \r
374          *            -limits - lists web services limits Please note that if input\r
375          *            file is specified other actions are ignored\r
376          * \r
377          *            OPTIONS: (only for use with -i action):\r
378          * \r
379          *            -r=<presetName> - name of the preset to use\r
380          * \r
381          *            -o=<outputFile> - full path to the file where to write an\r
382          *            alignment -f=<parameterInputFile> - the name of the file with\r
383          *            the list of parameters to use. Please note that -r and -f\r
384          *            options cannot be used together. Alignment is done with either\r
385          *            preset or a parameters from the file, but not both!\r
386          * \r
387          */\r
388         public static void main(String[] args) {\r
389 \r
390                 if (args == null) {\r
391                         printUsage(1);\r
392                 }\r
393                 if (args.length < 2) {\r
394                         System.out.println("Host and service names are required!");\r
395                         printUsage(1);\r
396                 }\r
397 \r
398                 try {\r
399                         new Jws2Client(args);\r
400                 } catch (IOException e) {\r
401                         log.log(Level.SEVERE, "IOException in client! " + e.getMessage(),\r
402                                         e.getCause());\r
403                         System.err.println("Cannot write output file! Stack trace: ");\r
404                         e.printStackTrace();\r
405                 }\r
406         }\r
407 }\r