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 static jalview.util.UrlConstants.DB_ACCESSION;
24 import static jalview.util.UrlConstants.SEQUENCE_ID;
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.SequenceI;
29 import java.util.Arrays;
30 import java.util.List;
32 import java.util.Vector;
37 * helper class to parse URL Link strings taken from applet parameters or
38 * jalview properties file using the com.stevesoft.pat.Regex implementation.
39 * Jalview 2.4 extension allows regular expressions to be used to parse ID
40 * strings and replace the result in the URL. Regex's operate on the whole ID
41 * string given to the matchURL method, if no regex is supplied, then only
42 * text following the first pipe symbol will be substituted. Usage
47 private static final String SEP = "|";
49 private static final String DELIM = "$";
51 private String urlSuffix;
53 private String urlPrefix;
55 private String target;
59 private String regexReplace;
61 private boolean dynamic = false;
63 private boolean usesDBaccession = false;
65 private String invalidMessage = null;
68 * parse the given linkString of the form '<label>SEP<url>' into parts url may
69 * contain a string $SEQUENCE_ID<=optional regex=>$ where <=optional regex=>
70 * must be of the form =/<perl style regex>/=$
74 public UrlLink(String link)
76 int sep = link.indexOf(SEP);
77 int psqid = link.indexOf(DELIM + DB_ACCESSION);
78 int nsqid = link.indexOf(DELIM + SEQUENCE_ID);
82 usesDBaccession = true;
84 sep = parseTargetAndLabel(sep, psqid, link);
86 parseUrl(link, DB_ACCESSION, psqid, sep);
91 sep = parseTargetAndLabel(sep, nsqid, link);
93 parseUrl(link, SEQUENCE_ID, nsqid, sep);
97 target = link.substring(0, sep);
98 sep = link.lastIndexOf(SEP);
99 label = link.substring(0, sep);
100 urlPrefix = link.substring(sep + 1).trim();
101 regexReplace = null; // implies we trim any prefix if necessary //
105 label = label.trim();
106 target = target.trim();
107 target = target.toUpperCase(); // DBRefEntry uppercases DB names
108 // NB getCanonicalName might be better but does not currently change case
112 * @return the url_suffix
114 public String getUrl_suffix()
120 * @return the url_prefix
122 public String getUrl_prefix()
130 public String getTarget()
138 public String getLabel()
144 * @return the regexReplace
146 public String getRegexReplace()
152 * @return the invalidMessage
154 public String getInvalidMessage()
156 return invalidMessage;
160 * Check if URL string was parsed properly.
162 * @return boolean - if false then <code>getInvalidMessage</code> returns an
165 public boolean isValid()
167 return invalidMessage == null;
172 * @return whether link is dynamic
174 public boolean isDynamic()
181 * @return whether link uses DB Accession id
183 public boolean usesDBAccession()
185 return usesDBaccession;
193 public void setLabel(String newlabel)
195 this.label = newlabel;
199 * return one or more URL strings by applying regex to the given idstring
202 * @param onlyIfMatches
203 * - when true url strings are only made if regex is defined and
205 * @return String[] { part of idstring substituted, full substituted url , ..
206 * next part, next url..}
208 public String[] makeUrls(String idstring, boolean onlyIfMatches)
212 if (regexReplace != null)
214 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
215 + regexReplace + "/");
216 if (rg.search(idstring))
218 int ns = rg.numSubs();
222 return new String[] { rg.stringMatched(),
223 urlPrefix + rg.stringMatched() + urlSuffix };
225 * else if (ns==1) { // take only subgroup match return new String[]
226 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
232 for (int s = 0; s <= rg.numSubs(); s++)
234 System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
235 + " : " + rg.matchedTo(s) + " : '"
236 + rg.stringMatched(s) + "'");
238 // try to collate subgroup matches
239 Vector subs = new Vector();
240 // have to loop through submatches, collating them at top level
245 if (s + 1 <= ns && rg.matchedTo(s) > -1
246 && rg.matchedTo(s + 1) > -1
247 && rg.matchedTo(s + 1) < rg.matchedTo(s))
249 // s is top level submatch. search for submatches enclosed by
253 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
255 if (rg.matchedFrom(r) > -1)
257 mtch += rg.stringMatched(r);
261 if (mtch.length() > 0)
263 subs.addElement(mtch);
264 subs.addElement(urlPrefix + mtch + urlSuffix);
270 if (rg.matchedFrom(s) > -1)
272 subs.addElement(rg.stringMatched(s));
273 subs.addElement(urlPrefix + rg.stringMatched(s)
280 String[] res = new String[subs.size()];
281 for (int r = 0, rs = subs.size(); r < rs; r++)
283 res[r] = (String) subs.elementAt(r);
285 subs.removeAllElements();
294 /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
295 if (idstring.indexOf(SEP) > -1)
297 idstring = idstring.substring(idstring.lastIndexOf(SEP) + 1);
300 // just return simple url substitution.
301 return new String[] { idstring, urlPrefix + idstring + urlSuffix };
305 return new String[] { "", urlPrefix };
310 public String toString()
312 String var = (usesDBaccession ? DB_ACCESSION : SEQUENCE_ID);
317 + (dynamic ? (DELIM + var + ((regexReplace != null) ? "="
318 + regexReplace + "=" + DELIM : DELIM)) : "")
319 + ((urlSuffix == null) ? "" : urlSuffix);
325 * Location of first occurrence of separator in link string
327 * Position of sequence id or name in link string
329 * Link string containing database name and url
330 * @return Position of last separator symbol prior to any regex symbols
332 protected int parseTargetAndLabel(int firstSep, int psqid, String link)
339 p = link.indexOf(SEP, sep + 1);
340 } while (p > sep && p < psqid);
341 // Assuming that the URL itself does not contain any SEP symbols
342 // sep now contains last pipe symbol position prior to any regex symbols
343 label = link.substring(0, sep);
344 if (label.indexOf(SEP) > -1)
346 // SEP terminated database name / www target at start of Label
347 target = label.substring(0, label.indexOf(SEP));
349 else if (label.indexOf(" ") > 2)
351 // space separated Label - matches database name
352 target = label.substring(0, label.indexOf(" "));
362 * Parse the URL part of the link string
365 * Link string containing database name and url
367 * Name of variable in url string (e.g. SEQUENCE_ID, SEQUENCE_NAME)
369 * Position of id or name in link string
371 * Position of separator in link string
373 protected void parseUrl(String link, String varName, int sqidPos, int sep)
375 urlPrefix = link.substring(sep + 1, sqidPos).trim();
377 // delimiter at start of regex: e.g. $SEQUENCE_ID=/
378 String startDelimiter = DELIM + varName + "=/";
380 // delimiter at end of regex: /=$
381 String endDelimiter = "/=" + DELIM;
383 int startLength = startDelimiter.length();
385 // Parse URL : Whole URL string first
386 int p = link.indexOf(endDelimiter, sqidPos + startLength);
388 if (link.indexOf(startDelimiter) == sqidPos
389 && (p > sqidPos + startLength))
391 // Extract Regex and suffix
392 urlSuffix = link.substring(p + endDelimiter.length());
393 regexReplace = link.substring(sqidPos + startLength, p);
396 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
397 + regexReplace + "/");
400 invalidMessage = "Invalid Regular Expression : '" + regexReplace
403 } catch (Exception e)
405 invalidMessage = "Invalid Regular Expression : '" + regexReplace
413 // verify format is really correct.
414 if (link.indexOf(DELIM + varName + DELIM) == sqidPos)
416 urlSuffix = link.substring(sqidPos + startLength - 1);
421 invalidMessage = "Warning: invalid regex structure for URL link : "
428 * Create a set of URL links for a sequence
431 * The sequence to create links for
433 * Map of links: key = id + SEP + link, value = [target, label, id,
436 public void createLinksFromSeq(final SequenceI seq,
437 Map<String, List<String>> linkset)
439 if (seq != null && dynamic)
441 createDynamicLinks(seq, linkset);
445 createStaticLink(linkset);
450 * Create a static URL link
453 * Map of links: key = id + SEP + link, value = [target, label, id,
456 protected void createStaticLink(Map<String, List<String>> linkset)
458 if (!linkset.containsKey(label + SEP + getUrl_prefix()))
460 // Add a non-dynamic link
461 linkset.put(label + SEP + getUrl_prefix(),
462 Arrays.asList(target, label, null, getUrl_prefix()));
467 * Create dynamic URL links
470 * The sequence to create links for
472 * Map of links: key = id + SEP + link, value = [target, label, id,
475 protected void createDynamicLinks(final SequenceI seq,
476 Map<String, List<String>> linkset)
478 // collect id string too
479 String id = seq.getName();
480 String descr = seq.getDescription();
481 if (descr != null && descr.length() < 1)
486 if (usesDBAccession()) // link is ID
488 // collect matching db-refs
489 DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
490 new String[] { target });
492 // if there are any dbrefs which match up with the link
495 for (int r = 0; r < dbr.length; r++)
497 // create Bare ID link for this URL
498 createBareURLLink(dbr[r].getAccessionId(), true, linkset);
502 else if (!usesDBAccession() && id != null) // link is name
504 // create Bare ID link for this URL
505 createBareURLLink(id, false, linkset);
508 // Create urls from description but only for URL links which are regex
510 if (descr != null && getRegexReplace() != null)
512 // create link for this URL from description where regex matches
513 createBareURLLink(descr, false, linkset);
518 * Create a bare URL Link
519 * Returns map where key = id + SEP + link, and value = [target, label, id, link]
521 protected void createBareURLLink(String id, Boolean combineLabel,
522 Map<String, List<String>> linkset)
524 String[] urls = makeUrls(id, true);
527 for (int u = 0; u < urls.length; u += 2)
529 if (!linkset.containsKey(urls[u] + SEP + urls[u + 1]))
531 String thisLabel = label;
534 // incorporate label with idstring
535 thisLabel = label + SEP + urls[u];
538 linkset.put(urls[u] + SEP + urls[u + 1],
539 Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
545 private static void testUrls(UrlLink ul, String idstring, String[] urls)
550 System.out.println("Created NO urls.");
554 System.out.println("Created " + (urls.length / 2) + " Urls.");
555 for (int uls = 0; uls < urls.length; uls += 2)
557 System.out.println("URL Replacement text : " + urls[uls]
558 + " : URL : " + urls[uls + 1]);
563 public static void main(String argv[])
565 String[] links = new String[] {
567 * "AlinkT|Target|http://foo.foo.soo/",
568 * "myUrl1|http://$SEQUENCE_ID=/[0-9]+/=$.someserver.org/foo",
569 * "myUrl2|http://$SEQUENCE_ID=/(([0-9]+).+([A-Za-z]+))/=$.someserver.org/foo"
571 * "myUrl3|http://$SEQUENCE_ID=/([0-9]+).+([A-Za-z]+)/=$.someserver.org/foo"
572 * , "myUrl4|target|http://$SEQUENCE_ID$.someserver.org/foo|too",
573 * "PF1|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(?:PFAM:)?(.+)/=$"
575 * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
577 * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
578 * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
580 "NESTED|http://nested/$" + DB_ACCESSION
581 + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
582 String[] idstrings = new String[] {
584 * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
585 * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
587 "Label:gi|9234|pdb|102L|A" };
588 // TODO: test the setLabel method.
589 for (int i = 0; i < links.length; i++)
591 UrlLink ul = new UrlLink(links[i]);
594 System.out.println("\n\n\n");
595 System.out.println("Link " + i + " " + links[i] + " : "
597 System.out.println(" pref : "
602 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
604 for (int ids = 0; ids < idstrings.length; ids++)
606 System.out.println("ID String : " + idstrings[ids]
607 + "\nWithout onlyIfMatches:");
608 String[] urls = ul.makeUrls(idstrings[ids], false);
609 testUrls(ul, idstrings[ids], urls);
610 System.out.println("With onlyIfMatches set.");
611 urls = ul.makeUrls(idstrings[ids], true);
612 testUrls(ul, idstrings[ids], urls);
617 System.err.println("Invalid URLLink : " + links[i] + " : "
618 + ul.getInvalidMessage());