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