JAL-1807 explicit imports (jalview.ws.*)
[jalview.git] / src / jalview / ws / jws1 / MsaWSThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws.jws1;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.analysis.AlignmentSorter;
25 import jalview.analysis.SeqsetUtils;
26 import jalview.bin.Cache;
27 import jalview.datamodel.Alignment;
28 import jalview.datamodel.AlignmentOrder;
29 import jalview.datamodel.AlignmentView;
30 import jalview.datamodel.ColumnSelection;
31 import jalview.datamodel.Sequence;
32 import jalview.datamodel.SequenceI;
33 import jalview.gui.AlignFrame;
34 import jalview.gui.Desktop;
35 import jalview.gui.WebserviceInfo;
36 import jalview.util.Comparison;
37 import jalview.util.MessageManager;
38 import jalview.ws.AWsJob;
39 import jalview.ws.JobStateSummary;
40 import jalview.ws.WSClientI;
41
42 import java.util.Hashtable;
43 import java.util.Vector;
44
45 import vamsas.objects.simple.MsaResult;
46
47 class MsaWSThread extends JWS1Thread implements WSClientI
48 {
49   boolean submitGaps = false; // pass sequences including gaps to alignment
50
51   // service
52
53   boolean preserveOrder = true; // and always store and recover sequence
54
55   // order
56
57   class MsaWSJob extends WSJob
58   {
59     // hold special input for this
60     vamsas.objects.simple.SequenceSet seqs = new vamsas.objects.simple.SequenceSet();
61
62     /**
63      * MsaWSJob
64      * 
65      * @param jobNum
66      *          int
67      * @param jobId
68      *          String
69      */
70     public MsaWSJob(int jobNum, SequenceI[] inSeqs)
71     {
72       this.jobnum = jobNum;
73       if (!prepareInput(inSeqs, 2))
74       {
75         submitted = true;
76         subjobComplete = true;
77         result = new MsaResult();
78         result.setFinished(true);
79         result.setStatus(MessageManager.getString("label.job_never_ran"));
80       }
81
82     }
83
84     Hashtable SeqNames = new Hashtable();
85
86     Vector emptySeqs = new Vector();
87
88     /**
89      * prepare input sequences for MsaWS service
90      * 
91      * @param seqs
92      *          jalview sequences to be prepared
93      * @param minlen
94      *          minimum number of residues required for this MsaWS service
95      * @return true if seqs contains sequences to be submitted to service.
96      */
97     private boolean prepareInput(SequenceI[] seqs, int minlen)
98     {
99       int nseqs = 0;
100       if (minlen < 0)
101       {
102         throw new Error(MessageManager.getString("error.implementation_error_minlen_must_be_greater_zero"));
103       }
104       for (int i = 0; i < seqs.length; i++)
105       {
106         if (seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
107         {
108           nseqs++;
109         }
110       }
111       boolean valid = nseqs > 1; // need at least two seqs
112       vamsas.objects.simple.Sequence[] seqarray = (valid) ? new vamsas.objects.simple.Sequence[nseqs]
113               : null;
114       for (int i = 0, n = 0; i < seqs.length; i++)
115       {
116
117         String newname = SeqsetUtils.unique_name(i); // same
118         // for
119         // any
120         // subjob
121         SeqNames.put(newname, SeqsetUtils.SeqCharacterHash(seqs[i]));
122         if (valid && seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
123         {
124           seqarray[n] = new vamsas.objects.simple.Sequence();
125           seqarray[n].setId(newname);
126           seqarray[n++].setSeq((submitGaps) ? seqs[i].getSequenceAsString()
127                   : AlignSeq.extractGaps(Comparison.GapChars,
128                           seqs[i].getSequenceAsString()));
129         }
130         else
131         {
132           String empty = null;
133           if (seqs[i].getEnd() >= seqs[i].getStart())
134           {
135             empty = (submitGaps) ? seqs[i].getSequenceAsString() : AlignSeq
136                     .extractGaps(Comparison.GapChars,
137                             seqs[i].getSequenceAsString());
138           }
139           emptySeqs.add(new String[]
140           { newname, empty });
141         }
142       }
143       this.seqs = new vamsas.objects.simple.SequenceSet();
144       this.seqs.setSeqs(seqarray);
145       return valid;
146     }
147
148     /**
149      * 
150      * @return true if getAlignment will return a valid alignment result.
151      */
152     public boolean hasResults()
153     {
154       if (subjobComplete && result != null && result.isFinished()
155               && ((MsaResult) result).getMsa() != null
156               && ((MsaResult) result).getMsa().getSeqs() != null)
157       {
158         return true;
159       }
160       return false;
161     }
162
163     public Object[] getAlignment()
164     {
165
166       if (result != null && result.isFinished())
167       {
168         SequenceI[] alseqs = null;
169         char alseq_gapchar = '-';
170         int alseq_l = 0;
171         if (((MsaResult) result).getMsa() != null)
172         {
173           alseqs = getVamsasAlignment(((MsaResult) result).getMsa());
174           alseq_gapchar = ((MsaResult) result).getMsa().getGapchar()
175                   .charAt(0);
176           alseq_l = alseqs.length;
177         }
178         if (emptySeqs.size() > 0)
179         {
180           SequenceI[] t_alseqs = new SequenceI[alseq_l + emptySeqs.size()];
181           // get width
182           int i, w = 0;
183           if (alseq_l > 0)
184           {
185             for (i = 0, w = alseqs[0].getLength(); i < alseq_l; i++)
186             {
187               if (w < alseqs[i].getLength())
188               {
189                 w = alseqs[i].getLength();
190               }
191               t_alseqs[i] = alseqs[i];
192               alseqs[i] = null;
193             }
194           }
195           // check that aligned width is at least as wide as emptySeqs width.
196           int ow = w, nw = w;
197           for (i = 0, w = emptySeqs.size(); i < w; i++)
198           {
199             String[] es = (String[]) emptySeqs.get(i);
200             if (es != null && es[1] != null)
201             {
202               int sw = es[1].length();
203               if (nw < sw)
204               {
205                 nw = sw;
206               }
207             }
208           }
209           // make a gapped string.
210           StringBuffer insbuff = new StringBuffer(w);
211           for (i = 0; i < nw; i++)
212           {
213             insbuff.append(alseq_gapchar);
214           }
215           if (ow < nw)
216           {
217             for (i = 0; i < alseq_l; i++)
218             {
219               int sw = t_alseqs[i].getLength();
220               if (nw > sw)
221               {
222                 // pad at end
223                 alseqs[i].setSequence(t_alseqs[i].getSequenceAsString()
224                         + insbuff.substring(0, sw - nw));
225               }
226             }
227           }
228           for (i = 0, w = emptySeqs.size(); i < w; i++)
229           {
230             String[] es = (String[]) emptySeqs.get(i);
231             if (es[1] == null)
232             {
233               t_alseqs[i + alseq_l] = new Sequence(es[0],
234                       insbuff.toString(), 1, 0);
235             }
236             else
237             {
238               if (es[1].length() < nw)
239               {
240                 t_alseqs[i + alseq_l] = new Sequence(
241                         es[0],
242                         es[1] + insbuff.substring(0, nw - es[1].length()),
243                         1, 1 + es[1].length());
244               }
245               else
246               {
247                 t_alseqs[i + alseq_l] = new Sequence(
248                         es[0], es[1]);
249               }
250             }
251           }
252           alseqs = t_alseqs;
253         }
254         AlignmentOrder msaorder = new AlignmentOrder(alseqs);
255         // always recover the order - makes parseResult()'s life easier.
256         AlignmentSorter.recoverOrder(alseqs);
257         // account for any missing sequences
258         SeqsetUtils.deuniquify(SeqNames, alseqs);
259         return new Object[]
260         { alseqs, msaorder };
261       }
262       return null;
263     }
264
265     /**
266      * mark subjob as cancelled and set result object appropriatly
267      */
268     void cancel()
269     {
270       cancelled = true;
271       subjobComplete = true;
272       result = null;
273     }
274
275     /**
276      * 
277      * @return boolean true if job can be submitted.
278      */
279     public boolean hasValidInput()
280     {
281       if (seqs.getSeqs() != null)
282       {
283         return true;
284       }
285       return false;
286     }
287   }
288
289   String alTitle; // name which will be used to form new alignment window.
290
291   Alignment dataset; // dataset to which the new alignment will be
292
293   // associated.
294
295   ext.vamsas.MuscleWS server = null;
296
297   /**
298    * set basic options for this (group) of Msa jobs
299    * 
300    * @param subgaps
301    *          boolean
302    * @param presorder
303    *          boolean
304    */
305   MsaWSThread(ext.vamsas.MuscleWS server, String wsUrl,
306           WebserviceInfo wsinfo, AlignFrame alFrame,
307           AlignmentView alview, String wsname, boolean subgaps,
308           boolean presorder)
309   {
310     super(alFrame, wsinfo, alview, wsname, wsUrl);
311     this.server = server;
312     this.submitGaps = subgaps;
313     this.preserveOrder = presorder;
314   }
315
316   /**
317    * create one or more Msa jobs to align visible seuqences in _msa
318    * 
319    * @param title
320    *          String
321    * @param _msa
322    *          AlignmentView
323    * @param subgaps
324    *          boolean
325    * @param presorder
326    *          boolean
327    * @param seqset
328    *          Alignment
329    */
330   MsaWSThread(ext.vamsas.MuscleWS server, String wsUrl,
331           WebserviceInfo wsinfo, AlignFrame alFrame,
332           String wsname, String title, AlignmentView _msa, boolean subgaps,
333           boolean presorder, Alignment seqset)
334   {
335     this(server, wsUrl, wsinfo, alFrame, _msa, wsname, subgaps, presorder);
336     OutputHeader = wsInfo.getProgressText();
337     alTitle = title;
338     dataset = seqset;
339
340     SequenceI[][] conmsa = _msa.getVisibleContigs('-');
341     if (conmsa != null)
342     {
343       int njobs = conmsa.length;
344       jobs = new MsaWSJob[njobs];
345       for (int j = 0; j < njobs; j++)
346       {
347         if (j != 0)
348         {
349           jobs[j] = new MsaWSJob(wsinfo.addJobPane(), conmsa[j]);
350         }
351         else
352         {
353           jobs[j] = new MsaWSJob(0, conmsa[j]);
354         }
355         if (njobs > 0)
356         {
357           wsinfo.setProgressName("region " + jobs[j].getJobnum(),
358                   jobs[j].getJobnum());
359         }
360         wsinfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
361       }
362     }
363   }
364
365   public boolean isCancellable()
366   {
367     return true;
368   }
369
370   public void cancelJob()
371   {
372     if (!jobComplete && jobs != null)
373     {
374       boolean cancelled = true;
375       for (int job = 0; job < jobs.length; job++)
376       {
377         if (jobs[job].isSubmitted() && !jobs[job].isSubjobComplete())
378         {
379           String cancelledMessage = "";
380           try
381           {
382             vamsas.objects.simple.WsJobId cancelledJob = server
383                     .cancel(jobs[job].getJobId());
384             if (cancelledJob.getStatus() == 2)
385             {
386               // CANCELLED_JOB
387               cancelledMessage = "Job cancelled.";
388               ((MsaWSJob) jobs[job]).cancel();
389               wsInfo.setStatus(jobs[job].getJobnum(),
390                       WebserviceInfo.STATE_CANCELLED_OK);
391             }
392             else if (cancelledJob.getStatus() == 3)
393             {
394               // VALID UNSTOPPABLE JOB
395               cancelledMessage += "Server cannot cancel this job. just close the window.\n";
396               cancelled = false;
397               // wsInfo.setStatus(jobs[job].jobnum,
398               // WebserviceInfo.STATE_RUNNING);
399             }
400
401             if (cancelledJob.getJobId() != null)
402             {
403               cancelledMessage += ("[" + cancelledJob.getJobId() + "]");
404             }
405
406             cancelledMessage += "\n";
407           } catch (Exception exc)
408           {
409             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
410                     + exc + "\n");
411             Cache.log.warn(
412                     "Exception whilst cancelling " + jobs[job].getJobId(),
413                     exc);
414           }
415           wsInfo.setProgressText(jobs[job].getJobnum(), OutputHeader
416                   + cancelledMessage + "\n");
417         }
418       }
419       if (cancelled)
420       {
421         wsInfo.setStatus(WebserviceInfo.STATE_CANCELLED_OK);
422         jobComplete = true;
423       }
424       this.interrupt(); // kick thread to update job states.
425     }
426     else
427     {
428       if (!jobComplete)
429       {
430         wsInfo.setProgressText(OutputHeader
431                 + "Server cannot cancel this job because it has not been submitted properly. just close the window.\n");
432       }
433     }
434   }
435
436   public void pollJob(AWsJob job) throws Exception
437   {
438     ((MsaWSJob) job).result = server.getResult(((MsaWSJob) job).getJobId());
439   }
440
441   public void StartJob(AWsJob job)
442   {
443     if (!(job instanceof MsaWSJob))
444     {
445       throw new Error(MessageManager.formatMessage("error.implementation_error_msawbjob_called", new String[]{job.getClass().toString()}));
446     }
447     MsaWSJob j = (MsaWSJob) job;
448     if (j.isSubmitted())
449     {
450       if (Cache.log.isDebugEnabled())
451       {
452         Cache.log.debug("Tried to submit an already submitted job "
453                 + j.getJobId());
454       }
455       return;
456     }
457     if (j.seqs.getSeqs() == null)
458     {
459       // special case - selection consisted entirely of empty sequences...
460       j.setSubmitted(true);
461       j.result = new MsaResult();
462       j.result.setFinished(true);
463       j.result.setStatus(MessageManager.getString("label.empty_alignment_job"));
464       ((MsaResult) j.result).setMsa(null);
465     }
466     try
467     {
468       vamsas.objects.simple.WsJobId jobsubmit = server.align(j.seqs);
469
470       if ((jobsubmit != null) && (jobsubmit.getStatus() == 1))
471       {
472         j.setJobId(jobsubmit.getJobId());
473         j.setSubmitted(true);
474         j.setSubjobComplete(false);
475         // System.out.println(WsURL + " Job Id '" + jobId + "'");
476       }
477       else
478       {
479         if (jobsubmit == null)
480         {
481           throw new Exception(MessageManager.formatMessage("exception.web_service_returned_null_try_later", new String[]{WsUrl}));
482         }
483
484         throw new Exception(jobsubmit.getJobId());
485       }
486     } catch (Exception e)
487     {
488       // TODO: JBPNote catch timeout or other fault types explicitly
489       // For unexpected errors
490       System.err
491               .println(WebServiceName
492                       + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
493                       + "When contacting Server:" + WsUrl + "\n"
494                       + e.toString() + "\n");
495       j.setAllowedServerExceptions(0);
496       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
497       wsInfo.setStatus(j.getJobnum(),
498               WebserviceInfo.STATE_STOPPED_SERVERERROR);
499       wsInfo.appendProgressText(
500               j.getJobnum(),
501               MessageManager.getString("info.failed_to_submit_sequences_for_alignment"));
502
503       // e.printStackTrace(); // TODO: JBPNote DEBUG
504     }
505   }
506
507   private Sequence[] getVamsasAlignment(
508           vamsas.objects.simple.Alignment valign)
509   {
510     // TODO: refactor to helper class for vamsas.objects.simple objects
511     vamsas.objects.simple.Sequence[] seqs = valign.getSeqs().getSeqs();
512     Sequence[] msa = new Sequence[seqs.length];
513
514     for (int i = 0, j = seqs.length; i < j; i++)
515     {
516       msa[i] = new Sequence(seqs[i].getId(),
517               seqs[i].getSeq());
518     }
519
520     return msa;
521   }
522
523   public void parseResult()
524   {
525     int results = 0; // number of result sets received
526     JobStateSummary finalState = new JobStateSummary();
527     try
528     {
529       for (int j = 0; j < jobs.length; j++)
530       {
531         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
532         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
533                 && jobs[j].hasResults())
534         {
535           results++;
536           // if (Cache.log.isDebugEnabled())
537           // {
538           // System.out.println("Job lob for job "+jobs[j].getJobId()+":"+jobs[j].getJobnum());
539           // System.out.println(jobs[j].getStatus());
540           // }
541
542           vamsas.objects.simple.Alignment valign = ((MsaResult) ((MsaWSJob) jobs[j]).result)
543                   .getMsa();
544           if (valign != null)
545           {
546             wsInfo.appendProgressText(jobs[j].getJobnum(),
547                     MessageManager.getString("info.alignment_object_method_notes"));
548             String[] lines = valign.getMethod();
549             for (int line = 0; line < lines.length; line++)
550             {
551               wsInfo.appendProgressText(jobs[j].getJobnum(), lines[line]
552                       + "\n");
553             }
554             // JBPNote The returned files from a webservice could be
555             // hidden behind icons in the monitor window that,
556             // when clicked, pop up their corresponding data
557
558           }
559         }
560       }
561     } catch (Exception ex)
562     {
563
564       Cache.log.error("Unexpected exception when processing results for "
565               + alTitle, ex);
566       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
567     }
568     if (results > 0)
569     {
570       wsInfo.showResultsNewFrame
571               .addActionListener(new java.awt.event.ActionListener()
572               {
573                 public void actionPerformed(java.awt.event.ActionEvent evt)
574                 {
575                   displayResults(true);
576                 }
577               });
578       wsInfo.mergeResults
579               .addActionListener(new java.awt.event.ActionListener()
580               {
581                 public void actionPerformed(java.awt.event.ActionEvent evt)
582                 {
583                   displayResults(false);
584                 }
585               });
586       wsInfo.setResultsReady();
587     }
588     else
589     {
590       wsInfo.setFinishedNoResults();
591     }
592   }
593
594   void displayResults(boolean newFrame)
595   {
596     // view input or result data for each block
597     Vector alorders = new Vector();
598     SequenceI[][] results = new SequenceI[jobs.length][];
599     AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
600     for (int j = 0; j < jobs.length; j++)
601     {
602       if (jobs[j].hasResults())
603       {
604         Object[] res = ((MsaWSJob) jobs[j]).getAlignment();
605         alorders.add(res[1]);
606         results[j] = (SequenceI[]) res[0];
607         orders[j] = (AlignmentOrder) res[1];
608
609         // SequenceI[] alignment = input.getUpdated
610       }
611       else
612       {
613         results[j] = null;
614       }
615     }
616     Object[] newview = input.getUpdatedView(results, orders, getGapChar());
617     // trash references to original result data
618     for (int j = 0; j < jobs.length; j++)
619     {
620       results[j] = null;
621       orders[j] = null;
622     }
623     SequenceI[] alignment = (SequenceI[]) newview[0];
624     ColumnSelection columnselection = (ColumnSelection) newview[1];
625     Alignment al = new Alignment(alignment);
626     // TODO: add 'provenance' property to alignment from the method notes
627     // accompanying each subjob
628     if (dataset != null)
629     {
630       al.setDataset(dataset);
631     }
632
633     propagateDatasetMappings(al);
634     // JBNote- TODO: warn user if a block is input rather than aligned data ?
635
636     if (newFrame)
637     {
638       AlignFrame af = new AlignFrame(al, columnselection,
639               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
640
641       // initialise with same renderer settings as in parent alignframe.
642       af.getFeatureRenderer().transferSettings(this.featureSettings);
643       // update orders
644       if (alorders.size() > 0)
645       {
646         if (alorders.size() == 1)
647         {
648           af.addSortByOrderMenuItem(WebServiceName + " Ordering",
649                   (AlignmentOrder) alorders.get(0));
650         }
651         else
652         {
653           // construct a non-redundant ordering set
654           Vector names = new Vector();
655           for (int i = 0, l = alorders.size(); i < l; i++)
656           {
657             String orderName = new String(" Region " + i);
658             int j = i + 1;
659
660             while (j < l)
661             {
662               if (((AlignmentOrder) alorders.get(i))
663                       .equals((alorders.get(j))))
664               {
665                 alorders.remove(j);
666                 l--;
667                 orderName += "," + j;
668               }
669               else
670               {
671                 j++;
672               }
673             }
674
675             if (i == 0 && j == 1)
676             {
677               names.add(new String(""));
678             }
679             else
680             {
681               names.add(orderName);
682             }
683           }
684           for (int i = 0, l = alorders.size(); i < l; i++)
685           {
686             af.addSortByOrderMenuItem(
687                     WebServiceName + ((String) names.get(i)) + " Ordering",
688                     (AlignmentOrder) alorders.get(i));
689           }
690         }
691       }
692
693       Desktop.addInternalFrame(af, alTitle, AlignFrame.DEFAULT_WIDTH,
694               AlignFrame.DEFAULT_HEIGHT);
695
696     }
697     else
698     {
699       System.out.println("MERGE WITH OLD FRAME");
700       // TODO: modify alignment in original frame, replacing old for new
701       // alignment using the commands.EditCommand model to ensure the update can
702       // be undone
703     }
704   }
705
706   public boolean canMergeResults()
707   {
708     return false;
709   }
710 }