tidied the exceptions and ws server error behaviour
[jalview.git] / src / jalview / ws / JPredClient.java
1 package jalview.ws;\r
2 \r
3 import org.apache.axis.client.*;\r
4 import javax.xml.namespace.QName;\r
5 import java.util.*;\r
6 import jalview.datamodel.*;\r
7 import jalview.gui.*;\r
8 import javax.swing.*;\r
9 import java.util.*;\r
10 import java.awt.*;\r
11 import jalview.analysis.AlignSeq;\r
12 import ext.vamsas.*;\r
13 \r
14 \r
15 public class JPredClient extends WSClient\r
16 {\r
17   ext.vamsas.JPredWS server;\r
18   String altitle = "";\r
19   java.util.Hashtable SequenceInfo = null;\r
20   private void setWebService() {\r
21     WebServiceName = "JNetWS";\r
22     WebServiceJobTitle = "JNet secondary structure prediction";\r
23     WebServiceReference="\"Cuff J. A and Barton G.J (1999) Application of enhanced "\r
24         + "multiple sequence alignment profiles to improve protein secondary structure prediction, "\r
25         + "Proteins 40:502-511\".";\r
26     WsURL="http://www.compbio.dundee.ac.uk/JalviewWS/services/jpred";\r
27   }\r
28   public JPredClient(String title, SequenceI[] msf)\r
29   {\r
30     setWebService();\r
31     wsInfo = new WebserviceInfo(WebServiceJobTitle, WebServiceReference);\r
32     SequenceI seq = msf[0];\r
33     altitle = "JNet prediction on "+seq.getName()+" using alignment from "+title;\r
34 \r
35     wsInfo.setProgressText("Job details for MSA based prediction ("+title+") on sequence :\n>"\r
36                    + seq.getName() + "\n"\r
37                    + AlignSeq.extractGaps("-. ",seq.getSequence()) + "\n");\r
38 \r
39     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
40 \r
41     JPredWSServiceLocator loc = new JPredWSServiceLocator(); // Default\r
42     // JBPNote url will be set from properties\r
43     try {\r
44       this.server = loc.getjpred(new java.net.URL(WsURL));\r
45     }\r
46     catch (Exception ex) {\r
47       JOptionPane.showMessageDialog(Desktop.desktop, "The Secondary Structure Prediction Service named "\r
48                                     +WebServiceName+" at "+WsURL+" couldn't be located.",\r
49                                     "Internal Jalview Error", JOptionPane.WARNING_MESSAGE);\r
50       wsInfo.setProgressText("Serious! "+WebServiceName+" Service location failed\nfor URL :"\r
51                      +WsURL+"\n"+ex.getMessage());\r
52     }\r
53 \r
54     JPredThread jthread = new JPredThread(msf);\r
55     jthread.start();\r
56   }\r
57 \r
58   public JPredClient(String title, SequenceI seq)\r
59   {\r
60     setWebService();\r
61     wsInfo = new WebserviceInfo(WebServiceJobTitle, WebServiceReference);\r
62     wsInfo.setProgressText("Job details for prediction on sequence :\n>"\r
63                    + seq.getName() + "\n" + AlignSeq.extractGaps("-. ",seq.getSequence()) + "\n");\r
64     altitle = "JNet prediction for sequence "+seq.getName()+" from "+title;\r
65     SequenceInfo = jalview.analysis.SeqsetUtils.SeqCharacterHash(seq);\r
66 \r
67     JPredWSServiceLocator loc = new JPredWSServiceLocator(); // Default\r
68     try {\r
69       this.server = loc.getjpred(new java.net.URL(WsURL)); // JBPNote will be set from properties\r
70       ((JpredSoapBindingStub) this.server).setTimeout(60000); // one minute stub\r
71     }\r
72     catch (Exception ex) {\r
73       JOptionPane.showMessageDialog(Desktop.desktop, "The Secondary Structure Prediction Service named "\r
74                                     +WebServiceName+" at "+WsURL+" couldn't be located.",\r
75                                     "Internal Jalview Error", JOptionPane.WARNING_MESSAGE);\r
76       wsInfo.setProgressText("Serious! "+WebServiceName+" Service location failed\nfor URL :"\r
77                      +WsURL+"\n"+ex.getMessage());\r
78       wsInfo.setStatus(wsInfo.STATE_STOPPED_SERVERERROR);\r
79     }\r
80 \r
81     JPredThread jthread = new JPredThread(seq);\r
82     jthread.start();\r
83   }\r
84 \r
85 \r
86   class JPredThread\r
87       extends Thread\r
88   {\r
89     String OutputHeader;\r
90     ext.vamsas.JpredResult result;\r
91     ext.vamsas.Sequence sequence;\r
92     ext.vamsas.Msfalignment msa;\r
93     String jobId;\r
94     boolean jobComplete = false;\r
95     int allowedServerExceptions = 3; // thread dies if too many exceptions.\r
96     JPredThread(SequenceI seq)\r
97     {\r
98       OutputHeader = wsInfo.getProgressText();\r
99       this.sequence = new ext.vamsas.Sequence();\r
100       this.sequence.setId(seq.getName());\r
101       this.sequence.setSeq(AlignSeq.extractGaps("-. ",seq.getSequence()));\r
102     }\r
103 \r
104     JPredThread(SequenceI[] msf)\r
105     {\r
106       OutputHeader = wsInfo.getProgressText();\r
107       this.sequence = new ext.vamsas.Sequence();\r
108       this.sequence.setId(msf[0].getName());\r
109       this.sequence.setSeq(AlignSeq.extractGaps("-. ",msf[0].getSequence()));\r
110       jalview.io.PileUpfile mwrite = new jalview.io.PileUpfile();\r
111       this.msa = new ext.vamsas.Msfalignment();\r
112       msa.setMsf(mwrite.print(msf));\r
113     }\r
114 \r
115 \r
116     public void run()\r
117     {\r
118 \r
119       StartJob();\r
120 \r
121       while (!jobComplete && (allowedServerExceptions > 0))\r
122       {\r
123         try\r
124         {\r
125           if ((result = server.getresult(jobId))==null)\r
126             throw(new Exception("Timed out when communicating with server\nTry again later.\n"));\r
127 \r
128          if( result.isRunning() )\r
129            wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);\r
130          else if( result.isQueued() )\r
131            wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);\r
132 \r
133           if (result.isFinished())\r
134           {\r
135             parseResult();\r
136             jobComplete = true;\r
137             jobsRunning--;\r
138           }\r
139           else\r
140           {\r
141             wsInfo.setProgressText(OutputHeader + "\n" + result.getStatus());\r
142             if (! (result.isJobFailed() || result.isServerError()))\r
143             {\r
144               try\r
145               {\r
146                 Thread.sleep(5000);\r
147               }\r
148               catch (InterruptedException ex1)\r
149               {\r
150               }\r
151               //  System.out.println("I'm alive "+seqid+" "+jobid);\r
152             } else {\r
153               wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
154             }\r
155           }\r
156         }\r
157         catch (Exception ex)\r
158         {\r
159           allowedServerExceptions--;\r
160           wsInfo.appendProgressText("\nJPredWS Server exception!\n" + ex.getMessage());\r
161           try\r
162           {\r
163             if (allowedServerExceptions>0)\r
164               Thread.sleep(5000);\r
165           }\r
166           catch (InterruptedException ex1)\r
167           {\r
168           }\r
169         }\r
170       }\r
171 \r
172       if (! (result.isJobFailed() || result.isServerError()))\r
173         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);\r
174       else\r
175         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);\r
176     }\r
177 \r
178     void StartJob()\r
179     {\r
180       try\r
181       {\r
182         if (msa!=null)  {\r
183           jobId = server.predictOnMsa(msa);\r
184         } else {\r
185           jobId = server.predict(sequence);\r
186         }\r
187         if (jobId!=null) {\r
188           if (jobId.startsWith("Broken")) {\r
189             throw new Exception("Submission " + jobId);\r
190           } else {\r
191             System.out.println(WsURL+" Job Id '"+jobId+"'");\r
192           }\r
193         } else {\r
194           throw new Exception("Server timed out - try again later\n");\r
195 \r
196         }\r
197       }\r
198       catch (Exception e)\r
199       {\r
200          wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);\r
201          allowedServerExceptions=0;\r
202          jobComplete=false;\r
203          wsInfo.appendProgressText("Failed to submit the prediction: "+e.toString()+"\nJust close the window\n");\r
204          System.err.println("JPredWS Client: Failed to submit the prediction\n" +\r
205                             e.toString() + "\n");\r
206          // e.printStackTrace(); TODO: JBPNote DEBUG\r
207       }\r
208     }\r
209 \r
210     private void addFloatAnnotations(Alignment al, int[] gapmap, Vector values, String Symname, String Visname, float min, float max, int winLength) {\r
211 \r
212       Annotation[] annotations = new Annotation[al.getWidth()];\r
213       for (int j = 0; j < values.size(); j++)\r
214       {\r
215         float value = Float.parseFloat(values.get(j).toString());\r
216         annotations[gapmap[j]] = new Annotation("", value+"",' ',value);\r
217       }\r
218       al.addAnnotation(new AlignmentAnnotation(Symname, Visname, annotations, min, max, winLength));\r
219     }\r
220 \r
221     void parseResult()\r
222     {\r
223       // OutputHeader = output.getText();\r
224       if (result.isFailed()) {\r
225         OutputHeader +="Job failed.\n";\r
226       }\r
227       if (result.getStatus()!=null) {\r
228         OutputHeader += "\n"+result.getStatus();\r
229       }\r
230       if (result.getPredfile()!=null) {\r
231         OutputHeader += "\n"+result.getPredfile();\r
232       // JBPNote The returned files from a webservice could be hidden behind icons in the monitor window that, when clicked, pop up their corresponding data\r
233       }\r
234       if (result.getAligfile()!=null) {\r
235         OutputHeader += "\n"+result.getAligfile();\r
236       }\r
237       wsInfo.setProgressText(OutputHeader);\r
238       try {\r
239         // JPredFile prediction = new JPredFile("C:/JalviewX/files/jpred.txt", "File");\r
240         jalview.io.JPredFile prediction = new jalview.io.JPredFile(result.getPredfile(), "Paste");\r
241         SequenceI[] preds = prediction.getSeqsAsArray();\r
242         Alignment al;\r
243         int FirstSeq; // the position of the query sequence in Alignment al\r
244         boolean noMsa = true; // set if no MSA has been returned by JPred\r
245 \r
246         if (this.msa!=null && result.getAligfile()!=null) {\r
247           // we ignore the returned alignment if we only predicted on a single sequence\r
248           String format = jalview.io.IdentifyFile.Identify(result.getAligfile(), "Paste");\r
249           if (jalview.io.FormatAdapter.formats.contains(format))\r
250           {\r
251             al = new Alignment(jalview.io.FormatAdapter.readFile(result.getAligfile(),"Paste",format));\r
252             noMsa = false;\r
253             FirstSeq = 0;\r
254           }\r
255           else\r
256           {\r
257             throw (new Exception("Unknown format 'format' for file : \n" +\r
258                              result.getAligfile()));\r
259           }\r
260 \r
261         } else {\r
262           al = new Alignment(preds);\r
263           FirstSeq = prediction.getQuerySeqPosition();\r
264         }\r
265 \r
266         if (!jalview.analysis.SeqsetUtils.SeqCharacterUnhash(al.getSequenceAt(FirstSeq), SequenceInfo))\r
267           throw (new Exception("Couldn't recover sequence properties for JNet Query sequence!"));\r
268 \r
269         AlignmentAnnotation annot;\r
270         Annotation [] annotations = null;\r
271         int i = 0;\r
272         int width = preds[0].getSequence().length();\r
273 \r
274 \r
275         int[] gapmap = al.getSequenceAt(FirstSeq).gapMap();\r
276 \r
277         if (gapmap.length!=width) {\r
278           throw (new Exception("Jnet Client Error\nNumber of residues in supposed query sequence :\n"\r
279                                +al.getSequenceAt(FirstSeq).getName()+"\n"\r
280                                +al.getSequenceAt(FirstSeq).getSequence()\r
281                                +"\nDiffer from number of prediction sites in \n"+result.getPredfile()+"\n"));\r
282         }\r
283         // JBPNote Should also rename the query sequence sometime...\r
284         i=0;\r
285         while (i < preds.length)\r
286         {\r
287           String id = preds[i].getName().toUpperCase();\r
288           if(id.startsWith("LUPAS") || id.startsWith("JNET") || id.startsWith("JPRED"))\r
289           {\r
290             annotations = new Annotation[al.getWidth()];\r
291 \r
292             if(id.equals("JNETPRED")\r
293                || id.equals("JNETPSSM")\r
294                || id.equals("JNETFREQ")\r
295                || id.equals("JNETHMM")\r
296                || id.equals("JNETALIGN")\r
297                || id.equals("JPRED"))\r
298             {\r
299               for (int j = 0; j < width; j++)\r
300                 annotations[gapmap[j]] = new Annotation("", "", preds[i].getCharAt(j), 0);\r
301             }\r
302             else if(id.equals("JNETCONF"))\r
303             {\r
304               for (int j = 0; j < width; j++)\r
305               {\r
306                 float value = Float.parseFloat(preds[i].getCharAt(j)+"");\r
307                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(j)+"", "",preds[i].getCharAt(j),value);\r
308               }\r
309             }\r
310             else\r
311             {\r
312               for (int j = 0; j < width; j++) {\r
313                 annotations[gapmap[j]] = new Annotation(preds[i].getCharAt(j)+"", "", ' ', 0);\r
314               }\r
315             }\r
316 \r
317             if(id.equals("JNETCONF"))\r
318               annot = new AlignmentAnnotation(preds[i].getName(),\r
319                                            "JNet Output",\r
320                                            annotations,0f,10f,1);\r
321 \r
322             else   annot = new AlignmentAnnotation(preds[i].getName(),\r
323                                             "JNet Output",\r
324                                             annotations);\r
325             al.addAnnotation(annot);\r
326             if (noMsa)\r
327               al.deleteSequence(preds[i]);\r
328           }\r
329           i++;\r
330         }\r
331 \r
332         Hashtable scores = prediction.getScores();\r
333       /*  addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPH"),\r
334                             "JnetpropH", "Jnet Helix Propensity", 0f,1f,1);\r
335 \r
336         addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPB"),\r
337                             "JnetpropB", "Jnet Beta Sheet Propensity", 0f,1f,1);\r
338 \r
339         addFloatAnnotations(al, gapmap,  (Vector)scores.get("JNETPROPC"),\r
340                             "JnetpropC", "Jnet Coil Propensity", 0f,1f,1);\r
341        */\r
342         AlignFrame af = new AlignFrame(al);\r
343 \r
344 \r
345         Desktop.addInternalFrame(af,\r
346                                  altitle,\r
347                                  AlignFrame.NEW_WINDOW_WIDTH, AlignFrame.NEW_WINDOW_HEIGHT);\r
348       }catch(Exception ex){ex.printStackTrace();}\r
349 \r
350     }\r
351 \r
352   }\r
353 }\r
354 \r