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