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