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