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