Improved consistency between JPredWS and MsaWS
[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("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("-. ", 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             wsInfo.setProgressText(OutputHeader + "\n" + result.getStatus());
178             if (! (result.isJobFailed() || result.isServerError()))
179             {
180               Thread.sleep(5000);
181               //  System.out.println("I'm alive "+seqid+" "+jobid);
182             }
183           }
184         }
185         catch (Exception ex)
186         {
187           allowedServerExceptions--;
188           wsInfo.appendProgressText("\n"+ServiceName+" Server exception!\n" + ex.getMessage());
189           ex.printStackTrace();
190         }
191       }
192
193       if (! (result!=null && (result.isJobFailed() || result.isServerError())))
194         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_OK);
195       else
196         wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
197     }
198
199     void StartJob()
200     {
201       try
202       {
203         vamsas.objects.simple.WsJobId jobsubmit = server.align(seqs);
204         if (jobsubmit.getStatus()==1) {
205           jobId=jobsubmit.getJobId();
206           System.out.println(WsURL+" Job Id '"+jobId+"'");
207         } else {
208           throw new Exception(jobsubmit.getJobId());
209         }
210       }
211       catch (Exception e)
212       {
213         System.out.println(ServiceName + " Client: Failed to submit the prediction\n" +
214                            e.toString() + "\n");
215         e.printStackTrace();
216       }
217     }
218
219     private void addFloatAnnotations(Alignment al, int[] gapmap, Vector values, String Symname, String Visname, float min, float max, int winLength) {
220
221       Annotation[] annotations = new Annotation[al.getWidth()];
222       for (int j = 0; j < values.size(); j++)
223       {
224         float value = Float.parseFloat(values.get(j).toString());
225         annotations[gapmap[j]] = new Annotation("", value+"",' ',value);
226       }
227       al.addAnnotation(new AlignmentAnnotation(Symname, Visname, annotations, min, max, winLength));
228     }
229     private jalview.datamodel.Sequence[] getVamsasAlignment(vamsas.objects.simple.Alignment valign) {
230       vamsas.objects.simple.Sequence[] seqs = valign.getSeqs().getSeqs();
231       jalview.datamodel.Sequence[] msa = new jalview.datamodel.Sequence[seqs.length];
232       for (int i=0, j=seqs.length; i<j;i++)
233         msa[i] = new jalview.datamodel.Sequence(seqs[i].getId(), seqs[i].getSeq());
234       return msa;
235     }
236     void parseResult()
237     {
238       SequenceI[] seqs=null;
239       try {
240         // OutputHeader = output.getText();
241         if (result.isFailed()) {
242           OutputHeader +="Job failed.\n";
243         }
244         if (result.getStatus()!=null) {
245           OutputHeader += "\n"+result.getStatus();
246         }
247         if (result.getMsa()!=null) {
248           OutputHeader += "\nAlignment Object Method Notes\n";
249           String lines[] = result.getMsa().getMethod();
250           for (int line=0;line<lines.length; line++)
251             OutputHeader+=lines[line]+"\n";
252
253           // JBPNote The returned files from a webservice could be hidden behind icons in the monitor window that, when clicked, pop up their corresponding data
254           seqs = getVamsasAlignment(result.getMsa());
255         }
256
257         wsInfo.setProgressText(OutputHeader);
258         if (seqs!=null) {
259           AlignmentOrder msaorder = new AlignmentOrder(seqs);
260
261           if (preserveOrder) {
262             jalview.analysis.AlignmentSorter.recoverOrder(seqs);
263           }
264
265           jalview.analysis.SeqsetUtils.deuniquify(SeqNames, seqs);
266
267           Alignment al = new Alignment(seqs);
268
269           // TODO: JBPNote Should also rename the query sequence sometime...
270           AlignFrame af = new AlignFrame(al);
271           af.addSortByOrderMenuItem(ServiceName+" Ordering", msaorder);
272
273           Desktop.addInternalFrame(af,
274                                    alTitle,
275                                    AlignFrame.NEW_WINDOW_WIDTH,
276                                    AlignFrame.NEW_WINDOW_HEIGHT);
277         }
278       }catch(Exception ex){ex.printStackTrace();}
279
280     }
281
282   }
283 }
284
285