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