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();
110 * @return the url_suffix
112 public String getUrl_suffix()
118 * @return the url_prefix
120 public String getUrl_prefix()
128 public String getTarget()
136 public String getLabel()
142 * @return the regexReplace
144 public String getRegexReplace()
150 * @return the invalidMessage
152 public String getInvalidMessage()
154 return invalidMessage;
158 * Check if URL string was parsed properly.
160 * @return boolean - if false then <code>getInvalidMessage</code> returns an
163 public boolean isValid()
165 return invalidMessage == null;
170 * @return whether link is dynamic
172 public boolean isDynamic()
179 * @return whether link uses DB Accession id
181 public boolean usesDBAccession()
183 return usesDBaccession;
191 public void setLabel(String newlabel)
193 this.label = newlabel;
197 * return one or more URL strings by applying regex to the given idstring
200 * @param onlyIfMatches
201 * - when true url strings are only made if regex is defined and
203 * @return String[] { part of idstring substituted, full substituted url , ..
204 * next part, next url..}
206 public String[] makeUrls(String idstring, boolean onlyIfMatches)
210 if (regexReplace != null)
212 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
213 + regexReplace + "/");
214 if (rg.search(idstring))
216 int ns = rg.numSubs();
220 return new String[] { rg.stringMatched(),
221 urlPrefix + rg.stringMatched() + urlSuffix };
223 * else if (ns==1) { // take only subgroup match return new String[]
224 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
230 for (int s = 0; s <= rg.numSubs(); s++)
232 System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
233 + " : " + rg.matchedTo(s) + " : '"
234 + rg.stringMatched(s) + "'");
236 // try to collate subgroup matches
237 Vector subs = new Vector();
238 // have to loop through submatches, collating them at top level
243 if (s + 1 <= ns && rg.matchedTo(s) > -1
244 && rg.matchedTo(s + 1) > -1
245 && rg.matchedTo(s + 1) < rg.matchedTo(s))
247 // s is top level submatch. search for submatches enclosed by
251 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
253 if (rg.matchedFrom(r) > -1)
255 mtch += rg.stringMatched(r);
259 if (mtch.length() > 0)
261 subs.addElement(mtch);
262 subs.addElement(urlPrefix + mtch + urlSuffix);
268 if (rg.matchedFrom(s) > -1)
270 subs.addElement(rg.stringMatched(s));
271 subs.addElement(urlPrefix + rg.stringMatched(s)
278 String[] res = new String[subs.size()];
279 for (int r = 0, rs = subs.size(); r < rs; r++)
281 res[r] = (String) subs.elementAt(r);
283 subs.removeAllElements();
292 /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
293 if (idstring.indexOf(SEP) > -1)
295 idstring = idstring.substring(idstring.lastIndexOf(SEP) + 1);
298 // just return simple url substitution.
299 return new String[] { idstring, urlPrefix + idstring + urlSuffix };
303 return new String[] { "", urlPrefix };
308 public String toString()
310 String var = (usesDBaccession ? DB_ACCESSION : SEQUENCE_ID);
315 + (dynamic ? (DELIM + var + ((regexReplace != null) ? "="
316 + regexReplace + "=" + DELIM : DELIM)) : "")
317 + ((urlSuffix == null) ? "" : urlSuffix);
323 * Location of first occurrence of separator in link string
325 * Position of sequence id or name in link string
327 * Link string containing database name and url
328 * @return Position of last separator symbol prior to any regex symbols
330 protected int parseTargetAndLabel(int firstSep, int psqid, String link)
337 p = link.indexOf(SEP, sep + 1);
338 } while (p > sep && p < psqid);
339 // Assuming that the URL itself does not contain any SEP symbols
340 // sep now contains last pipe symbol position prior to any regex symbols
341 label = link.substring(0, sep);
342 if (label.indexOf(SEP) > -1)
344 // SEP terminated database name / www target at start of Label
345 target = label.substring(0, label.indexOf(SEP));
347 else if (label.indexOf(" ") > 2)
349 // space separated Label - matches database name
350 target = label.substring(0, label.indexOf(" "));
360 * Parse the URL part of the link string
363 * Link string containing database name and url
365 * Name of variable in url string (e.g. SEQUENCE_ID, SEQUENCE_NAME)
367 * Position of id or name in link string
369 * Position of separator in link string
371 protected void parseUrl(String link, String varName, int sqidPos, int sep)
373 urlPrefix = link.substring(sep + 1, sqidPos).trim();
375 // delimiter at start of regex: e.g. $SEQUENCE_ID=/
376 String startDelimiter = DELIM + varName + "=/";
378 // delimiter at end of regex: /=$
379 String endDelimiter = "/=" + DELIM;
381 int startLength = startDelimiter.length();
383 // Parse URL : Whole URL string first
384 int p = link.indexOf(endDelimiter, sqidPos + startLength);
386 if (link.indexOf(startDelimiter) == sqidPos
387 && (p > sqidPos + startLength))
389 // Extract Regex and suffix
390 urlSuffix = link.substring(p + endDelimiter.length());
391 regexReplace = link.substring(sqidPos + startLength, p);
394 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
395 + regexReplace + "/");
398 invalidMessage = "Invalid Regular Expression : '" + regexReplace
401 } catch (Exception e)
403 invalidMessage = "Invalid Regular Expression : '" + regexReplace
411 // verify format is really correct.
412 if (link.indexOf(DELIM + varName + DELIM) == sqidPos)
414 urlSuffix = link.substring(sqidPos + startLength - 1);
419 invalidMessage = "Warning: invalid regex structure for URL link : "
426 * Create a set of URL links for a sequence
429 * The sequence to create links for
431 * Map of links: key = id + SEP + link, value = [target, label, id,
434 public void createLinksFromSeq(final SequenceI seq,
435 Map<String, List<String>> linkset)
437 if (seq != null && dynamic)
439 createDynamicLinks(seq, linkset);
443 createStaticLink(linkset);
448 * Create a static URL link
451 * Map of links: key = id + SEP + link, value = [target, label, id,
454 protected void createStaticLink(Map<String, List<String>> linkset)
456 if (!linkset.containsKey(label + SEP + getUrl_prefix()))
458 // Add a non-dynamic link
459 linkset.put(label + SEP + getUrl_prefix(),
460 Arrays.asList(target, label, null, getUrl_prefix()));
465 * Create dynamic URL links
468 * The sequence to create links for
470 * Map of links: key = id + SEP + link, value = [target, label, id,
473 protected void createDynamicLinks(final SequenceI seq,
474 Map<String, List<String>> linkset)
476 // collect id string too
477 String id = seq.getName();
478 String descr = seq.getDescription();
479 if (descr != null && descr.length() < 1)
484 if (usesDBAccession()) // link is ID
486 // collect matching db-refs
487 DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
488 new String[] { target });
490 // if there are any dbrefs which match up with the link
493 for (int r = 0; r < dbr.length; r++)
495 // create Bare ID link for this URL
496 createBareURLLink(dbr[r].getAccessionId(), true, linkset);
500 else if (!usesDBAccession() && id != null) // link is name
502 // create Bare ID link for this URL
503 createBareURLLink(id, false, linkset);
506 // Create urls from description but only for URL links which are regex
508 if (descr != null && getRegexReplace() != null)
510 // create link for this URL from description where regex matches
511 createBareURLLink(descr, false, linkset);
516 * Create a bare URL Link
517 * Returns map where key = id + SEP + link, and value = [target, label, id, link]
519 protected void createBareURLLink(String id, Boolean combineLabel,
520 Map<String, List<String>> linkset)
522 String[] urls = makeUrls(id, true);
525 for (int u = 0; u < urls.length; u += 2)
527 if (!linkset.containsKey(urls[u] + SEP + urls[u + 1]))
529 String thisLabel = label;
532 // incorporate label with idstring
533 thisLabel = label + SEP + urls[u];
536 linkset.put(urls[u] + SEP + urls[u + 1],
537 Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
543 private static void testUrls(UrlLink ul, String idstring, String[] urls)
548 System.out.println("Created NO urls.");
552 System.out.println("Created " + (urls.length / 2) + " Urls.");
553 for (int uls = 0; uls < urls.length; uls += 2)
555 System.out.println("URL Replacement text : " + urls[uls]
556 + " : URL : " + urls[uls + 1]);
561 public static void main(String argv[])
563 String[] links = new String[] {
565 * "AlinkT|Target|http://foo.foo.soo/",
566 * "myUrl1|http://$SEQUENCE_ID=/[0-9]+/=$.someserver.org/foo",
567 * "myUrl2|http://$SEQUENCE_ID=/(([0-9]+).+([A-Za-z]+))/=$.someserver.org/foo"
569 * "myUrl3|http://$SEQUENCE_ID=/([0-9]+).+([A-Za-z]+)/=$.someserver.org/foo"
570 * , "myUrl4|target|http://$SEQUENCE_ID$.someserver.org/foo|too",
571 * "PF1|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(?:PFAM:)?(.+)/=$"
573 * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
575 * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
576 * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
578 "NESTED|http://nested/$" + DB_ACCESSION
579 + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
580 String[] idstrings = new String[] {
582 * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
583 * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
585 "Label:gi|9234|pdb|102L|A" };
586 // TODO: test the setLabel method.
587 for (int i = 0; i < links.length; i++)
589 UrlLink ul = new UrlLink(links[i]);
592 System.out.println("\n\n\n");
593 System.out.println("Link " + i + " " + links[i] + " : "
595 System.out.println(" pref : "
600 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
602 for (int ids = 0; ids < idstrings.length; ids++)
604 System.out.println("ID String : " + idstrings[ids]
605 + "\nWithout onlyIfMatches:");
606 String[] urls = ul.makeUrls(idstrings[ids], false);
607 testUrls(ul, idstrings[ids], urls);
608 System.out.println("With onlyIfMatches set.");
609 urls = ul.makeUrls(idstrings[ids], true);
610 testUrls(ul, idstrings[ids], urls);
615 System.err.println("Invalid URLLink : " + links[i] + " : "
616 + ul.getInvalidMessage());