formatting
[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 (true) // 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         try
601         {
602           Thread.sleep(50);
603         } catch (InterruptedException x)
604         {
605         }
606         ;
607       }
608       ;
609     } while (lastchunk >= 0 && j.getLastChunk() != lastchunk);
610     return changed;
611   }
612
613   public void StartJob(AWsJob job)
614   {
615     Exception lex = null;
616     // boiler plate template
617     if (!(job instanceof MsaWSJob))
618     {
619       throw new Error("StartJob(MsaWSJob) called on a WSJobInstance "
620               + job.getClass());
621     }
622     MsaWSJob j = (MsaWSJob) job;
623     if (j.isSubmitted())
624     {
625       if (Cache.log.isDebugEnabled())
626       {
627         Cache.log.debug("Tried to submit an already submitted job "
628                 + j.getJobId());
629       }
630       return;
631     }
632     // end boilerplate
633
634     if (j.seqs == null || j.seqs.size() == 0)
635     {
636       // special case - selection consisted entirely of empty sequences...
637       j.setjobStatus(JobStatus.FINISHED);
638       j.setStatus("Empty Alignment Job");
639     }
640     try
641     {
642       j.addInitialStatus(); // list the presets/parameters used for the job in
643                             // status
644       if (j.isPresetJob())
645       {
646         j.setJobId(server.presetAlign(j.seqs, j.getServerPreset()));
647       }
648       else if (j.hasArguments())
649       {
650         j.setJobId(server.customAlign(j.seqs, j.getJabaArguments()));
651       }
652       else
653       {
654         j.setJobId(server.align(j.seqs));
655       }
656
657       if (j.getJobId() != null)
658       {
659         j.setSubmitted(true);
660         j.setSubjobComplete(false);
661         // System.out.println(WsURL + " Job Id '" + jobId + "'");
662         return;
663       }
664       else
665       {
666         throw new Exception(
667                 "Server at "
668                         + WsUrl
669                         + " returned null string for job id, it probably cannot be contacted. Try again later ?");
670       }
671     } catch (compbio.metadata.UnsupportedRuntimeException _lex)
672     {
673       lex = _lex;
674       wsInfo.appendProgressText("Job could not be run because the server doesn't support this program.\n"
675               + _lex.getMessage());
676       wsInfo.warnUser(_lex.getMessage(), "Service not supported!");
677       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
678       wsInfo.setStatus(j.getJobnum(),
679               WebserviceInfo.STATE_STOPPED_SERVERERROR);
680     } catch (compbio.metadata.LimitExceededException _lex)
681     {
682       lex = _lex;
683       wsInfo.appendProgressText("Job could not be run because it exceeded a hard limit on the server.\n"
684               + _lex.getMessage());
685       wsInfo.warnUser(_lex.getMessage(), "Input is too big!");
686       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
687       wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
688     } catch (compbio.metadata.WrongParameterException _lex)
689     {
690       lex = _lex;
691       wsInfo.warnUser(_lex.getMessage(), "Invalid job parameter set!");
692       wsInfo.appendProgressText("Job could not be run because some of the parameter settings are not supported by the server.\n"
693               + _lex.getMessage()
694               + "\nPlease check to make sure you have used the correct parameter set for this service!\n");
695       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
696       wsInfo.setStatus(j.getJobnum(), WebserviceInfo.STATE_STOPPED_ERROR);
697     } catch (Error e)
698     {
699       // For unexpected errors
700       System.err
701               .println(WebServiceName
702                       + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
703                       + "When contacting Server:" + WsUrl + "\n");
704       e.printStackTrace(System.err);
705       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
706       wsInfo.setStatus(j.getJobnum(),
707               WebserviceInfo.STATE_STOPPED_SERVERERROR);
708     } catch (Exception e)
709     {
710       // For unexpected errors
711       System.err
712               .println(WebServiceName
713                       + "Client: Failed to submit the sequences for alignment (probably a server side problem)\n"
714                       + "When contacting Server:" + WsUrl + "\n");
715       e.printStackTrace(System.err);
716       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_SERVERERROR);
717       wsInfo.setStatus(j.getJobnum(),
718               WebserviceInfo.STATE_STOPPED_SERVERERROR);
719     } finally
720     {
721       if (!j.isSubmitted())
722       {
723         // Boilerplate code here
724         // TODO: JBPNote catch timeout or other fault types explicitly
725
726         j.setAllowedServerExceptions(0);
727         wsInfo.appendProgressText(j.getJobnum(),
728                 "Failed to submit sequences for alignment.\n"
729                         + "Just close the window\n");
730       }
731     }
732   }
733
734   public void parseResult()
735   {
736     long progbar = System.currentTimeMillis();
737     wsInfo.setProgressBar("Collecting job results.", progbar);
738     int results = 0; // number of result sets received
739     JobStateSummary finalState = new JobStateSummary();
740     try
741     {
742       for (int j = 0; j < jobs.length; j++)
743       {
744         MsaWSJob msjob = ((MsaWSJob) jobs[j]);
745         if (jobs[j].isFinished() && msjob.alignment == null)
746         {
747           int nunchanged = 3, nexcept = 3;
748           boolean jpchanged = false, jpex = false;
749           do
750           {
751             try
752             {
753               jpchanged = updateJobProgress(msjob);
754               jpex = false;
755               if (jpchanged)
756               {
757                 nexcept = 3;
758               }
759             } catch (Exception e)
760             {
761
762               Cache.log
763                       .warn("Exception when retrieving remaining Job progress data for job "
764                               + msjob.getJobId() + " on server " + WsUrl);
765               e.printStackTrace();
766               nexcept--;
767               nunchanged = 3;
768               // set flag remember that we've had an exception.
769               jpex = true;
770               jpchanged = false;
771             }
772             if (!jpchanged)
773             {
774               try
775               {
776                 Thread.sleep(jpex ? 2400 : 1200); // wait a bit longer if we
777                                                   // experienced an exception.
778               } catch (Exception ex)
779               {
780               }
781               ;
782               nunchanged--;
783             }
784           } while (nunchanged > 0 && nexcept > 0);
785
786           if (Cache.log.isDebugEnabled())
787           {
788             System.out.println("Job Execution file for job: "
789                     + msjob.getJobId() + " on server " + WsUrl);
790             System.out.println(msjob.getStatus());
791             System.out.println("*** End of status");
792
793           }
794           try
795           {
796             msjob.alignment = server.getResult(msjob.getJobId());
797           } catch (compbio.metadata.ResultNotAvailableException e)
798           {
799             // job has failed for some reason - probably due to invalid
800             // parameters
801             Cache.log
802                     .debug("Results not available for finished job - marking as broken job.",
803                             e);
804             msjob.jobProgress
805                     .append("\nResult not available. Probably due to invalid input or parameter settings. Server error message below:\n\n"
806                             + e.getLocalizedMessage());
807             msjob.setjobStatus(JobStatus.FAILED);
808           } catch (Exception e)
809           {
810             Cache.log.error("Couldn't get Alignment for job.", e);
811             // TODO: Increment count and retry ?
812             msjob.setjobStatus(JobStatus.UNDEFINED);
813           }
814         }
815         finalState.updateJobPanelState(wsInfo, OutputHeader, jobs[j]);
816         if (jobs[j].isSubmitted() && jobs[j].isSubjobComplete()
817                 && jobs[j].hasResults())
818         {
819           results++;
820           compbio.data.sequence.Alignment alignment = ((MsaWSJob) jobs[j]).alignment;
821           if (alignment != null)
822           {
823             // server.close(jobs[j].getJobnum());
824             // wsInfo.appendProgressText(jobs[j].getJobnum(),
825             // "\nAlignment Object Method Notes\n");
826             // wsInfo.appendProgressText(jobs[j].getJobnum(),
827             // "Calculated with "+alignment.getMetadata().getProgram().toString());
828             // JBPNote The returned files from a webservice could be
829             // hidden behind icons in the monitor window that,
830             // when clicked, pop up their corresponding data
831           }
832         }
833       }
834     } catch (Exception ex)
835     {
836
837       Cache.log.error("Unexpected exception when processing results for "
838               + alTitle, ex);
839       wsInfo.setStatus(WebserviceInfo.STATE_STOPPED_ERROR);
840     }
841     if (results > 0)
842     {
843       wsInfo.showResultsNewFrame
844               .addActionListener(new java.awt.event.ActionListener()
845               {
846                 public void actionPerformed(java.awt.event.ActionEvent evt)
847                 {
848                   displayResults(true);
849                 }
850               });
851       wsInfo.mergeResults
852               .addActionListener(new java.awt.event.ActionListener()
853               {
854                 public void actionPerformed(java.awt.event.ActionEvent evt)
855                 {
856                   displayResults(false);
857                 }
858               });
859       wsInfo.setResultsReady();
860     }
861     else
862     {
863       wsInfo.setFinishedNoResults();
864     }
865     updateGlobalStatus(finalState);
866     wsInfo.setProgressBar(null, progbar);
867   }
868
869   void displayResults(boolean newFrame)
870   {
871     // view input or result data for each block
872     Vector alorders = new Vector();
873     SequenceI[][] results = new SequenceI[jobs.length][];
874     AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
875     String lastProgram = null;
876     MsaWSJob msjob;
877     for (int j = 0; j < jobs.length; j++)
878     {
879       if (jobs[j].hasResults())
880       {
881         msjob = (MsaWSJob) jobs[j];
882         Object[] res = msjob.getAlignment();
883         lastProgram = msjob.getAlignmentProgram();
884         alorders.add(res[1]);
885         results[j] = (SequenceI[]) res[0];
886         orders[j] = (AlignmentOrder) res[1];
887
888         // SequenceI[] alignment = input.getUpdated
889       }
890       else
891       {
892         results[j] = null;
893       }
894     }
895     Object[] newview = input.getUpdatedView(results, orders, getGapChar());
896     // trash references to original result data
897     for (int j = 0; j < jobs.length; j++)
898     {
899       results[j] = null;
900       orders[j] = null;
901     }
902     SequenceI[] alignment = (SequenceI[]) newview[0];
903     ColumnSelection columnselection = (ColumnSelection) newview[1];
904     Alignment al = new Alignment(alignment);
905     // TODO: add 'provenance' property to alignment from the method notes
906     if (lastProgram != null)
907     {
908       al.setProperty("Alignment Program", lastProgram);
909     }
910     // accompanying each subjob
911     if (dataset != null)
912     {
913       al.setDataset(dataset);
914     }
915
916     propagateDatasetMappings(al);
917     // JBNote- TODO: warn user if a block is input rather than aligned data ?
918
919     if (newFrame)
920     {
921       AlignFrame af = new AlignFrame(al, columnselection,
922               AlignFrame.DEFAULT_WIDTH, AlignFrame.DEFAULT_HEIGHT);
923
924       // initialise with same renderer settings as in parent alignframe.
925       af.getFeatureRenderer().transferSettings(this.featureSettings);
926       // update orders
927       if (alorders.size() > 0)
928       {
929         if (alorders.size() == 1)
930         {
931           af.addSortByOrderMenuItem(WebServiceName + " Ordering",
932                   (AlignmentOrder) alorders.get(0));
933         }
934         else
935         {
936           // construct a non-redundant ordering set
937           Vector names = new Vector();
938           for (int i = 0, l = alorders.size(); i < l; i++)
939           {
940             String orderName = new String(" Region " + i);
941             int j = i + 1;
942
943             while (j < l)
944             {
945               if (((AlignmentOrder) alorders.get(i))
946                       .equals(((AlignmentOrder) alorders.get(j))))
947               {
948                 alorders.remove(j);
949                 l--;
950                 orderName += "," + j;
951               }
952               else
953               {
954                 j++;
955               }
956             }
957
958             if (i == 0 && j == 1)
959             {
960               names.add(new String(""));
961             }
962             else
963             {
964               names.add(orderName);
965             }
966           }
967           for (int i = 0, l = alorders.size(); i < l; i++)
968           {
969             af.addSortByOrderMenuItem(
970                     WebServiceName + ((String) names.get(i)) + " Ordering",
971                     (AlignmentOrder) alorders.get(i));
972           }
973         }
974       }
975
976       Desktop.addInternalFrame(af, alTitle, AlignFrame.DEFAULT_WIDTH,
977               AlignFrame.DEFAULT_HEIGHT);
978
979     }
980     else
981     {
982       System.out.println("MERGE WITH OLD FRAME");
983       // TODO: modify alignment in original frame, replacing old for new
984       // alignment using the commands.EditCommand model to ensure the update can
985       // be undone
986     }
987   }
988
989   public boolean canMergeResults()
990   {
991     return false;
992   }
993 }