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.ColumnSelection;
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(restClient.service
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(restClient.service
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(), input.getValue()
232 .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);
289 extractJobId(rj, response);
290 completeStatus(rj, response);
293 markAsFailed(rj, response);
294 completeStatus(rj, response, "" + getStage(stg)
295 + "failed. Reason below:\n");
299 // Some other response. Probably need to pop up the content in a window.
300 // TODO: deal with all other HTTP response codes from server.
301 Cache.log.warn("Unhandled response status when " + getStage(stg)
302 + "for " + postUrl + ": " + response.getStatusLine());
304 rj.setAllowedServerExceptions(0);
305 rj.setSubjobComplete(true);
306 rj.setSubmitted(true);
314 + " resulted in an unexpected server response.<br/>Url concerned was <a href=\""
318 + "</a><br/>Filtered response content below:<br/>");
319 } catch (IOException e)
321 Cache.log.debug("IOException when consuming unhandled response",
329 private void markAsFailed(RestJob rj, HttpResponse response)
332 rj.setSubmitted(true);
333 rj.setAllowedServerExceptions(0);
334 rj.setSubjobComplete(true);
340 * set the jobRunning flag and post a link to the physical result page encoded
345 private void markJobAsRunning(RestJob rj)
347 rj.statMessage = "<br>Job submitted successfully. Results available at this URL:\n"
357 * extract the job ID URL from the redirect page. Does nothing if job is
363 private void extractJobId(RestJob rj, HttpResponse response)
366 if (!rj.isSubmitted())
369 // redirect URL - typical for IBIVU type jobs.
370 if ((loc = response.getHeaders(HTTPConstants.HEADER_LOCATION)) != null
376 .warn("Ignoring additional "
378 + " location(s) provided in response header ( next one is '"
379 + loc[1].getValue() + "' )");
381 rj.setJobId(loc[0].getValue());
382 rj.setSubmitted(true);
388 * job has completed. Something valid should be available from con
393 * is a stateless request - expected to return the same data
394 * regardless of how many times its called.
396 private void processResultSet(RestJob rj, HttpResponse con,
399 if (rj.statMessage == null)
403 rj.statMessage += "Job Complete.\n";
406 rj.resSet = new HttpResultSet(rj, con, req);
408 } catch (IOException e)
410 rj.statMessage += "Couldn't parse results. Failed.";
412 rj.gotresult = false;
416 private void completeStatus(RestJob rj, HttpResponse con)
419 completeStatus(rj, con, null);
423 private void completeStatus(RestJob rj, HttpResponse con, String prefix)
426 StringBuffer sb = new StringBuffer();
432 if (rj.statMessage != null && rj.statMessage.length() > 0)
434 sb.append(rj.statMessage);
436 HttpEntity en = con.getEntity();
438 * Just append the content as a string.
441 StringBuffer content = new StringBuffer(f = EntityUtils.toString(en));
443 int body = f.indexOf("<body");
446 content.delete(0, f.indexOf(">", body) + 1);
448 if (body > -1 && sb.length() > 0)
451 content.insert(0, sb);
455 rj.statMessage = content.toString();
459 public void pollJob(AWsJob job) throws Exception
461 assert (job instanceof RestJob);
462 System.err.println("Debug RestJob: Polling Job");
463 doPoll((RestJob) job);
467 public void StartJob(AWsJob job)
469 assert (job instanceof RestJob);
472 System.err.println("Debug RestJob: Posting Job");
473 doPost((RestJob) job);
474 } catch (NoValidInputDataException erex)
476 job.setSubjobComplete(true);
477 job.setSubmitted(true);
478 ((RestJob) job).statMessage = "<br>It looks like there was a problem with the data sent to the service :<br>"
479 + erex.getMessage() + "\n";
480 ((RestJob) job).error = true;
482 } catch (Exception ex)
484 job.setSubjobComplete(true);
485 job.setAllowedServerExceptions(-1);
486 Cache.log.error("Exception when trying to start Rest Job.", ex);
491 public void parseResult()
493 // crazy users will see this message
494 // TODO: finish this! and remove the message below!
495 Cache.log.warn("Rest job result parser is currently INCOMPLETE!");
497 for (RestJob rj : (RestJob[]) jobs)
499 if (rj.hasResponse() && rj.resSet != null && rj.resSet.isValid())
504 Cache.log.debug("Parsing data for job " + rj.getJobId());
510 Cache.log.debug("Finished parsing data for job " + rj.getJobId());
514 Cache.log.warn("Failed to finish parsing data for job "
516 ex.printStackTrace();
517 } catch (Exception ex)
519 Cache.log.warn("Failed to finish parsing data for job "
521 ex.printStackTrace();
525 rj.statMessage = "Error whilst parsing data for this job.<br>URL for job response is :<a href=\""
535 // add listeners and activate result display gui elements
537 * decisions based on job result content + state of alignFrame that
538 * originated the job:
541 * 1. Can/Should this job automatically open a new window for results
545 // preserver current jalview behaviour
546 wsInfo.setViewResultsImmediatly(true);
550 // realiseResults(true, true);
552 // otherwise, should automatically view results
554 // TODO: check if at least one or more contexts are valid - if so, enable
556 wsInfo.showResultsNewFrame.addActionListener(new ActionListener()
560 public void actionPerformed(ActionEvent e)
562 realiseResults(false);
566 wsInfo.mergeResults.addActionListener(new ActionListener()
570 public void actionPerformed(ActionEvent e)
572 realiseResults(true);
577 wsInfo.setResultsReady();
581 // tell the user nothing was returned.
582 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
583 wsInfo.setFinishedNoResults();
588 * instructions for whether to create new alignment view on current alignment
589 * set, add to current set, or create new alignFrame
591 private enum AddDataTo
594 * add annotation, trees etc to current view
598 * create a new view derived from current view and add data to that
602 * create a new alignment frame for the result set and add annotation to
608 public void realiseResults(boolean merge)
611 * 2. Should the job modify the parent alignment frame/view(s) (if they
612 * still exist and the alignment hasn't been edited) in order to display new
613 * annotation/features.
616 * alignment panels derived from each alignment set returned by service.
618 ArrayList<jalview.gui.AlignmentPanel> destPanels = new ArrayList<jalview.gui.AlignmentPanel>();
620 * list of instructions for how to process each distinct alignment set
621 * returned by the job set
623 ArrayList<AddDataTo> resultDest = new ArrayList<AddDataTo>();
625 * when false, zeroth pane is panel derived from input deta.
627 boolean newAlignment = false;
629 * gap character to be used for alignment reconstruction
631 char gapCharacter = restClient.av.getGapCharacter();
632 // Now, iterate over all alignment sets returned from all jobs:
633 // first inspect jobs and collate results data in order to count alignments
635 // then assemble results from decomposed (v followed by h-separated) jobs
636 // finally, new views and alignments will be created and displayed as
638 boolean hsepjobs = restClient.service.isHseparable();
639 boolean vsepjobs = restClient.service.isVseparable();
640 // total number of distinct alignment sets generated by job set.
641 int numAlSets = 0, als = 0;
642 List<AlignmentI> destAls = new ArrayList<AlignmentI>();
643 List<jalview.datamodel.ColumnSelection> destColsel = new ArrayList<jalview.datamodel.ColumnSelection>();
644 List<List<NewickFile>> trees = new ArrayList<List<NewickFile>>();
649 // iterate over each alignment set returned from each subjob. Treating
650 // each one returned in parallel with others.
651 // Result collation arrays
654 * mapping between index of sequence in alignment that was submitted to
655 * server and index of sequence in the input alignment
657 int[][] ordermap = new int[jobs.length][];
658 SequenceI[][] rseqs = new SequenceI[jobs.length][];
659 AlignmentOrder[] orders = new AlignmentOrder[jobs.length];
660 AlignmentAnnotation[][] alan = new AlignmentAnnotation[jobs.length][];
661 SequenceGroup[][] sgrp = new SequenceGroup[jobs.length][];
662 // Now collect all data for alignment Set als from job array
663 for (int j = 0; j < jobs.length; j++)
665 RestJob rj = (RestJob) jobs[j];
668 JalviewDataset rset = rj.context;
669 if (rset.hasAlignments())
671 if (numAlSets < rset.getAl().size())
673 numAlSets = rset.getAl().size();
675 if (als < rset.getAl().size()
676 && rset.getAl().get(als).isModified())
678 // Collate result data
679 // TODO: decide if all alignmentI should be collected rather than
680 // specific alignment data containers
681 // for moment, we just extract content, but this means any
682 // alignment properties may be lost.
683 AlignmentSet alset = rset.getAl().get(als);
684 alan[j] = alset.al.getAlignmentAnnotation();
685 if (alset.al.getGroups() != null)
687 sgrp[j] = new SequenceGroup[alset.al.getGroups().size()];
688 alset.al.getGroups().toArray(sgrp[j]);
694 orders[j] = new AlignmentOrder(alset.al);
695 rseqs[j] = alset.al.getSequencesArray();
696 ordermap[j] = rj.getOrderMap();
697 // if (rj.isInputUniquified()) {
698 // jalview.analysis.AlignmentSorter.recoverOrder(rseqs[als]);
701 if (alset.trees != null)
703 trees.add(new ArrayList<NewickFile>(alset.trees));
707 trees.add(new ArrayList<NewickFile>());
713 // Now aggregate and present results from this frame of alignment data.
714 int nvertsep = 0, nvertseps = 1;
717 // Jobs relate to different rows of input alignment.
718 // Jobs are subdivided by rows before columns,
719 // so there will now be a number of subjobs according tohsep for each
721 // TODO: get vertical separation intervals for each job and set
723 // TODO: merge data from each group/sequence onto whole
727 * index into rest jobs subdivided vertically
730 // Destination alignments for all result data.
731 ArrayList<SequenceGroup> visgrps = new ArrayList<SequenceGroup>();
732 Hashtable<String, SequenceGroup> groupNames = new Hashtable<String, SequenceGroup>();
733 ArrayList<AlignmentAnnotation> visAlAn = null;
734 for (nvertsep = 0; nvertsep < nvertseps; nvertsep++)
736 // TODO: set scope w.r.t. original alignment view for vertical
739 // results for a job exclude hidden columns of input data, so map
740 // back on to all visible regions
742 * rest job result we are working with
746 RestJob rj = (RestJob) jobs[nrj];
747 int contigs[] = input.getVisibleContigs();
748 AlignmentI destAl = null;
749 jalview.datamodel.ColumnSelection destCs = null;
750 // Resolve destAl for this data.
751 if (als == 0 && rj.isInputContextModified())
753 // special case: transfer features, annotation, groups, etc,
755 // context to align panel derived from input data
756 if (destAls.size() > als)
758 destAl = destAls.get(als);
762 if (!restClient.isAlignmentModified() && merge)
764 destAl = restClient.av.getAlignment();
765 destCs = restClient.av.getColumnSelection();
767 .add(restClient.isShowResultsInNewView() ? AddDataTo.newView
768 : AddDataTo.currentView);
769 destPanels.add(restClient.recoverAlignPanelForView());
774 // recreate the input alignment data
775 Object[] idat = input
776 .getAlignmentAndColumnSelection(gapCharacter);
777 destAl = new Alignment((SequenceI[]) idat[0]);
778 destCs = (ColumnSelection) idat[1];
779 resultDest.add(AddDataTo.newAlignment);
780 // but do not add to the alignment panel list - since we need to
781 // create a whole new alignFrame set.
784 destColsel.add(destCs);
789 // alignment(s) returned by service is to be re-integrated and
791 if (destAls.size() > als)
795 // TODO: decide if multiple multiple alignments returned by
796 // non-vseparable services are allowed.
798 .warn("dealing with multiple alignment products returned by non-vertically separable service.");
800 // recover reference to last alignment created for this rest frame
801 // ready for extension
802 destAl = destAls.get(als);
803 destCs = destColsel.get(als);
811 // single alignment for any job that gets mapped back on to
812 // input data. Reconstruct by interleaving parts of returned
813 // alignment with hidden parts of input data.
814 SequenceI[][] nsq = splitSeqsOnVisibleContigs(rseqs[nrj],
815 contigs, gapCharacter);
816 AlignmentOrder alo[] = new AlignmentOrder[nsq.length];
817 for (int no = 0; no < alo.length; no++)
819 alo[no] = new AlignmentOrder(orders[nrj].getOrder());
821 newview = input.getUpdatedView(nsq, orders, gapCharacter);
825 // each job maps to a single visible contig, and all need to be
826 // stitched back together.
827 // reconstruct using sub-region based MSA alignment construction
829 newview = input.getUpdatedView(rseqs, orders, gapCharacter);
831 destAl = new Alignment((SequenceI[]) newview[0]);
832 destCs = (ColumnSelection) newview[1];
834 // TODO create alignment from result data with propagated
837 destColsel.add(destCs);
838 resultDest.add(AddDataTo.newAlignment);
841 .getString("error.implementation_error")
846 * save initial job in this set in case alignment is h-separable
850 for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
854 // single alignment for any job that gets mapped back on to input
859 // each job maps to a single visible contig, and all need to be
860 // stitched back together.
865 // TODO: apply options for group merging and annotation merging.
866 // If merging not supported, then either clear hashtables now or
867 // use them to rename the new annotation/groups for each contig if
868 // a conflict occurs.
870 if (sgrp[nrj] != null)
872 for (SequenceGroup sg : sgrp[nrj])
874 boolean recovered = false;
875 SequenceGroup exsg = null;
876 if (sg.getName() != null)
878 exsg = groupNames.get(sg.getName());
882 exsg = new SequenceGroup(sg);
883 groupNames.put(exsg.getName(), exsg);
885 exsg.setStartRes(sg.getStartRes() + contigs[ncnt]);
886 exsg.setEndRes(sg.getEndRes() + contigs[ncnt]);
892 // now replace any references from the result set with
893 // corresponding refs from alignment input set.
895 // TODO: cope with recovering hidden sequences from
898 for (SequenceI oseq : sg.getSequences(null))
900 SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
901 ordermap[nrj], destAl);
906 exsg.deleteSequence(oseq, false);
908 exsg.addSequence(nseq, false);
913 .warn("Couldn't resolve original sequence for new sequence.");
918 if (exsg.getSeqrep() == sg.getSeqrep())
920 // lift over sequence rep reference too
921 SequenceI oseq = sg.getSeqrep();
922 SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
923 ordermap[nrj], destAl);
926 exsg.setSeqrep(nseq);
933 // adjust boundaries of recovered group w.r.t. new group being
934 // merged on to original alignment.
935 int start = sg.getStartRes() + contigs[ncnt], end = sg
936 .getEndRes() + contigs[ncnt];
937 if (start < exsg.getStartRes())
939 exsg.setStartRes(start);
941 if (end > exsg.getEndRes())
951 // and finally add in annotation and any trees for each job
952 for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
956 // single alignment for any job that gets mapped back on to input
961 // each job maps to a single visible contig, and all need to be
962 // stitched back together.
969 // merge alignmentAnnotation into one row
970 if (alan[nrj] != null)
972 for (int an = 0; an < alan[nrj].length; an++)
974 SequenceI sqass = null;
975 SequenceGroup grass = null;
976 if (alan[nrj][an].sequenceRef != null)
978 // TODO: ensure this relocates sequence reference to local
980 sqass = getNewSeq(alan[nrj][an].sequenceRef, rseqs[nrj],
981 ordermap[nrj], destAl);
983 if (alan[nrj][an].groupRef != null)
985 // TODO: verify relocate group reference to local context
987 grass = groupNames.get(alan[nrj][an].groupRef.getName());
991 .error("Couldn't relocate group referemce for group "
992 + alan[nrj][an].groupRef.getName());
997 visAlAn = new ArrayList<AlignmentAnnotation>();
999 AlignmentAnnotation visan = null;
1000 for (AlignmentAnnotation v : visAlAn)
1003 && v.label.equals(alan[nrj][an].label))
1010 visan = new AlignmentAnnotation(alan[nrj][an]);
1011 // copy annotations, and wipe out/update refs.
1012 visan.annotations = new Annotation[input.getWidth()];
1013 visan.groupRef = grass;
1014 visan.sequenceRef = sqass;
1017 if (contigs[ncnt] + alan[nrj][an].annotations.length > visan.annotations.length)
1019 // increase width of annotation row
1020 Annotation[] newannv = new Annotation[contigs[ncnt]
1021 + alan[nrj][an].annotations.length];
1022 System.arraycopy(visan.annotations, 0, newannv, 0,
1023 visan.annotations.length);
1024 visan.annotations = newannv;
1026 // now copy local annotation data into correct position
1027 System.arraycopy(alan[nrj][an].annotations, 0,
1028 visan.annotations, contigs[ncnt],
1029 alan[nrj][an].annotations.length);
1034 if (trees.get(nrj).size() > 0)
1036 for (NewickFile nf : trees.get(nrj))
1038 // TODO: process each newick file, lifting over sequence refs to
1039 // current alignment, if necessary.
1041 .error("Tree recovery from restjob not yet implemented.");
1046 } // end of vseps loops.
1047 if (visAlAn != null)
1049 for (AlignmentAnnotation v : visAlAn)
1051 destAls.get(als).addAnnotation(v);
1054 if (visgrps != null)
1056 for (SequenceGroup sg : visgrps)
1058 destAls.get(als).addGroup(sg);
1061 } while (++als < numAlSets);
1062 // Finally, assemble each new alignment, and create new gui components to
1065 * current AlignFrame where results will go.
1067 AlignFrame destaf = restClient.recoverAlignFrameForView();
1069 * current pane being worked with
1071 jalview.gui.AlignmentPanel destPanel = restClient
1072 .recoverAlignPanelForView();
1074 for (AddDataTo action : resultDest)
1077 ColumnSelection destcs;
1078 String alTitle = MessageManager.formatMessage(
1079 "label.webservice_job_title_on", new String[] {
1080 restClient.service.details.Action,
1081 restClient.service.details.Name, restClient.viewTitle });
1085 destal = destAls.get(als);
1086 destcs = destColsel.get(als);
1087 destaf = new AlignFrame(destal, destcs, AlignFrame.DEFAULT_WIDTH,
1088 AlignFrame.DEFAULT_HEIGHT);
1089 PaintRefresher.Refresh(destaf, destaf.getViewport()
1090 .getSequenceSetId());
1091 // todo transfer any feature settings and colouring
1093 * destaf.getFeatureRenderer().transferSettings(this.featureSettings);
1094 * // update orders if (alorders.size() > 0) { if (alorders.size() == 1)
1095 * { af.addSortByOrderMenuItem(WebServiceName + " Ordering",
1096 * (AlignmentOrder) alorders.get(0)); } else { // construct a
1097 * non-redundant ordering set Vector names = new Vector(); for (int i =
1098 * 0, l = alorders.size(); i < l; i++) { String orderName = new
1099 * String(" Region " + i); int j = i + 1;
1101 * while (j < l) { if (((AlignmentOrder) alorders.get(i))
1102 * .equals(((AlignmentOrder) alorders.get(j)))) { alorders.remove(j);
1103 * l--; orderName += "," + j; } else { j++; } }
1105 * if (i == 0 && j == 1) { names.add(new String("")); } else {
1106 * names.add(orderName); } } for (int i = 0, l = alorders.size(); i < l;
1107 * i++) { af.addSortByOrderMenuItem( WebServiceName + ((String)
1108 * names.get(i)) + " Ordering", (AlignmentOrder) alorders.get(i)); } } }
1110 // TODO: modify this and previous alignment's title if many alignments
1111 // have been returned.
1112 Desktop.addInternalFrame(destaf, alTitle, AlignFrame.DEFAULT_WIDTH,
1113 AlignFrame.DEFAULT_HEIGHT);
1117 // TODO: determine title for view
1125 if (restClient.isShowResultsInNewView())
1127 // destPanel = destPanel.alignFrame.newView(false);
1135 * if (als) // add the destination panel to frame zero of result panel set }
1136 * } if (destPanels.size()==0) { AlignFrame af = new AlignFrame((AlignmentI)
1137 * idat[0], (ColumnSelection) idat[1], AlignFrame.DEFAULT_WIDTH,
1138 * AlignFrame.DEFAULT_HEIGHT);
1140 * jalview.gui.Desktop.addInternalFrame(af, "Results for " +
1141 * restClient.service.details.Name + " " + restClient.service.details.Action
1142 * + " on " + restClient.af.getTitle(), AlignFrame.DEFAULT_WIDTH,
1143 * AlignFrame.DEFAULT_HEIGHT); destPanel = af.alignPanel; // create totally
1144 * new alignment from stashed data/results
1151 * alignments. New alignments are added to dataset, and subsequently
1152 * annotated/visualised accordingly. 1. New alignment frame created for new
1153 * alignment. Decide if any vis settings should be inherited from old
1154 * alignment frame (e.g. sequence ordering ?). 2. Subsequent data added to
1155 * alignment as below:
1158 * annotation update to original/newly created context alignment: 1.
1159 * identify alignment where annotation is to be loaded onto. 2. Add
1160 * annotation, excluding any duplicates. 3. Ensure annotation is visible on
1161 * alignment - honouring ordering given by file.
1164 * features updated to original or newly created context alignment: 1.
1165 * Features are(or were already) added to dataset. 2. Feature settings
1166 * modified to ensure all features are displayed - honouring any ordering
1167 * given by result file. Consider merging action with the code used by the
1168 * DAS fetcher to update alignment views with new info.
1171 * Seq associated data files (PDB files). 1. locate seq association in
1172 * current dataset/alignment context and add file as normal - keep handle of
1173 * any created ref objects. 2. decide if new data should be displayed : PDB
1174 * display: if alignment has PDB display already, should new pdb files be
1178 // destPanel.adjustAnnotationHeight();
1183 * split the given array of sequences into blocks of subsequences
1184 * corresponding to each visible contig
1189 * padding character for ragged ends of visible contig region.
1192 private SequenceI[][] splitSeqsOnVisibleContigs(SequenceI[] sequenceIs,
1193 int[] contigs, char gapChar)
1195 int nvc = contigs == null ? 1 : contigs.length / 2;
1196 SequenceI[][] blocks = new SequenceI[nvc][];
1197 if (contigs == null)
1199 blocks[0] = new SequenceI[sequenceIs.length];
1200 System.arraycopy(sequenceIs, 0, blocks[0], 0, sequenceIs.length);
1204 // deja vu - have I written this before ?? propagateGaps does this in a
1206 char[] gapset = null;
1207 int start = 0, width = 0;
1208 for (int c = 0; c < nvc; c++)
1210 width = contigs[c * 2 + 1] - contigs[c * 2] + 1;
1211 for (int s = 0; s < sequenceIs.length; s++)
1213 int end = sequenceIs[s].getLength();
1216 if (start + width < end)
1218 blocks[c][s] = sequenceIs[s].getSubSequence(start, start
1223 blocks[c][s] = sequenceIs[s].getSubSequence(start, end);
1224 String sq = blocks[c][s].getSequenceAsString();
1225 for (int n = start + width; n > end; n--)
1233 if (gapset == null || gapset.length < width)
1235 char ng[] = new char[width];
1239 System.arraycopy(gapset, 0, ng, 0, gs = gapset.length);
1241 while (gs < ng.length)
1246 blocks[c][s] = sequenceIs[s].getSubSequence(end, end);
1247 blocks[c][s].setSequence(gapset.toString().substring(0, width));
1252 // adjust window for next visible segnment
1253 start += contigs[c * 2 + 1] - contigs[c * 2];
1261 * recover corresponding sequence from original input data corresponding to
1262 * sequence in a specific job's input data.
1270 private SequenceI getNewSeq(SequenceI oseq, SequenceI[] sequenceIs,
1271 int[] is, AlignmentI destAl)
1274 while (p < sequenceIs.length && sequenceIs[p] != oseq)
1278 if (p < sequenceIs.length && p < destAl.getHeight())
1280 return destAl.getSequenceAt(is[p]);
1287 * @return true if the run method is safe to call
1289 public boolean isValid()
1291 ArrayList<String> _warnings = new ArrayList<String>();
1292 boolean validt = true;
1295 for (RestJob rj : (RestJob[]) jobs)
1297 if (!rj.hasValidInput())
1299 // invalid input for this job
1300 System.err.println("Job " + rj.getJobnum()
1301 + " has invalid input. ( " + rj.getStatus() + ")");
1302 if (rj.hasStatus() && !_warnings.contains(rj.getStatus()))
1304 _warnings.add(rj.getStatus());
1313 for (String st : _warnings)
1315 if (warnings.length() > 0)
1326 protected String warnings;
1328 public boolean hasWarnings()
1330 // TODO Auto-generated method stub
1331 return warnings != null && warnings.length() > 0;
1335 * get any informative messages about why the job thread couldn't start.
1339 public String getWarnings()
1341 return isValid() ? "Job can be started. No warnings."
1342 : hasWarnings() ? warnings : "";