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.
23 import jalview.datamodel.Sequence;
24 import jalview.datamodel.SequenceI;
26 import java.util.Hashtable;
28 public class GroupUrlLink
30 public class UrlStringTooLongException extends Exception
32 public UrlStringTooLongException(int lng)
40 public String toString()
42 return "Generated url is estimated to be too long (" + urlLength
48 * Helper class based on the UrlLink class which enables URLs to be
49 * constructed from sequences or IDs associated with a group of sequences. URL
50 * definitions consist of a pipe separated string containing a <label>|<url
51 * construct>|<separator character>[|<sequence separator character>]. The url
52 * construct includes regex qualified tokens which are replaced with seuqence
53 * IDs ($SEQUENCE_IDS$) and/or seuqence regions ($SEQUENCES$) that are
54 * extracted from the group. See <code>UrlLink</code> for more information
55 * about the approach, and the original implementation. Documentation to come.
56 * Note - groupUrls can be very big!
58 private String url_prefix, target, label;
61 * these are all filled in order of the occurence of each token in the url
64 private String url_suffix[], separators[], regexReplace[];
66 private String invalidMessage = null;
69 * tokens that can be replaced in the URL.
71 private static String[] tokens;
74 * position of each token (which can appear once only) in the url
79 * contains tokens in the order they appear in the URL template.
81 private String[] mtch;
86 tokens = new String[] { "SEQUENCEIDS", "SEQUENCES", "DATASETID" };
91 * test for GroupURLType bitfield (with default tokens)
93 public static final int SEQUENCEIDS = 1;
96 * test for GroupURLType bitfield (with default tokens)
98 public static final int SEQUENCES = 2;
101 * test for GroupURLType bitfield (with default tokens)
103 public static final int DATASETID = 4;
105 // private int idseg = -1, seqseg = -1;
108 * parse the given linkString of the form '<label>|<url>|separator
109 * char[|optional sequence separator char]' into parts. url may contain a
110 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
111 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
112 * $SEQUENCES<=optional regex=>$.
116 public GroupUrlLink(String link)
118 int sep = link.indexOf("|");
119 segs = new int[tokens.length];
121 for (int i = 0; i < segs.length; i++)
123 if ((segs[i] = link.indexOf("$" + tokens[i])) > -1)
128 // expect at least one token
131 invalidMessage = "Group URL string must contain at least one of ";
132 for (int i = 0; i < segs.length; i++)
134 invalidMessage += " '$" + tokens[i] + "[=/regex=/]$'";
139 int[] ptok = new int[ntoks + 1];
140 String[] tmtch = new String[ntoks + 1];
141 mtch = new String[ntoks];
142 for (int i = 0, t = 0; i < segs.length; i++)
147 tmtch[t++] = tokens[i];
150 ptok[ntoks] = link.length();
151 tmtch[ntoks] = "$$$$$$$$$";
152 jalview.util.QuickSort.sort(ptok, tmtch);
153 for (int i = 0; i < ntoks; i++)
155 mtch[i] = tmtch[i]; // TODO: check order is ascending
158 * replaces the specific code below {}; if (psqids > -1 && pseqs > -1) { if
159 * (psqids > pseqs) { idseg = 1; seqseg = 0;
161 * ptok = new int[] { pseqs, psqids, link.length() }; mtch = new String[] {
162 * "$SEQUENCES", "$SEQUENCEIDS" }; } else { idseg = 0; seqseg = 1; ptok =
163 * new int[] { psqids, pseqs, link.length() }; mtch = new String[] {
164 * "$SEQUENCEIDS", "$SEQUENCES" }; } } else { if (psqids != -1) { idseg = 0;
165 * ptok = new int[] { psqids, link.length() }; mtch = new String[] {
166 * "$SEQUENCEIDS" }; } else { seqseg = 0; ptok = new int[] { pseqs,
167 * link.length() }; mtch = new String[] { "$SEQUENCES" }; } }
171 // first get the label and target part before the first |
175 p = link.indexOf("|", sep + 1);
176 } while (p > sep && p < ptok[0]);
177 // Assuming that the URL itself does not contain any '|' symbols
178 // sep now contains last pipe symbol position prior to any regex symbols
179 label = link.substring(0, sep);
180 if (label.indexOf("|") > -1)
182 // | terminated database name / www target at start of Label
183 target = label.substring(0, label.indexOf("|"));
185 else if (label.indexOf(" ") > 2)
187 // space separated Label - matches database name
188 target = label.substring(0, label.indexOf(" "));
194 // Now Parse URL : Whole URL string first
195 url_prefix = link.substring(sep + 1, ptok[0]);
196 url_suffix = new String[mtch.length];
197 regexReplace = new String[mtch.length];
198 // and loop through tokens
199 for (int pass = 0; pass < mtch.length; pass++)
201 int mlength = 3 + mtch[pass].length();
202 if (link.indexOf("$" + mtch[pass] + "=/") == ptok[pass] && (p = link
203 .indexOf("/=$", ptok[pass] + mlength)) > ptok[pass] + mlength)
205 // Extract Regex and suffix
206 if (ptok[pass + 1] < p + 3)
208 // tokens are not allowed inside other tokens - e.g. inserting a
209 // $sequences$ into the regex match for the sequenceid
210 invalidMessage = "Token regexes cannot contain other regexes (did you terminate the $"
211 + mtch[pass] + " regex with a '/=$' ?";
214 url_suffix[pass] = link.substring(p + 3, ptok[pass + 1]);
215 regexReplace[pass] = link.substring(ptok[pass] + mlength, p);
218 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex
219 .perlCode("/" + regexReplace[pass] + "/");
222 invalidMessage = "Invalid Regular Expression : '"
223 + regexReplace[pass] + "'\n";
225 } catch (Exception e)
227 invalidMessage = "Invalid Regular Expression : '"
228 + regexReplace[pass] + "'\n";
233 regexReplace[pass] = null;
234 // verify format is really correct.
235 if ((p = link.indexOf("$" + mtch[pass] + "$")) == ptok[pass])
237 url_suffix[pass] = link.substring(p + mtch[pass].length() + 2,
242 invalidMessage = "Warning: invalid regex structure (after '"
243 + mtch[0] + "') for URL link : " + link;
248 separators = new String[url_suffix.length];
249 String suffices = url_suffix[url_suffix.length - 1], lastsep = ",";
250 // have a look in the last suffix for any more separators.
251 while ((p = suffices.indexOf('|')) > -1)
253 separators[pass] = suffices.substring(p + 1);
256 // trim the original suffix string
257 url_suffix[url_suffix.length - 1] = suffices.substring(0, p);
261 lastsep = (separators[pass - 1] = separators[pass - 1].substring(0,
264 suffices = separators[pass];
269 lastsep = separators[pass - 1];
271 // last separator is always used for all the remaining separators
272 while (pass < separators.length)
274 separators[pass++] = lastsep;
279 * @return the url_suffix
281 public String getUrl_suffix()
283 return url_suffix[url_suffix.length - 1];
287 * @return the url_prefix
289 public String getUrl_prefix()
297 public String getTarget()
305 public String getLabel()
311 * @return the sequence ID regexReplace
313 public String getIDRegexReplace()
315 return _replaceFor(tokens[0]);
318 private String _replaceFor(String token)
320 for (int i = 0; i < mtch.length; i++)
322 if (segs[i] > -1 && mtch[i].equals(token))
324 return regexReplace[i];
331 * @return the sequence ID regexReplace
333 public String getSeqRegexReplace()
335 return _replaceFor(tokens[1]);
339 * @return the invalidMessage
341 public String getInvalidMessage()
343 return invalidMessage;
347 * Check if URL string was parsed properly.
349 * @return boolean - if false then <code>getInvalidMessage</code> returns an
352 public boolean isValid()
354 return invalidMessage == null;
358 * return one or more URL strings by applying regex to the given idstring
361 * array of id strings to pass to service
363 * array of seq strings to pass to service
364 * @param onlyIfMatches
365 * - when true url strings are only made if regex is defined and
366 * matches for all qualified tokens in groupURL - TODO: consider if
367 * onlyIfMatches is really a useful parameter!
368 * @return null or Object[] { int[] { number of seqs substituted},boolean[] {
369 * which seqs were substituted }, StringBuffer[] { substituted lists
370 * for each token }, String[] { url } }
371 * @throws UrlStringTooLongException
373 public Object[] makeUrls(String[] idstrings, String[] seqstrings,
374 String dsstring, boolean onlyIfMatches)
375 throws UrlStringTooLongException
377 Hashtable rstrings = replacementArgs(idstrings, seqstrings, dsstring);
378 return makeUrls(rstrings, onlyIfMatches);
382 * gathers input into a hashtable
389 private Hashtable replacementArgs(String[] idstrings, String[] seqstrings,
392 Hashtable rstrings = new Hashtable();
393 rstrings.put(tokens[0], idstrings);
394 rstrings.put(tokens[1], seqstrings);
395 rstrings.put(tokens[2], new String[] { dsstring });
396 if (idstrings.length != seqstrings.length)
398 throw new Error(MessageManager.getString(
399 "error.idstring_seqstrings_only_one_per_sequence"));
404 public Object[] makeUrls(Hashtable repstrings, boolean onlyIfMatches)
405 throws UrlStringTooLongException
407 return makeUrlsIf(true, repstrings, onlyIfMatches);
416 * @return URL stub objects ready to pass to constructFrom
417 * @throws UrlStringTooLongException
419 public Object[] makeUrlStubs(String[] ids, String[] seqstr, String string,
420 boolean b) throws UrlStringTooLongException
422 Hashtable rstrings = replacementArgs(ids, seqstr, string);
423 Object[] stubs = makeUrlsIf(false, rstrings, b);
426 return new Object[] { stubs[0], stubs[1], rstrings,
430 // TODO Auto-generated method stub
435 * generate the URL for the given URL stub object array returned from
439 * @return URL string.
440 * @throws UrlStringTooLongException
442 public String constructFrom(Object[] stubs)
443 throws UrlStringTooLongException
445 Object[] results = makeUrlsIf(true, (Hashtable) stubs[2],
446 ((boolean[]) stubs[3])[0]);
447 return ((String[]) results[3])[0];
451 * conditionally generate urls or stubs for a given input.
453 * @param createFullUrl
454 * set to false if you only want to test if URLs would be generated.
456 * @param onlyIfMatches
457 * @return null if no url is generated. Object[] { int[] { number of matches
458 * seqs }, boolean[] { which matched }, (if createFullUrl also has
459 * StringBuffer[] { segment generated from inputs that is used in URL
460 * }, String[] { url })}
461 * @throws UrlStringTooLongException
463 protected Object[] makeUrlsIf(boolean createFullUrl, Hashtable repstrings,
464 boolean onlyIfMatches) throws UrlStringTooLongException
468 // prepare string arrays in correct order to be assembled into URL input
469 String[][] idseq = new String[mtch.length][]; // indexed by pass
470 int mins = 0, maxs = 0; // allowed two values, 1 or n-sequences.
471 for (int i = 0; i < mtch.length; i++)
473 idseq[i] = (String[]) repstrings.get(mtch[i]);
474 if (idseq[i].length >= 1)
476 if (mins == 0 && idseq[i].length == 1)
482 maxs = idseq[i].length;
486 if (maxs != idseq[i].length)
488 throw new Error(MessageManager.formatMessage(
489 "error.cannot_have_mixed_length_replacement_vectors",
492 Integer.valueOf(idseq[i].length).toString(),
493 Integer.valueOf(maxs).toString() }));
499 throw new Error(MessageManager.getString(
500 "error.cannot_have_zero_length_vector_replacement_strings"));
503 // iterate through input, collating segments to be inserted into url
504 StringBuffer matched[] = new StringBuffer[idseq.length];
505 // and precompile regexes
506 com.stevesoft.pat.Regex[] rgxs = new com.stevesoft.pat.Regex[matched.length];
507 for (pass = 0; pass < matched.length; pass++)
509 matched[pass] = new StringBuffer();
510 if (regexReplace[pass] != null)
512 rgxs[pass] = com.stevesoft.pat.Regex
513 .perlCode("/" + regexReplace[pass] + "/");
520 // tot up the invariant lengths for this url
521 int urllength = url_prefix.length();
522 for (pass = 0; pass < matched.length; pass++)
524 urllength += url_suffix[pass].length();
527 // flags to record which of the input sequences were actually used to
530 boolean[] thismatched = new boolean[maxs];
532 for (int sq = 0; sq < maxs; sq++)
534 // initialise flag for match
535 thismatched[sq] = false;
536 StringBuffer[] thematches = new StringBuffer[rgxs.length];
537 for (pass = 0; pass < rgxs.length; pass++)
539 thematches[pass] = new StringBuffer(); // initialise - in case there are
542 // if a regex is provided, then it must match for all sequences in all
543 // tokens for it to be considered.
544 if (idseq[pass].length <= sq)
546 // no more replacement strings to try for this token
549 if (rgxs[pass] != null)
551 com.stevesoft.pat.Regex rg = rgxs[pass];
553 // concatenate all matches of re in the given string!
554 while (rg.searchFrom(idseq[pass][sq], rematchat))
556 rematchat = rg.matchedTo();
557 thismatched[sq] |= true;
558 urllength += rg.charsMatched(); // count length
559 if ((urllength + 32) > Platform.getMaxCommandLineLength())
561 throw new UrlStringTooLongException(urllength);
566 continue; // don't bother making the URL replacement text.
568 // do we take the cartesian products of the substituents ?
569 int ns = rg.numSubs();
572 thematches[pass].append(rg.stringMatched());// take whole regex
575 * else if (ns==1) { // take only subgroup match return new String[]
576 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
579 // deal with multiple submatch case - for moment we do the simplest
580 // - concatenate the matched regions, instead of creating a complete
581 // list for each alternate match over all sequences.
582 // TODO: specify a 'replace pattern' - next refinement
587 * for (int s = 0; s <= rg.numSubs(); s++) {
588 * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
589 * " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
592 // try to collate subgroup matches
593 StringBuffer subs = new StringBuffer();
594 // have to loop through submatches, collating them at top level
599 if (s + 1 <= ns && rg.matchedTo(s) > -1
600 && rg.matchedTo(s + 1) > -1
601 && rg.matchedTo(s + 1) < rg.matchedTo(s))
603 // s is top level submatch. search for submatches enclosed by
606 StringBuffer rmtch = new StringBuffer();
607 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
609 if (rg.matchedFrom(r) > -1)
611 rmtch.append(rg.stringMatched(r));
615 if (rmtch.length() > 0)
617 subs.append(rmtch); // simply concatenate
623 if (rg.matchedFrom(s) > -1)
625 subs.append(rg.stringMatched(s)); // concatenate
630 thematches[pass].append(subs);
636 // are we only supposed to take regex matches ?
639 thismatched[sq] |= true;
640 urllength += idseq[pass][sq].length(); // tot up length
643 thematches[pass] = new StringBuffer(idseq[pass][sq]); // take
646 // regardless - probably not a
649 * TODO: do some boilerplate trimming of the fields to make them
650 * sensible e.g. trim off any 'prefix' in the id string (see
651 * UrlLink for the below) - pre 2.4 Jalview behaviour if
652 * (idstring.indexOf("|") > -1) { idstring =
653 * idstring.substring(idstring.lastIndexOf("|") + 1); }
661 // check if we are going to add this sequence's results ? all token
662 // replacements must be valid for this to happen!
663 // (including single value replacements - eg. dataset name)
668 for (pass = 0; pass < matched.length; pass++)
670 if (idseq[pass].length > 1 && matched[pass].length() > 0)
672 matched[pass].append(separators[pass]);
674 matched[pass].append(thematches[pass]);
680 // finally, if any sequences matched, then form the URL and return
681 if (seqsmatched == 0 || (createFullUrl && matched[0].length() == 0))
683 // no matches - no url generated
686 // check if we are beyond the feasible command line string limit for this
688 if ((urllength + 32) > Platform.getMaxCommandLineLength())
690 throw new UrlStringTooLongException(urllength);
694 // just return the essential info about what the URL would be generated
696 return new Object[] { new int[] { 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]);
711 return new Object[] { new int[] { seqsmatched }, thismatched, matched,
713 { submiturl.toString() } };
719 * @return number of distinct sequence (id or seuqence) replacements predicted
722 public int getNumberInvolved(Object[] urlstub)
724 return ((int[]) urlstub[0])[0]; // returns seqsmatched from
725 // makeUrlsIf(false,...)
729 * get token types present in this url as a bitfield indicating presence of
730 * each token from tokens (LSB->MSB).
732 * @return groupURL class as integer
734 public int getGroupURLType()
737 for (int pass = 0; pass < tokens.length; pass++)
739 for (int i = 0; i < mtch.length; i++)
741 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]);
824 public static void main(String argv[])
826 // note - JAL-1383 - these services are all dead
827 String[] links = new String[] {
828 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
829 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCES$&inputType=1|,",
830 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCEIDS$&inputType=0|,",
831 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
832 "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
833 "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
834 "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|,",
835 "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|,"
837 * http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?input=P38389,P38398
838 * &inputType=0&workflow=Enfin%20Default%20Workflow&datasetName=
839 * linkInDatasetFromPRIDE
843 SequenceI[] seqs = new SequenceI[] {
844 new Sequence("StupidLabel:gi|9234|pdb|102L|A",
845 "asdiasdpasdpadpwpadasdpaspdw"), };
846 String[][] seqsandids = formStrings(seqs);
847 for (int i = 0; i < links.length; i++)
849 GroupUrlLink ul = new GroupUrlLink(links[i]);
852 System.out.println("\n\n\n");
854 "Link " + i + " " + links[i] + " : " + ul.toString());
855 System.out.println(" pref : " + ul.getUrl_prefix());
856 System.out.println(" IdReplace : " + ul.getIDRegexReplace());
857 System.out.println(" SeqReplace : " + ul.getSeqRegexReplace());
858 System.out.println(" Suffixes : " + ul.getUrl_suffix());
861 "<insert input id and sequence strings here> Without onlyIfMatches:");
865 urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset",
867 testUrls(ul, seqsandids, urls);
868 } catch (UrlStringTooLongException ex)
870 System.out.println("too long exception " + ex);
873 "<insert input id and sequence strings here> With onlyIfMatches set:");
876 urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset",
878 testUrls(ul, seqsandids, urls);
879 } catch (UrlStringTooLongException ex)
881 System.out.println("too long exception " + ex);
886 System.err.println("Invalid URLLink : " + links[i] + " : "
887 + ul.getInvalidMessage());
893 * covenience method to generate the id and sequence string vector from a set
894 * of seuqences using each sequence's getName() and getSequenceAsString()
898 * @return String[][] {{sequence ids},{sequence strings}}
900 public static String[][] formStrings(SequenceI[] seqs)
902 String[][] idset = new String[2][seqs.length];
903 for (int i = 0; i < seqs.length; i++)
905 idset[0][i] = seqs[i].getName();
906 idset[1][i] = seqs[i].getSequenceAsString();
911 public void setLabel(String newlabel)
913 this.label = newlabel;