tidied the exceptions and ws server error behaviour
[jalview.git] / src / jalview / ws / MsaWSClient.java
1 package jalview.ws;
2
3 import org.apache.axis.client.*;
4 import javax.xml.namespace.QName;
5 import java.util.*;
6 import jalview.datamodel.*;
7 import jalview.gui.*;
8 import javax.swing.*;
9 import java.util.*;
10 import java.awt.*;
11 import jalview.analysis.AlignSeq;
12 import ext.vamsas.*;
13 import vamsas.objects.*;
14
15
16
17
18 public class MsaWSClient
19     extends WSClient
20 {
21     /**
22      * server is a WSDL2Java generated stub for an archetypal MsaWSI service.
23      */
24     ext.vamsas.MuscleWS server;
25
26   private boolean setWebService(String MsaWSName) {
27     if (MsaWServices.info.containsKey(MsaWSName)) {
28       WebServiceName = MsaWSName;
29       String[] wsinfo = (String[]) MsaWServices.info.get(MsaWSName);
30       WsURL = wsinfo[0];
31       WebServiceJobTitle = wsinfo[1];
32       WebServiceReference = wsinfo[2];
33       return true;
34     } else {
35       return false;
36     }
37   }
38
39
40   public MsaWSClient(String MsaWSName, String altitle, SequenceI[] msa, boolean submitGaps, boolean preserveOrder)
41   {
42     if (setWebService(MsaWSName)==false) {
43       JOptionPane.showMessageDialog(Desktop.desktop, "The Multiple Sequence Alignment Service named "+MsaWSName+" is unknown",
44                                     "Internal Jalview Error", JOptionPane.WARNING_MESSAGE);
45       return;
46     }
47
48     wsInfo = new jalview.gui.WebserviceInfo(WebServiceJobTitle, WebServiceReference);
49
50     wsInfo.setProgressText(((submitGaps) ? "Re-alignment" : "Alignment")+" of "+altitle+"\nJob details\n");
51
52     // TODO: MuscleWS transmuted to generic MsaWS client
53     MuscleWSServiceLocator loc = new MuscleWSServiceLocator(); // Default
54     try {
55       this.server = (MuscleWS) loc.getMuscleWS(new java.net.URL(WsURL));
56       ((MuscleWSSoapBindingStub) this.server).setTimeout(60000); // One minute timeout
57     }
58     catch (Exception ex) {
59       wsInfo.setProgressText("Serious! "+WebServiceName+" Service location failed\nfor URL :"
60                      +WsURL+"\n"+ex.getMessage());
61       wsInfo.setStatus(wsInfo.ERROR);
62       ex.printStackTrace();
63     }
64     loc.getEngine().setOption("axis","1");
65     MsaWSThread musclethread = new MsaWSThread(WebServiceName+" alignment of "+altitle, msa, submitGaps, preserveOrder);
66     wsInfo.setthisService(musclethread);
67     musclethread.start();
68   }
69
70
71   protected class MsaWSThread extends Thread implements WSClientI
72   {
73     String ServiceName = WebServiceName;
74
75     public boolean isCancellable()
76     {
77       return true;
78     }
79
80     String OutputHeader;
81     vamsas.objects.simple.MsaResult result = null;
82
83     vamsas.objects.simple.SequenceSet seqs = new vamsas.objects.simple.
84         SequenceSet();
85
86     Hashtable SeqNames = null;
87     boolean submitGaps = false,// default is to strip gaps from sequences
88         preserveOrder = true; // and always store and recover sequence order
89
90     String jobId;
91     String alTitle; // name which will be used to form new alignment window.
92     int allowedServerExceptions = 3; // thread dies if too many exceptions.
93     MsaWSThread(String title, SequenceI[] msa, boolean subgaps, boolean presorder)
94     {
95       alTitle = title;
96       submitGaps = subgaps;
97       preserveOrder = presorder;
98
99       OutputHeader = wsInfo.getProgressText();
100       SeqNames = new Hashtable();
101       vamsas.objects.simple.Sequence[] seqarray = new vamsas.objects.simple.
102           Sequence[msa.length];
103
104       for (int i = 0; i < msa.length; i++)
105       {
106         String newname = jalview.analysis.SeqsetUtils.unique_name(i);
107         // uniquify as we go
108         // TODO: JBPNote: this is a ubiquitous transformation - set of jalview seq objects to vamsas sequences with name preservation
109         SeqNames.put(newname, jalview.analysis.SeqsetUtils.SeqCharacterHash(msa[i]));
110         seqarray[i] = new vamsas.objects.simple.Sequence();
111         seqarray[i].setId(newname);
112         seqarray[i].setSeq((submitGaps) ? msa[i].getSequence()
113                            : AlignSeq.extractGaps(jalview.util.Comparison.GapChars, msa[i].getSequence()));
114       }
115
116       this.seqs = new vamsas.objects.simple.SequenceSet();
117       this.seqs.setSeqs(seqarray);
118     }
119
120     boolean jobComplete = false;
121
122     public void cancelJob() {
123       if (jobId!=null && !jobId.equals("") && !jobComplete) {
124         String cancelledMessage="";
125         try {
126           vamsas.objects.simple.WsJobId cancelledJob = server.cancel(jobId);
127           if (cancelledJob.getStatus() == 2)
128           {
129             // CANCELLED_JOB
130             cancelledMessage = "Job cancelled.";
131             wsInfo.setStatus(WebserviceInfo.STATE_CANCELLED_OK);
132             jobComplete = true;
133             jobsRunning--;
134             result = null;
135           }
136           else
137           if (cancelledJob.getStatus() == 3)
138           {
139             // VALID UNSTOPPABLE JOB
140             cancelledMessage +=
141                 "Server cannot cancel this job. just close the window.\n";
142           }
143           if (cancelledJob.getJobId() != null)
144             cancelledMessage += "[" + cancelledJob.getJobId() + "]";
145           cancelledMessage +="\n";
146         } catch (Exception exc) {
147           cancelledMessage +="\nProblems cancelling the job : Exception received...\n"+exc+"\n";
148           exc.printStackTrace();
149         }
150         wsInfo.setProgressText(OutputHeader + cancelledMessage+"\n");
151       } else {
152         if (!jobComplete)
153         {
154           wsInfo.setProgressText(OutputHeader + "Server cannot cancel this job because it has not been submitted properly. just close the window.\n");
155         }
156       }
157     }
158
159     public void run()
160     {
161
162       StartJob();
163
164       while (!jobComplete && (allowedServerExceptions > 0))
165       {
166         try
167         {
168           if ((result = server.getResult(jobId))==null)
169             throw(new Exception("Timed out when communicating with server\nTry again later.\n"));
170
171           if (result.isRunning())
172             wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);
173           else if (result.isQueued())
174             wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);
175
176           if (result.isFinished())
177           {
178             parseResult();
179             jobComplete = true;
180             jobsRunning--;
181           }
182           else
183           {
184             if (result.getStatus() != null)
185               wsInfo.setProgressText(OutputHeader + "\n" + result.getStatus());
186             if (! (result.isJobFailed() || result.isServerError()))
187             {
188               Thread.sleep(5000);
189               //  System.out.println("I'm alive "+seqid+" "+jobid);
190             }
191             else
192             {
193               break;
194             }
195           }
196         }
197         catch (Exception ex)
198         {
199           allowedServerExceptions--;
200           wsInfo.appendProgressText("\n" + ServiceName + " Server exception!\n" +
201                                     ex.getMessage());
202           System.err.println(ServiceName + " Server exception: " +
203                                     ex.getMessage());
204           //          ex.printStackTrace(); JBPNote Debug
205           try
206           {
207             if (allowedServerExceptions>0)
208               Thread.sleep(5000);
209           }
210           catch (InterruptedException ex1)
211           {
212           }
213
214         }
215       }
216       if (allowedServerExceptions == 0)
217       {
218         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
219       }
220       else
221       {
222         if (! (result != null && (result.isJobFailed() || result.isServerError())))
223           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
224         else
225         {
226           if (result.isFailed())
227             wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
228           if (result.isServerError())
229             wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
230         }
231       }
232     }
233     void StartJob()
234     {
235       try
236       {
237         vamsas.objects.simple.WsJobId jobsubmit = server.align(seqs);
238         if (jobsubmit!=null && jobsubmit.getStatus()==1) {
239           jobId=jobsubmit.getJobId();
240           System.out.println(WsURL+" Job Id '"+jobId+"'");
241         } else {
242           if (jobsubmit == null) {
243             throw new Exception("Server at "+WsURL+" returned null object, it probably cannot be contacted. Try again later ?");
244           }
245           throw new Exception(jobsubmit.getJobId());
246         }
247       }
248       catch (Exception e)
249       {
250         // TODO: JBPNote catch timeout or other fault types explicitly
251         // For unexpected errors
252         System.err.println(WebServiceName + " Client: Failed to submit the sequences for alignment.\n"+WsURL+" : " +
253                            e.toString() + "\n");
254         this.allowedServerExceptions=0;
255         wsInfo.setStatus(wsInfo.STATE_STOPPED_SERVERERROR);
256         wsInfo.appendProgressText("Server problems! "+e.toString()+"\nFailed to submit sequences for alignment. Just close the window\n");
257         // e.printStackTrace(); // TODO: JBPNote DEBUG
258       }
259     }
260
261     private void addFloatAnnotations(Alignment al, int[] gapmap, Vector values, String Symname, String Visname, float min, float max, int winLength) {
262
263       Annotation[] annotations = new Annotation[al.getWidth()];
264       for (int j = 0; j < values.size(); j++)
265       {
266         float value = Float.parseFloat(values.get(j).toString());
267         annotations[gapmap[j]] = new Annotation("", value+"",' ',value);
268       }
269       al.addAnnotation(new AlignmentAnnotation(Symname, Visname, annotations, min, max, winLength));
270     }
271     private jalview.datamodel.Sequence[] getVamsasAlignment(vamsas.objects.simple.Alignment valign) {
272       vamsas.objects.simple.Sequence[] seqs = valign.getSeqs().getSeqs();
273       jalview.datamodel.Sequence[] msa = new jalview.datamodel.Sequence[seqs.length];
274       for (int i=0, j=seqs.length; i<j;i++)
275         msa[i] = new jalview.datamodel.Sequence(seqs[i].getId(), seqs[i].getSeq());
276       return msa;
277     }
278     void parseResult()
279     {
280       SequenceI[] seqs=null;
281       try {
282         // OutputHeader = output.getText();
283         if (result.isFailed()) {
284           OutputHeader +="Job failed.\n";
285         }
286         if (result.getStatus()!=null) {
287           OutputHeader += "\n"+result.getStatus();
288         }
289         if (result.getMsa()!=null) {
290           OutputHeader += "\nAlignment Object Method Notes\n";
291           String lines[] = result.getMsa().getMethod();
292           for (int line=0;line<lines.length; line++)
293             OutputHeader+=lines[line]+"\n";
294
295           // JBPNote The returned files from a webservice could be hidden behind icons in the monitor window that, when clicked, pop up their corresponding data
296           seqs = getVamsasAlignment(result.getMsa());
297         }
298
299         wsInfo.setProgressText(OutputHeader);
300         if (seqs!=null) {
301           AlignmentOrder msaorder = new AlignmentOrder(seqs);
302
303           if (preserveOrder) {
304             jalview.analysis.AlignmentSorter.recoverOrder(seqs);
305           }
306
307           jalview.analysis.SeqsetUtils.deuniquify(SeqNames, seqs);
308
309           Alignment al = new Alignment(seqs);
310
311           // TODO: JBPNote Should also rename the query sequence sometime...
312           AlignFrame af = new AlignFrame(al);
313           af.addSortByOrderMenuItem(ServiceName+" Ordering", msaorder);
314
315           Desktop.addInternalFrame(af,
316                                    alTitle,
317                                    AlignFrame.NEW_WINDOW_WIDTH,
318                                    AlignFrame.NEW_WINDOW_HEIGHT);
319         }
320       }catch(Exception ex){ex.printStackTrace();}
321
322     }
323
324   }
325 }
326
327