c4fc66bbfb7801846c9e9bf29152cdef42e197bc
[jalview.git] / src / jalview / ws / jws2 / 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.jws2;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.bin.Cache;
25 import jalview.datamodel.Alignment;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentOrder;
28 import jalview.datamodel.AlignmentView;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.Sequence;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.AlignFrame;
33 import jalview.gui.Desktop;
34 import jalview.gui.SplitFrame;
35 import jalview.gui.WebserviceInfo;
36 import jalview.util.MessageManager;
37 import jalview.ws.AWsJob;
38 import jalview.ws.JobStateSummary;
39 import jalview.ws.WSClientI;
40 import jalview.ws.jws2.dm.JabaWsParamSet;
41 import jalview.ws.params.WsParamSetI;
42
43 import java.util.ArrayList;
44 import java.util.Hashtable;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Vector;
48
49 import javax.swing.JInternalFrame;
50
51 import compbio.data.msa.MsaWS;
52 import compbio.metadata.Argument;
53 import compbio.metadata.ChunkHolder;
54 import compbio.metadata.JobStatus;
55 import compbio.metadata.Preset;
56
57 class MsaWSThread extends AWS2Thread implements WSClientI
58 {
59   boolean submitGaps = false; // pass sequences including gaps to alignment
60
61   // service
62
63   boolean preserveOrder = true; // and always store and recover sequence
64
65   // order
66
67   class MsaWSJob extends JWs2Job
68   {
69     long lastChunk = 0;
70
71     WsParamSetI preset = null;
72
73     List<Argument> arguments = null;
74
75     /**
76      * input
77      */
78     ArrayList<compbio.data.sequence.FastaSequence> seqs = new ArrayList<>();
79
80     /**
81      * output
82      */
83     compbio.data.sequence.Alignment alignment;
84
85     // set if the job didn't get run - then the input is simply returned to the
86     // user
87     private boolean returnInput = false;
88
89     /**
90      * MsaWSJob
91      * 
92      * @param jobNum
93      *          int
94      * @param jobId
95      *          String
96      */
97     public MsaWSJob(int jobNum, SequenceI[] inSeqs)
98     {
99       this.jobnum = jobNum;
100       if (!prepareInput(inSeqs, 2))
101       {
102         submitted = true;
103         subjobComplete = true;
104         returnInput = true;
105       }
106
107     }
108
109     Hashtable<String, Map> SeqNames = new Hashtable();
110
111     Vector<String[]> emptySeqs = new Vector();
112
113     /**
114      * prepare input sequences for MsaWS service
115      * 
116      * @param seqs
117      *          jalview sequences to be prepared
118      * @param minlen
119      *          minimum number of residues required for this MsaWS service
120      * @return true if seqs contains sequences to be submitted to service.
121      */
122     // TODO: return compbio.seqs list or nothing to indicate validity.
123     private boolean prepareInput(SequenceI[] seqs, int minlen)
124     {
125       int nseqs = 0;
126       if (minlen < 0)
127       {
128         throw new Error(MessageManager.getString(
129                 "error.implementation_error_minlen_must_be_greater_zero"));
130       }
131       for (int i = 0; i < seqs.length; i++)
132       {
133         if (seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
134         {
135           nseqs++;
136         }
137       }
138       boolean valid = nseqs > 1; // need at least two seqs
139       compbio.data.sequence.FastaSequence seq;
140       for (int i = 0, n = 0; i < seqs.length; i++)
141       {
142         String newname = jalview.analysis.SeqsetUtils.unique_name(i); // same
143         // for
144         // any
145         // subjob
146         SeqNames.put(newname,
147                 jalview.analysis.SeqsetUtils.SeqCharacterHash(seqs[i]));
148         if (valid && seqs[i].getEnd() - seqs[i].getStart() > minlen - 1)
149         {
150           // make new input sequence with or without gaps
151           seq = new compbio.data.sequence.FastaSequence(newname,
152                   (submitGaps) ? seqs[i].getSequenceAsString()
153                           : AlignSeq.extractGaps(
154                                   jalview.util.Comparison.GapChars,
155                                   seqs[i].getSequenceAsString()));
156           this.seqs.add(seq);
157         }
158         else
159         {
160           String empty = null;
161           if (seqs[i].getEnd() >= seqs[i].getStart())
162           {
163             empty = (submitGaps) ? seqs[i].getSequenceAsString()
164                     : AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
165                             seqs[i].getSequenceAsString());
166           }
167           emptySeqs.add(new String[] { newname, empty });
168         }
169       }
170       return valid;
171     }
172
173     /**
174      * 
175      * @return true if getAlignment will return a valid alignment result.
176      */
177     @Override
178     public boolean hasResults()
179     {
180       if (subjobComplete && isFinished() && (alignment != null
181               || (emptySeqs != null && emptySeqs.size() > 0)))
182       {
183         return true;
184       }
185       return false;
186     }
187
188     /**
189      * 
190      * get the alignment including any empty sequences in the original order
191      * with original ids. Caller must access the alignment.getMetadata() object
192      * to annotate the final result passsed to the user.
193      * 
194      * @return { SequenceI[], AlignmentOrder }
195      */
196     public Object[] getAlignment()
197     {
198       // is this a generic subjob or a Jws2 specific Object[] return signature
199       if (hasResults())
200       {
201         SequenceI[] alseqs = null;
202         char alseq_gapchar = '-';
203         int alseq_l = 0;
204         if (alignment.getSequences().size() > 0)
205         {
206           alseqs = new SequenceI[alignment.getSequences().size()];
207           for (compbio.data.sequence.FastaSequence seq : alignment
208                   .getSequences())
209           {
210             alseqs[alseq_l++] = new Sequence(seq.getId(),
211                     seq.getSequence());
212           }
213           alseq_gapchar = alignment.getMetadata().getGapchar();
214
215         }
216         // add in the empty seqs.
217         if (emptySeqs.size() > 0)
218         {
219           SequenceI[] t_alseqs = new SequenceI[alseq_l + emptySeqs.size()];
220           // get width
221           int i, w = 0;
222           if (alseq_l > 0)
223           {
224             for (i = 0, w = alseqs[0].getLength(); i < alseq_l; i++)
225             {
226               if (w < alseqs[i].getLength())
227               {
228                 w = alseqs[i].getLength();
229               }
230               t_alseqs[i] = alseqs[i];
231               alseqs[i] = null;
232             }
233           }
234           // check that aligned width is at least as wide as emptySeqs width.
235           int ow = w, nw = w;
236           for (i = 0, w = emptySeqs.size(); i < w; i++)
237           {
238             String[] es = emptySeqs.get(i);
239             if (es != null && es[1] != null)
240             {
241               int sw = es[1].length();
242               if (nw < sw)
243               {
244                 nw = sw;
245               }
246             }
247           }
248           // make a gapped string.
249           StringBuffer insbuff = new StringBuffer(w);
250           for (i = 0; i < nw; i++)
251           {
252             insbuff.append(alseq_gapchar);
253           }
254           if (ow < nw)
255           {
256             for (i = 0; i < alseq_l; i++)
257             {
258               int sw = t_alseqs[i].getLength();
259               if (nw > sw)
260               {
261                 // pad at end
262                 alseqs[i].setSequence(t_alseqs[i].getSequenceAsString()
263                         + insbuff.substring(0, sw - nw));
264               }
265             }
266           }
267           for (i = 0, w = emptySeqs.size(); i < w; i++)
268           {
269             String[] es = emptySeqs.get(i);
270             if (es[1] == null)
271             {
272               t_alseqs[i + alseq_l] = new jalview.datamodel.Sequence(es[0],
273                       insbuff.toString(), 1, 0);
274             }
275             else
276             {
277               if (es[1].length() < nw)
278               {
279                 t_alseqs[i + alseq_l] = new jalview.datamodel.Sequence(
280                         es[0],
281                         es[1] + insbuff.substring(0, nw - es[1].length()),
282                         1, 1 + es[1].length());
283               }
284               else
285               {
286                 t_alseqs[i + alseq_l] = new jalview.datamodel.Sequence(
287                         es[0], es[1]);
288               }
289             }
290           }
291           alseqs = t_alseqs;
292         }
293         AlignmentOrder msaorder = new AlignmentOrder(alseqs);
294         // always recover the order - makes parseResult()'s life easier.
295         jalview.analysis.AlignmentSorter.recoverOrder(alseqs);
296         // account for any missing sequences
297         jalview.analysis.SeqsetUtils.deuniquify(SeqNames, alseqs);
298         return new Object[] { alseqs, msaorder };
299       }
300       return null;
301     }
302
303     /**
304      * mark subjob as cancelled and set result object appropriatly
305      */
306     void cancel()
307     {
308       cancelled = true;
309       subjobComplete = true;
310       alignment = null;
311     }
312
313     /**
314      * 
315      * @return boolean true if job can be submitted.
316      */
317     @Override
318     public boolean hasValidInput()
319     {
320       // TODO: get attributes for this MsaWS instance to check if it can do two
321       // sequence alignment.
322       if (seqs != null && seqs.size() >= 2) // two or more sequences is valid ?
323       {
324         return true;
325       }
326       return false;
327     }
328
329     StringBuffer jobProgress = new StringBuffer();
330
331     public void setStatus(String string)
332     {
333       jobProgress.setLength(0);
334       jobProgress.append(string);
335     }
336
337     @Override
338     public String getStatus()
339     {
340       return jobProgress.toString();
341     }
342
343     @Override
344     public boolean hasStatus()
345     {
346       return jobProgress != null;
347     }
348
349     /**
350      * @return the lastChunk
351      */
352     public long getLastChunk()
353     {
354       return lastChunk;
355     }
356
357     /**
358      * @param lastChunk
359      *          the lastChunk to set
360      */
361     public void setLastChunk(long lastChunk)
362     {
363       this.lastChunk = lastChunk;
364     }
365
366     String alignmentProgram = null;
367
368     public String getAlignmentProgram()
369     {
370       return alignmentProgram;
371     }
372
373     public boolean hasArguments()
374     {
375       return (arguments != null && arguments.size() > 0)
376               || (preset != null && preset instanceof JabaWsParamSet);
377     }
378
379     public List<Argument> getJabaArguments()
380     {
381       List<Argument> newargs = new ArrayList<>();
382       if (preset != null && preset instanceof JabaWsParamSet)
383       {
384         newargs.addAll(((JabaWsParamSet) preset).getjabaArguments());
385       }
386       if (arguments != null && arguments.size() > 0)
387       {
388         newargs.addAll(arguments);
389       }
390       return newargs;
391     }
392
393     /**
394      * add a progess header to status string containing presets/args used
395      */
396     public void addInitialStatus()
397     {
398       if (preset != null)
399       {
400         jobProgress.append("Using "
401                 + (preset instanceof JabaPreset ? "Server" : "User")
402                 + "Preset: " + preset.getName());
403         if (preset instanceof JabaWsParamSet)
404         {
405           for (Argument opt : ((JabaWsParamSet) preset).getjabaArguments())
406           {
407             jobProgress.append(
408                     opt.getName() + " " + opt.getDefaultValue() + "\n");
409           }
410         }
411       }
412       if (arguments != null && arguments.size() > 0)
413       {
414         jobProgress.append("With custom parameters : \n");
415         // merge arguments with preset's own arguments.
416         for (Argument opt : arguments)
417         {
418           jobProgress.append(
419                   opt.getName() + " " + opt.getDefaultValue() + "\n");
420         }
421       }
422       jobProgress.append("\nJob Output:\n");
423     }
424
425     public boolean isPresetJob()
426     {
427       return preset != null && preset instanceof JabaPreset;
428     }
429
430     public Preset getServerPreset()
431     {
432       return (isPresetJob()) ? ((JabaPreset) preset).p : null;
433     }
434   }
435
436   String alTitle; // name which will be used to form new alignment window.
437
438   AlignmentI dataset; // dataset to which the new alignment will be
439
440   // associated.
441
442   @SuppressWarnings("unchecked")
443   MsaWS server = null;
444
445   /**
446    * set basic options for this (group) of Msa jobs
447    * 
448    * @param subgaps
449    *          boolean
450    * @param presorder
451    *          boolean
452    */
453   private MsaWSThread(MsaWS server, String wsUrl, WebserviceInfo wsinfo,
454           jalview.gui.AlignFrame alFrame, AlignmentView alview,
455           String wsname, boolean subgaps, boolean presorder)
456   {
457     super(alFrame, wsinfo, alview, wsname, wsUrl);
458     this.server = server;
459     this.submitGaps = subgaps;
460     this.preserveOrder = presorder;
461   }
462
463   /**
464    * create one or more Msa jobs to align visible seuqences in _msa
465    * 
466    * @param title
467    *          String
468    * @param _msa
469    *          AlignmentView
470    * @param subgaps
471    *          boolean
472    * @param presorder
473    *          boolean
474    * @param seqset
475    *          Alignment
476    */
477   MsaWSThread(MsaWS server2, WsParamSetI preset, List<Argument> paramset,
478           String wsUrl, WebserviceInfo wsinfo,
479           jalview.gui.AlignFrame alFrame, String wsname, String title,
480           AlignmentView _msa, boolean subgaps, boolean presorder,
481           AlignmentI seqset)
482   {
483     this(server2, wsUrl, wsinfo, alFrame, _msa, wsname, subgaps, presorder);
484     OutputHeader = wsInfo.getProgressText();
485     alTitle = title;
486     dataset = seqset;
487
488     SequenceI[][] conmsa = _msa.getVisibleContigs('-');
489     if (conmsa != null)
490     {
491       int nvalid = 0, njobs = conmsa.length;
492       jobs = new MsaWSJob[njobs];
493       for (int j = 0; j < njobs; j++)
494       {
495         if (j != 0)
496         {
497           jobs[j] = new MsaWSJob(wsinfo.addJobPane(), conmsa[j]);
498         }
499         else
500         {
501           jobs[j] = new MsaWSJob(0, conmsa[j]);
502         }
503         if (((MsaWSJob) jobs[j]).hasValidInput())
504         {
505           nvalid++;
506         }
507         ((MsaWSJob) jobs[j]).preset = preset;
508         ((MsaWSJob) jobs[j]).arguments = paramset;
509         ((MsaWSJob) jobs[j]).alignmentProgram = wsname;
510         if (njobs > 0)
511         {
512           wsinfo.setProgressName("region " + jobs[j].getJobnum(),
513                   jobs[j].getJobnum());
514         }
515         wsinfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
516       }
517       validInput = nvalid > 0;
518     }
519   }
520
521   boolean validInput = false;
522
523   /**
524    * 
525    * @return true if the thread will perform a calculation
526    */
527   public boolean hasValidInput()
528   {
529     return validInput;
530   }
531
532   @Override
533   public boolean isCancellable()
534   {
535     return true;
536   }
537
538   @Override
539   public void cancelJob()
540   {
541     if (!jobComplete && jobs != null)
542     {
543       boolean cancelled = true;
544       for (int job = 0; job < jobs.length; job++)
545       {
546         if (jobs[job].isSubmitted() && !jobs[job].isSubjobComplete())
547         {
548           String cancelledMessage = "";
549           try
550           {
551             boolean cancelledJob = server.cancelJob(jobs[job].getJobId());
552             if (true) // cancelledJob || true)
553             {
554               // CANCELLED_JOB
555               // if the Jaba server indicates the job can't be cancelled, its
556               // because its running on the server's local execution engine
557               // so we just close the window anyway.
558               cancelledMessage = "Job cancelled.";
559               ((MsaWSJob) jobs[job]).cancel(); // TODO: refactor to avoid this
560                                                // ugliness -
561               wsInfo.setStatus(jobs[job].getJobnum(),
562                       WebserviceInfo.STATE_CANCELLED_OK);
563             }
564             else
565             {
566               // VALID UNSTOPPABLE JOB
567               cancelledMessage += "Server cannot cancel this job. just close the window.\n";
568               cancelled = false;
569               // wsInfo.setStatus(jobs[job].jobnum,
570               // WebserviceInfo.STATE_RUNNING);
571             }
572           } catch (Exception exc)
573           {
574             cancelledMessage += ("\nProblems cancelling the job : Exception received...\n"
575                     + exc + "\n");
576             Cache.log.warn(
577                     "Exception whilst cancelling " + jobs[job].getJobId(),
578                     exc);
579           }
580           wsInfo.setProgressText(jobs[job].getJobnum(),
581                   OutputHeader + cancelledMessage + "\n");
582         }
583         else
584         {
585           // if we hadn't submitted then just mark the job as cancelled.
586           jobs[job].setSubjobComplete(true);
587           wsInfo.setStatus(jobs[job].getJobnum(),
588                   WebserviceInfo.STATE_CANCELLED_OK);
589
590         }
591       }
592       if (cancelled)
593       {
594         wsInfo.setStatus(WebserviceInfo.STATE_CANCELLED_OK);
595         jobComplete = true;
596       }
597       this.interrupt(); // kick thread to update job states.
598     }
599     else
600     {
601       if (!jobComplete)
602       {
603         wsInfo.setProgressText(OutputHeader
604                 + "Server cannot cancel this job because it has not been submitted properly. just close the window.\n");
605       }
606     }
607   }
608
609   @Override
610   public void pollJob(AWsJob job) throws Exception
611   {
612     // TODO: investigate if we still need to cast here in J1.6
613     MsaWSJob j = ((MsaWSJob) job);
614     // this is standard code, but since the interface doesn't comprise of a
615     // basic one that implements (getJobStatus, pullExecStatistics) we have to
616     // repeat the code for all jw2s services.
617     j.setjobStatus(server.getJobStatus(job.getJobId()));
618     updateJobProgress(j);
619   }
620
621   /**
622    * 
623    * @param j
624    * @return true if more job progress data was available
625    * @throws Exception
626    */
627   protected boolean updateJobProgress(MsaWSJob j) throws Exception
628   {
629     StringBuffer response = j.jobProgress;
630     long lastchunk = j.getLastChunk();
631     boolean changed = false;
632     do
633     {
634       j.setLastChunk(lastchunk);
635       ChunkHolder chunk = server.pullExecStatistics(j.getJobId(),
636               lastchunk);
637       if (chunk != null)
638       {
639         changed |= chunk.getChunk().length() > 0;
640         response.append(chunk.getChunk());
641         lastchunk = chunk.getNextPosition();
642         try
643         {
644           Thread.sleep(50);
645         } catch (InterruptedException x)
646         {
647         }
648         ;
649       }
650       ;
651     } while (lastchunk >= 0 && j.getLastChunk() != lastchunk);
652     return changed;
653   }
654
655   @Override
656   public void StartJob(AWsJob job)
657   {
658     Exception lex = null;
659     // boiler plate template
660     if (!(job instanceof MsaWSJob))
661     {
662       throw new Error(MessageManager.formatMessage(
663               "error.implementation_error_msawbjob_called", new String[]
664               { job.getClass().toString() }));
665     }
666     MsaWSJob j = (MsaWSJob) job;
667     if (j.isSubmitted())
668     {
669       if (Cache.log.isDebugEnabled())
670       {
671         Cache.log.debug(
672                 "Tried to submit an already submitted job " + j.getJobId());
673       }
674       return;
675     }
676     // end boilerplate
677
678     if (j.seqs == null || j.seqs.size() == 0)
679     {
680       // special case - selection consisted entirely of empty sequences...
681       j.setjobStatus(JobStatus.FINISHED);
682       j.setStatus(MessageManager.getString("label.empty_alignment_job"));
683     }
684     try
685     {
686       j.addInitialStatus(); // list the presets/parameters used for the job in
687                             // status
688       if (j.isPresetJob())
689       {
690         j.setJobId(server.presetAlign(j.seqs, j.getServerPreset()));
691       }
692       else if (j.hasArguments())
693       {
694         j.setJobId(server.customAlign(j.seqs, j.getJabaArguments()));
695       }
696       else
697       {
698         j.setJobId(server.align(j.seqs));
699       }
700
701       if (j.getJobId() != null)
702       {
703         j.setSubmitted(true);
704         j.setSubjobComplete(false);
705         // System.out.println(WsURL + " Job Id '" + jobId + "'");
706         return;
707       }
708       else
709       {
710         throw new Exception(MessageManager.formatMessage(
711                 "exception.web_service_returned_null_try_later",
712                 new String[]
713                 { WsUrl }));
714       }
715     } catch (compbio.metadata.UnsupportedRuntimeException _lex)
716     {
717       lex = _lex;
718       wsInfo.appendProgressText(MessageManager.formatMessage(
719               "info.job_couldnt_be_run_server_doesnt_support_program",
720               new String[]
721               { _lex.getMessage() }));
722       wsInfo.warnUser(_lex.getMessage(),
723               MessageManager.getString("warn.service_not_supported"));
724       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
725       wsInfo.setStatus(j.getJobnum(),
726               WebserviceInfo.STATE_STOPPED_SERVERERROR);
727     } catch (compbio.metadata.LimitExceededException _lex)
728     {
729       lex = _lex;
730       wsInfo.appendProgressText(MessageManager.formatMessage(
731               "info.job_couldnt_be_run_exceeded_hard_limit", new String[]
732               { _lex.getMessage() }));
733       wsInfo.warnUser(_lex.getMessage(),
734               MessageManager.getString("warn.input_is_too_big"));
735       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
736       wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
737     } catch (compbio.metadata.WrongParameterException _lex)
738     {
739       lex = _lex;
740       wsInfo.warnUser(_lex.getMessage(),
741               MessageManager.getString("warn.invalid_job_param_set"));
742       wsInfo.appendProgressText(MessageManager.formatMessage(
743               "info.job_couldnt_be_run_incorrect_param_setting",
744               new String[]
745               { _lex.getMessage() }));
746       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
747       wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
748     } catch (Error e)
749     {
750       // For unexpected errors
751       System.err.println(WebServiceName
752               + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
753               + "When contacting Server:" + WsUrl + "\n");
754       e.printStackTrace(System.err);
755       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
756       wsInfo.setStatus(j.getJobnum(),
757               WebserviceInfo.STATE_STOPPED_SERVERERROR);
758     } catch (Exception e)
759     {
760       // For unexpected errors
761       System.err.println(WebServiceName
762               + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
763               + "When contacting Server:" + WsUrl + "\n");
764       e.printStackTrace(System.err);
765       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
766       wsInfo.setStatus(j.getJobnum(),
767               WebserviceInfo.STATE_STOPPED_SERVERERROR);
768     } finally
769     {
770       if (!j.isSubmitted())
771       {
772         // Boilerplate code here
773         // TODO: JBPNote catch timeout or other fault types explicitly
774
775         j.setAllowedServerExceptions(0);
776         wsInfo.appendProgressText(j.getJobnum(), MessageManager.getString(
777                 "info.failed_to_submit_sequences_for_alignment"));
778       }
779     }
780   }
781
782   @Override
783   public void parseResult()
784   {
785     long progbar = System.currentTimeMillis();
786     wsInfo.setProgressBar(
787             MessageManager.getString("status.collecting_job_results"),
788             progbar);
789     int results = 0; // number of result sets received
790     JobStateSummary finalState = new JobStateSummary();
791     try
792     {
793       for (int j = 0; j < jobs.length; j++)
794       {
795         MsaWSJob msjob = ((MsaWSJob) jobs[j]);
796         if (jobs[j].isFinished() && msjob.alignment == null)
797         {
798           int nunchanged = 3, nexcept = 3;
799           boolean jpchanged = false, jpex = false;
800           do
801           {
802             try
803             {
804               jpchanged = updateJobProgress(msjob);
805               jpex = false;
806               if (jpchanged)
807               {
808                 nexcept = 3;
809               }
810             } catch (Exception e)
811             {
812
813               Cache.log.warn(
814                       "Exception when retrieving remaining Job progress data for job "
815                               + msjob.getJobId() + " on server " + WsUrl);
816               e.printStackTrace();
817               nexcept--;
818               nunchanged = 3;
819               // set flag remember that we've had an exception.
820               jpex = true;
821               jpchanged = false;
822             }
823             if (!jpchanged)
824             {
825               try
826               {
827                 Thread.sleep(jpex ? 2400 : 1200); // wait a bit longer if we
828                                                   // experienced an exception.
829               } catch (Exception ex)
830               {
831               }
832               ;
833               nunchanged--;
834             }
835           } while (nunchanged > 0 && nexcept > 0);
836
837           if (Cache.log.isDebugEnabled())
838           {
839             System.out.println("Job Execution file for job: "
840                     + msjob.getJobId() + " on server " + WsUrl);
841             System.out.println(msjob.getStatus());
842             System.out.println("*** End of status");
843
844           }
845           try
846           {
847             msjob.alignment = server.getResult(msjob.getJobId());
848           } catch (compbio.metadata.ResultNotAvailableException e)
849           {
850             // job has failed for some reason - probably due to invalid
851             // parameters
852             Cache.log.debug(
853                     "Results not available for finished job - marking as broken job.",
854                     e);
855             msjob.jobProgress.append(
856                     "\nResult not available. Probably due to invalid input or parameter settings. Server error message below:\n\n"
857                             + e.getLocalizedMessage());
858             msjob.setjobStatus(JobStatus.FAILED);
859           } catch (Exception e)
860           {
861             Cache.log.error("Couldn't get Alignment for job.", e);
862             // TODO: Increment count and retry ?
863             msjob.setjobStatus(JobStatus.UNDEFINED);
864           }
865         }
866         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
867         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
868                 && jobs[j].hasResults())
869         {
870           results++;
871           compbio.data.sequence.Alignment alignment = ((MsaWSJob) jobs[j]).alignment;
872           if (alignment != null)
873           {
874             // server.close(jobs[j].getJobnum());
875             // wsInfo.appendProgressText(jobs[j].getJobnum(),
876             // "\nAlignment Object Method Notes\n");
877             // wsInfo.appendProgressText(jobs[j].getJobnum(),
878             // "Calculated with
879             // "+alignment.getMetadata().getProgram().toString());
880             // JBPNote The returned files from a webservice could be
881             // hidden behind icons in the monitor window that,
882             // when clicked, pop up their corresponding data
883           }
884         }
885       }
886     } catch (Exception ex)
887     {
888
889       Cache.log.error(
890               "Unexpected exception when processing results for " + alTitle,
891               ex);
892       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
893     }
894     if (results > 0)
895     {
896       wsInfo.showResultsNewFrame
897               .addActionListener(new java.awt.event.ActionListener()
898               {
899                 @Override
900                 public void actionPerformed(java.awt.event.ActionEvent evt)
901                 {
902                   displayResults(true);
903                 }
904               });
905       wsInfo.mergeResults
906               .addActionListener(new java.awt.event.ActionListener()
907               {
908                 @Override
909                 public void actionPerformed(java.awt.event.ActionEvent evt)
910                 {
911                   displayResults(false);
912                 }
913               });
914       wsInfo.setResultsReady();
915     }
916     else
917     {
918       wsInfo.setFinishedNoResults();
919     }
920     updateGlobalStatus(finalState);
921     wsInfo.setProgressBar(null, progbar);
922   }
923
924   /**
925    * Display alignment results in a new frame (or - not currently supported -
926    * added to an existing alignment).
927    * 
928    * @param newFrame
929    */
930   void displayResults(boolean newFrame)
931   {
932     // view input or result data for each block
933     List<AlignmentOrder> alorders = new ArrayList<>();
934     SequenceI[][] results = new SequenceI[jobs.length][];
935     AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
936     String lastProgram = null;
937     MsaWSJob msjob;
938     for (int j = 0; j < jobs.length; j++)
939     {
940       if (jobs[j].hasResults())
941       {
942         msjob = (MsaWSJob) jobs[j];
943         Object[] res = msjob.getAlignment();
944         lastProgram = msjob.getAlignmentProgram();
945         alorders.add((AlignmentOrder) res[1]);
946         results[j] = (SequenceI[]) res[0];
947         orders[j] = (AlignmentOrder) res[1];
948
949         // SequenceI[] alignment = input.getUpdated
950       }
951       else
952       {
953         results[j] = null;
954       }
955     }
956     Object[] newview = input.getUpdatedView(results, orders, getGapChar());
957     // trash references to original result data
958     for (int j = 0; j < jobs.length; j++)
959     {
960       results[j] = null;
961       orders[j] = null;
962     }
963     SequenceI[] alignment = (SequenceI[]) newview[0];
964     HiddenColumns hidden = (HiddenColumns) newview[1];
965     Alignment al = new Alignment(alignment);
966     // TODO: add 'provenance' property to alignment from the method notes
967     if (lastProgram != null)
968     {
969       al.setProperty("Alignment Program", lastProgram);
970     }
971     // accompanying each subjob
972     if (dataset != null)
973     {
974       al.setDataset(dataset);
975     }
976
977     propagateDatasetMappings(al);
978     // JBNote- TODO: warn user if a block is input rather than aligned data ?
979
980     if (newFrame)
981     {
982       displayInNewFrame(al, alorders, hidden);
983     }
984     else
985     {
986       // TODO 2.9.x feature
987       System.out.println("MERGE WITH OLD FRAME");
988       // TODO: modify alignment in original frame, replacing old for new
989       // alignment using the commands.EditCommand model to ensure the update can
990       // be undone
991     }
992   }
993
994   /**
995    * Display the alignment result in a new frame.
996    * 
997    * @param al
998    * @param alorders
999    * @param columnselection
1000    */
1001   protected void displayInNewFrame(AlignmentI al,
1002           List<AlignmentOrder> alorders, HiddenColumns hidden)
1003   {
1004     AlignFrame af = new AlignFrame(al, hidden, AlignFrame.DEFAULT_WIDTH,
1005             AlignFrame.DEFAULT_HEIGHT);
1006
1007     // initialise with same renderer settings as in parent alignframe.
1008     af.getFeatureRenderer().transferSettings(this.featureSettings);
1009
1010     if (alorders.size() > 0)
1011     {
1012       addSortByMenuItems(af, alorders);
1013     }
1014
1015     // TODO: refactor retrieve and show as new splitFrame as Desktop method
1016
1017     /*
1018      * If alignment was requested from one half of a SplitFrame, show in a
1019      * SplitFrame with the other pane similarly aligned.
1020      */
1021     AlignFrame requestedBy = getRequestingAlignFrame();
1022     if (requestedBy != null && requestedBy.getSplitViewContainer() != null
1023             && requestedBy.getSplitViewContainer()
1024                     .getComplement(requestedBy) != null)
1025     {
1026       AlignmentI complement = requestedBy.getSplitViewContainer()
1027               .getComplement(requestedBy);
1028       String complementTitle = requestedBy.getSplitViewContainer()
1029               .getComplementTitle(requestedBy);
1030       // becomes null if the alignment window was closed before the alignment
1031       // job finished.
1032       AlignmentI copyComplement = new Alignment(complement);
1033       // todo should this be done by copy constructor?
1034       copyComplement.setGapCharacter(complement.getGapCharacter());
1035       // share the same dataset (and the mappings it holds)
1036       copyComplement.setDataset(complement.getDataset());
1037       copyComplement.alignAs(al);
1038       if (copyComplement.getHeight() > 0)
1039       {
1040         af.setTitle(alTitle);
1041         AlignFrame af2 = new AlignFrame(copyComplement,
1042                 AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
1043         af2.setTitle(complementTitle);
1044         String linkedTitle = MessageManager
1045                 .getString("label.linked_view_title");
1046         JInternalFrame splitFrame = new SplitFrame(
1047                 al.isNucleotide() ? af : af2, al.isNucleotide() ? af2 : af);
1048         Desktop.addInternalFrame(splitFrame, linkedTitle, -1, -1);
1049         return;
1050       }
1051     }
1052
1053     /*
1054      * Not from SplitFrame, or failed to created a complementary alignment
1055      */
1056     Desktop.addInternalFrame(af, alTitle, AlignFrame.DEFAULT_WIDTH,
1057             AlignFrame.DEFAULT_HEIGHT);
1058   }
1059
1060   /**
1061    * Add sort order options to the AlignFrame menus.
1062    * 
1063    * @param af
1064    * @param alorders
1065    */
1066   protected void addSortByMenuItems(AlignFrame af,
1067           List<AlignmentOrder> alorders)
1068   {
1069     // update orders
1070     if (alorders.size() == 1)
1071     {
1072       af.addSortByOrderMenuItem(WebServiceName + " Ordering",
1073               alorders.get(0));
1074     }
1075     else
1076     {
1077       // construct a non-redundant ordering set
1078       List<String> names = new ArrayList<>();
1079       for (int i = 0, l = alorders.size(); i < l; i++)
1080       {
1081         String orderName = " Region " + i;
1082         int j = i + 1;
1083
1084         while (j < l)
1085         {
1086           if (alorders.get(i).equals(alorders.get(j)))
1087           {
1088             alorders.remove(j);
1089             l--;
1090             orderName += "," + j;
1091           }
1092           else
1093           {
1094             j++;
1095           }
1096         }
1097
1098         if (i == 0 && j == 1)
1099         {
1100           names.add("");
1101         }
1102         else
1103         {
1104           names.add(orderName);
1105         }
1106       }
1107       for (int i = 0, l = alorders.size(); i < l; i++)
1108       {
1109         af.addSortByOrderMenuItem(
1110                 WebServiceName + (names.get(i)) + " Ordering",
1111                 alorders.get(i));
1112       }
1113     }
1114   }
1115
1116   @Override
1117   public boolean canMergeResults()
1118   {
1119     return false;
1120   }
1121 }