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