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 java.util.Locale;
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;
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;
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;
66 public class RestJobThread extends AWSThread
73 protected RestClient restClient;
75 public RestJobThread(RestClient restClient)
77 super(restClient.af, null, restClient._input,
78 restClient.service.postUrl);
79 this.restClient = restClient; // may not be needed
81 // minimal job - submit given input and parse result onto alignment as
82 // annotation/whatever
84 // look for tree data, etc.
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())
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.
102 int[] viscontig = restClient._input.getVisibleContigs();
103 AlignmentI[] viscontigals = restClient._input
104 .getVisibleContigAlignments(
105 restClient.service.getGapCharacter());
106 if (viscontigals != null && viscontigals.length > 0)
108 jobs = new RestJob[viscontigals.length];
109 for (int j = 0; j < jobs.length; j++)
111 int[] visc = new int[] { viscontig[j * 2], viscontig[j * 2 + 1] };
114 jobs[j] = new RestJob(j, this, viscontigals[j], visc);
118 jobs[j] = new RestJob(0, this, viscontigals[j], visc);
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,
130 if (!restClient.service.isHseparable())
133 // create a bunch of subjobs per visible contig to ensure result honours
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
141 // create a single subjob for the visible/selected input
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 -
150 * create gui components for monitoring jobs
152 * @param webserviceInfo
154 public void setWebServiceInfo(WebserviceInfo webserviceInfo)
156 wsInfo = webserviceInfo;
157 for (int j = 0; j < jobs.length; j++)
160 // Copy over any per job params
163 wsInfo.setProgressName("region " + jobs[j].getJobnum(),
164 jobs[j].getJobnum());
168 wsInfo.setProgressText(jobs[j].getJobnum(), OutputHeader);
173 private String getStage(Stage stg)
175 if (stg == Stage.SUBMIT)
177 return "submitting ";
179 if (stg == Stage.POLL)
181 return "checking status of ";
184 return (" being confused about ");
187 private void doPoll(RestJob rj) throws Exception
189 String postUrl = rj.getPollUrl();
190 doHttpReq(Stage.POLL, rj, postUrl);
194 * construct the post and handle the response.
198 public void doPost(RestJob rj) throws Exception
200 String postUrl = rj.getPostUrl();
201 doHttpReq(Stage.SUBMIT, rj, postUrl);
206 * do the HTTP request - and respond/set statuses appropriate to the current
211 * - provides any data needed for posting and used to record state
213 * - actual URL to post/get from
216 protected void doHttpReq(Stage stg, RestJob rj, String postUrl)
219 HttpRequestBase request = null;
220 String messages = "";
221 if (stg == Stage.SUBMIT)
224 // http://evgenyg.wordpress.com/2010/05/01/uploading-files-multipart-post-apache/
226 HttpPost htpost = new HttpPost(postUrl);
227 MultipartEntity postentity = new MultipartEntity(
228 HttpMultipartMode.STRICT);
229 for (Entry<String, InputType> input : rj.getInputParams())
231 if (input.getValue().validFor(rj))
233 postentity.addPart(input.getKey(),
234 input.getValue().formatForInput(rj));
238 messages += "Skipped an input (" + input.getKey()
239 + ") - Couldn't generate it from available data.";
242 htpost.setEntity(postentity);
247 request = new HttpGet(postUrl);
251 DefaultHttpClient httpclient = new DefaultHttpClient();
253 HttpResponse response = null;
256 response = httpclient.execute(request);
257 } catch (ClientProtocolException he)
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;
265 Cache.log.fatal("Unexpected REST Job " + getStage(stg)
266 + "exception for URL " + rj.rsd.postUrl);
268 } catch (IOException e)
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);
279 switch (response.getStatusLine().getStatusCode())
283 Cache.log.debug("Processing result set.");
284 processResultSet(rj, response, request);
288 markJobAsRunning(rj);
292 // Created - redirect may be present. Fallthrough to 302
294 extractJobId(rj, response);
295 completeStatus(rj, response);
298 markAsFailed(rj, response);
299 completeStatus(rj, response, "" + getStage(stg)
300 + "failed. Reason below:\n");
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());
308 rj.setAllowedServerExceptions(0);
309 rj.setSubjobComplete(true);
310 rj.setSubmitted(true);
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)
319 Cache.log.debug("IOException when consuming unhandled response",
327 private void markAsFailed(RestJob rj, HttpResponse response)
330 rj.setSubmitted(true);
331 rj.setAllowedServerExceptions(0);
332 rj.setSubjobComplete(true);
338 * set the jobRunning flag and post a link to the physical result page encoded
343 private void markJobAsRunning(RestJob rj)
345 rj.statMessage = "<br>Job submitted successfully. Results available at this URL:\n"
355 * extract the job ID URL from the redirect page. Does nothing if job is
361 private void extractJobId(RestJob rj, HttpResponse response)
364 if (!rj.isSubmitted())
367 // redirect URL - typical for IBIVU type jobs.
368 if ((loc = response.getHeaders(HTTPConstants.HEADER_LOCATION)) != null
374 .warn("Ignoring additional "
376 + " location(s) provided in response header ( next one is '"
377 + loc[1].getValue() + "' )");
379 rj.setJobId(loc[0].getValue());
380 rj.setSubmitted(true);
386 * job has completed. Something valid should be available from con
391 * is a stateless request - expected to return the same data
392 * regardless of how many times its called.
394 private void processResultSet(RestJob rj, HttpResponse con,
397 if (rj.statMessage == null)
401 rj.statMessage += "Job Complete.\n";
404 rj.resSet = new HttpResultSet(rj, con, req);
406 } catch (IOException e)
408 rj.statMessage += "Couldn't parse results. Failed.";
410 rj.gotresult = false;
414 private void completeStatus(RestJob rj, HttpResponse con)
417 completeStatus(rj, con, null);
421 private void completeStatus(RestJob rj, HttpResponse con, String prefix)
424 StringBuffer sb = new StringBuffer();
430 if (rj.statMessage != null && rj.statMessage.length() > 0)
432 sb.append(rj.statMessage);
434 HttpEntity en = con.getEntity();
436 * Just append the content as a string.
439 StringBuffer content = new StringBuffer(f = EntityUtils.toString(en));
440 f = f.toLowerCase(Locale.ROOT);
441 int body = f.indexOf("<body");
444 content.delete(0, f.indexOf(">", body) + 1);
446 if (body > -1 && sb.length() > 0)
449 content.insert(0, sb);
453 rj.statMessage = content.toString();
457 public void pollJob(AWsJob job) throws Exception
459 assert (job instanceof RestJob);
460 System.err.println("Debug RestJob: Polling Job");
461 doPoll((RestJob) job);
465 public void StartJob(AWsJob job)
467 assert (job instanceof RestJob);
470 System.err.println("Debug RestJob: Posting Job");
471 doPost((RestJob) job);
472 } catch (NoValidInputDataException erex)
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;
480 } catch (Exception ex)
482 job.setSubjobComplete(true);
483 job.setAllowedServerExceptions(-1);
484 Cache.log.error("Exception when trying to start Rest Job.", ex);
489 public void parseResult()
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!");
495 for (RestJob rj : (RestJob[]) jobs)
497 if (rj.hasResponse() && rj.resSet != null && rj.resSet.isValid())
502 Cache.log.debug("Parsing data for job " + rj.getJobId());
508 Cache.log.debug("Finished parsing data for job " + rj.getJobId());
513 "Failed to finish parsing data for job " + rj.getJobId());
514 ex.printStackTrace();
515 } catch (Exception ex)
518 "Failed to finish parsing data for job " + rj.getJobId());
519 ex.printStackTrace();
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()
531 // add listeners and activate result display gui elements
533 * decisions based on job result content + state of alignFrame that
534 * originated the job:
537 * 1. Can/Should this job automatically open a new window for results
541 // preserver current jalview behaviour
542 wsInfo.setViewResultsImmediatly(true);
546 // realiseResults(true, true);
548 // otherwise, should automatically view results
550 // TODO: check if at least one or more contexts are valid - if so, enable
552 wsInfo.showResultsNewFrame.addActionListener(new ActionListener()
556 public void actionPerformed(ActionEvent e)
558 realiseResults(false);
562 wsInfo.mergeResults.addActionListener(new ActionListener()
566 public void actionPerformed(ActionEvent e)
568 realiseResults(true);
573 wsInfo.setResultsReady();
577 // tell the user nothing was returned.
578 wsInfo.setStatus(wsInfo.STATE_STOPPED_ERROR);
579 wsInfo.setFinishedNoResults();
584 * instructions for whether to create new alignment view on current alignment
585 * set, add to current set, or create new alignFrame
587 private enum AddDataTo
590 * add annotation, trees etc to current view
594 * create a new view derived from current view and add data to that
598 * create a new alignment frame for the result set and add annotation to
604 public void realiseResults(boolean merge)
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.
612 * alignment panels derived from each alignment set returned by service.
614 ArrayList<jalview.gui.AlignmentPanel> destPanels = new ArrayList<>();
616 * list of instructions for how to process each distinct alignment set
617 * returned by the job set
619 ArrayList<AddDataTo> resultDest = new ArrayList<>();
621 * when false, zeroth pane is panel derived from input deta.
623 boolean newAlignment = false;
625 * gap character to be used for alignment reconstruction
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
631 // then assemble results from decomposed (v followed by h-separated) jobs
632 // finally, new views and alignments will be created and displayed as
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<>();
645 // iterate over each alignment set returned from each subjob. Treating
646 // each one returned in parallel with others.
647 // Result collation arrays
650 * mapping between index of sequence in alignment that was submitted to
651 * server and index of sequence in the input alignment
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++)
661 RestJob rj = (RestJob) jobs[j];
664 JalviewDataset rset = rj.context;
665 if (rset.hasAlignments())
667 if (numAlSets < rset.getAl().size())
669 numAlSets = rset.getAl().size();
671 if (als < rset.getAl().size()
672 && rset.getAl().get(als).isModified())
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)
683 sgrp[j] = new SequenceGroup[alset.al.getGroups().size()];
684 alset.al.getGroups().toArray(sgrp[j]);
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]);
697 if (alset.trees != null)
699 trees.add(new ArrayList<>(alset.trees));
703 trees.add(new ArrayList<NewickFile>());
709 // Now aggregate and present results from this frame of alignment data.
710 int nvertsep = 0, nvertseps = 1;
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
717 // TODO: get vertical separation intervals for each job and set
719 // TODO: merge data from each group/sequence onto whole
723 * index into rest jobs subdivided vertically
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++)
732 // TODO: set scope w.r.t. original alignment view for vertical
735 // results for a job exclude hidden columns of input data, so map
736 // back on to all visible regions
738 * rest job result we are working with
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())
749 // special case: transfer features, annotation, groups, etc,
751 // context to align panel derived from input data
752 if (destAls.size() > als)
754 destAl = destAls.get(als);
758 if (!restClient.isAlignmentModified() && merge)
760 destAl = restClient.av.getAlignment();
761 destHCs = restClient.av.getAlignment().getHiddenColumns();
762 resultDest.add(restClient.isShowResultsInNewView()
764 : AddDataTo.currentView);
765 destPanels.add(restClient.recoverAlignPanelForView());
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.
780 destColsel.add(destHCs);
785 // alignment(s) returned by service is to be re-integrated and
787 if (destAls.size() > als)
791 // TODO: decide if multiple multiple alignments returned by
792 // non-vseparable services are allowed.
794 "dealing with multiple alignment products returned by non-vertically separable service.");
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);
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++)
815 alo[no] = new AlignmentOrder(orders[nrj].getOrder());
817 newview = input.getUpdatedView(nsq, orders, gapCharacter);
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
825 newview = input.getUpdatedView(rseqs, orders, gapCharacter);
827 destAl = new Alignment((SequenceI[]) newview[0]);
828 destHCs = (HiddenColumns) newview[1];
830 // TODO create alignment from result data with propagated
833 destColsel.add(destHCs);
834 resultDest.add(AddDataTo.newAlignment);
836 MessageManager.getString("error.implementation_error")
841 * save initial job in this set in case alignment is h-separable
845 for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
849 // single alignment for any job that gets mapped back on to input
854 // each job maps to a single visible contig, and all need to be
855 // stitched back together.
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.
865 if (sgrp[nrj] != null)
867 for (SequenceGroup sg : sgrp[nrj])
869 boolean recovered = false;
870 SequenceGroup exsg = null;
871 if (sg.getName() != null)
873 exsg = groupNames.get(sg.getName());
877 exsg = new SequenceGroup(sg);
878 groupNames.put(exsg.getName(), exsg);
880 exsg.setStartRes(sg.getStartRes() + contigs[ncnt]);
881 exsg.setEndRes(sg.getEndRes() + contigs[ncnt]);
887 // now replace any references from the result set with
888 // corresponding refs from alignment input set.
890 // TODO: cope with recovering hidden sequences from
893 for (SequenceI oseq : sg.getSequences(null))
895 SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
896 ordermap[nrj], destAl);
901 exsg.deleteSequence(oseq, false);
903 exsg.addSequence(nseq, false);
908 "Couldn't resolve original sequence for new sequence.");
913 if (exsg.getSeqrep() == sg.getSeqrep())
915 // lift over sequence rep reference too
916 SequenceI oseq = sg.getSeqrep();
917 SequenceI nseq = getNewSeq(oseq, rseqs[nrj],
918 ordermap[nrj], destAl);
921 exsg.setSeqrep(nseq);
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())
934 exsg.setStartRes(start);
936 if (end > exsg.getEndRes())
946 // and finally add in annotation and any trees for each job
947 for (int ncnt = 0; ncnt < contigs.length; ncnt += 2)
951 // single alignment for any job that gets mapped back on to input
956 // each job maps to a single visible contig, and all need to be
957 // stitched back together.
964 // merge alignmentAnnotation into one row
965 if (alan[nrj] != null)
967 for (int an = 0; an < alan[nrj].length; an++)
969 SequenceI sqass = null;
970 SequenceGroup grass = null;
971 if (alan[nrj][an].sequenceRef != null)
973 // TODO: ensure this relocates sequence reference to local
975 sqass = getNewSeq(alan[nrj][an].sequenceRef, rseqs[nrj],
976 ordermap[nrj], destAl);
978 if (alan[nrj][an].groupRef != null)
980 // TODO: verify relocate group reference to local context
982 grass = groupNames.get(alan[nrj][an].groupRef.getName());
986 "Couldn't relocate group referemce for group "
987 + alan[nrj][an].groupRef.getName());
992 visAlAn = new ArrayList<>();
994 AlignmentAnnotation visan = null;
995 for (AlignmentAnnotation v : visAlAn)
998 && v.label.equals(alan[nrj][an].label))
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;
1013 + alan[nrj][an].annotations.length > visan.annotations.length)
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;
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);
1030 if (trees.get(nrj).size() > 0)
1032 for (NewickFile nf : trees.get(nrj))
1034 // TODO: process each newick file, lifting over sequence refs to
1035 // current alignment, if necessary.
1037 "Tree recovery from restjob not yet implemented.");
1042 } // end of vseps loops.
1043 if (visAlAn != null)
1045 for (AlignmentAnnotation v : visAlAn)
1047 destAls.get(als).addAnnotation(v);
1050 if (visgrps != null)
1052 for (SequenceGroup sg : visgrps)
1054 destAls.get(als).addGroup(sg);
1057 } while (++als < numAlSets);
1058 // Finally, assemble each new alignment, and create new gui components to
1061 * current AlignFrame where results will go.
1063 AlignFrame destaf = restClient.recoverAlignFrameForView();
1065 * current pane being worked with
1067 jalview.gui.AlignmentPanel destPanel = restClient
1068 .recoverAlignPanelForView();
1070 for (AddDataTo action : resultDest)
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 });
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
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;
1098 * while (j < l) { if (((AlignmentOrder) alorders.get(i))
1099 * .equals(((AlignmentOrder) alorders.get(j)))) { alorders.remove(j);
1100 * l--; orderName += "," + j; } else { j++; } }
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)); } } }
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);
1114 // TODO: determine title for view
1122 if (restClient.isShowResultsInNewView())
1124 // destPanel = destPanel.alignFrame.newView(false);
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);
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
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:
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.
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.
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
1175 // destPanel.adjustAnnotationHeight();
1180 * split the given array of sequences into blocks of subsequences
1181 * corresponding to each visible contig
1186 * padding character for ragged ends of visible contig region.
1189 private SequenceI[][] splitSeqsOnVisibleContigs(SequenceI[] sequenceIs,
1190 int[] contigs, char gapChar)
1192 int nvc = contigs == null ? 1 : contigs.length / 2;
1193 SequenceI[][] blocks = new SequenceI[nvc][];
1194 if (contigs == null)
1196 blocks[0] = new SequenceI[sequenceIs.length];
1197 System.arraycopy(sequenceIs, 0, blocks[0], 0, sequenceIs.length);
1201 // deja vu - have I written this before ?? propagateGaps does this in a
1203 char[] gapset = null;
1204 int start = 0, width = 0;
1205 for (int c = 0; c < nvc; c++)
1207 width = contigs[c * 2 + 1] - contigs[c * 2] + 1;
1208 for (int s = 0; s < sequenceIs.length; s++)
1210 int end = sequenceIs[s].getLength();
1213 if (start + width < end)
1215 blocks[c][s] = sequenceIs[s].getSubSequence(start,
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--)
1230 if (gapset == null || gapset.length < width)
1232 char ng[] = new char[width];
1236 System.arraycopy(gapset, 0, ng, 0, gs = gapset.length);
1238 while (gs < ng.length)
1243 blocks[c][s] = sequenceIs[s].getSubSequence(end, end);
1244 blocks[c][s].setSequence(gapset.toString().substring(0, width));
1249 // adjust window for next visible segnment
1250 start += contigs[c * 2 + 1] - contigs[c * 2];
1258 * recover corresponding sequence from original input data corresponding to
1259 * sequence in a specific job's input data.
1267 private SequenceI getNewSeq(SequenceI oseq, SequenceI[] sequenceIs,
1268 int[] is, AlignmentI destAl)
1271 while (p < sequenceIs.length && sequenceIs[p] != oseq)
1275 if (p < sequenceIs.length && p < destAl.getHeight())
1277 return destAl.getSequenceAt(is[p]);
1284 * @return true if the run method is safe to call
1286 public boolean isValid()
1288 ArrayList<String> _warnings = new ArrayList<>();
1289 boolean validt = true;
1292 for (RestJob rj : (RestJob[]) jobs)
1294 if (!rj.hasValidInput())
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()))
1301 _warnings.add(rj.getStatus());
1310 for (String st : _warnings)
1312 if (warnings.length() > 0)
1323 protected String warnings;
1325 public boolean hasWarnings()
1327 // TODO Auto-generated method stub
1328 return warnings != null && warnings.length() > 0;
1332 * get any informative messages about why the job thread couldn't start.
1336 public String getWarnings()
1338 return isValid() ? "Job can be started. No warnings."
1339 : hasWarnings() ? warnings : "";