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