2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, 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
28 public class UrlStringTooLongException extends Exception
30 public UrlStringTooLongException(int lng)
37 public String toString()
39 return "Generated url is estimated to be too long (" + urlLength
45 * Helper class based on the UrlLink class which enables URLs to be
46 * constructed from sequences or IDs associated with a group of sequences. URL
47 * definitions consist of a pipe separated string containing a <label>|<url
48 * construct>|<separator character>[|<sequence separator character>]. The url
49 * construct includes regex qualified tokens which are replaced with seuqence
50 * IDs ($SEQUENCE_IDS$) and/or seuqence regions ($SEQUENCES$) that are
51 * extracted from the group. See <code>UrlLink</code> for more information
52 * about the approach, and the original implementation. Documentation to come.
53 * Note - groupUrls can be very big!
55 private String url_prefix, target, label;
58 * these are all filled in order of the occurence of each token in the url
61 private String url_suffix[], separators[], regexReplace[];
63 private String invalidMessage = null;
66 * tokens that can be replaced in the URL.
68 private static String[] tokens;
71 * position of each token (which can appear once only) in the url
76 * contains tokens in the order they appear in the URL template.
78 private String[] mtch;
84 { "SEQUENCEIDS", "SEQUENCES", "DATASETID" };
89 * test for GroupURLType bitfield (with default tokens)
91 public static final int SEQUENCEIDS = 1;
94 * test for GroupURLType bitfield (with default tokens)
96 public static final int SEQUENCES = 2;
99 * test for GroupURLType bitfield (with default tokens)
101 public static final int DATASETID = 4;
103 // private int idseg = -1, seqseg = -1;
106 * parse the given linkString of the form '<label>|<url>|separator
107 * char[|optional sequence separator char]' into parts. url may contain a
108 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
109 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
110 * $SEQUENCES<=optional regex=>$.
114 public GroupUrlLink(String link)
116 int sep = link.indexOf("|");
117 segs = new int[tokens.length];
119 for (int i = 0; i < segs.length; i++)
121 if ((segs[i] = link.indexOf("$" + tokens[i])) > -1)
126 // expect at least one token
129 invalidMessage = "Group URL string must contain at least one of ";
130 for (int i = 0; i < segs.length; i++)
132 invalidMessage += " '$" + tokens[i] + "[=/regex=/]$'";
137 int[] ptok = new int[ntoks + 1];
138 String[] tmtch = new String[ntoks + 1];
139 mtch = new String[ntoks];
140 for (int i = 0, t = 0; i < segs.length; i++)
145 tmtch[t++] = tokens[i];
148 ptok[ntoks] = link.length();
149 tmtch[ntoks] = "$$$$$$$$$";
150 jalview.util.QuickSort.sort(ptok, tmtch);
151 for (int i = 0; i < ntoks; i++)
153 mtch[i] = tmtch[i]; // TODO: check order is ascending
156 * replaces the specific code below {}; if (psqids > -1 && pseqs > -1) { if
157 * (psqids > pseqs) { idseg = 1; seqseg = 0;
159 * ptok = new int[] { pseqs, psqids, link.length() }; mtch = new String[] {
160 * "$SEQUENCES", "$SEQUENCEIDS" }; } else { idseg = 0; seqseg = 1; ptok =
161 * new int[] { psqids, pseqs, link.length() }; mtch = new String[] {
162 * "$SEQUENCEIDS", "$SEQUENCES" }; } } else { if (psqids != -1) { idseg = 0;
163 * ptok = new int[] { psqids, link.length() }; mtch = new String[] {
164 * "$SEQUENCEIDS" }; } else { seqseg = 0; ptok = new int[] { pseqs,
165 * link.length() }; mtch = new String[] { "$SEQUENCES" }; } }
169 // first get the label and target part before the first |
173 p = link.indexOf("|", sep + 1);
174 } while (p > sep && p < ptok[0]);
175 // Assuming that the URL itself does not contain any '|' symbols
176 // sep now contains last pipe symbol position prior to any regex symbols
177 label = link.substring(0, sep);
178 if (label.indexOf("|") > -1)
180 // | terminated database name / www target at start of Label
181 target = label.substring(0, label.indexOf("|"));
183 else if (label.indexOf(" ") > 2)
185 // space separated Label - matches database name
186 target = label.substring(0, label.indexOf(" "));
192 // Now Parse URL : Whole URL string first
193 url_prefix = link.substring(sep + 1, ptok[0]);
194 url_suffix = new String[mtch.length];
195 regexReplace = new String[mtch.length];
196 // and loop through tokens
197 for (int pass = 0; pass < mtch.length; pass++)
199 int mlength = 3 + mtch[pass].length();
200 if (link.indexOf("$" + mtch[pass] + "=/") == ptok[pass]
201 && (p = link.indexOf("/=$", ptok[pass] + mlength)) > ptok[pass]
204 // Extract Regex and suffix
205 if (ptok[pass + 1] < p + 3)
207 // tokens are not allowed inside other tokens - e.g. inserting a
208 // $sequences$ into the regex match for the sequenceid
209 invalidMessage = "Token regexes cannot contain other regexes (did you terminate the $"
210 + mtch[pass] + " regex with a '/=$' ?";
213 url_suffix[pass] = link.substring(p + 3, ptok[pass + 1]);
214 regexReplace[pass] = link.substring(ptok[pass] + mlength, p);
217 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
218 + regexReplace[pass] + "/");
221 invalidMessage = "Invalid Regular Expression : '"
222 + regexReplace[pass] + "'\n";
224 } catch (Exception e)
226 invalidMessage = "Invalid Regular Expression : '"
227 + regexReplace[pass] + "'\n";
232 regexReplace[pass] = null;
233 // verify format is really correct.
234 if ((p = link.indexOf("$" + mtch[pass] + "$")) == ptok[pass])
236 url_suffix[pass] = link.substring(p + mtch[pass].length() + 2,
241 invalidMessage = "Warning: invalid regex structure (after '"
242 + mtch[0] + "') for URL link : " + link;
247 separators = new String[url_suffix.length];
248 String suffices = url_suffix[url_suffix.length - 1], lastsep = ",";
249 // have a look in the last suffix for any more separators.
250 while ((p = suffices.indexOf('|')) > -1)
252 separators[pass] = suffices.substring(p + 1);
255 // trim the original suffix string
256 url_suffix[url_suffix.length - 1] = suffices.substring(0, p);
260 lastsep = (separators[pass - 1] = separators[pass - 1].substring(0,
263 suffices = separators[pass];
268 lastsep = separators[pass - 1];
270 // last separator is always used for all the remaining separators
271 while (pass < separators.length)
273 separators[pass++] = lastsep;
278 * @return the url_suffix
280 public String getUrl_suffix()
282 return url_suffix[url_suffix.length - 1];
286 * @return the url_prefix
288 public String getUrl_prefix()
296 public String getTarget()
304 public String getLabel()
310 * @return the sequence ID regexReplace
312 public String getIDRegexReplace()
314 return _replaceFor(tokens[0]);
317 private String _replaceFor(String token)
319 for (int i = 0; i < mtch.length; i++)
320 if (segs[i] > -1 && mtch[i].equals(token))
322 return regexReplace[i];
328 * @return the sequence ID regexReplace
330 public String getSeqRegexReplace()
332 return _replaceFor(tokens[1]);
336 * @return the invalidMessage
338 public String getInvalidMessage()
340 return invalidMessage;
344 * Check if URL string was parsed properly.
346 * @return boolean - if false then <code>getInvalidMessage</code> returns an
349 public boolean isValid()
351 return invalidMessage == null;
355 * return one or more URL strings by applying regex to the given idstring
358 * array of id strings to pass to service
360 * array of seq strings to pass to service
361 * @param onlyIfMatches
362 * - when true url strings are only made if regex is defined and
363 * matches for all qualified tokens in groupURL - TODO: consider if
364 * onlyIfMatches is really a useful parameter!
365 * @return null or Object[] { int[] { number of seqs substituted},boolean[] {
366 * which seqs were substituted }, StringBuffer[] { substituted lists
367 * for each token }, String[] { url } }
368 * @throws UrlStringTooLongException
370 public Object[] makeUrls(String[] idstrings, String[] seqstrings,
371 String dsstring, boolean onlyIfMatches)
372 throws UrlStringTooLongException
374 Hashtable rstrings = replacementArgs(idstrings, seqstrings, dsstring);
375 return makeUrls(rstrings, onlyIfMatches);
379 * gathers input into a hashtable
386 private Hashtable replacementArgs(String[] idstrings,
387 String[] seqstrings, String dsstring)
389 Hashtable rstrings = new Hashtable();
390 rstrings.put(tokens[0], idstrings);
391 rstrings.put(tokens[1], seqstrings);
392 rstrings.put(tokens[2], new String[]
394 if (idstrings.length != seqstrings.length)
397 "idstrings and seqstrings contain one string each per sequence.");
402 public Object[] makeUrls(Hashtable repstrings, boolean onlyIfMatches)
403 throws UrlStringTooLongException
405 return makeUrlsIf(true, repstrings, onlyIfMatches);
414 * @return URL stub objects ready to pass to constructFrom
415 * @throws UrlStringTooLongException
417 public Object[] makeUrlStubs(String[] ids, String[] seqstr,
418 String string, boolean b) throws UrlStringTooLongException
420 Hashtable rstrings = replacementArgs(ids, seqstr, string);
421 Object[] stubs = makeUrlsIf(false, rstrings, b);
425 { stubs[0], stubs[1], rstrings, new boolean[]
428 // TODO Auto-generated method stub
433 * generate the URL for the given URL stub object array returned from
437 * @return URL string.
438 * @throws UrlStringTooLongException
440 public String constructFrom(Object[] stubs)
441 throws UrlStringTooLongException
443 Object[] results = makeUrlsIf(true, (Hashtable) stubs[2],
444 ((boolean[]) stubs[3])[0]);
445 return ((String[]) results[3])[0];
449 * conditionally generate urls or stubs for a given input.
451 * @param createFullUrl
452 * set to false if you only want to test if URLs would be generated.
454 * @param onlyIfMatches
455 * @return null if no url is generated. Object[] { int[] { number of matches
456 * seqs }, boolean[] { which matched }, (if createFullUrl also has
457 * StringBuffer[] { segment generated from inputs that is used in URL
458 * }, String[] { url })}
459 * @throws UrlStringTooLongException
461 protected Object[] makeUrlsIf(boolean createFullUrl,
462 Hashtable repstrings, boolean onlyIfMatches)
463 throws UrlStringTooLongException
467 // prepare string arrays in correct order to be assembled into URL input
468 String[][] idseq = new String[mtch.length][]; // indexed by pass
469 int mins = 0, maxs = 0; // allowed two values, 1 or n-sequences.
470 for (int i = 0; i < mtch.length; i++)
472 idseq[i] = (String[]) repstrings.get(mtch[i]);
473 if (idseq[i].length >= 1)
475 if (mins == 0 && idseq[i].length == 1)
481 maxs = idseq[i].length;
485 if (maxs != idseq[i].length)
488 "Cannot have mixed length replacement vectors. Replacement vector for "
489 + (mtch[i]) + " is " + idseq[i].length
490 + " strings long, and have already seen a "
491 + maxs + " length vector.");
498 "Cannot have zero length vector of replacement strings - either 1 value or n values.");
501 // iterate through input, collating segments to be inserted into url
502 StringBuffer matched[] = new StringBuffer[idseq.length];
503 // and precompile regexes
504 com.stevesoft.pat.Regex[] rgxs = new com.stevesoft.pat.Regex[matched.length];
505 for (pass = 0; pass < matched.length; pass++)
507 matched[pass] = new StringBuffer();
508 if (regexReplace[pass] != null)
510 rgxs[pass] = com.stevesoft.pat.Regex.perlCode("/"
511 + regexReplace[pass] + "/");
518 // tot up the invariant lengths for this url
519 int urllength = url_prefix.length();
520 for (pass = 0; pass < matched.length; pass++)
522 urllength += url_suffix[pass].length();
525 // flags to record which of the input sequences were actually used to
528 boolean[] thismatched = new boolean[maxs];
530 for (int sq = 0; sq < maxs; sq++)
532 // initialise flag for match
533 thismatched[sq] = false;
534 StringBuffer[] thematches = new StringBuffer[rgxs.length];
535 for (pass = 0; pass < rgxs.length; pass++)
537 thematches[pass] = new StringBuffer(); // initialise - in case there are
540 // if a regex is provided, then it must match for all sequences in all
541 // tokens for it to be considered.
542 if (idseq[pass].length <= sq)
544 // no more replacement strings to try for this token
547 if (rgxs[pass] != null)
549 com.stevesoft.pat.Regex rg = rgxs[pass];
551 // concatenate all matches of re in the given string!
552 while (rg.searchFrom(idseq[pass][sq], rematchat))
554 rematchat = rg.matchedTo();
555 thismatched[sq] |= true;
556 urllength += rg.charsMatched(); // count length
557 if ((urllength + 32) > Platform.getMaxCommandLineLength())
559 throw new UrlStringTooLongException(urllength);
564 continue; // don't bother making the URL replacement text.
566 // do we take the cartesian products of the substituents ?
567 int ns = rg.numSubs();
570 thematches[pass].append(rg.stringMatched());// take whole regex
573 * else if (ns==1) { // take only subgroup match return new String[]
574 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
577 // deal with multiple submatch case - for moment we do the simplest
578 // - concatenate the matched regions, instead of creating a complete
579 // list for each alternate match over all sequences.
580 // TODO: specify a 'replace pattern' - next refinement
585 * for (int s = 0; s <= rg.numSubs(); s++) {
586 * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
587 * " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
590 // try to collate subgroup matches
591 StringBuffer subs = new StringBuffer();
592 // have to loop through submatches, collating them at top level
597 if (s + 1 <= ns && rg.matchedTo(s) > -1
598 && rg.matchedTo(s + 1) > -1
599 && rg.matchedTo(s + 1) < rg.matchedTo(s))
601 // s is top level submatch. search for submatches enclosed by
604 StringBuffer rmtch = new StringBuffer();
605 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
607 if (rg.matchedFrom(r) > -1)
609 rmtch.append(rg.stringMatched(r));
613 if (rmtch.length() > 0)
615 subs.append(rmtch); // simply concatenate
621 if (rg.matchedFrom(s) > -1)
623 subs.append(rg.stringMatched(s)); // concatenate
628 thematches[pass].append(subs);
634 // are we only supposed to take regex matches ?
637 thismatched[sq] |= true;
638 urllength += idseq[pass][sq].length(); // tot up length
641 thematches[pass] = new StringBuffer(idseq[pass][sq]); // take
644 // regardless - probably not a
647 * TODO: do some boilerplate trimming of the fields to make them
648 * sensible e.g. trim off any 'prefix' in the id string (see
649 * UrlLink for the below) - pre 2.4 Jalview behaviour if
650 * (idstring.indexOf("|") > -1) { idstring =
651 * idstring.substring(idstring.lastIndexOf("|") + 1); }
659 // check if we are going to add this sequence's results ? all token
660 // replacements must be valid for this to happen!
661 // (including single value replacements - eg. dataset name)
666 for (pass = 0; pass < matched.length; pass++)
668 if (idseq[pass].length > 1 && matched[pass].length() > 0)
670 matched[pass].append(separators[pass]);
672 matched[pass].append(thematches[pass]);
678 // finally, if any sequences matched, then form the URL and return
679 if (seqsmatched == 0 || (createFullUrl && matched[0].length() == 0))
681 // no matches - no url generated
684 // check if we are beyond the feasible command line string limit for this
686 if ((urllength + 32) > Platform.getMaxCommandLineLength())
688 throw new UrlStringTooLongException(urllength);
692 // just return the essential info about what the URL would be generated
696 { seqsmatched }, thismatched };
698 // otherwise, create the URL completely.
700 StringBuffer submiturl = new StringBuffer();
701 submiturl.append(url_prefix);
702 for (pass = 0; pass < matched.length; pass++)
704 submiturl.append(matched[pass]);
705 if (url_suffix[pass] != null)
707 submiturl.append(url_suffix[pass]);
713 { seqsmatched }, thismatched, matched, new String[]
714 { submiturl.toString() } };
720 * @return number of distinct sequence (id or seuqence) replacements predicted
723 public int getNumberInvolved(Object[] urlstub)
725 return ((int[]) urlstub[0])[0]; // returns seqsmatched from
726 // makeUrlsIf(false,...)
730 * get token types present in this url as a bitfield indicating presence of
731 * each token from tokens (LSB->MSB).
733 * @return groupURL class as integer
735 public int getGroupURLType()
738 for (int pass = 0; pass < tokens.length; pass++)
740 for (int i = 0; i < mtch.length; i++)
742 if (mtch[i].equals(tokens[pass]))
751 public String toString()
753 StringBuffer result = new StringBuffer();
754 result.append(label + "|" + url_prefix);
756 for (r = 0; r < url_suffix.length; r++)
759 result.append(mtch[r]);
760 if (regexReplace[r] != null)
763 result.append(regexReplace[r]);
767 result.append(url_suffix[r]);
769 for (r = 0; r < separators.length; r++)
772 result.append(separators[r]);
774 return result.toString();
778 * report stats about the generated url string given an input set
784 private static void testUrls(GroupUrlLink ul, String[][] idstring,
790 System.out.println("Created NO urls.");
794 System.out.println("Created a url from " + ((int[]) url[0])[0]
795 + "out of " + idstring[0].length + " sequences.");
796 System.out.println("Sequences that did not match:");
797 for (int sq = 0; sq < idstring[0].length; sq++)
799 if (!((boolean[]) url[1])[sq])
801 System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
805 System.out.println("Sequences that DID match:");
806 for (int sq = 0; sq < idstring[0].length; sq++)
808 if (((boolean[]) url[1])[sq])
810 System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
814 System.out.println("The generated URL:");
815 System.out.println(((String[]) url[3])[0]);
819 public static void main(String argv[])
821 String[] links = new String[]
823 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
824 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCES$&inputType=1|,",
825 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCEIDS$&inputType=0|,",
826 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
827 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
828 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
829 "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|,",
830 "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|,"
832 * http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?input=P38389,P38398
833 * &inputType=0&workflow=Enfin%20Default%20Workflow&datasetName=
834 * linkInDatasetFromPRIDE
838 SequenceI[] seqs = new SequenceI[]
839 { new Sequence("StupidLabel:gi|9234|pdb|102L|A",
840 "asdiasdpasdpadpwpadasdpaspdw"), };
841 String[][] seqsandids = formStrings(seqs);
842 for (int i = 0; i < links.length; i++)
844 GroupUrlLink ul = new GroupUrlLink(links[i]);
847 System.out.println("\n\n\n");
848 System.out.println("Link " + i + " " + links[i] + " : "
850 System.out.println(" pref : " + ul.getUrl_prefix());
851 System.out.println(" IdReplace : " + ul.getIDRegexReplace());
852 System.out.println(" SeqReplace : " + ul.getSeqRegexReplace());
853 System.out.println(" Suffixes : " + ul.getUrl_suffix());
856 .println("<insert input id and sequence strings here> Without onlyIfMatches:");
860 urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset",
862 testUrls(ul, seqsandids, urls);
863 } catch (UrlStringTooLongException ex)
865 System.out.println("too long exception " + ex);
868 .println("<insert input id and sequence strings here> With onlyIfMatches set:");
871 urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset",
873 testUrls(ul, seqsandids, urls);
874 } catch (UrlStringTooLongException ex)
876 System.out.println("too long exception " + ex);
881 System.err.println("Invalid URLLink : " + links[i] + " : "
882 + ul.getInvalidMessage());
888 * covenience method to generate the id and sequence string vector from a set
889 * of seuqences using each sequence's getName() and getSequenceAsString()
893 * @return String[][] {{sequence ids},{sequence strings}}
895 public static String[][] formStrings(SequenceI[] seqs)
897 String[][] idset = new String[2][seqs.length];
898 for (int i = 0; i < seqs.length; i++)
900 idset[0][i] = seqs[i].getName();
901 idset[1][i] = seqs[i].getSequenceAsString();
906 public void setLabel(String newlabel)
908 this.label = newlabel;