2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.ws.rest;
21 import jalview.datamodel.SequenceI;
22 import jalview.util.GroupUrlLink.UrlStringTooLongException;
23 import jalview.util.Platform;
24 import jalview.ws.rest.params.Alignment;
25 import jalview.ws.rest.params.AnnotationFile;
26 import jalview.ws.rest.params.SeqGroupIndexVector;
28 import java.util.HashMap;
29 import java.util.Hashtable;
33 public class RestServiceDescription
44 public RestServiceDescription(String action,String description,String name, String postUrl,
45 String urlSuffix, Map<String, InputType> inputParams,
46 boolean hseparable, boolean vseparable, char gapCharacter)
49 this.details = new UIinfo();
50 details.Action= action;
51 details.description = description;
53 this.postUrl = postUrl;
54 this.urlSuffix = urlSuffix;
55 this.inputParams = inputParams;
56 this.hseparable = hseparable;
57 this.vseparable = vseparable;
58 this.gapCharacter = gapCharacter;
61 * Service UI Info { Action, Specific Name of Service, Brief Description }
69 UIinfo details = new UIinfo();
75 * suffix that should be added to any url used if it does not already end in the suffix.
82 * { formatter for type, parser for type }
85 /** input info given as key/value pairs - mapped to post arguments
87 Map<String,InputType> inputParams=new HashMap();
89 * service requests alignment data
93 * service requests alignment and/or seuqence annotationo data
97 * service requests partitions defined over input (alignment) data
99 boolean partitiondata;
102 * process ths input data and set the appropriate shorthand flags describing the input the service wants
104 public void setInvolvesFlags() {
105 aligndata = inputInvolves(Alignment.class);
106 annotdata = inputInvolves(AnnotationFile.class);
107 partitiondata = inputInvolves(SeqGroupIndexVector.class);
110 /** Service return info { alignment, annotation file (loaded back on to alignment), tree (loaded back on to alignment), sequence annotation - loaded back on to alignment), text report, pdb structures with sequence mapping )
114 /** Start with bare minimum: input is alignment + groups on alignment
121 * Helper class based on the UrlLink class which enables URLs to be
122 * constructed from sequences or IDs associated with a group of sequences. URL
123 * definitions consist of a pipe separated string containing a <label>|<url
124 * construct>|<separator character>[|<sequence separator character>]. The url
125 * construct includes regex qualified tokens which are replaced with seuqence
126 * IDs ($SEQUENCE_IDS$) and/or seuqence regions ($SEQUENCES$) that are
127 * extracted from the group. See <code>UrlLink</code> for more information
128 * about the approach, and the original implementation. Documentation to come.
129 * Note - groupUrls can be very big!
131 private String url_prefix, target, label;
134 * these are all filled in order of the occurence of each token in the url
137 private String url_suffix[], separators[], regexReplace[];
139 private String invalidMessage = null;
142 * tokens that can be replaced in the URL.
144 private static String[] tokens;
147 * position of each token (which can appear once only) in the url
152 * contains tokens in the order they appear in the URL template.
154 private String[] mtch;
159 tokens = new String[]
160 { "SEQUENCEIDS", "SEQUENCES", "DATASETID" };
165 * test for GroupURLType bitfield (with default tokens)
167 public static final int SEQUENCEIDS = 1;
170 * test for GroupURLType bitfield (with default tokens)
172 public static final int SEQUENCES = 2;
175 * test for GroupURLType bitfield (with default tokens)
177 public static final int DATASETID = 4;
179 // private int idseg = -1, seqseg = -1;
182 * parse the given linkString of the form '<label>|<url>|separator
183 * char[|optional sequence separator char]' into parts. url may contain a
184 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
185 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
186 * $SEQUENCES<=optional regex=>$.
190 public RestServiceDescription(String link)
192 int sep = link.indexOf("|");
193 segs = new int[tokens.length];
195 for (int i = 0; i < segs.length; i++)
197 if ((segs[i] = link.indexOf("$" + tokens[i])) > -1)
202 // expect at least one token
205 invalidMessage = "Group URL string must contain at least one of ";
206 for (int i = 0; i < segs.length; i++)
208 invalidMessage += " '$" + tokens[i] + "[=/regex=/]$'";
213 int[] ptok = new int[ntoks + 1];
214 String[] tmtch = new String[ntoks + 1];
215 mtch = new String[ntoks];
216 for (int i = 0, t = 0; i < segs.length; i++)
221 tmtch[t++] = tokens[i];
224 ptok[ntoks] = link.length();
225 tmtch[ntoks] = "$$$$$$$$$";
226 jalview.util.QuickSort.sort(ptok, tmtch);
227 for (int i = 0; i < ntoks; i++)
229 mtch[i] = tmtch[i]; // TODO: check order is ascending
232 * replaces the specific code below {}; if (psqids > -1 && pseqs > -1) { if
233 * (psqids > pseqs) { idseg = 1; seqseg = 0;
235 * ptok = new int[] { pseqs, psqids, link.length() }; mtch = new String[] {
236 * "$SEQUENCES", "$SEQUENCEIDS" }; } else { idseg = 0; seqseg = 1; ptok =
237 * new int[] { psqids, pseqs, link.length() }; mtch = new String[] {
238 * "$SEQUENCEIDS", "$SEQUENCES" }; } } else { if (psqids != -1) { idseg = 0;
239 * ptok = new int[] { psqids, link.length() }; mtch = new String[] {
240 * "$SEQUENCEIDS" }; } else { seqseg = 0; ptok = new int[] { pseqs,
241 * link.length() }; mtch = new String[] { "$SEQUENCES" }; } }
245 // first get the label and target part before the first |
249 p = link.indexOf("|", sep + 1);
250 } while (p > sep && p < ptok[0]);
251 // Assuming that the URL itself does not contain any '|' symbols
252 // sep now contains last pipe symbol position prior to any regex symbols
253 label = link.substring(0, sep);
254 if (label.indexOf("|") > -1)
256 // | terminated database name / www target at start of Label
257 target = label.substring(0, label.indexOf("|"));
259 else if (label.indexOf(" ") > 2)
261 // space separated Label - matches database name
262 target = label.substring(0, label.indexOf(" "));
268 // Now Parse URL : Whole URL string first
269 url_prefix = link.substring(sep + 1, ptok[0]);
270 url_suffix = new String[mtch.length];
271 regexReplace = new String[mtch.length];
272 // and loop through tokens
273 for (int pass = 0; pass < mtch.length; pass++)
275 int mlength = 3 + mtch[pass].length();
276 if (link.indexOf("$" + mtch[pass] + "=/") == ptok[pass]
277 && (p = link.indexOf("/=$", ptok[pass] + mlength)) > ptok[pass]
280 // Extract Regex and suffix
281 if (ptok[pass + 1] < p + 3)
283 // tokens are not allowed inside other tokens - e.g. inserting a
284 // $sequences$ into the regex match for the sequenceid
285 invalidMessage = "Token regexes cannot contain other regexes (did you terminate the $"
286 + mtch[pass] + " regex with a '/=$' ?";
289 url_suffix[pass] = link.substring(p + 3, ptok[pass + 1]);
290 regexReplace[pass] = link.substring(ptok[pass] + mlength, p);
293 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
294 + regexReplace[pass] + "/");
297 invalidMessage = "Invalid Regular Expression : '"
298 + regexReplace[pass] + "'\n";
300 } catch (Exception e)
302 invalidMessage = "Invalid Regular Expression : '"
303 + regexReplace[pass] + "'\n";
308 regexReplace[pass] = null;
309 // verify format is really correct.
310 if ((p = link.indexOf("$" + mtch[pass] + "$")) == ptok[pass])
312 url_suffix[pass] = link.substring(p + mtch[pass].length() + 2,
317 invalidMessage = "Warning: invalid regex structure (after '"
318 + mtch[0] + "') for URL link : " + link;
323 separators = new String[url_suffix.length];
324 String suffices = url_suffix[url_suffix.length - 1], lastsep = ",";
325 // have a look in the last suffix for any more separators.
326 while ((p = suffices.indexOf('|')) > -1)
328 separators[pass] = suffices.substring(p + 1);
331 // trim the original suffix string
332 url_suffix[url_suffix.length - 1] = suffices.substring(0, p);
336 lastsep = (separators[pass - 1] = separators[pass - 1].substring(0,
339 suffices = separators[pass];
344 lastsep = separators[pass - 1];
346 // last separator is always used for all the remaining separators
347 while (pass < separators.length)
349 separators[pass++] = lastsep;
354 * @return the url_suffix
356 public String getUrl_suffix()
358 return url_suffix[url_suffix.length - 1];
362 * @return the url_prefix
364 public String getUrl_prefix()
372 public String getTarget()
380 public String getLabel()
386 * @return the sequence ID regexReplace
388 public String getIDRegexReplace()
390 return _replaceFor(tokens[0]);
393 private String _replaceFor(String token)
395 for (int i = 0; i < mtch.length; i++)
396 if (segs[i] > -1 && mtch[i].equals(token))
398 return regexReplace[i];
404 * @return the sequence ID regexReplace
406 public String getSeqRegexReplace()
408 return _replaceFor(tokens[1]);
412 * @return the invalidMessage
414 public String getInvalidMessage()
416 return invalidMessage;
420 * Check if URL string was parsed properly.
422 * @return boolean - if false then <code>getInvalidMessage</code> returns an
425 public boolean isValid()
427 return invalidMessage == null;
432 * gathers input into a hashtable
439 private Hashtable replacementArgs(String[] idstrings,
440 String[] seqstrings, String dsstring)
442 Hashtable rstrings = new Hashtable();
443 rstrings.put(tokens[0], idstrings);
444 rstrings.put(tokens[1], seqstrings);
445 rstrings.put(tokens[2], new String[]
447 if (idstrings.length != seqstrings.length)
450 "idstrings and seqstrings contain one string each per sequence.");
459 * conditionally generate urls or stubs for a given input.
461 * @param createFullUrl
462 * set to false if you only want to test if URLs would be generated.
464 * @param onlyIfMatches
465 * @return null if no url is generated. Object[] { int[] { number of matches
466 * seqs }, boolean[] { which matched }, (if createFullUrl also has
467 * StringBuffer[] { segment generated from inputs that is used in URL
468 * }, String[] { url })}
470 * @throws UrlStringTooLongException
472 protected Object[] makeUrlsIf(boolean createFullUrl,
473 Hashtable repstrings, boolean onlyIfMatches) throws Exception
477 // prepare string arrays in correct order to be assembled into URL input
478 String[][] idseq = new String[mtch.length][]; // indexed by pass
479 int mins = 0, maxs = 0; // allowed two values, 1 or n-sequences.
480 for (int i = 0; i < mtch.length; i++)
482 idseq[i] = (String[]) repstrings.get(mtch[i]);
483 if (idseq[i].length >= 1)
485 if (mins == 0 && idseq[i].length == 1)
491 maxs = idseq[i].length;
495 if (maxs != idseq[i].length)
498 "Cannot have mixed length replacement vectors. Replacement vector for "
499 + (mtch[i]) + " is " + idseq[i].length
500 + " strings long, and have already seen a "
501 + maxs + " length vector.");
508 "Cannot have zero length vector of replacement strings - either 1 value or n values.");
511 // iterate through input, collating segments to be inserted into url
512 StringBuffer matched[] = new StringBuffer[idseq.length];
513 // and precompile regexes
514 com.stevesoft.pat.Regex[] rgxs = new com.stevesoft.pat.Regex[matched.length];
515 for (pass = 0; pass < matched.length; pass++)
517 matched[pass] = new StringBuffer();
518 if (regexReplace[pass] != null)
520 rgxs[pass] = com.stevesoft.pat.Regex.perlCode("/"
521 + regexReplace[pass] + "/");
528 // tot up the invariant lengths for this url
529 int urllength = url_prefix.length();
530 for (pass = 0; pass < matched.length; pass++)
532 urllength += url_suffix[pass].length();
535 // flags to record which of the input sequences were actually used to
538 boolean[] thismatched = new boolean[maxs];
540 for (int sq = 0; sq < maxs; sq++)
542 // initialise flag for match
543 thismatched[sq] = false;
544 StringBuffer[] thematches = new StringBuffer[rgxs.length];
545 for (pass = 0; pass < rgxs.length; pass++)
547 thematches[pass] = new StringBuffer(); // initialise - in case there are
550 // if a regex is provided, then it must match for all sequences in all
551 // tokens for it to be considered.
552 if (idseq[pass].length <= sq)
554 // no more replacement strings to try for this token
557 if (rgxs[pass] != null)
559 com.stevesoft.pat.Regex rg = rgxs[pass];
561 // concatenate all matches of re in the given string!
562 while (rg.searchFrom(idseq[pass][sq], rematchat))
564 rematchat = rg.matchedTo();
565 thismatched[sq] |= true;
566 urllength += rg.charsMatched(); // count length
567 if ((urllength + 32) > Platform.getMaxCommandLineLength())
569 throw new Exception("urllength");
574 continue; // don't bother making the URL replacement text.
576 // do we take the cartesian products of the substituents ?
577 int ns = rg.numSubs();
580 thematches[pass].append(rg.stringMatched());// take whole regex
583 * else if (ns==1) { // take only subgroup match return new String[]
584 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
587 // deal with multiple submatch case - for moment we do the simplest
588 // - concatenate the matched regions, instead of creating a complete
589 // list for each alternate match over all sequences.
590 // TODO: specify a 'replace pattern' - next refinement
595 * for (int s = 0; s <= rg.numSubs(); s++) {
596 * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
597 * " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
600 // try to collate subgroup matches
601 StringBuffer subs = new StringBuffer();
602 // have to loop through submatches, collating them at top level
607 if (s + 1 <= ns && rg.matchedTo(s) > -1
608 && rg.matchedTo(s + 1) > -1
609 && rg.matchedTo(s + 1) < rg.matchedTo(s))
611 // s is top level submatch. search for submatches enclosed by
614 StringBuffer rmtch = new StringBuffer();
615 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
617 if (rg.matchedFrom(r) > -1)
619 rmtch.append(rg.stringMatched(r));
623 if (rmtch.length() > 0)
625 subs.append(rmtch); // simply concatenate
631 if (rg.matchedFrom(s) > -1)
633 subs.append(rg.stringMatched(s)); // concatenate
638 thematches[pass].append(subs);
644 // are we only supposed to take regex matches ?
647 thismatched[sq] |= true;
648 urllength += idseq[pass][sq].length(); // tot up length
651 thematches[pass] = new StringBuffer(idseq[pass][sq]); // take
654 // regardless - probably not a
657 * TODO: do some boilerplate trimming of the fields to make them
658 * sensible e.g. trim off any 'prefix' in the id string (see
659 * UrlLink for the below) - pre 2.4 Jalview behaviour if
660 * (idstring.indexOf("|") > -1) { idstring =
661 * idstring.substring(idstring.lastIndexOf("|") + 1); }
669 // check if we are going to add this sequence's results ? all token
670 // replacements must be valid for this to happen!
671 // (including single value replacements - eg. dataset name)
676 for (pass = 0; pass < matched.length; pass++)
678 if (idseq[pass].length > 1 && matched[pass].length() > 0)
680 matched[pass].append(separators[pass]);
682 matched[pass].append(thematches[pass]);
688 // finally, if any sequences matched, then form the URL and return
689 if (seqsmatched == 0 || (createFullUrl && matched[0].length() == 0))
691 // no matches - no url generated
694 // check if we are beyond the feasible command line string limit for this
696 if ((urllength + 32) > Platform.getMaxCommandLineLength())
698 throw new Exception("urllength");
702 // just return the essential info about what the URL would be generated
706 { seqsmatched }, thismatched };
708 // otherwise, create the URL completely.
710 StringBuffer submiturl = new StringBuffer();
711 submiturl.append(url_prefix);
712 for (pass = 0; pass < matched.length; pass++)
714 submiturl.append(matched[pass]);
715 if (url_suffix[pass] != null)
717 submiturl.append(url_suffix[pass]);
723 { seqsmatched }, thismatched, matched, new String[]
724 { submiturl.toString() } };
730 * @return number of distinct sequence (id or seuqence) replacements predicted
733 public int getNumberInvolved(Object[] urlstub)
735 return ((int[]) urlstub[0])[0]; // returns seqsmatched from
736 // makeUrlsIf(false,...)
740 * get token types present in this url as a bitfield indicating presence of
741 * each token from tokens (LSB->MSB).
743 * @return groupURL class as integer
745 public int getGroupURLType()
748 for (int pass = 0; pass < tokens.length; pass++)
750 for (int i = 0; i < mtch.length; i++)
752 if (mtch[i].equals(tokens[pass]))
761 public String toString()
763 StringBuffer result = new StringBuffer();
764 result.append(label + "|" + url_prefix);
766 for (r = 0; r < url_suffix.length; r++)
769 result.append(mtch[r]);
770 if (regexReplace[r] != null)
773 result.append(regexReplace[r]);
777 result.append(url_suffix[r]);
779 for (r = 0; r < separators.length; r++)
782 result.append(separators[r]);
784 return result.toString();
788 * report stats about the generated url string given an input set
794 private static void testUrls(RestServiceDescription
795 ul, String[][] idstring,
801 System.out.println("Created NO urls.");
805 System.out.println("Created a url from " + ((int[]) url[0])[0]
806 + "out of " + idstring[0].length + " sequences.");
807 System.out.println("Sequences that did not match:");
808 for (int sq = 0; sq < idstring[0].length; sq++)
810 if (!((boolean[]) url[1])[sq])
812 System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
816 System.out.println("Sequences that DID match:");
817 for (int sq = 0; sq < idstring[0].length; sq++)
819 if (((boolean[]) url[1])[sq])
821 System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
825 System.out.println("The generated URL:");
826 System.out.println(((String[]) url[3])[0]);
830 public static void main(String argv[])
835 * covenience method to generate the id and sequence string vector from a set
836 * of seuqences using each sequence's getName() and getSequenceAsString()
840 * @return String[][] {{sequence ids},{sequence strings}}
842 public static String[][] formStrings(SequenceI[] seqs)
844 String[][] idset = new String[2][seqs.length];
845 for (int i = 0; i < seqs.length; i++)
847 idset[0][i] = seqs[i].getName();
848 idset[1][i] = seqs[i].getSequenceAsString();
853 public void setLabel(String newlabel)
855 this.label = newlabel;
859 * can this service be run on the visible portion of an alignment regardless of hidden boundaries ?
861 boolean hseparable=false;
862 boolean vseparable=false;
864 public boolean isHseparable()
866 // TODO Auto-generated method stub
873 public boolean isVseparable()
875 // TODO Auto-generated method stub
880 * search the input types for an instance of the given class
881 * @param <validInput.inputType> class1
884 public boolean inputInvolves(Class<?> class1)
886 assert(InputType.class.isAssignableFrom(class1));
887 for (InputType val:inputParams.values())
889 if (class1.isAssignableFrom(val.getClass()))
896 char gapCharacter = '-';
899 * @return the preferred gap character for alignments input/output by this service
901 public char getGapCharacter()
906 public String getDecoratedResultUrl(String jobId)
908 // TODO: correctly write ?/& appropriate to result URL format.
909 return jobId+urlSuffix;