2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
21 package jalview.ws.rest;
23 import jalview.bin.Cache;
24 import jalview.datamodel.Alignment;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.AlignmentOrder;
28 import jalview.datamodel.Annotation;
29 import jalview.datamodel.HiddenColumns;
30 import jalview.datamodel.SequenceGroup;
31 import jalview.datamodel.SequenceI;
32 import jalview.gui.AlignFrame;
33 import jalview.gui.Desktop;
34 import jalview.gui.PaintRefresher;
35 import jalview.gui.WebserviceInfo;
36 import jalview.io.NewickFile;
37 import jalview.io.packed.JalviewDataset;
38 import jalview.io.packed.JalviewDataset.AlignmentSet;
39 import jalview.util.MessageManager;
40 import jalview.ws.AWSThread;
41 import jalview.ws.AWsJob;
43 import java.awt.event.ActionEvent;
44 import java.awt.event.ActionListener;
45 import java.io.IOException;
46 import java.util.ArrayList;
47 import java.util.Hashtable;
48 import java.util.List;
49 import java.util.Map.Entry;
51 import org.apache.axis.transport.http.HTTPConstants;
52 import org.apache.http.Header;
53 import org.apache.http.HttpEntity;
54 import org.apache.http.HttpResponse;
55 import org.apache.http.client.ClientProtocolException;
56 import org.apache.http.client.methods.HttpGet;
57 import org.apache.http.client.methods.HttpPost;
58 import org.apache.http.client.methods.HttpRequestBase;
59 import org.apache.http.entity.mime.HttpMultipartMode;
60 import org.apache.http.entity.mime.MultipartEntity;
61 import org.apache.http.impl.client.DefaultHttpClient;
62 import org.apache.http.util.EntityUtils;
64 public class RestJobThread extends AWSThread
71 protected RestClient restClient;
73 public RestJobThread(RestClient restClient)
75 super(restClient.af, null, restClient._input,
76 restClient.service.postUrl);
77 this.restClient = restClient; // may not be needed
79 // minimal job - submit given input and parse result onto alignment as
80 // annotation/whatever
82 // look for tree data, etc.
84 // for moment do following job type only
85 // input=visiblealignment,groupsindex
86 // ie one subjob using groups defined on alignment.
87 if (!restClient.service.isHseparable())
89 jobs = new RestJob[1];
90 jobs[0] = new RestJob(0, this,
91 restClient._input.getVisibleAlignment(
92 restClient.service.getGapCharacter()),
93 restClient._input.getVisibleContigs());
94 // need a function to get a range on a view/alignment and return both
95 // annotation, groups and selection subsetted to just that region.
100 int[] viscontig = restClient._input.getVisibleContigs();
101 AlignmentI[] viscontigals = restClient._input
102 .getVisibleContigAlignments(
103 restClient.service.getGapCharacter());
104 if (viscontigals != null && viscontigals.length > 0)
106 jobs = new RestJob[viscontigals.length];
107 for (int j = 0; j < jobs.length; j++)
109 int[] visc = new int[] { viscontig[j * 2], viscontig[j * 2 + 1] };
112 jobs[j] = new RestJob(j, this, viscontigals[j], visc);
116 jobs[j] = new RestJob(0, this, viscontigals[j], visc);
123 * subjob types row based: per sequence in alignment/selected region { input
124 * is one sequence or sequence ID } per alignment/selected region { input is
125 * set of sequences, alignment, one or more sets of sequence IDs,
128 if (!restClient.service.isHseparable())
131 // create a bunch of subjobs per visible contig to ensure result honours
133 // TODO: determine if a 'soft' hSeperable property is needed - e.g. if
134 // user does SS-pred on sequence with big hidden regions, its going to be
139 // create a single subjob for the visible/selected input
142 // TODO: decide if vSeperable exists: eg. column wide analysis where hidden
143 // rows do not affect output - generally no analysis that generates
144 // alignment annotation is vSeparable -
148 * create gui components for monitoring jobs
150 * @param webserviceInfo
152 public void setWebServiceInfo(WebserviceInfo webserviceInfo)
154 wsInfo = webserviceInfo;
155 for (int j = 0; j < jobs.length; j++)
158 // Copy over any per job params
161 wsInfo.setProgressName("region " + jobs[j].getJobnum(),
162 jobs[j].getJobnum());
166 wsInfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
171 private String getStage(Stage stg)
173 if (stg == Stage.SUBMIT)
175 return "submitting ";
177 if (stg == Stage.POLL)
179 return "checking status of ";
182 return (" being confused about ");
185 private void doPoll(RestJob rj) throws Exception
187 String postUrl = rj.getPollUrl();
188 doHttpReq(Stage.POLL, rj, postUrl);
192 * construct the post and handle the response.
196 public void doPost(RestJob rj) throws Exception
198 String postUrl = rj.getPostUrl();
199 doHttpReq(Stage.SUBMIT, rj, postUrl);
204 * do the HTTP request - and respond/set statuses appropriate to the current
209 * - provides any data needed for posting and used to record state
211 * - actual URL to post/get from
214 protected void doHttpReq(Stage stg, RestJob rj, String postUrl)
217 HttpRequestBase request = null;
218 String messages = "";
219 if (stg == Stage.SUBMIT)
222 // http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache/
224 HttpPost htpost = new HttpPost(postUrl);
225 MultipartEntity postentity = new MultipartEntity(
226 HttpMultipartMode.STRICT);
227 for (Entry<String, InputType> input : rj.getInputParams())
229 if (input.getValue().validFor(rj))
231 postentity.addPart(input.getKey(),
232 input.getValue().formatForInput(rj));
236 messages += "Skipped an input (" + input.getKey()
237 + ") - Couldn't generate it from available data.";
240 htpost.setEntity(postentity);
245 request = new HttpGet(postUrl);
249 DefaultHttpClient httpclient = new DefaultHttpClient();
251 HttpResponse response = null;
254 response = httpclient.execute(request);
255 } catch (ClientProtocolException he)
257 rj.statMessage = "Web Protocol Exception when " + getStage(stg)
258 + "Job. <br>Problematic url was <a href=\""
259 + request.getURI() + "\">" + request.getURI()
260 + "</a><br>See Console output for details.";
261 rj.setAllowedServerExceptions(0);// unrecoverable;
263 Cache.log.fatal("Unexpected REST Job " + getStage(stg)
264 + "exception for URL " + rj.rsd.postUrl);
266 } catch (IOException e)
268 rj.statMessage = "IO Exception when " + getStage(stg)
269 + "Job. <br>Problematic url was <a href=\""
270 + request.getURI() + "\">" + request.getURI()
271 + "</a><br>See Console output for details.";
272 Cache.log.warn("IO Exception for REST Job " + getStage(stg)
273 + "exception for URL " + rj.rsd.postUrl);
277 switch (response.getStatusLine().getStatusCode())
281 Cache.log.debug("Processing result set.");
282 processResultSet(rj, response, request);
286 markJobAsRunning(rj);
290 // Created - redirect may be present. Fallthrough to 302
292 extractJobId(rj, response);
293 completeStatus(rj, response);
296 markAsFailed(rj, response);
297 completeStatus(rj, response, "" + getStage(stg)
298 + "failed. Reason below:\n");
301 // Some other response. Probably need to pop up the content in a window.
302 // TODO: deal with all other HTTP response codes from server.
303 Cache.log.warn("Unhandled response status when " + getStage(stg)
304 + "for " + postUrl + ": " + response.getStatusLine());
306 rj.setAllowedServerExceptions(0);
307 rj.setSubjobComplete(true);
308 rj.setSubmitted(true);
311 completeStatus(rj, response, "" + getStage(stg)
312 + " resulted in an unexpected server response.<br/>Url concerned was <a href=\""
313 + request.getURI() + "\">" + request.getURI()
314 + "</a><br/>Filtered response content below:<br/>");
315 } catch (IOException e)
317 Cache.log.debug("IOException when consuming unhandled response",
325 private void markAsFailed(RestJob rj, HttpResponse response)
328 rj.setSubmitted(true);
329 rj.setAllowedServerExceptions(0);
330 rj.setSubjobComplete(true);
336 * set the jobRunning flag and post a link to the physical result page encoded
341 private void markJobAsRunning(RestJob rj)
343 rj.statMessage = "<br>Job submitted successfully. Results available at this URL:\n"
353 * extract the job ID URL from the redirect page. Does nothing if job is
359 private void extractJobId(RestJob rj, HttpResponse response)
362 if (!rj.isSubmitted())
365 // redirect URL - typical for IBIVU type jobs.
366 if ((loc = response.getHeaders(HTTPConstants.HEADER_LOCATION)) != null
372 .warn("Ignoring additional "
374 + " location(s) provided in response header ( next one is '"
375 + loc[1].getValue() + "' )");
377 rj.setJobId(loc[0].getValue());
378 rj.setSubmitted(true);
384 * job has completed. Something valid should be available from con
389 * is a stateless request - expected to return the same data
390 * regardless of how many times its called.
392 private void processResultSet(RestJob rj, HttpResponse con,
395 if (rj.statMessage == null)
399 rj.statMessage += "Job Complete.\n";
402 rj.resSet = new HttpResultSet(rj, con, req);
404 } catch (IOException e)
406 rj.statMessage += "Couldn't parse results. Failed.";
408 rj.gotresult = false;
412 private void completeStatus(RestJob rj, HttpResponse con)
415 completeStatus(rj, con, null);
419 private void completeStatus(RestJob rj, HttpResponse con, String prefix)
422 StringBuffer sb = new StringBuffer();
428 if (rj.statMessage != null && rj.statMessage.length() > 0)
430 sb.append(rj.statMessage);
432 HttpEntity en = con.getEntity();
434 * Just append the content as a string.
437 StringBuffer content = new StringBuffer(f = EntityUtils.toString(en));
439 int body = f.indexOf("<body");
442 content.delete(0, f.indexOf(">", body) + 1);
444 if (body > -1 && sb.length() > 0)
447 content.insert(0, sb);
451 rj.statMessage = content.toString();
455 public void pollJob(AWsJob job) throws Exception
457 assert (job instanceof RestJob);
458 System.err.println("Debug RestJob: Polling Job");
459 doPoll((RestJob) job);
463 public void StartJob(AWsJob job)
465 assert (job instanceof RestJob);
468 System.err.println("Debug RestJob: Posting Job");
469 doPost((RestJob) job);
470 } catch (NoValidInputDataException erex)
472 job.setSubjobComplete(true);
473 job.setSubmitted(true);
474 ((RestJob) job).statMessage = "<br>It looks like there was a problem with the data sent to the service :<br>"
475 + erex.getMessage() + "\n";
476 ((RestJob) job).error = true;
478 } catch (Exception ex)
480 job.setSubjobComplete(true);
481 job.setAllowedServerExceptions(-1);
482 Cache.log.error("Exception when trying to start Rest Job.", ex);
487 public void parseResult()
489 // crazy users will see this message
490 // TODO: finish this! and remove the message below!
491 Cache.log.warn("Rest job result parser is currently INCOMPLETE!");
493 for (RestJob rj : (RestJob[]) jobs)
495 if (rj.hasResponse() && rj.resSet != null && rj.resSet.isValid())
500 Cache.log.debug("Parsing data for job " + rj.getJobId());
506 Cache.log.debug("Finished parsing data for job " + rj.getJobId());
511 "Failed to finish parsing data for job " + rj.getJobId());
512 ex.printStackTrace();
513 } catch (Exception ex)
516 "Failed to finish parsing data for job " + rj.getJobId());
517 ex.printStackTrace();
521 rj.statMessage = "Error whilst parsing data for this job.<br>URL for job response is :<a href=\""
522 + rj.resSet.getUrl() + "\">" + rj.resSet.getUrl()
529 // add listeners and activate result display gui elements
531 * decisions based on job result content + state of alignFrame that
532 * originated the job:
535 * 1. Can/Should this job automatically open a new window for results
539 // preserver current jalview behaviour
540 wsInfo.setViewResultsImmediatly(true);
544 // realiseResults(true, true);
546 // otherwise, should automatically view results
548 // TODO: check if at least one or more contexts are valid - if so, enable
550 wsInfo.showResultsNewFrame.addActionListener(new ActionListener()
554 public void actionPerformed(ActionEvent e)
556 realiseResults(false);
560 wsInfo.mergeResults.addActionListener(new ActionListener()
564 public void actionPerformed(ActionEvent e)
566 realiseResults(true);
571 wsInfo.setResultsReady();
575 // tell the user nothing was returned.
576 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
577 wsInfo.setFinishedNoResults();
582 * instructions for whether to create new alignment view on current alignment
583 * set, add to current set, or create new alignFrame
585 private enum AddDataTo
588 * add annotation, trees etc to current view
592 * create a new view derived from current view and add data to that
596 * create a new alignment frame for the result set and add annotation to
602 public void realiseResults(boolean merge)
605 * 2. Should the job modify the parent alignment frame/view(s) (if they
606 * still exist and the alignment hasn't been edited) in order to display new
607 * annotation/features.
610 * alignment panels derived from each alignment set returned by service.
612 ArrayList<jalview.gui.AlignmentPanel> destPanels = new ArrayList<>();
614 * list of instructions for how to process each distinct alignment set
615 * returned by the job set
617 ArrayList<AddDataTo> resultDest = new ArrayList<>();
619 * when false, zeroth pane is panel derived from input deta.
621 boolean newAlignment = false;
623 * gap character to be used for alignment reconstruction
625 char gapCharacter = restClient.av.getGapCharacter();
626 // Now, iterate over all alignment sets returned from all jobs:
627 // first inspect jobs and collate results data in order to count alignments
629 // then assemble results from decomposed (v followed by h-separated) jobs
630 // finally, new views and alignments will be created and displayed as
632 boolean hsepjobs = restClient.service.isHseparable();
633 boolean vsepjobs = restClient.service.isVseparable();
634 // total number of distinct alignment sets generated by job set.
635 int numAlSets = 0, als = 0;
636 List<AlignmentI> destAls = new ArrayList<>();
637 List<jalview.datamodel.HiddenColumns> destColsel = new ArrayList<>();
638 List<List<NewickFile>> trees = new ArrayList<>();
643 // iterate over each alignment set returned from each subjob. Treating
644 // each one returned in parallel with others.
645 // Result collation arrays
648 * mapping between index of sequence in alignment that was submitted to
649 * server and index of sequence in the input alignment
651 int[][] ordermap = new int[jobs.length][];
652 SequenceI[][] rseqs = new SequenceI[jobs.length][];
653 AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
654 AlignmentAnnotation[][] alan = new AlignmentAnnotation[jobs.length][];
655 SequenceGroup[][] sgrp = new SequenceGroup[jobs.length][];
656 // Now collect all data for alignment Set als from job array
657 for (int j = 0; j < jobs.length; j++)
659 RestJob rj = (RestJob) jobs[j];
662 JalviewDataset rset = rj.context;
663 if (rset.hasAlignments())
665 if (numAlSets < rset.getAl().size())
667 numAlSets = rset.getAl().size();
669 if (als < rset.getAl().size()
670 && rset.getAl().get(als).isModified())
672 // Collate result data
673 // TODO: decide if all alignmentI should be collected rather than
674 // specific alignment data containers
675 // for moment, we just extract content, but this means any
676 // alignment properties may be lost.
677 AlignmentSet alset = rset.getAl().get(als);
678 alan[j] = alset.al.getAlignmentAnnotation();
679 if (alset.al.getGroups() != null)
681 sgrp[j] = new SequenceGroup[alset.al.getGroups().size()];
682 alset.al.getGroups().toArray(sgrp[j]);
688 orders[j] = new AlignmentOrder(alset.al);
689 rseqs[j] = alset.al.getSequencesArray();
690 ordermap[j] = rj.getOrderMap();
691 // if (rj.isInputUniquified()) {
692 // jalview.analysis.AlignmentSorter.recoverOrder(rseqs[als]);
695 if (alset.trees != null)
697 trees.add(new ArrayList<>(alset.trees));
701 trees.add(new ArrayList<NewickFile>());
707 // Now aggregate and present results from this frame of alignment data.
708 int nvertsep = 0, nvertseps = 1;
711 // Jobs relate to different rows of input alignment.
712 // Jobs are subdivided by rows before columns,
713 // so there will now be a number of subjobs according tohsep for each
715 // TODO: get vertical separation intervals for each job and set
717 // TODO: merge data from each group/sequence onto whole
721 * index into rest jobs subdivided vertically
724 // Destination alignments for all result data.
725 ArrayList<SequenceGroup> visgrps = new ArrayList<>();
726 Hashtable<String, SequenceGroup> groupNames = new Hashtable<>();
727 ArrayList<AlignmentAnnotation> visAlAn = null;
728 for (nvertsep = 0; nvertsep < nvertseps; nvertsep++)
730 // TODO: set scope w.r.t. original alignment view for vertical
733 // results for a job exclude hidden columns of input data, so map
734 // back on to all visible regions
736 * rest job result we are working with
740 RestJob rj = (RestJob) jobs[nrj];
741 int contigs[] = input.getVisibleContigs();
742 AlignmentI destAl = null;
743 jalview.datamodel.HiddenColumns destHCs = null;
744 // Resolve destAl for this data.
745 if (als == 0 && rj.isInputContextModified())
747 // special case: transfer features, annotation, groups, etc,
749 // context to align panel derived from input data
750 if (destAls.size() > als)
752 destAl = destAls.get(als);
756 if (!restClient.isAlignmentModified() && merge)
758 destAl = restClient.av.getAlignment();
759 destHCs = restClient.av.getAlignment().getHiddenColumns();
760 resultDest.add(restClient.isShowResultsInNewView()
762 : AddDataTo.currentView);
763 destPanels.add(restClient.recoverAlignPanelForView());
768 // recreate the input alignment data
769 Object[] idat = input
770 .getAlignmentAndHiddenColumns(gapCharacter);
771 destAl = new Alignment((SequenceI[]) idat[0]);
772 destHCs = (HiddenColumns) idat[1];
773 resultDest.add(AddDataTo.newAlignment);
774 // but do not add to the alignment panel list - since we need to
775 // create a whole new alignFrame set.
778 destColsel.add(destHCs);
783 // alignment(s) returned by service is to be re-integrated and
785 if (destAls.size() > als)
789 // TODO: decide if multiple multiple alignments returned by
790 // non-vseparable services are allowed.
792 "dealing with multiple alignment products returned by non-vertically separable service.");
794 // recover reference to last alignment created for this rest frame
795 // ready for extension
796 destAl = destAls.get(als);
797 destHCs = destColsel.get(als);
805 // single alignment for any job that gets mapped back on to
806 // input data. Reconstruct by interleaving parts of returned
807 // alignment with hidden parts of input data.
808 SequenceI[][] nsq = splitSeqsOnVisibleContigs(rseqs[nrj],
809 contigs, gapCharacter);
810 AlignmentOrder alo[] = new AlignmentOrder[nsq.length];
811 for (int no = 0; no < alo.length; no++)
813 alo[no] = new AlignmentOrder(orders[nrj].getOrder());
815 newview = input.getUpdatedView(nsq, orders, gapCharacter);
819 // each job maps to a single visible contig, and all need to be
820 // stitched back together.
821 // reconstruct using sub-region based MSA alignment construction
823 newview = input.getUpdatedView(rseqs, orders, gapCharacter);
825 destAl = new Alignment((SequenceI[]) newview[0]);
826 destHCs = (HiddenColumns) newview[1];
828 // TODO create alignment from result data with propagated
831 destColsel.add(destHCs);
832 resultDest.add(AddDataTo.newAlignment);
834 MessageManager.getString("error.implementation_error")
839 * save initial job in this set in case alignment is h-separable
843 for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
847 // single alignment for any job that gets mapped back on to input
852 // each job maps to a single visible contig, and all need to be
853 // stitched back together.
858 // TODO: apply options for group merging and annotation merging.
859 // If merging not supported, then either clear hashtables now or
860 // use them to rename the new annotation/groups for each contig if
861 // a conflict occurs.
863 if (sgrp[nrj] != null)
865 for (SequenceGroup sg : sgrp[nrj])
867 boolean recovered = false;
868 SequenceGroup exsg = null;
869 if (sg.getName() != null)
871 exsg = groupNames.get(sg.getName());
875 exsg = new SequenceGroup(sg);
876 groupNames.put(exsg.getName(), exsg);
878 exsg.setStartRes(sg.getStartRes() + contigs[ncnt]);
879 exsg.setEndRes(sg.getEndRes() + contigs[ncnt]);
885 // now replace any references from the result set with
886 // corresponding refs from alignment input set.
888 // TODO: cope with recovering hidden sequences from
891 for (SequenceI oseq : sg.getSequences(null))
893 SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
894 ordermap[nrj], destAl);
899 exsg.deleteSequence(oseq, false);
901 exsg.addSequence(nseq, false);
906 "Couldn't resolve original sequence for new sequence.");
911 if (exsg.getSeqrep() == sg.getSeqrep())
913 // lift over sequence rep reference too
914 SequenceI oseq = sg.getSeqrep();
915 SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
916 ordermap[nrj], destAl);
919 exsg.setSeqrep(nseq);
926 // adjust boundaries of recovered group w.r.t. new group being
927 // merged on to original alignment.
928 int start = sg.getStartRes() + contigs[ncnt],
929 end = sg.getEndRes() + contigs[ncnt];
930 if (start < exsg.getStartRes())
932 exsg.setStartRes(start);
934 if (end > exsg.getEndRes())
944 // and finally add in annotation and any trees for each job
945 for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
949 // single alignment for any job that gets mapped back on to input
954 // each job maps to a single visible contig, and all need to be
955 // stitched back together.
962 // merge alignmentAnnotation into one row
963 if (alan[nrj] != null)
965 for (int an = 0; an < alan[nrj].length; an++)
967 SequenceI sqass = null;
968 SequenceGroup grass = null;
969 if (alan[nrj][an].sequenceRef != null)
971 // TODO: ensure this relocates sequence reference to local
973 sqass = getNewSeq(alan[nrj][an].sequenceRef, rseqs[nrj],
974 ordermap[nrj], destAl);
976 if (alan[nrj][an].groupRef != null)
978 // TODO: verify relocate group reference to local context
980 grass = groupNames.get(alan[nrj][an].groupRef.getName());
984 "Couldn't relocate group referemce for group "
985 + alan[nrj][an].groupRef.getName());
990 visAlAn = new ArrayList<>();
992 AlignmentAnnotation visan = null;
993 for (AlignmentAnnotation v : visAlAn)
996 && v.label.equals(alan[nrj][an].label))
1003 visan = new AlignmentAnnotation(alan[nrj][an]);
1004 // copy annotations, and wipe out/update refs.
1005 visan.annotations = new Annotation[input.getWidth()];
1006 visan.groupRef = grass;
1007 visan.sequenceRef = sqass;
1011 + alan[nrj][an].annotations.length > visan.annotations.length)
1013 // increase width of annotation row
1014 Annotation[] newannv = new Annotation[contigs[ncnt]
1015 + alan[nrj][an].annotations.length];
1016 System.arraycopy(visan.annotations, 0, newannv, 0,
1017 visan.annotations.length);
1018 visan.annotations = newannv;
1020 // now copy local annotation data into correct position
1021 System.arraycopy(alan[nrj][an].annotations, 0,
1022 visan.annotations, contigs[ncnt],
1023 alan[nrj][an].annotations.length);
1028 if (trees.get(nrj).size() > 0)
1030 for (NewickFile nf : trees.get(nrj))
1032 // TODO: process each newick file, lifting over sequence refs to
1033 // current alignment, if necessary.
1035 "Tree recovery from restjob not yet implemented.");
1040 } // end of vseps loops.
1041 if (visAlAn != null)
1043 for (AlignmentAnnotation v : visAlAn)
1045 destAls.get(als).addAnnotation(v);
1048 if (visgrps != null)
1050 for (SequenceGroup sg : visgrps)
1052 destAls.get(als).addGroup(sg);
1055 } while (++als < numAlSets);
1056 // Finally, assemble each new alignment, and create new gui components to
1059 * current AlignFrame where results will go.
1061 AlignFrame destaf = restClient.recoverAlignFrameForView();
1063 * current pane being worked with
1065 jalview.gui.AlignmentPanel destPanel = restClient
1066 .recoverAlignPanelForView();
1068 for (AddDataTo action : resultDest)
1071 HiddenColumns destcs;
1072 String alTitle = MessageManager
1073 .formatMessage("label.webservice_job_title_on", new String[]
1074 { restClient.service.details.getAction(),
1075 restClient.service.details.getName(),
1076 restClient.viewTitle });
1080 destal = destAls.get(als);
1081 destcs = destColsel.get(als);
1082 destaf = new AlignFrame(destal, destcs, AlignFrame.DEFAULT_WIDTH,
1083 AlignFrame.DEFAULT_HEIGHT);
1084 PaintRefresher.Refresh(destaf,
1085 destaf.getViewport().getSequenceSetId());
1086 // todo transfer any feature settings and colouring
1088 * destaf.getFeatureRenderer().transferSettings(this.featureSettings);
1089 * // update orders if (alorders.size() > 0) { if (alorders.size() == 1)
1090 * { af.addSortByOrderMenuItem(WebServiceName + " Ordering",
1091 * (AlignmentOrder) alorders.get(0)); } else { // construct a
1092 * non-redundant ordering set Vector names = new Vector(); for (int i =
1093 * 0, l = alorders.size(); i < l; i++) { String orderName = new
1094 * String(" Region " + i); int j = i + 1;
1096 * while (j < l) { if (((AlignmentOrder) alorders.get(i))
1097 * .equals(((AlignmentOrder) alorders.get(j)))) { alorders.remove(j);
1098 * l--; orderName += "," + j; } else { j++; } }
1100 * if (i == 0 && j == 1) { names.add(new String("")); } else {
1101 * names.add(orderName); } } for (int i = 0, l = alorders.size(); i < l;
1102 * i++) { af.addSortByOrderMenuItem( WebServiceName + ((String)
1103 * names.get(i)) + " Ordering", (AlignmentOrder) alorders.get(i)); } } }
1105 // TODO: modify this and previous alignment's title if many alignments
1106 // have been returned.
1107 Desktop.addInternalFrame(destaf, alTitle, AlignFrame.DEFAULT_WIDTH,
1108 AlignFrame.DEFAULT_HEIGHT);
1112 // TODO: determine title for view
1120 if (restClient.isShowResultsInNewView())
1122 // destPanel = destPanel.alignFrame.newView(false);
1130 * if (als) // add the destination panel to frame zero of result panel set }
1131 * } if (destPanels.size()==0) { AlignFrame af = new AlignFrame((AlignmentI)
1132 * idat[0], (ColumnSelection) idat[1], AlignFrame.DEFAULT_WIDTH,
1133 * AlignFrame.DEFAULT_HEIGHT);
1135 * jalview.gui.Desktop.addInternalFrame(af, "Results for " +
1136 * restClient.service.details.Name + " " + restClient.service.details.Action
1137 * + " on " + restClient.af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1138 * AlignFrame.DEFAULT_HEIGHT); destPanel = af.alignPanel; // create totally
1139 * new alignment from stashed data/results
1146 * alignments. New alignments are added to dataset, and subsequently
1147 * annotated/visualised accordingly. 1. New alignment frame created for new
1148 * alignment. Decide if any vis settings should be inherited from old
1149 * alignment frame (e.g. sequence ordering ?). 2. Subsequent data added to
1150 * alignment as below:
1153 * annotation update to original/newly created context alignment: 1.
1154 * identify alignment where annotation is to be loaded onto. 2. Add
1155 * annotation, excluding any duplicates. 3. Ensure annotation is visible on
1156 * alignment - honouring ordering given by file.
1159 * features updated to original or newly created context alignment: 1.
1160 * Features are(or were already) added to dataset. 2. Feature settings
1161 * modified to ensure all features are displayed - honouring any ordering
1162 * given by result file. Consider merging action with the code used by the
1163 * DAS fetcher to update alignment views with new info.
1166 * Seq associated data files (PDB files). 1. locate seq association in
1167 * current dataset/alignment context and add file as normal - keep handle of
1168 * any created ref objects. 2. decide if new data should be displayed : PDB
1169 * display: if alignment has PDB display already, should new pdb files be
1173 // destPanel.adjustAnnotationHeight();
1178 * split the given array of sequences into blocks of subsequences
1179 * corresponding to each visible contig
1184 * padding character for ragged ends of visible contig region.
1187 private SequenceI[][] splitSeqsOnVisibleContigs(SequenceI[] sequenceIs,
1188 int[] contigs, char gapChar)
1190 int nvc = contigs == null ? 1 : contigs.length / 2;
1191 SequenceI[][] blocks = new SequenceI[nvc][];
1192 if (contigs == null)
1194 blocks[0] = new SequenceI[sequenceIs.length];
1195 System.arraycopy(sequenceIs, 0, blocks[0], 0, sequenceIs.length);
1199 // deja vu - have I written this before ?? propagateGaps does this in a
1201 char[] gapset = null;
1202 int start = 0, width = 0;
1203 for (int c = 0; c < nvc; c++)
1205 width = contigs[c * 2 + 1] - contigs[c * 2] + 1;
1206 for (int s = 0; s < sequenceIs.length; s++)
1208 int end = sequenceIs[s].getLength();
1211 if (start + width < end)
1213 blocks[c][s] = sequenceIs[s].getSubSequence(start,
1218 blocks[c][s] = sequenceIs[s].getSubSequence(start, end);
1219 String sq = blocks[c][s].getSequenceAsString();
1220 for (int n = start + width; n > end; n--)
1228 if (gapset == null || gapset.length < width)
1230 char ng[] = new char[width];
1234 System.arraycopy(gapset, 0, ng, 0, gs = gapset.length);
1236 while (gs < ng.length)
1241 blocks[c][s] = sequenceIs[s].getSubSequence(end, end);
1242 blocks[c][s].setSequence(gapset.toString().substring(0, width));
1247 // adjust window for next visible segnment
1248 start += contigs[c * 2 + 1] - contigs[c * 2];
1256 * recover corresponding sequence from original input data corresponding to
1257 * sequence in a specific job's input data.
1265 private SequenceI getNewSeq(SequenceI oseq, SequenceI[] sequenceIs,
1266 int[] is, AlignmentI destAl)
1269 while (p < sequenceIs.length && sequenceIs[p] != oseq)
1273 if (p < sequenceIs.length && p < destAl.getHeight())
1275 return destAl.getSequenceAt(is[p]);
1282 * @return true if the run method is safe to call
1284 public boolean isValid()
1286 ArrayList<String> _warnings = new ArrayList<>();
1287 boolean validt = true;
1290 for (RestJob rj : (RestJob[]) jobs)
1292 if (!rj.hasValidInput())
1294 // invalid input for this job
1295 System.err.println("Job " + rj.getJobnum()
1296 + " has invalid input. ( " + rj.getStatus() + ")");
1297 if (rj.hasStatus() && !_warnings.contains(rj.getStatus()))
1299 _warnings.add(rj.getStatus());
1308 for (String st : _warnings)
1310 if (warnings.length() > 0)
1321 protected String warnings;
1323 public boolean hasWarnings()
1325 // TODO Auto-generated method stub
1326 return warnings != null && warnings.length() > 0;
1330 * get any informative messages about why the job thread couldn't start.
1334 public String getWarnings()
1336 return isValid() ? "Job can be started. No warnings."
1337 : hasWarnings() ? warnings : "";