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