Clean-up, refactoring, commenting. Parameters file containts only options since Jalvi...
[jabaws.git] / webservices / compbio / ws / client / WSTester.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.hostkey;\r
22 import static compbio.ws.client.Constraints.pseparator;\r
23 import static compbio.ws.client.Constraints.servicekey;\r
24 \r
25 import java.io.ByteArrayInputStream;\r
26 import java.io.Closeable;\r
27 import java.io.IOException;\r
28 import java.io.PrintWriter;\r
29 import java.net.ConnectException;\r
30 import java.util.Arrays;\r
31 import java.util.List;\r
32 \r
33 import javax.xml.ws.WebServiceException;\r
34 \r
35 import compbio.data.msa.JABAService;\r
36 import compbio.data.msa.Metadata;\r
37 import compbio.data.msa.MsaWS;\r
38 import compbio.data.msa.SequenceAnnotation;\r
39 import compbio.data.sequence.Alignment;\r
40 import compbio.data.sequence.FastaSequence;\r
41 import compbio.data.sequence.ScoreManager;\r
42 import compbio.data.sequence.SequenceUtil;\r
43 import compbio.metadata.JobStatus;\r
44 import compbio.metadata.Limit;\r
45 import compbio.metadata.LimitsManager;\r
46 import compbio.metadata.Option;\r
47 import compbio.metadata.Preset;\r
48 import compbio.metadata.PresetManager;\r
49 import compbio.metadata.RunnerConfig;\r
50 import compbio.metadata.UnsupportedRuntimeException;\r
51 import compbio.util.FileUtil;\r
52 import compbio.util.Util;\r
53 \r
54 /**\r
55  * Class for testing web services\r
56  * \r
57  * @author pvtroshin\r
58  * \r
59  * @version 1.0 February 2010\r
60  */\r
61 public class WSTester {\r
62 \r
63         /**\r
64          * Sequences to be used as input for all WS\r
65          */\r
66         public static final String fastaInput = ">Foo\n"\r
67                         + "MTADGPRELLQLRAAVRHRPQDFVAWLMLADAELGMGDTTAGEMAVQRGLALHPGHPEAV"\r
68                         + "\n>Bar\n"\r
69                         + "ASDAAPEHPGIALWLHALEDAGQAEAAAAYTRAHQLLPEEPYITAQLLNAVA\n";\r
70 \r
71         public static final String fastaAlignment = ">Foo\n"\r
72                         + "MTADGPRELLQLRAAVRHRPQDFVAWLMLADAELGMGDTTAGEMAVQRGLALHPGHPEAV--------\n"\r
73                         + ">Bar\n"\r
74                         + "ASDAAPEH------------PGIALWLHALE-DAGQAEAAA---AYTRAHQLLPEEPYITAQLLNAVA\n"\r
75                         + "";\r
76 \r
77         \r
78         \r
79         static final List<FastaSequence> seqs = loadSeqs();\r
80 \r
81         private static final String FAILED = "FAILED";\r
82         private static final String OK = "OK";\r
83 \r
84         private static final String UNSUPPORTED = "UNSUPPORTED";\r
85 \r
86         /**\r
87          * Converting input to a form accepted by WS\r
88          * \r
89          * @return List of FastaSequence records\r
90          */\r
91         private static List<FastaSequence> loadSeqs() {\r
92                 try {\r
93                         return SequenceUtil.readFasta(new ByteArrayInputStream(fastaInput\r
94                                         .getBytes()));\r
95                 } catch (IOException ignored) {\r
96                         // Should not happen as a source is not a external stream\r
97                         ignored.printStackTrace();\r
98                 }\r
99                 return null;\r
100         }\r
101 \r
102         /**\r
103          * Converting input to a form accepted by WS\r
104          * \r
105          * @return List of FastaSequence records\r
106          */\r
107         private static List<FastaSequence> loadAlignment() {\r
108                 try {\r
109                         return SequenceUtil.readFasta(new ByteArrayInputStream(\r
110                                         fastaAlignment.getBytes()));\r
111                 } catch (IOException ignored) {\r
112                         // Should not happen as a source is not a external stream\r
113                         ignored.printStackTrace();\r
114                 }\r
115                 return null;\r
116         }\r
117 \r
118         private final PrintWriter writer;\r
119         private final String hostname;\r
120 \r
121         /**\r
122          * Construct an instance of JABAWS tester\r
123          * \r
124          * @param hostname\r
125          *            - fully qualified host and context name of JABAWS e.g.\r
126          *            http://nanna.cluster.lifesci.dundee.ac.uk:8080/jaba\r
127          * @param writer\r
128          *            a PrintWriter instance to writer test log to.\r
129          */\r
130         public WSTester(String hostname, PrintWriter writer) {\r
131                 if (Util.isEmpty(hostname)) {\r
132                         throw new NullPointerException("Hostname must be provided!");\r
133                 }\r
134                 this.hostname = hostname;\r
135                 this.writer = writer;\r
136         }\r
137 \r
138         /**\r
139          * Prints usage\r
140          */\r
141         static void printUsage() {\r
142                 System.out.println("Usage: <Class or Jar file name> " + hostkey\r
143                                 + pseparator + "host_and_context " + "<" + servicekey\r
144                                 + pseparator + "serviceName>");\r
145                 System.out.println();\r
146                 System.out\r
147                                 .println(hostkey\r
148                                                 + pseparator\r
149                                                 + "<host_and_context> - a full URL to the JABAWS web server including context path e.g. http://10.31.1.159:8080/ws");\r
150                 System.out\r
151                                 .println(servicekey\r
152                                                 + pseparator\r
153                                                 + "<ServiceName> - optional if unspecified all services are tested otherwise one of "\r
154                                                 + Arrays.toString(Services.values()));\r
155                 System.out.println();\r
156 \r
157         }\r
158 \r
159         /**\r
160          * Calls alignment with preset\r
161          * \r
162          * @param <T>\r
163          * @param msaws\r
164          * @param presets\r
165          *            list of the Preset\r
166          * @throws UnsupportedRuntimeException\r
167          */\r
168         private <T> boolean presetAlign(MsaWS<T> msaws, List<Preset<T>> presets)\r
169                         throws UnsupportedRuntimeException {\r
170                 boolean succeed = false;\r
171                 for (Preset<T> preset : presets) {\r
172                         writer.print("Aligning with preset '" + preset.getName() + "'... ");\r
173                         Alignment al = null;\r
174                         try {\r
175                                 String taskId = msaws.presetAlign(seqs, preset);\r
176                                 al = msaws.getResult(taskId);\r
177                                 if (al != null) {\r
178                                         writer.println(OK);\r
179                                 }\r
180                                 succeed = true;\r
181                         } catch (Exception e) {\r
182                                 if (e instanceof UnsupportedRuntimeException) {\r
183                                         // If executable is not supported than none of the presets\r
184                                         // are\r
185                                         // going to work\r
186                                         throw (UnsupportedRuntimeException) e;\r
187                                 } else {\r
188                                         reportException(e);\r
189                                 }\r
190                                 continue;\r
191                         }\r
192                 }\r
193                 return succeed;\r
194         }\r
195 \r
196         private <T> boolean testMsaWS(MsaWS<T> msaws) throws Exception {\r
197                 assert msaws != null;\r
198 \r
199                 boolean succeed = testDefaultAlignment(msaws);\r
200                 // If exception above is thrown than the tests below is not run\r
201 \r
202                 PresetManager<T> pmanager = msaws.getPresets();\r
203                 if (pmanager != null && pmanager.getPresets().size() > 0) {\r
204                         writer.println("Testing alignment with presets:");\r
205                         List<Preset<T>> plist = pmanager.getPresets();\r
206                         succeed = !succeed ? presetAlign(msaws, plist) : succeed;\r
207                 }\r
208                 testMetadata(msaws);\r
209                 return succeed;\r
210         }\r
211         \r
212         /**\r
213          * Call most of web services functions and check the output\r
214          * \r
215          * @param <T>\r
216          *            web service type\r
217          * @param msaws\r
218          * @throws UnsupportedRuntimeException\r
219          *             is thrown if the connection to a web service was made, but\r
220          *             the web service is not functional. e.g. when native\r
221          *             executable does not exists for a server platform\r
222          */\r
223         @SuppressWarnings("unchecked")\r
224         private <T> boolean checkService(JABAService wservice, Services service) {\r
225                 try {\r
226                         if (wservice == null) {\r
227                                 throw new NullPointerException(\r
228                                                 "JABAService instance must be provided!");\r
229                         }\r
230 \r
231                         if (wservice instanceof MsaWS) {\r
232                                 return testMsaWS((MsaWS<T>) wservice);\r
233                         } else if (wservice instanceof SequenceAnnotation) {\r
234                                 return testSequenceAnnotationWS(\r
235                                                 (SequenceAnnotation<T>) wservice, service);\r
236                         } else {\r
237                                 throw new UnsupportedOperationException("The service: "\r
238                                                 + wservice.getClass() + " is not supported! ");\r
239                         }\r
240                 } catch (Exception e) {\r
241                         reportException(e);\r
242                         return false;\r
243                 }\r
244         }\r
245 \r
246         private <T> boolean testSequenceAnnotationWS(\r
247                         SequenceAnnotation<T> wservice, Services service) throws Exception {\r
248                 writer.print("Calling analyse.........");\r
249 \r
250                 List<FastaSequence> input = loadSeqs();\r
251                 if (service == Services.AAConWS || service == Services.RNAalifoldWS) {\r
252                         input = loadAlignment();\r
253                 }\r
254                 boolean success = testDefaultAnalyse(input, wservice, null, null);\r
255 \r
256                 PresetManager<T> presetman = wservice.getPresets();\r
257                 if (presetman != null) {\r
258                         List<Preset<T>> presets = presetman.getPresets();\r
259                         if (presets != null && !presets.isEmpty()) {\r
260                                 Preset<T> preset = presets.get(0);\r
261                                 writer.print("Calling analyse with Preset.........");\r
262                                 success = testDefaultAnalyse(input, wservice, preset, null);\r
263                         }\r
264                 }\r
265                 testMetadata(wservice);\r
266                 return success;\r
267         }\r
268 \r
269         private <T> boolean testDefaultAnalyse(List<FastaSequence> fastalist,\r
270                         SequenceAnnotation<T> wsproxy, Preset<T> preset,\r
271                         List<Option<T>> customOptions) throws Exception {\r
272 \r
273                 ScoreManager scores = null;\r
274 \r
275                 String jobId = null;\r
276                 if (customOptions != null) {\r
277                         jobId = wsproxy.customAnalize(fastalist, customOptions);\r
278                 } else if (preset != null) {\r
279                         jobId = wsproxy.presetAnalize(fastalist, preset);\r
280                 } else {\r
281                         jobId = wsproxy.analize(fastalist);\r
282                 }\r
283                 Thread.sleep(1000);\r
284                 scores = wsproxy.getAnnotation(jobId);\r
285                 if (scores != null) {\r
286                         writer.println(OK);\r
287                 }\r
288 \r
289                 return scores != null;\r
290         }\r
291 \r
292         private void reportException(Exception e) {\r
293                 writer.println(FAILED);\r
294                 writer.println("Exception while waiting for results. "\r
295                                 + "Exception details are below:");\r
296                 writer.println(e.getLocalizedMessage());\r
297                 e.printStackTrace(writer);\r
298         }\r
299 \r
300         private <T> void testMetadata(Metadata<T> msaws)\r
301                         throws UnsupportedRuntimeException {\r
302 \r
303                 writer.print("Querying presets...");\r
304                 PresetManager<T> pmanager = msaws.getPresets();\r
305                 if (pmanager != null && pmanager.getPresets().size() > 0) {\r
306                         writer.println(OK);\r
307                 } else {\r
308                         writer.println(UNSUPPORTED);\r
309                 }\r
310 \r
311                 writer.print("Querying Parameters...");\r
312                 RunnerConfig<T> options = msaws.getRunnerOptions();\r
313                 if (options != null && options.getArguments().size() > 0) {\r
314                         writer.println(OK);\r
315                 } else {\r
316                         writer.println(UNSUPPORTED);\r
317                 }\r
318 \r
319                 writer.print("Querying Limits...");\r
320                 LimitsManager<T> limits = msaws.getLimits();\r
321                 if (limits != null && limits.getLimits().size() > 0) {\r
322                         writer.println(OK);\r
323                         // writer.println("Limits details: \n" + limits.toString());\r
324                 } else {\r
325                         writer.println(UNSUPPORTED);\r
326                 }\r
327 \r
328                 writer.print("Querying Local Engine Limits...");\r
329                 Limit<T> localLimit = msaws\r
330                                 .getLimit(PresetManager.LOCAL_ENGINE_LIMIT_PRESET);\r
331                 if (localLimit != null) {\r
332                         writer.println(OK);\r
333                 } else {\r
334                         writer.println(UNSUPPORTED);\r
335                 }\r
336         }\r
337 \r
338         /**\r
339          * Align using default settings\r
340          * \r
341          * @param <T>\r
342          * @param msaws\r
343          * @throws UnsupportedRuntimeException\r
344          */\r
345         private <T> boolean testDefaultAlignment(MsaWS<T> msaws) throws Exception {\r
346                 writer.print("Testing alignment with default parameters:");\r
347                 Alignment al = null;\r
348                 boolean succeed = false;\r
349 \r
350                 String taskId = msaws.align(seqs);\r
351                 writer.print("\nQuerying job status...");\r
352                 JobStatus status = msaws.getJobStatus(taskId);\r
353                 while (status != JobStatus.FINISHED) {\r
354                         Thread.sleep(1000);\r
355                         status = msaws.getJobStatus(taskId);\r
356                 }\r
357                 writer.println(OK);\r
358                 writer.print("Retrieving results...");\r
359                 al = msaws.getResult(taskId);\r
360                 succeed = true;\r
361                 if (al != null) {\r
362                         writer.println(OK);\r
363                 }\r
364                 return succeed;\r
365         }\r
366         \r
367         \r
368         /**\r
369          * Test JWS2 web services\r
370          * \r
371          * @param <T>\r
372          *            web service type\r
373          * @param args\r
374          *            -h=<Your web application server host name, port and JWS2\r
375          *            context path>\r
376          * \r
377          *            -s=<ServiceName> which is optional. If service name is not\r
378          *            provided then all known JWS2 web services are tested\r
379          * @throws IOException\r
380          */\r
381         public static <T> void main(String[] args) throws IOException {\r
382 \r
383                 if (args == null || args.length < 1) {\r
384                         WSTester.printUsage();\r
385                         System.exit(0);\r
386                 }\r
387                 String host = CmdHelper.getHost(args);\r
388                 String serviceName = CmdHelper.getServiceName(args);\r
389                 if (!Jws2Client.validURL(host)) {\r
390                         System.err\r
391                                         .println("<host_and_context> parameter is not provided or is incorrect!");\r
392                         System.exit(1);\r
393                 }\r
394                 WSTester tester = new WSTester(host, new PrintWriter(System.out, true));\r
395 \r
396                 if (serviceName != null) {\r
397                         Services service = Services.getService(serviceName);\r
398                         if (service == null) {\r
399                                 tester.writer.println("Service '" + serviceName\r
400                                                 + "' is not supported. Valid values are: "\r
401                                                 + Arrays.toString(Services.values()));\r
402                                 tester.writer.println();\r
403                                 printUsage();\r
404                                 System.exit(1);\r
405                         }\r
406                         tester.checkService(service);\r
407                         System.exit(0);\r
408                 }\r
409 \r
410                 tester.writer\r
411                                 .println("<ServiceName> is not provided checking all known services...");\r
412 \r
413                 for (Services serv : Services.values()) {\r
414                         tester.writer.println();\r
415                         tester.checkService(serv);\r
416                 }\r
417 \r
418         }\r
419 \r
420         /**\r
421          * Test JABA web service\r
422          * \r
423          * @param service\r
424          *            the service to test\r
425          * @return true if the service works as expected, false otherwise\r
426          * @throws WebServiceException\r
427          * @throws ConnectException\r
428          */\r
429         public boolean checkService(Services service) throws ConnectException,\r
430                         WebServiceException {\r
431                 JABAService ws = Jws2Client.connect(hostname, service);\r
432                 if (ws == null) {\r
433                         writer.println("Cannot estabilish the connection to host "\r
434                                         + hostname + " with service " + service.toString());\r
435                         return false;\r
436                 }\r
437                 boolean succeed = false;\r
438                 try {\r
439                         writer.println("Checking service " + service.toString());\r
440                         succeed = checkService(ws, service);\r
441                 } finally {\r
442                         FileUtil.closeSilently(((Closeable) ws));\r
443                 }\r
444                 reportResults(service, succeed);\r
445                 return succeed;\r
446         }\r
447 \r
448         private void reportResults(Services serv, boolean succeed) {\r
449                 if (succeed) {\r
450                         writer.println("Check is completed. The Service " + serv\r
451                                         + " IS WORKING\n");\r
452                 } else {\r
453                         writer.println("Check is aborted. The Service " + serv\r
454                                         + " HAS SOME PROBLEMS\n");\r
455                 }\r
456         }\r
457 }\r