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