Merge commit 'alpha/update_2_12_for_2_11_2_series_merge^2' into HEAD
[jalview.git] / src / jalview / ws / rest / RestJobThread.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.ws.rest;
22
23 import java.util.Locale;
24
25 import jalview.bin.Cache;
26 import jalview.datamodel.Alignment;
27 import jalview.datamodel.AlignmentAnnotation;
28 import jalview.datamodel.AlignmentI;
29 import jalview.datamodel.AlignmentOrder;
30 import jalview.datamodel.Annotation;
31 import jalview.datamodel.HiddenColumns;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.gui.AlignFrame;
35 import jalview.gui.Desktop;
36 import jalview.gui.PaintRefresher;
37 import jalview.gui.WebserviceInfo;
38 import jalview.io.NewickFile;
39 import jalview.io.packed.JalviewDataset;
40 import jalview.io.packed.JalviewDataset.AlignmentSet;
41 import jalview.util.MessageManager;
42 import jalview.ws.AWSThread;
43 import jalview.ws.AWsJob;
44
45 import java.awt.event.ActionEvent;
46 import java.awt.event.ActionListener;
47 import java.io.IOException;
48 import java.util.ArrayList;
49 import java.util.Hashtable;
50 import java.util.List;
51 import java.util.Map.Entry;
52
53 import org.apache.axis.transport.http.HTTPConstants;
54 import org.apache.http.Header;
55 import org.apache.http.HttpEntity;
56 import org.apache.http.HttpResponse;
57 import org.apache.http.client.ClientProtocolException;
58 import org.apache.http.client.methods.HttpGet;
59 import org.apache.http.client.methods.HttpPost;
60 import org.apache.http.client.methods.HttpRequestBase;
61 import org.apache.http.entity.mime.HttpMultipartMode;
62 import org.apache.http.entity.mime.MultipartEntity;
63 import org.apache.http.impl.client.DefaultHttpClient;
64 import org.apache.http.util.EntityUtils;
65
66 public class RestJobThread extends AWSThread
67 {
68   enum Stage
69   {
70     SUBMIT, POLL
71   }
72
73   protected RestClient restClient;
74
75   public RestJobThread(RestClient restClient)
76   {
77     super(restClient.af, null, restClient._input,
78             restClient.service.postUrl);
79     this.restClient = restClient; // may not be needed
80     // Test Code
81     // minimal job - submit given input and parse result onto alignment as
82     // annotation/whatever
83
84     // look for tree data, etc.
85
86     // for moment do following job type only
87     // input=visiblealignment,groupsindex
88     // ie one subjob using groups defined on alignment.
89     if (!restClient.service.isHseparable())
90     {
91       jobs = new RestJob[1];
92       jobs[0] = new RestJob(0, this,
93               restClient._input.getVisibleAlignment(
94                       restClient.service.getGapCharacter()),
95               restClient._input.getVisibleContigs());
96       // need a function to get a range on a view/alignment and return both
97       // annotation, groups and selection subsetted to just that region.
98
99     }
100     else
101     {
102       int[] viscontig = restClient._input.getVisibleContigs();
103       AlignmentI[] viscontigals = restClient._input
104               .getVisibleContigAlignments(
105                       restClient.service.getGapCharacter());
106       if (viscontigals != null && viscontigals.length > 0)
107       {
108         jobs = new RestJob[viscontigals.length];
109         for (int j = 0; j < jobs.length; j++)
110         {
111           int[] visc = new int[] { viscontig[j * 2], viscontig[j * 2 + 1] };
112           if (j != 0)
113           {
114             jobs[j] = new RestJob(j, this, viscontigals[j], visc);
115           }
116           else
117           {
118             jobs[j] = new RestJob(0, this, viscontigals[j], visc);
119           }
120         }
121       }
122     }
123     // end Test Code
124     /**
125      * subjob types row based: per sequence in alignment/selected region { input
126      * is one sequence or sequence ID } per alignment/selected region { input is
127      * set of sequences, alignment, one or more sets of sequence IDs,
128      */
129
130     if (!restClient.service.isHseparable())
131     {
132
133       // create a bunch of subjobs per visible contig to ensure result honours
134       // hidden boundaries
135       // TODO: determine if a 'soft' hSeperable property is needed - e.g. if
136       // user does SS-pred on sequence with big hidden regions, its going to be
137       // less reliable.
138     }
139     else
140     {
141       // create a single subjob for the visible/selected input
142
143     }
144     // TODO: decide if vSeperable exists: eg. column wide analysis where hidden
145     // rows do not affect output - generally no analysis that generates
146     // alignment annotation is vSeparable -
147   }
148
149   /**
150    * create gui components for monitoring jobs
151    * 
152    * @param webserviceInfo
153    */
154   public void setWebServiceInfo(WebserviceInfo webserviceInfo)
155   {
156     wsInfo = webserviceInfo;
157     for (int j = 0; j < jobs.length; j++)
158     {
159       wsInfo.addJobPane();
160       // Copy over any per job params
161       if (jobs.length > 1)
162       {
163         wsInfo.setProgressName("region " + jobs[j].getJobnum(),
164                 jobs[j].getJobnum());
165       }
166       else
167       {
168         wsInfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
169       }
170     }
171   }
172
173   private String getStage(Stage stg)
174   {
175     if (stg == Stage.SUBMIT)
176     {
177       return "submitting ";
178     }
179     if (stg == Stage.POLL)
180     {
181       return "checking status of ";
182     }
183
184     return (" being confused about ");
185   }
186
187   private void doPoll(RestJob rj) throws Exception
188   {
189     String postUrl = rj.getPollUrl();
190     doHttpReq(Stage.POLL, rj, postUrl);
191   }
192
193   /**
194    * construct the post and handle the response.
195    * 
196    * @throws Exception
197    */
198   public void doPost(RestJob rj) throws Exception
199   {
200     String postUrl = rj.getPostUrl();
201     doHttpReq(Stage.SUBMIT, rj, postUrl);
202     wsInfo.invalidate();
203   }
204
205   /**
206    * do the HTTP request - and respond/set statuses appropriate to the current
207    * stage.
208    * 
209    * @param stg
210    * @param rj
211    *          - provides any data needed for posting and used to record state
212    * @param postUrl
213    *          - actual URL to post/get from
214    * @throws Exception
215    */
216   protected void doHttpReq(Stage stg, RestJob rj, String postUrl)
217           throws Exception
218   {
219     HttpRequestBase request = null;
220     String messages = "";
221     if (stg == Stage.SUBMIT)
222     {
223       // Got this from
224       // http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache/
225
226       HttpPost htpost = new HttpPost(postUrl);
227       MultipartEntity postentity = new MultipartEntity(
228               HttpMultipartMode.STRICT);
229       for (Entry<String, InputType> input : rj.getInputParams())
230       {
231         if (input.getValue().validFor(rj))
232         {
233           postentity.addPart(input.getKey(),
234                   input.getValue().formatForInput(rj));
235         }
236         else
237         {
238           messages += "Skipped an input (" + input.getKey()
239                   + ") - Couldn't generate it from available data.";
240         }
241       }
242       htpost.setEntity(postentity);
243       request = htpost;
244     }
245     else
246     {
247       request = new HttpGet(postUrl);
248     }
249     if (request != null)
250     {
251       DefaultHttpClient httpclient = new DefaultHttpClient();
252
253       HttpResponse response = null;
254       try
255       {
256         response = httpclient.execute(request);
257       } catch (ClientProtocolException he)
258       {
259         rj.statMessage = "Web Protocol Exception when " + getStage(stg)
260                 + "Job. <br>Problematic url was <a href=\""
261                 + request.getURI() + "\">" + request.getURI()
262                 + "</a><br>See Console output for details.";
263         rj.setAllowedServerExceptions(0);// unrecoverable;
264         rj.error = true;
265         Cache.log.fatal("Unexpected REST Job " + getStage(stg)
266                 + "exception for URL " + rj.rsd.postUrl);
267         throw (he);
268       } catch (IOException e)
269       {
270         rj.statMessage = "IO Exception when " + getStage(stg)
271                 + "Job. <br>Problematic url was <a href=\""
272                 + request.getURI() + "\">" + request.getURI()
273                 + "</a><br>See Console output for details.";
274         Cache.log.warn("IO Exception for REST Job " + getStage(stg)
275                 + "exception for URL " + rj.rsd.postUrl);
276
277         throw (e);
278       }
279       switch (response.getStatusLine().getStatusCode())
280       {
281       case 200:
282         rj.running = false;
283         Cache.log.debug("Processing result set.");
284         processResultSet(rj, response, request);
285         break;
286
287       case 202:
288         markJobAsRunning(rj);
289         break;
290
291       case 201:
292         // Created - redirect may be present. Fallthrough to 302
293       case 302:
294         extractJobId(rj, response);
295         completeStatus(rj, response);
296         break;
297       case 500:
298         markAsFailed(rj, response);
299         completeStatus(rj, response, "" + getStage(stg)
300                 + "failed. Reason below:\n");
301         break;
302       default:
303         // Some other response. Probably need to pop up the content in a window.
304         // TODO: deal with all other HTTP response codes from server.
305         Cache.log.warn("Unhandled response status when " + getStage(stg)
306                 + "for " + postUrl + ": " + response.getStatusLine());
307         rj.error = true;
308         rj.setAllowedServerExceptions(0);
309         rj.setSubjobComplete(true);
310         rj.setSubmitted(true);
311         try
312         {
313           completeStatus(rj, response, "" + getStage(stg)
314                   + " resulted in an unexpected server response.<br/>Url concerned was <a href=\""
315                   + request.getURI() + "\">" + request.getURI()
316                   + "</a><br/>Filtered response content below:<br/>");
317         } catch (IOException e)
318         {
319           Cache.log.debug("IOException when consuming unhandled response",
320                   e);
321         }
322         ;
323       }
324     }
325   }
326
327   private void markAsFailed(RestJob rj, HttpResponse response)
328   {
329     // Failed.
330     rj.setSubmitted(true);
331     rj.setAllowedServerExceptions(0);
332     rj.setSubjobComplete(true);
333     rj.error = true;
334     rj.running = false;
335   }
336
337   /**
338    * set the jobRunning flag and post a link to the physical result page encoded
339    * in rj.getJobId()
340    * 
341    * @param rj
342    */
343   private void markJobAsRunning(RestJob rj)
344   {
345     rj.statMessage = "<br>Job submitted successfully. Results available at this URL:\n"
346             + "<a href="
347             + rj.getJobId()
348             + "\">"
349             + rj.getJobId()
350             + "</a><br>";
351     rj.running = true;
352   }
353
354   /**
355    * extract the job ID URL from the redirect page. Does nothing if job is
356    * already running.
357    * 
358    * @param rj
359    * @param response
360    */
361   private void extractJobId(RestJob rj, HttpResponse response)
362   {
363     Header[] loc;
364     if (!rj.isSubmitted())
365     {
366
367       // redirect URL - typical for IBIVU type jobs.
368       if ((loc = response.getHeaders(HTTPConstants.HEADER_LOCATION)) != null
369               && loc.length > 0)
370       {
371         if (loc.length > 1)
372         {
373           Cache.log
374                   .warn("Ignoring additional "
375                           + (loc.length - 1)
376                           + " location(s) provided in response header ( next one is '"
377                           + loc[1].getValue() + "' )");
378         }
379         rj.setJobId(loc[0].getValue());
380         rj.setSubmitted(true);
381       }
382     }
383   }
384
385   /**
386    * job has completed. Something valid should be available from con
387    * 
388    * @param rj
389    * @param con
390    * @param req
391    *          is a stateless request - expected to return the same data
392    *          regardless of how many times its called.
393    */
394   private void processResultSet(RestJob rj, HttpResponse con,
395           HttpRequestBase req)
396   {
397     if (rj.statMessage == null)
398     {
399       rj.statMessage = "";
400     }
401     rj.statMessage += "Job Complete.\n";
402     try
403     {
404       rj.resSet = new HttpResultSet(rj, con, req);
405       rj.gotresult = true;
406     } catch (IOException e)
407     {
408       rj.statMessage += "Couldn't parse results. Failed.";
409       rj.error = true;
410       rj.gotresult = false;
411     }
412   }
413
414   private void completeStatus(RestJob rj, HttpResponse con)
415           throws IOException
416   {
417     completeStatus(rj, con, null);
418
419   }
420
421   private void completeStatus(RestJob rj, HttpResponse con, String prefix)
422           throws IOException
423   {
424     StringBuffer sb = new StringBuffer();
425     if (prefix != null)
426     {
427       sb.append(prefix);
428     }
429     ;
430     if (rj.statMessage != null && rj.statMessage.length() > 0)
431     {
432       sb.append(rj.statMessage);
433     }
434     HttpEntity en = con.getEntity();
435     /*
436      * Just append the content as a string.
437      */
438     String f;
439     StringBuffer content = new StringBuffer(f = EntityUtils.toString(en));
440     f = f.toLowerCase(Locale.ROOT);
441     int body = f.indexOf("<body");
442     if (body > -1)
443     {
444       content.delete(0, f.indexOf(">", body) + 1);
445     }
446     if (body > -1 && sb.length() > 0)
447     {
448       sb.append("\n");
449       content.insert(0, sb);
450       sb = null;
451     }
452     f = null;
453     rj.statMessage = content.toString();
454   }
455
456   @Override
457   public void pollJob(AWsJob job) throws Exception
458   {
459     assert (job instanceof RestJob);
460     System.err.println("Debug RestJob: Polling Job");
461     doPoll((RestJob) job);
462   }
463
464   @Override
465   public void StartJob(AWsJob job)
466   {
467     assert (job instanceof RestJob);
468     try
469     {
470       System.err.println("Debug RestJob: Posting Job");
471       doPost((RestJob) job);
472     } catch (NoValidInputDataException erex)
473     {
474       job.setSubjobComplete(true);
475       job.setSubmitted(true);
476       ((RestJob) job).statMessage = "<br>It looks like there was a problem with the data sent to the service :<br>"
477               + erex.getMessage() + "\n";
478       ((RestJob) job).error = true;
479
480     } catch (Exception ex)
481     {
482       job.setSubjobComplete(true);
483       job.setAllowedServerExceptions(-1);
484       Cache.log.error("Exception when trying to start Rest Job.", ex);
485     }
486   }
487
488   @Override
489   public void parseResult()
490   {
491     // crazy users will see this message
492     // TODO: finish this! and remove the message below!
493     Cache.log.warn("Rest job result parser is currently INCOMPLETE!");
494     int validres = 0;
495     for (RestJob rj : (RestJob[]) jobs)
496     {
497       if (rj.hasResponse() && rj.resSet != null && rj.resSet.isValid())
498       {
499         String ln = null;
500         try
501         {
502           Cache.log.debug("Parsing data for job " + rj.getJobId());
503           rj.parseResultSet();
504           if (rj.hasResults())
505           {
506             validres++;
507           }
508           Cache.log.debug("Finished parsing data for job " + rj.getJobId());
509
510         } catch (Error ex)
511         {
512           Cache.log.warn(
513                   "Failed to finish parsing data for job " + rj.getJobId());
514           ex.printStackTrace();
515         } catch (Exception ex)
516         {
517           Cache.log.warn(
518                   "Failed to finish parsing data for job " + rj.getJobId());
519           ex.printStackTrace();
520         } finally
521         {
522           rj.error = true;
523           rj.statMessage = "Error whilst parsing data for this job.<br>URL for job response is :<a href=\""
524                   + rj.resSet.getUrl() + "\">" + rj.resSet.getUrl()
525                   + "</a><br>";
526         }
527       }
528     }
529     if (validres > 0)
530     {
531       // add listeners and activate result display gui elements
532       /**
533        * decisions based on job result content + state of alignFrame that
534        * originated the job:
535        */
536       /*
537        * 1. Can/Should this job automatically open a new window for results
538        */
539       if (true)
540       {
541         // preserver current jalview behaviour
542         wsInfo.setViewResultsImmediatly(true);
543       }
544       else
545       {
546         // realiseResults(true, true);
547       }
548       // otherwise, should automatically view results
549
550       // TODO: check if at least one or more contexts are valid - if so, enable
551       // gui
552       wsInfo.showResultsNewFrame.addActionListener(new ActionListener()
553       {
554
555         @Override
556         public void actionPerformed(ActionEvent e)
557         {
558           realiseResults(false);
559         }
560
561       });
562       wsInfo.mergeResults.addActionListener(new ActionListener()
563       {
564
565         @Override
566         public void actionPerformed(ActionEvent e)
567         {
568           realiseResults(true);
569         }
570
571       });
572
573       wsInfo.setResultsReady();
574     }
575     else
576     {
577       // tell the user nothing was returned.
578       wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
579       wsInfo.setFinishedNoResults();
580     }
581   }
582
583   /**
584    * instructions for whether to create new alignment view on current alignment
585    * set, add to current set, or create new alignFrame
586    */
587   private enum AddDataTo
588   {
589     /**
590      * add annotation, trees etc to current view
591      */
592     currentView,
593     /**
594      * create a new view derived from current view and add data to that
595      */
596     newView,
597     /**
598      * create a new alignment frame for the result set and add annotation to
599      * that.
600      */
601     newAlignment
602   };
603
604   public void realiseResults(boolean merge)
605   {
606     /*
607      * 2. Should the job modify the parent alignment frame/view(s) (if they
608      * still exist and the alignment hasn't been edited) in order to display new
609      * annotation/features.
610      */
611     /**
612      * alignment panels derived from each alignment set returned by service.
613      */
614     ArrayList<jalview.gui.AlignmentPanel> destPanels = new ArrayList<>();
615     /**
616      * list of instructions for how to process each distinct alignment set
617      * returned by the job set
618      */
619     ArrayList<AddDataTo> resultDest = new ArrayList<>();
620     /**
621      * when false, zeroth pane is panel derived from input deta.
622      */
623     boolean newAlignment = false;
624     /**
625      * gap character to be used for alignment reconstruction
626      */
627     char gapCharacter = restClient.av.getGapCharacter();
628     // Now, iterate over all alignment sets returned from all jobs:
629     // first inspect jobs and collate results data in order to count alignments
630     // and other results
631     // then assemble results from decomposed (v followed by h-separated) jobs
632     // finally, new views and alignments will be created and displayed as
633     // necessary.
634     boolean hsepjobs = restClient.service.isHseparable();
635     boolean vsepjobs = restClient.service.isVseparable();
636     // total number of distinct alignment sets generated by job set.
637     int numAlSets = 0, als = 0;
638     List<AlignmentI> destAls = new ArrayList<>();
639     List<jalview.datamodel.HiddenColumns> destColsel = new ArrayList<>();
640     List<List<NewickFile>> trees = new ArrayList<>();
641
642     do
643     {
644       // Step 1.
645       // iterate over each alignment set returned from each subjob. Treating
646       // each one returned in parallel with others.
647       // Result collation arrays
648
649       /**
650        * mapping between index of sequence in alignment that was submitted to
651        * server and index of sequence in the input alignment
652        */
653       int[][] ordermap = new int[jobs.length][];
654       SequenceI[][] rseqs = new SequenceI[jobs.length][];
655       AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
656       AlignmentAnnotation[][] alan = new AlignmentAnnotation[jobs.length][];
657       SequenceGroup[][] sgrp = new SequenceGroup[jobs.length][];
658       // Now collect all data for alignment Set als from job array
659       for (int j = 0; j < jobs.length; j++)
660       {
661         RestJob rj = (RestJob) jobs[j];
662         if (rj.hasResults())
663         {
664           JalviewDataset rset = rj.context;
665           if (rset.hasAlignments())
666           {
667             if (numAlSets < rset.getAl().size())
668             {
669               numAlSets = rset.getAl().size();
670             }
671             if (als < rset.getAl().size()
672                     && rset.getAl().get(als).isModified())
673             {
674               // Collate result data
675               // TODO: decide if all alignmentI should be collected rather than
676               // specific alignment data containers
677               // for moment, we just extract content, but this means any
678               // alignment properties may be lost.
679               AlignmentSet alset = rset.getAl().get(als);
680               alan[j] = alset.al.getAlignmentAnnotation();
681               if (alset.al.getGroups() != null)
682               {
683                 sgrp[j] = new SequenceGroup[alset.al.getGroups().size()];
684                 alset.al.getGroups().toArray(sgrp[j]);
685               }
686               else
687               {
688                 sgrp[j] = null;
689               }
690               orders[j] = new AlignmentOrder(alset.al);
691               rseqs[j] = alset.al.getSequencesArray();
692               ordermap[j] = rj.getOrderMap();
693               // if (rj.isInputUniquified()) {
694               // jalview.analysis.AlignmentSorter.recoverOrder(rseqs[als]);
695               // }
696
697               if (alset.trees != null)
698               {
699                 trees.add(new ArrayList<>(alset.trees));
700               }
701               else
702               {
703                 trees.add(new ArrayList<NewickFile>());
704               }
705             }
706           }
707         }
708       }
709       // Now aggregate and present results from this frame of alignment data.
710       int nvertsep = 0, nvertseps = 1;
711       if (vsepjobs)
712       {
713         // Jobs relate to different rows of input alignment.
714         // Jobs are subdivided by rows before columns,
715         // so there will now be a number of subjobs according tohsep for each
716         // vertsep
717         // TODO: get vertical separation intervals for each job and set
718         // nvertseps
719         // TODO: merge data from each group/sequence onto whole
720         // alignment
721       }
722       /**
723        * index into rest jobs subdivided vertically
724        */
725       int vrestjob = 0;
726       // Destination alignments for all result data.
727       ArrayList<SequenceGroup> visgrps = new ArrayList<>();
728       Hashtable<String, SequenceGroup> groupNames = new Hashtable<>();
729       ArrayList<AlignmentAnnotation> visAlAn = null;
730       for (nvertsep = 0; nvertsep < nvertseps; nvertsep++)
731       {
732         // TODO: set scope w.r.t. original alignment view for vertical
733         // separation.
734         {
735           // results for a job exclude hidden columns of input data, so map
736           // back on to all visible regions
737           /**
738            * rest job result we are working with
739            */
740           int nrj = vrestjob;
741
742           RestJob rj = (RestJob) jobs[nrj];
743           int contigs[] = input.getVisibleContigs();
744           AlignmentI destAl = null;
745           jalview.datamodel.HiddenColumns destHCs = null;
746           // Resolve destAl for this data.
747           if (als == 0 && rj.isInputContextModified())
748           {
749             // special case: transfer features, annotation, groups, etc,
750             // from input
751             // context to align panel derived from input data
752             if (destAls.size() > als)
753             {
754               destAl = destAls.get(als);
755             }
756             else
757             {
758               if (!restClient.isAlignmentModified() && merge)
759               {
760                 destAl = restClient.av.getAlignment();
761                 destHCs = restClient.av.getAlignment().getHiddenColumns();
762                 resultDest.add(restClient.isShowResultsInNewView()
763                         ? AddDataTo.newView
764                         : AddDataTo.currentView);
765                 destPanels.add(restClient.recoverAlignPanelForView());
766               }
767               else
768               {
769                 newAlignment = true;
770                 // recreate the input alignment data
771                 Object[] idat = input
772                         .getAlignmentAndHiddenColumns(gapCharacter);
773                 destAl = new Alignment((SequenceI[]) idat[0]);
774                 destHCs = (HiddenColumns) idat[1];
775                 resultDest.add(AddDataTo.newAlignment);
776                 // but do not add to the alignment panel list - since we need to
777                 // create a whole new alignFrame set.
778               }
779               destAls.add(destAl);
780               destColsel.add(destHCs);
781             }
782           }
783           else
784           {
785             // alignment(s) returned by service is to be re-integrated and
786             // displayed
787             if (destAls.size() > als)
788             {
789               if (!vsepjobs)
790               {
791                 // TODO: decide if multiple multiple alignments returned by
792                 // non-vseparable services are allowed.
793                 Cache.log.warn(
794                         "dealing with multiple alignment products returned by non-vertically separable service.");
795               }
796               // recover reference to last alignment created for this rest frame
797               // ready for extension
798               destAl = destAls.get(als);
799               destHCs = destColsel.get(als);
800             }
801             else
802             {
803               Object[] newview;
804
805               if (!hsepjobs)
806               {
807                 // single alignment for any job that gets mapped back on to
808                 // input data. Reconstruct by interleaving parts of returned
809                 // alignment with hidden parts of input data.
810                 SequenceI[][] nsq = splitSeqsOnVisibleContigs(rseqs[nrj],
811                         contigs, gapCharacter);
812                 AlignmentOrder alo[] = new AlignmentOrder[nsq.length];
813                 for (int no = 0; no < alo.length; no++)
814                 {
815                   alo[no] = new AlignmentOrder(orders[nrj].getOrder());
816                 }
817                 newview = input.getUpdatedView(nsq, orders, gapCharacter);
818               }
819               else
820               {
821                 // each job maps to a single visible contig, and all need to be
822                 // stitched back together.
823                 // reconstruct using sub-region based MSA alignment construction
824                 // mechanism
825                 newview = input.getUpdatedView(rseqs, orders, gapCharacter);
826               }
827               destAl = new Alignment((SequenceI[]) newview[0]);
828               destHCs = (HiddenColumns) newview[1];
829               newAlignment = true;
830               // TODO create alignment from result data with propagated
831               // references.
832               destAls.add(destAl);
833               destColsel.add(destHCs);
834               resultDest.add(AddDataTo.newAlignment);
835               throw new Error(
836                       MessageManager.getString("error.implementation_error")
837                               + "TODO: ");
838             }
839           }
840           /**
841            * save initial job in this set in case alignment is h-separable
842            */
843           int initnrj = nrj;
844           // Now add in groups
845           for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
846           {
847             if (!hsepjobs)
848             {
849               // single alignment for any job that gets mapped back on to input
850               // data.
851             }
852             else
853             {
854               // each job maps to a single visible contig, and all need to be
855               // stitched back together.
856               if (ncnt > 0)
857               {
858                 nrj++;
859               }
860               // TODO: apply options for group merging and annotation merging.
861               // If merging not supported, then either clear hashtables now or
862               // use them to rename the new annotation/groups for each contig if
863               // a conflict occurs.
864             }
865             if (sgrp[nrj] != null)
866             {
867               for (SequenceGroup sg : sgrp[nrj])
868               {
869                 boolean recovered = false;
870                 SequenceGroup exsg = null;
871                 if (sg.getName() != null)
872                 {
873                   exsg = groupNames.get(sg.getName());
874                 }
875                 if (exsg == null)
876                 {
877                   exsg = new SequenceGroup(sg);
878                   groupNames.put(exsg.getName(), exsg);
879                   visgrps.add(exsg);
880                   exsg.setStartRes(sg.getStartRes() + contigs[ncnt]);
881                   exsg.setEndRes(sg.getEndRes() + contigs[ncnt]);
882                 }
883                 else
884                 {
885                   recovered = true;
886                 }
887                 // now replace any references from the result set with
888                 // corresponding refs from alignment input set.
889
890                 // TODO: cope with recovering hidden sequences from
891                 // resultContext
892                 {
893                   for (SequenceI oseq : sg.getSequences(null))
894                   {
895                     SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
896                             ordermap[nrj], destAl);
897                     if (nseq != null)
898                     {
899                       if (!recovered)
900                       {
901                         exsg.deleteSequence(oseq, false);
902                       }
903                       exsg.addSequence(nseq, false);
904                     }
905                     else
906                     {
907                       Cache.log.warn(
908                               "Couldn't resolve original sequence for new sequence.");
909                     }
910                   }
911                   if (sg.hasSeqrep())
912                   {
913                     if (exsg.getSeqrep() == sg.getSeqrep())
914                     {
915                       // lift over sequence rep reference too
916                       SequenceI oseq = sg.getSeqrep();
917                       SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
918                               ordermap[nrj], destAl);
919                       if (nseq != null)
920                       {
921                         exsg.setSeqrep(nseq);
922                       }
923                     }
924                   }
925                 }
926                 if (recovered)
927                 {
928                   // adjust boundaries of recovered group w.r.t. new group being
929                   // merged on to original alignment.
930                   int start = sg.getStartRes() + contigs[ncnt],
931                           end = sg.getEndRes() + contigs[ncnt];
932                   if (start < exsg.getStartRes())
933                   {
934                     exsg.setStartRes(start);
935                   }
936                   if (end > exsg.getEndRes())
937                   {
938                     exsg.setEndRes(end);
939                   }
940                 }
941               }
942             }
943           }
944           // reset job counter
945           nrj = initnrj;
946           // and finally add in annotation and any trees for each job
947           for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
948           {
949             if (!hsepjobs)
950             {
951               // single alignment for any job that gets mapped back on to input
952               // data.
953             }
954             else
955             {
956               // each job maps to a single visible contig, and all need to be
957               // stitched back together.
958               if (ncnt > 0)
959               {
960                 nrj++;
961               }
962             }
963
964             // merge alignmentAnnotation into one row
965             if (alan[nrj] != null)
966             {
967               for (int an = 0; an < alan[nrj].length; an++)
968               {
969                 SequenceI sqass = null;
970                 SequenceGroup grass = null;
971                 if (alan[nrj][an].sequenceRef != null)
972                 {
973                   // TODO: ensure this relocates sequence reference to local
974                   // context.
975                   sqass = getNewSeq(alan[nrj][an].sequenceRef, rseqs[nrj],
976                           ordermap[nrj], destAl);
977                 }
978                 if (alan[nrj][an].groupRef != null)
979                 {
980                   // TODO: verify relocate group reference to local context
981                   // works correctly
982                   grass = groupNames.get(alan[nrj][an].groupRef.getName());
983                   if (grass == null)
984                   {
985                     Cache.log.error(
986                             "Couldn't relocate group referemce for group "
987                                     + alan[nrj][an].groupRef.getName());
988                   }
989                 }
990                 if (visAlAn == null)
991                 {
992                   visAlAn = new ArrayList<>();
993                 }
994                 AlignmentAnnotation visan = null;
995                 for (AlignmentAnnotation v : visAlAn)
996                 {
997                   if (v.label != null
998                           && v.label.equals(alan[nrj][an].label))
999                   {
1000                     visan = v;
1001                   }
1002                 }
1003                 if (visan == null)
1004                 {
1005                   visan = new AlignmentAnnotation(alan[nrj][an]);
1006                   // copy annotations, and wipe out/update refs.
1007                   visan.annotations = new Annotation[input.getWidth()];
1008                   visan.groupRef = grass;
1009                   visan.sequenceRef = sqass;
1010                   visAlAn.add(visan);
1011                 }
1012                 if (contigs[ncnt]
1013                         + alan[nrj][an].annotations.length > visan.annotations.length)
1014                 {
1015                   // increase width of annotation row
1016                   Annotation[] newannv = new Annotation[contigs[ncnt]
1017                           + alan[nrj][an].annotations.length];
1018                   System.arraycopy(visan.annotations, 0, newannv, 0,
1019                           visan.annotations.length);
1020                   visan.annotations = newannv;
1021                 }
1022                 // now copy local annotation data into correct position
1023                 System.arraycopy(alan[nrj][an].annotations, 0,
1024                         visan.annotations, contigs[ncnt],
1025                         alan[nrj][an].annotations.length);
1026
1027               }
1028             }
1029             // Trees
1030             if (trees.get(nrj).size() > 0)
1031             {
1032               for (NewickFile nf : trees.get(nrj))
1033               {
1034                 // TODO: process each newick file, lifting over sequence refs to
1035                 // current alignment, if necessary.
1036                 Cache.log.error(
1037                         "Tree recovery from restjob not yet implemented.");
1038               }
1039             }
1040           }
1041         }
1042       } // end of vseps loops.
1043       if (visAlAn != null)
1044       {
1045         for (AlignmentAnnotation v : visAlAn)
1046         {
1047           destAls.get(als).addAnnotation(v);
1048         }
1049       }
1050       if (visgrps != null)
1051       {
1052         for (SequenceGroup sg : visgrps)
1053         {
1054           destAls.get(als).addGroup(sg);
1055         }
1056       }
1057     } while (++als < numAlSets);
1058     // Finally, assemble each new alignment, and create new gui components to
1059     // present it.
1060     /**
1061      * current AlignFrame where results will go.
1062      */
1063     AlignFrame destaf = restClient.recoverAlignFrameForView();
1064     /**
1065      * current pane being worked with
1066      */
1067     jalview.gui.AlignmentPanel destPanel = restClient
1068             .recoverAlignPanelForView();
1069     als = 0;
1070     for (AddDataTo action : resultDest)
1071     {
1072       AlignmentI destal;
1073       HiddenColumns destcs;
1074       String alTitle = MessageManager
1075               .formatMessage("label.webservice_job_title_on", new String[]
1076               { restClient.service.details.getAction(),
1077                   restClient.service.details.getName(),
1078                   restClient.viewTitle });
1079       switch (action)
1080       {
1081       case newAlignment:
1082         destal = destAls.get(als);
1083         destcs = destColsel.get(als);
1084         destaf = new AlignFrame(destal, destcs, AlignFrame.DEFAULT_WIDTH,
1085                 AlignFrame.DEFAULT_HEIGHT);
1086         PaintRefresher.Refresh(destaf,
1087                 destaf.getViewport().getSequenceSetId());
1088         // todo transfer any feature settings and colouring
1089         /*
1090          * destaf.getFeatureRenderer().transferSettings(this.featureSettings);
1091          * // update orders if (alorders.size() > 0) { if (alorders.size() == 1)
1092          * { af.addSortByOrderMenuItem(WebServiceName + " Ordering",
1093          * (AlignmentOrder) alorders.get(0)); } else { // construct a
1094          * non-redundant ordering set Vector names = new Vector(); for (int i =
1095          * 0, l = alorders.size(); i < l; i++) { String orderName = new
1096          * String(" Region " + i); int j = i + 1;
1097          * 
1098          * while (j < l) { if (((AlignmentOrder) alorders.get(i))
1099          * .equals(((AlignmentOrder) alorders.get(j)))) { alorders.remove(j);
1100          * l--; orderName += "," + j; } else { j++; } }
1101          * 
1102          * if (i == 0 && j == 1) { names.add(new String("")); } else {
1103          * names.add(orderName); } } for (int i = 0, l = alorders.size(); i < l;
1104          * i++) { af.addSortByOrderMenuItem( WebServiceName + ((String)
1105          * names.get(i)) + " Ordering", (AlignmentOrder) alorders.get(i)); } } }
1106          */
1107         // TODO: modify this and previous alignment's title if many alignments
1108         // have been returned.
1109         Desktop.addInternalFrame(destaf, alTitle, AlignFrame.DEFAULT_WIDTH,
1110                 AlignFrame.DEFAULT_HEIGHT);
1111
1112         break;
1113       case newView:
1114         // TODO: determine title for view
1115         break;
1116       case currentView:
1117         break;
1118       }
1119     }
1120     if (!newAlignment)
1121     {
1122       if (restClient.isShowResultsInNewView())
1123       {
1124         // destPanel = destPanel.alignFrame.newView(false);
1125       }
1126     }
1127     else
1128     {
1129
1130     }
1131     /*
1132      * if (als) // add the destination panel to frame zero of result panel set }
1133      * } if (destPanels.size()==0) { AlignFrame af = new AlignFrame((AlignmentI)
1134      * idat[0], (ColumnSelection) idat[1], AlignFrame.DEFAULT_WIDTH,
1135      * AlignFrame.DEFAULT_HEIGHT);
1136      * 
1137      * jalview.gui.Desktop.addInternalFrame(af, "Results for " +
1138      * restClient.service.details.Name + " " + restClient.service.details.Action
1139      * + " on " + restClient.af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1140      * AlignFrame.DEFAULT_HEIGHT); destPanel = af.alignPanel; // create totally
1141      * new alignment from stashed data/results
1142      */
1143
1144     /*
1145      */
1146
1147     /**
1148      * alignments. New alignments are added to dataset, and subsequently
1149      * annotated/visualised accordingly. 1. New alignment frame created for new
1150      * alignment. Decide if any vis settings should be inherited from old
1151      * alignment frame (e.g. sequence ordering ?). 2. Subsequent data added to
1152      * alignment as below:
1153      */
1154     /**
1155      * annotation update to original/newly created context alignment: 1.
1156      * identify alignment where annotation is to be loaded onto. 2. Add
1157      * annotation, excluding any duplicates. 3. Ensure annotation is visible on
1158      * alignment - honouring ordering given by file.
1159      */
1160     /**
1161      * features updated to original or newly created context alignment: 1.
1162      * Features are(or were already) added to dataset. 2. Feature settings
1163      * modified to ensure all features are displayed - honouring any ordering
1164      * given by result file. Consider merging action with the code used by the
1165      * DAS fetcher to update alignment views with new info.
1166      */
1167     /**
1168      * Seq associated data files (PDB files). 1. locate seq association in
1169      * current dataset/alignment context and add file as normal - keep handle of
1170      * any created ref objects. 2. decide if new data should be displayed : PDB
1171      * display: if alignment has PDB display already, should new pdb files be
1172      * aligned to it ?
1173      * 
1174      */
1175     // destPanel.adjustAnnotationHeight();
1176
1177   }
1178
1179   /**
1180    * split the given array of sequences into blocks of subsequences
1181    * corresponding to each visible contig
1182    * 
1183    * @param sequenceIs
1184    * @param contigs
1185    * @param gapChar
1186    *          padding character for ragged ends of visible contig region.
1187    * @return
1188    */
1189   private SequenceI[][] splitSeqsOnVisibleContigs(SequenceI[] sequenceIs,
1190           int[] contigs, char gapChar)
1191   {
1192     int nvc = contigs == null ? 1 : contigs.length / 2;
1193     SequenceI[][] blocks = new SequenceI[nvc][];
1194     if (contigs == null)
1195     {
1196       blocks[0] = new SequenceI[sequenceIs.length];
1197       System.arraycopy(sequenceIs, 0, blocks[0], 0, sequenceIs.length);
1198     }
1199     else
1200     {
1201       // deja vu - have I written this before ?? propagateGaps does this in a
1202       // way
1203       char[] gapset = null;
1204       int start = 0, width = 0;
1205       for (int c = 0; c < nvc; c++)
1206       {
1207         width = contigs[c * 2 + 1] - contigs[c * 2] + 1;
1208         for (int s = 0; s < sequenceIs.length; s++)
1209         {
1210           int end = sequenceIs[s].getLength();
1211           if (start < end)
1212           {
1213             if (start + width < end)
1214             {
1215               blocks[c][s] = sequenceIs[s].getSubSequence(start,
1216                       start + width);
1217             }
1218             else
1219             {
1220               blocks[c][s] = sequenceIs[s].getSubSequence(start, end);
1221               String sq = blocks[c][s].getSequenceAsString();
1222               for (int n = start + width; n > end; n--)
1223               {
1224                 sq += gapChar;
1225               }
1226             }
1227           }
1228           else
1229           {
1230             if (gapset == null || gapset.length < width)
1231             {
1232               char ng[] = new char[width];
1233               int gs = 0;
1234               if (gapset != null)
1235               {
1236                 System.arraycopy(gapset, 0, ng, 0, gs = gapset.length);
1237               }
1238               while (gs < ng.length)
1239               {
1240                 ng[gs++] = gapChar;
1241               }
1242             }
1243             blocks[c][s] = sequenceIs[s].getSubSequence(end, end);
1244             blocks[c][s].setSequence(gapset.toString().substring(0, width));
1245           }
1246         }
1247         if (c > 0)
1248         {
1249           // adjust window for next visible segnment
1250           start += contigs[c * 2 + 1] - contigs[c * 2];
1251         }
1252       }
1253     }
1254     return blocks;
1255   }
1256
1257   /**
1258    * recover corresponding sequence from original input data corresponding to
1259    * sequence in a specific job's input data.
1260    * 
1261    * @param oseq
1262    * @param sequenceIs
1263    * @param is
1264    * @param destAl
1265    * @return
1266    */
1267   private SequenceI getNewSeq(SequenceI oseq, SequenceI[] sequenceIs,
1268           int[] is, AlignmentI destAl)
1269   {
1270     int p = 0;
1271     while (p < sequenceIs.length && sequenceIs[p] != oseq)
1272     {
1273       p++;
1274     }
1275     if (p < sequenceIs.length && p < destAl.getHeight())
1276     {
1277       return destAl.getSequenceAt(is[p]);
1278     }
1279     return null;
1280   }
1281
1282   /**
1283    * 
1284    * @return true if the run method is safe to call
1285    */
1286   public boolean isValid()
1287   {
1288     ArrayList<String> _warnings = new ArrayList<>();
1289     boolean validt = true;
1290     if (jobs != null)
1291     {
1292       for (RestJob rj : (RestJob[]) jobs)
1293       {
1294         if (!rj.hasValidInput())
1295         {
1296           // invalid input for this job
1297           System.err.println("Job " + rj.getJobnum()
1298                   + " has invalid input. ( " + rj.getStatus() + ")");
1299           if (rj.hasStatus() && !_warnings.contains(rj.getStatus()))
1300           {
1301             _warnings.add(rj.getStatus());
1302           }
1303           validt = false;
1304         }
1305       }
1306     }
1307     if (!validt)
1308     {
1309       warnings = "";
1310       for (String st : _warnings)
1311       {
1312         if (warnings.length() > 0)
1313         {
1314           warnings += "\n";
1315         }
1316         warnings += st;
1317
1318       }
1319     }
1320     return validt;
1321   }
1322
1323   protected String warnings;
1324
1325   public boolean hasWarnings()
1326   {
1327     // TODO Auto-generated method stub
1328     return warnings != null && warnings.length() > 0;
1329   }
1330
1331   /**
1332    * get any informative messages about why the job thread couldn't start.
1333    * 
1334    * @return
1335    */
1336   public String getWarnings()
1337   {
1338     return isValid() ? "Job can be started. No warnings."
1339             : hasWarnings() ? warnings : "";
1340   }
1341
1342 }