Added clustalW 'realignment' (primitive)
[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     }
57     catch (Exception ex) {
58       wsInfo.setProgressText("Serious! "+WebServiceName+" Service location failed\nfor URL :"
59                      +WsURL+"\n"+ex.getMessage());
60       wsInfo.setStatus(wsInfo.ERROR);
61       ex.printStackTrace();
62     }
63
64     MsaWSThread musclethread = new MsaWSThread(WebServiceName+" alignment of "+altitle, msa, submitGaps, preserveOrder);
65     wsInfo.setthisService(musclethread);
66     musclethread.start();
67   }
68
69
70   protected class MsaWSThread extends Thread implements WSClientI
71   {
72     String ServiceName = WebServiceName;
73
74     public boolean isCancellable()
75     {
76       return true;
77     }
78
79     String OutputHeader;
80     vamsas.objects.simple.MsaResult result = null;
81
82     vamsas.objects.simple.SequenceSet seqs = new vamsas.objects.simple.
83         SequenceSet();
84
85     Hashtable SeqNames = null;
86     boolean submitGaps = false,// default is to strip gaps from sequences
87         preserveOrder = true; // and always store and recover sequence order
88
89     String jobId;
90     String alTitle; // name which will be used to form new alignment window.
91     int allowedServerExceptions = 3; // thread dies if too many exceptions.
92     MsaWSThread(String title, SequenceI[] msa, boolean subgaps, boolean presorder)
93     {
94       alTitle = title;
95       submitGaps = subgaps;
96       preserveOrder = presorder;
97
98       OutputHeader = wsInfo.getProgressText();
99       SeqNames = new Hashtable();
100       vamsas.objects.simple.Sequence[] seqarray = new vamsas.objects.simple.
101           Sequence[msa.length];
102
103       for (int i = 0; i < msa.length; i++)
104       {
105         String newname = jalview.analysis.SeqsetUtils.unique_name(i);
106         // uniquify as we go
107         // TODO: JBPNote: this is a ubiquitous transformation - set of jalview seq objects to vamsas sequences with name preservation
108         SeqNames.put(newname, jalview.analysis.SeqsetUtils.SeqCharacterHash(msa[i]));
109         seqarray[i] = new vamsas.objects.simple.Sequence();
110         seqarray[i].setId(newname);
111         seqarray[i].setSeq((submitGaps) ? msa[i].getSequence()
112                            : AlignSeq.extractGaps(jalview.util.Comparison.GapChars, msa[i].getSequence()));
113       }
114
115       this.seqs = new vamsas.objects.simple.SequenceSet();
116       this.seqs.setSeqs(seqarray);
117     }
118
119     boolean jobComplete = false;
120
121     public void cancelJob() {
122       if (!jobComplete) {
123         String cancelledMessage="";
124         try {
125           vamsas.objects.simple.WsJobId cancelledJob = server.cancel(jobId);
126           if (cancelledJob.getStatus() == 2)
127           {
128             // CANCELLED_JOB
129             cancelledMessage = "Job cancelled.";
130             wsInfo.setStatus(WebserviceInfo.STATE_CANCELLED_OK);
131             jobComplete = true;
132             jobsRunning--;
133             result = null;
134           }
135           else
136           if (cancelledJob.getStatus() == 3)
137           {
138             // VALID UNSTOPPABLE JOB
139             cancelledMessage +=
140                 "Server cannot cancel this job. just close the window.\n";
141           }
142           if (cancelledJob.getJobId() != null)
143             cancelledMessage += "[" + cancelledJob.getJobId() + "]";
144           cancelledMessage +="\n";
145         } catch (Exception exc) {
146           cancelledMessage +="\nProblems cancelling the job : Exception received...\n"+exc+"\n";
147           exc.printStackTrace();
148         }
149         wsInfo.setProgressText(OutputHeader + cancelledMessage+"\n");
150       }
151     }
152
153     public void run()
154     {
155
156       StartJob();
157
158       while (!jobComplete && (allowedServerExceptions > 0))
159       {
160         try
161         {
162           result = server.getResult(jobId);
163
164           if (result.isRunning())
165             wsInfo.setStatus(WebserviceInfo.STATE_RUNNING);
166           else if (result.isQueued())
167             wsInfo.setStatus(WebserviceInfo.STATE_QUEUING);
168
169           if (result.isFinished())
170           {
171             parseResult();
172             jobComplete = true;
173             jobsRunning--;
174           }
175           else
176           {
177             if (result.getStatus() != null)
178               wsInfo.setProgressText(OutputHeader + "\n" + result.getStatus());
179             if (! (result.isJobFailed() || result.isServerError()))
180             {
181               Thread.sleep(5000);
182               //  System.out.println("I'm alive "+seqid+" "+jobid);
183             }
184             else
185             {
186               break;
187             }
188           }
189         }
190         catch (Exception ex)
191         {
192           allowedServerExceptions--;
193           wsInfo.appendProgressText("\n" + ServiceName + " Server exception!\n" +
194                                     ex.getMessage());
195           ex.printStackTrace();
196         }
197       }
198       if (allowedServerExceptions == 0)
199       {
200         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
201       }
202       else
203       {
204         if (! (result != null && (result.isJobFailed() || result.isServerError())))
205           wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
206         else
207         {
208           if (result.isFailed())
209             wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
210           if (result.isServerError())
211             wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
212         }
213       }
214     }
215     void StartJob()
216     {
217       try
218       {
219         vamsas.objects.simple.WsJobId jobsubmit = server.align(seqs);
220         if (jobsubmit.getStatus()==1) {
221           jobId=jobsubmit.getJobId();
222           System.out.println(WsURL+" Job Id '"+jobId+"'");
223         } else {
224           throw new Exception(jobsubmit.getJobId());
225         }
226       }
227       catch (Exception e)
228       {
229         System.err.println(ServiceName + " Client: Failed to submit the prediction\n" +
230                            e.toString() + "\n");
231         e.printStackTrace();
232       }
233     }
234
235     private void addFloatAnnotations(Alignment al, int[] gapmap, Vector values, String Symname, String Visname, float min, float max, int winLength) {
236
237       Annotation[] annotations = new Annotation[al.getWidth()];
238       for (int j = 0; j < values.size(); j++)
239       {
240         float value = Float.parseFloat(values.get(j).toString());
241         annotations[gapmap[j]] = new Annotation("", value+"",' ',value);
242       }
243       al.addAnnotation(new AlignmentAnnotation(Symname, Visname, annotations, min, max, winLength));
244     }
245     private jalview.datamodel.Sequence[] getVamsasAlignment(vamsas.objects.simple.Alignment valign) {
246       vamsas.objects.simple.Sequence[] seqs = valign.getSeqs().getSeqs();
247       jalview.datamodel.Sequence[] msa = new jalview.datamodel.Sequence[seqs.length];
248       for (int i=0, j=seqs.length; i<j;i++)
249         msa[i] = new jalview.datamodel.Sequence(seqs[i].getId(), seqs[i].getSeq());
250       return msa;
251     }
252     void parseResult()
253     {
254       SequenceI[] seqs=null;
255       try {
256         // OutputHeader = output.getText();
257         if (result.isFailed()) {
258           OutputHeader +="Job failed.\n";
259         }
260         if (result.getStatus()!=null) {
261           OutputHeader += "\n"+result.getStatus();
262         }
263         if (result.getMsa()!=null) {
264           OutputHeader += "\nAlignment Object Method Notes\n";
265           String lines[] = result.getMsa().getMethod();
266           for (int line=0;line<lines.length; line++)
267             OutputHeader+=lines[line]+"\n";
268
269           // JBPNote The returned files from a webservice could be hidden behind icons in the monitor window that, when clicked, pop up their corresponding data
270           seqs = getVamsasAlignment(result.getMsa());
271         }
272
273         wsInfo.setProgressText(OutputHeader);
274         if (seqs!=null) {
275           AlignmentOrder msaorder = new AlignmentOrder(seqs);
276
277           if (preserveOrder) {
278             jalview.analysis.AlignmentSorter.recoverOrder(seqs);
279           }
280
281           jalview.analysis.SeqsetUtils.deuniquify(SeqNames, seqs);
282
283           Alignment al = new Alignment(seqs);
284
285           // TODO: JBPNote Should also rename the query sequence sometime...
286           AlignFrame af = new AlignFrame(al);
287           af.addSortByOrderMenuItem(ServiceName+" Ordering", msaorder);
288
289           Desktop.addInternalFrame(af,
290                                    alTitle,
291                                    AlignFrame.NEW_WINDOW_WIDTH,
292                                    AlignFrame.NEW_WINDOW_HEIGHT);
293         }
294       }catch(Exception ex){ex.printStackTrace();}
295
296     }
297
298   }
299 }
300
301