2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.5)
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/>.
20 import jalview.datamodel.Sequence;
21 import jalview.datamodel.SequenceI;
23 import java.util.Hashtable;
24 import java.util.Vector;
26 public class GroupUrlLink
30 * Helper class based on the UrlLink class which enables URLs to be
31 * constructed from sequences or IDs associated with a group of sequences. URL
32 * definitions consist of a pipe separated string containing a <label>|<url
33 * construct>|<separator character>[|<sequence separator character>]. The url
34 * construct includes regex qualified tokens which are replaced with seuqence
35 * IDs ($SEQUENCE_IDS$) and/or seuqence regions ($SEQUENCES$) that are
36 * extracted from the group. See <code>UrlLink</code> for more information
37 * about the approach, and the original implementation. Documentation to come.
38 * Note - groupUrls can be very big!
40 private String url_prefix, target, label;
43 * these are all filled in order of the occurence of each token in the url
46 private String url_suffix[], separators[], regexReplace[];
48 private String invalidMessage = null;
51 * tokens that can be replaced in the URL.
53 private static String[] tokens;
56 * position of each token (which can appear once only) in the url
61 * contains tokens in the order they appear in the URL template.
63 private String[] mtch;
69 { "SEQUENCEIDS", "SEQUENCES", "DATASETID" };
73 * test for GroupURLType bitfield (with default tokens)
75 public static final int SEQUENCEIDS = 1;
77 * test for GroupURLType bitfield (with default tokens)
79 public static final int SEQUENCES = 2;
81 * test for GroupURLType bitfield (with default tokens)
83 public static final int DATASETID = 4;
85 // private int idseg = -1, seqseg = -1;
88 * parse the given linkString of the form '<label>|<url>|separator
89 * char[|optional sequence separator char]' into parts. url may contain a
90 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
91 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
92 * $SEQUENCES<=optional regex=>$.
96 public GroupUrlLink(String link)
98 int sep = link.indexOf("|");
99 segs = new int[tokens.length];
101 for (int i = 0; i < segs.length; i++)
103 if ((segs[i] = link.indexOf("$" + tokens[i])) > -1)
108 // expect at least one token
111 invalidMessage = "Group URL string must contain at least one of ";
112 for (int i = 0; i < segs.length; i++)
114 invalidMessage += " '$" + tokens[i] + "[=/regex=/]$'";
119 int[] ptok = new int[ntoks + 1];
120 String[] tmtch = new String[ntoks + 1];
121 mtch = new String[ntoks];
122 for (int i = 0, t = 0; i < segs.length; i++)
127 tmtch[t++] = tokens[i];
130 ptok[ntoks] = link.length();
131 tmtch[ntoks] = "$$$$$$$$$";
132 jalview.util.QuickSort.sort(ptok, tmtch);
133 for (int i = 0; i < ntoks; i++)
135 mtch[i] = tmtch[i]; // TODO: check order is ascending
138 * replaces the specific code below {}; if (psqids > -1 && pseqs > -1) { if
139 * (psqids > pseqs) { idseg = 1; seqseg = 0;
141 * ptok = new int[] { pseqs, psqids, link.length() }; mtch = new String[] {
142 * "$SEQUENCES", "$SEQUENCEIDS" }; } else { idseg = 0; seqseg = 1; ptok =
143 * new int[] { psqids, pseqs, link.length() }; mtch = new String[] {
144 * "$SEQUENCEIDS", "$SEQUENCES" }; } } else { if (psqids != -1) { idseg = 0;
145 * ptok = new int[] { psqids, link.length() }; mtch = new String[] {
146 * "$SEQUENCEIDS" }; } else { seqseg = 0; ptok = new int[] { pseqs,
147 * link.length() }; mtch = new String[] { "$SEQUENCES" }; } }
151 // first get the label and target part before the first |
155 p = link.indexOf("|", sep + 1);
156 } while (p > sep && p < ptok[0]);
157 // Assuming that the URL itself does not contain any '|' symbols
158 // sep now contains last pipe symbol position prior to any regex symbols
159 label = link.substring(0, sep);
160 if (label.indexOf("|") > -1)
162 // | terminated database name / www target at start of Label
163 target = label.substring(0, label.indexOf("|"));
165 else if (label.indexOf(" ") > 2)
167 // space separated Label - matches database name
168 target = label.substring(0, label.indexOf(" "));
174 // Now Parse URL : Whole URL string first
175 url_prefix = link.substring(sep + 1, ptok[0]);
176 url_suffix = new String[mtch.length];
177 regexReplace = new String[mtch.length];
178 // and loop through tokens
179 for (int pass = 0; pass < mtch.length; pass++)
181 int mlength = 3 + mtch[pass].length();
182 if (link.indexOf("$" + mtch[pass] + "=/") == ptok[pass]
183 && (p = link.indexOf("/=$", ptok[pass] + mlength)) > ptok[pass]
186 // Extract Regex and suffix
187 if (ptok[pass + 1] < p + 3)
189 // tokens are not allowed inside other tokens - e.g. inserting a
190 // $sequences$ into the regex match for the sequenceid
191 invalidMessage = "Token regexes cannot contain other regexes (did you terminate the $"
192 + mtch[pass] + " regex with a '/=$' ?";
195 url_suffix[pass] = link.substring(p + 3, ptok[pass + 1]);
196 regexReplace[pass] = link.substring(ptok[pass] + mlength, p);
199 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
200 + regexReplace[pass] + "/");
203 invalidMessage = "Invalid Regular Expression : '"
204 + regexReplace[pass] + "'\n";
206 } catch (Exception e)
208 invalidMessage = "Invalid Regular Expression : '"
209 + regexReplace[pass] + "'\n";
214 regexReplace[pass] = null;
215 // verify format is really correct.
216 if ((p = link.indexOf("$" + mtch[pass] + "$")) == ptok[pass])
218 url_suffix[pass] = link.substring(p + mtch[pass].length() + 2,
223 invalidMessage = "Warning: invalid regex structure (after '"
224 + mtch[0] + "') for URL link : " + link;
229 separators = new String[url_suffix.length];
230 String suffices = url_suffix[url_suffix.length - 1], lastsep = ",";
231 // have a look in the last suffix for any more separators.
232 while ((p = suffices.indexOf('|')) > -1)
234 separators[pass] = suffices.substring(p + 1);
237 // trim the original suffix string
238 url_suffix[url_suffix.length - 1] = suffices.substring(0, p);
242 lastsep = (separators[pass - 1] = separators[pass - 1].substring(0,
245 suffices = separators[pass];
250 lastsep = separators[pass - 1];
252 // last separator is always used for all the remaining separators
253 while (pass < separators.length)
255 separators[pass++] = lastsep;
260 * @return the url_suffix
262 public String getUrl_suffix()
264 return url_suffix[url_suffix.length - 1];
268 * @return the url_prefix
270 public String getUrl_prefix()
278 public String getTarget()
286 public String getLabel()
292 * @return the sequence ID regexReplace
294 public String getIDRegexReplace()
296 return _replaceFor(tokens[0]);
299 private String _replaceFor(String token)
301 for (int i = 0; i < mtch.length; i++)
302 if (segs[i] > -1 && mtch[i].equals(token))
304 return regexReplace[i];
310 * @return the sequence ID regexReplace
312 public String getSeqRegexReplace()
314 return _replaceFor(tokens[1]);
318 * @return the invalidMessage
320 public String getInvalidMessage()
322 return invalidMessage;
326 * Check if URL string was parsed properly.
328 * @return boolean - if false then <code>getInvalidMessage</code> returns an
331 public boolean isValid()
333 return invalidMessage == null;
337 * return one or more URL strings by applying regex to the given idstring
340 * array of id strings to pass to service
342 * array of seq strings to pass to service
343 * @param onlyIfMatches
344 * - when true url strings are only made if regex is defined and
345 * matches for all qualified tokens in groupURL - TODO: consider if
346 * onlyIfMatches is really a useful parameter!
347 * @return null or Object[] { int[] { number of seqs substituted},boolean[] {
348 * which seqs were substituted }, StringBuffer[] { substituted lists
349 * for each token }, String[] { url } }
351 public Object[] makeUrls(String[] idstrings, String[] seqstrings,
352 String dsstring, boolean onlyIfMatches)
354 Hashtable rstrings = replacementArgs(idstrings, seqstrings, dsstring);
355 return makeUrls(rstrings, onlyIfMatches);
359 * gathers input into a hashtable
366 private Hashtable replacementArgs(String[] idstrings,
367 String[] seqstrings, String dsstring)
369 Hashtable rstrings = new Hashtable();
370 rstrings.put(tokens[0], idstrings);
371 rstrings.put(tokens[1], seqstrings);
372 rstrings.put(tokens[2], new String[]
374 if (idstrings.length != seqstrings.length)
377 "idstrings and seqstrings contain one string each per sequence.");
382 public Object[] makeUrls(Hashtable repstrings, boolean onlyIfMatches)
384 return makeUrlsIf(true, repstrings, onlyIfMatches);
393 * @return URL stub objects ready to pass to constructFrom
395 public Object[] makeUrlStubs(String[] ids, String[] seqstr,
396 String string, boolean b)
398 Hashtable rstrings = replacementArgs(ids, seqstr, string);
399 Object[] stubs = makeUrlsIf(false, rstrings, b);
403 { stubs[0], stubs[1], rstrings, new boolean[]
406 // TODO Auto-generated method stub
411 * generate the URL for the given URL stub object array returned from
415 * @return URL string.
417 public String constructFrom(Object[] stubs)
419 Object[] results = makeUrlsIf(true, (Hashtable) stubs[2],
420 ((boolean[]) stubs[3])[0]);
421 return ((String[]) results[3])[0];
425 * conditionally generate urls or stubs for a given input.
427 * @param createFullUrl
428 * set to false if you only want to test if URLs would be generated.
430 * @param onlyIfMatches
431 * @return null if no url is generated. Object[] { int[] { number of matches
432 * seqs }, boolean[] { which matched }, (if createFullUrl also has
433 * StringBuffer[] { segment generated from inputs that is used in URL
434 * }, String[] { url })}
436 protected Object[] makeUrlsIf(boolean createFullUrl,
437 Hashtable repstrings, boolean onlyIfMatches)
441 // prepare string arrays in correct order to be assembled into URL input
442 String[][] idseq = new String[mtch.length][]; // indexed by pass
443 int mins = 0, maxs = 0; // allowed two values, 1 or n-sequences.
444 for (int i = 0; i < mtch.length; i++)
446 idseq[i] = (String[]) repstrings.get(mtch[i]);
447 if (idseq[i].length >= 1)
449 if (mins == 0 && idseq[i].length == 1)
455 maxs = idseq[i].length;
459 if (maxs != idseq[i].length)
462 "Cannot have mixed length replacement vectors. Replacement vector for "
463 + (mtch[i]) + " is " + idseq[i].length
464 + " strings long, and have already seen a "
465 + maxs + " length vector.");
472 "Cannot have zero length vector of replacement strings - either 1 value or n values.");
475 // iterate through input, collating segments to be inserted into url
476 StringBuffer matched[] = new StringBuffer[idseq.length];
477 // and precompile regexes
478 com.stevesoft.pat.Regex[] rgxs = new com.stevesoft.pat.Regex[matched.length];
479 for (pass = 0; pass < matched.length; pass++)
481 matched[pass] = new StringBuffer();
482 if (regexReplace[pass] != null)
484 rgxs[pass] = com.stevesoft.pat.Regex.perlCode("/"
485 + regexReplace[pass] + "/");
492 // tot up the invariant lengths for this url
493 int urllength = url_prefix.length();
494 for (pass = 0; pass < matched.length; pass++)
496 urllength += url_suffix[pass].length();
499 // flags to record which of the input sequences were actually used to
502 boolean[] thismatched = new boolean[maxs];
504 for (int sq = 0; sq < maxs; sq++)
506 // initialise flag for match
507 thismatched[sq] = false;
508 StringBuffer[] thematches = new StringBuffer[rgxs.length];
509 for (pass = 0; pass < rgxs.length; pass++)
511 thematches[pass] = new StringBuffer(); // initialise - in case there are
514 // if a regex is provided, then it must match for all sequences in all
515 // tokens for it to be considered.
516 if (idseq[pass].length <= sq)
518 // no more replacement strings to try for this token
521 if (rgxs[pass] != null)
523 com.stevesoft.pat.Regex rg = rgxs[pass];
525 // concatenate all matches of re in the given string!
526 while (rg.searchFrom(idseq[pass][sq], rematchat))
528 rematchat = rg.matchedTo();
529 thismatched[sq] |= true;
530 urllength += rg.charsMatched(); // count length
533 continue; // don't bother making the URL replacement text.
535 // do we take the cartesian products of the substituents ?
536 int ns = rg.numSubs();
539 thematches[pass].append(rg.stringMatched());// take whole regex
542 * else if (ns==1) { // take only subgroup match return new String[]
543 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
546 // deal with multiple submatch case - for moment we do the simplest
547 // - concatenate the matched regions, instead of creating a complete
548 // list for each alternate match over all sequences.
549 // TODO: specify a 'replace pattern' - next refinement
554 * for (int s = 0; s <= rg.numSubs(); s++) {
555 * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
556 * " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
559 // try to collate subgroup matches
560 StringBuffer subs = new StringBuffer();
561 // have to loop through submatches, collating them at top level
566 if (s + 1 <= ns && rg.matchedTo(s) > -1
567 && rg.matchedTo(s + 1) > -1
568 && rg.matchedTo(s + 1) < rg.matchedTo(s))
570 // s is top level submatch. search for submatches enclosed by
573 StringBuffer rmtch = new StringBuffer();
574 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
576 if (rg.matchedFrom(r) > -1)
578 rmtch.append(rg.stringMatched(r));
582 if (rmtch.length() > 0)
584 subs.append(rmtch); // simply concatenate
590 if (rg.matchedFrom(s) > -1)
592 subs.append(rg.stringMatched(s)); // concatenate
597 thematches[pass].append(subs);
603 // are we only supposed to take regex matches ?
606 thismatched[sq] |= true;
607 urllength += idseq[pass][sq].length(); // tot up length
610 thematches[pass] = new StringBuffer(idseq[pass][sq]); // take
613 // regardless - probably not a
616 * TODO: do some boilerplate trimming of the fields to make them
617 * sensible e.g. trim off any 'prefix' in the id string (see
618 * UrlLink for the below) - pre 2.4 Jalview behaviour if
619 * (idstring.indexOf("|") > -1) { idstring =
620 * idstring.substring(idstring.lastIndexOf("|") + 1); }
628 // check if we are going to add this sequence's results ? all token
629 // replacements must be valid for this to happen!
630 // (including single value replacements - eg. dataset name)
635 for (pass = 0; pass < matched.length; pass++)
637 if (idseq[pass].length > 1 && matched[pass].length() > 0)
639 matched[pass].append(separators[pass]);
641 matched[pass].append(thematches[pass]);
647 // finally, if any sequences matched, then form the URL and return
648 if (seqsmatched == 0 || (createFullUrl && matched[0].length() == 0))
650 // no matches - no url generated
653 // check if we are beyond the feasible command line string limit for this
655 if ((urllength + 32) > Platform.getMaxCommandLineLength())
657 System.err.println("URL estimated to be too long " + urllength);
662 // just return the essential info about what the URL would be generated
666 { seqsmatched }, thismatched };
668 // otherwise, create the URL completely.
670 StringBuffer submiturl = new StringBuffer();
671 submiturl.append(url_prefix);
672 for (pass = 0; pass < matched.length; pass++)
674 submiturl.append(matched[pass]);
675 if (url_suffix[pass] != null)
677 submiturl.append(url_suffix[pass]);
683 { seqsmatched }, thismatched, matched, new String[]
684 { submiturl.toString() } };
690 * @return number of distinct sequence (id or seuqence) replacements predicted
693 public int getNumberInvolved(Object[] urlstub)
695 return ((int[]) urlstub[0])[0]; // returns seqsmatched from
696 // makeUrlsIf(false,...)
700 * get token types present in this url as a bitfield indicating presence of
701 * each token from tokens (LSB->MSB).
703 * @return groupURL class as integer
705 public int getGroupURLType()
708 for (int pass = 0; pass < tokens.length; pass++)
710 for (int i = 0; i < mtch.length; i++)
712 if (mtch[i].equals(tokens[pass]))
721 public String toString()
723 StringBuffer result = new StringBuffer();
724 result.append(label + "|" + url_prefix);
726 for (r = 0; r < url_suffix.length; r++)
729 result.append(mtch[r]);
730 if (regexReplace[r] != null)
733 result.append(regexReplace[r]);
737 result.append(url_suffix[r]);
739 for (r = 0; r < separators.length; r++)
742 result.append(separators[r]);
744 return result.toString();
748 * report stats about the generated url string given an input set
754 private static void testUrls(GroupUrlLink ul, String[][] idstring,
760 System.out.println("Created NO urls.");
764 System.out.println("Created a url from " + ((int[]) url[0])[0]
765 + "out of " + idstring[0].length + " sequences.");
766 System.out.println("Sequences that did not match:");
767 for (int sq = 0; sq < idstring[0].length; sq++)
769 if (!((boolean[]) url[1])[sq])
771 System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
775 System.out.println("Sequences that DID match:");
776 for (int sq = 0; sq < idstring[0].length; sq++)
778 if (((boolean[]) url[1])[sq])
780 System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
784 System.out.println("The generated URL:");
785 System.out.println(((String[]) url[3])[0]);
789 public static void main(String argv[])
791 String[] links = new String[]
793 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
794 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCES$&inputType=1|,",
795 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCEIDS$&inputType=0|,",
796 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
797 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
798 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
799 "EnVision2 Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Default&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCES=/([a-zA-Z]+)/=$&inputType=1|,",
800 "EnVision2 Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Default&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCES=/[A-Za-z]+/=$&inputType=1|,"
802 * http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?input=P38389,P38398
803 * &inputType=0&workflow=Enfin%20Default%20Workflow&datasetName=
804 * linkInDatasetFromPRIDE
808 SequenceI[] seqs = new SequenceI[]
809 { new Sequence("StupidLabel:gi|9234|pdb|102L|A",
810 "asdiasdpasdpadpwpadasdpaspdw"), };
811 String[][] seqsandids = formStrings(seqs);
812 for (int i = 0; i < links.length; i++)
814 GroupUrlLink ul = new GroupUrlLink(links[i]);
817 System.out.println("\n\n\n");
818 System.out.println("Link " + i + " " + links[i] + " : "
820 System.out.println(" pref : " + ul.getUrl_prefix());
821 System.out.println(" IdReplace : " + ul.getIDRegexReplace());
822 System.out.println(" SeqReplace : " + ul.getSeqRegexReplace());
823 System.out.println(" Suffixes : " + ul.getUrl_suffix());
826 .println("<insert input id and sequence strings here> Without onlyIfMatches:");
827 Object[] urls = ul.makeUrls(seqsandids[0], seqsandids[1],
829 testUrls(ul, seqsandids, urls);
831 .println("<insert input id and sequence strings here> With onlyIfMatches set:");
832 urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset", true);
833 testUrls(ul, seqsandids, urls);
837 System.err.println("Invalid URLLink : " + links[i] + " : "
838 + ul.getInvalidMessage());
844 * covenience method to generate the id and sequence string vector from a set
845 * of seuqences using each sequence's getName() and getSequenceAsString()
849 * @return String[][] {{sequence ids},{sequence strings}}
851 public static String[][] formStrings(SequenceI[] seqs)
853 String[][] idset = new String[2][seqs.length];
854 for (int i = 0; i < seqs.length; i++)
856 idset[0][i] = seqs[i].getName();
857 idset[1][i] = seqs[i].getSequenceAsString();
862 public void setLabel(String newlabel)
864 this.label = newlabel;