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.DELIM;
25 import static jalview.util.UrlConstants.SEP;
26 import static jalview.util.UrlConstants.SEQUENCE_ID;
28 import jalview.datamodel.DBRefEntry;
29 import jalview.datamodel.SequenceI;
31 import java.util.Arrays;
32 import java.util.List;
34 import java.util.Vector;
39 * helper class to parse URL Link strings taken from applet parameters or
40 * jalview properties file using the com.stevesoft.pat.Regex implementation.
41 * Jalview 2.4 extension allows regular expressions to be used to parse ID
42 * strings and replace the result in the URL. Regex's operate on the whole ID
43 * string given to the matchURL method, if no regex is supplied, then only
44 * text following the first pipe symbol will be substituted. Usage
48 private String urlSuffix;
50 private String urlPrefix;
52 private String target;
56 private String regexReplace;
58 private boolean dynamic = false;
60 private boolean usesDBaccession = false;
62 private String invalidMessage = null;
65 * parse the given linkString of the form '<label>SEP<url>' into parts url may
66 * contain a string $SEQUENCE_ID<=optional regex=>$ where <=optional regex=>
67 * must be of the form =/<perl style regex>/=$
71 public UrlLink(String link)
73 int sep = link.indexOf(SEP);
74 int psqid = link.indexOf(DELIM + DB_ACCESSION);
75 int nsqid = link.indexOf(DELIM + SEQUENCE_ID);
79 usesDBaccession = true;
81 sep = parseTargetAndLabel(sep, psqid, link);
83 parseUrl(link, DB_ACCESSION, psqid, sep);
88 sep = parseTargetAndLabel(sep, nsqid, link);
90 parseUrl(link, SEQUENCE_ID, nsqid, sep);
94 target = link.substring(0, sep);
95 sep = link.lastIndexOf(SEP);
96 label = link.substring(0, sep);
97 urlPrefix = link.substring(sep + 1).trim();
98 regexReplace = null; // implies we trim any prefix if necessary //
102 label = label.trim();
103 target = target.trim();
107 * Alternative constructor for separate name and link
112 public UrlLink(String name, String url)
114 this(name + SEP + url);
118 * @return the url_suffix
120 public String getUrl_suffix()
126 * @return the url_prefix
128 public String getUrl_prefix()
136 public String getTarget()
144 public String getLabel()
149 public String getUrlWithToken()
151 String var = (usesDBaccession ? DB_ACCESSION : SEQUENCE_ID);
154 + (dynamic ? (DELIM + var + ((regexReplace != null) ? "="
155 + regexReplace + "=" + DELIM : DELIM)) : "")
156 + ((urlSuffix == null) ? "" : urlSuffix);
160 * @return the regexReplace
162 public String getRegexReplace()
168 * @return the invalidMessage
170 public String getInvalidMessage()
172 return invalidMessage;
176 * Check if URL string was parsed properly.
178 * @return boolean - if false then <code>getInvalidMessage</code> returns an
181 public boolean isValid()
183 return invalidMessage == null;
188 * @return whether link is dynamic
190 public boolean isDynamic()
197 * @return whether link uses DB Accession id
199 public boolean usesDBAccession()
201 return usesDBaccession;
209 public void setLabel(String newlabel)
211 this.label = newlabel;
215 * return one or more URL strings by applying regex to the given idstring
218 * @param onlyIfMatches
219 * - when true url strings are only made if regex is defined and
221 * @return String[] { part of idstring substituted, full substituted url , ..
222 * next part, next url..}
224 public String[] makeUrls(String idstring, boolean onlyIfMatches)
228 if (regexReplace != null)
230 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
231 + regexReplace + "/");
232 if (rg.search(idstring))
234 int ns = rg.numSubs();
238 return new String[] { rg.stringMatched(),
239 urlPrefix + rg.stringMatched() + urlSuffix };
241 * else if (ns==1) { // take only subgroup match return new String[]
242 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
248 for (int s = 0; s <= rg.numSubs(); s++)
250 System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
251 + " : " + rg.matchedTo(s) + " : '"
252 + rg.stringMatched(s) + "'");
254 // try to collate subgroup matches
255 Vector subs = new Vector();
256 // have to loop through submatches, collating them at top level
261 if (s + 1 <= ns && rg.matchedTo(s) > -1
262 && rg.matchedTo(s + 1) > -1
263 && rg.matchedTo(s + 1) < rg.matchedTo(s))
265 // s is top level submatch. search for submatches enclosed by
269 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
271 if (rg.matchedFrom(r) > -1)
273 mtch += rg.stringMatched(r);
277 if (mtch.length() > 0)
279 subs.addElement(mtch);
280 subs.addElement(urlPrefix + mtch + urlSuffix);
286 if (rg.matchedFrom(s) > -1)
288 subs.addElement(rg.stringMatched(s));
289 subs.addElement(urlPrefix + rg.stringMatched(s)
296 String[] res = new String[subs.size()];
297 for (int r = 0, rs = subs.size(); r < rs; r++)
299 res[r] = (String) subs.elementAt(r);
301 subs.removeAllElements();
310 /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
311 if (idstring.indexOf(SEP) > -1)
313 idstring = idstring.substring(idstring.lastIndexOf(SEP) + 1);
316 // just return simple url substitution.
317 return new String[] { idstring, urlPrefix + idstring + urlSuffix };
321 return new String[] { "", urlPrefix };
326 public String toString()
328 return label + SEP + getUrlWithToken();
334 * Location of first occurrence of separator in link string
336 * Position of sequence id or name in link string
338 * Link string containing database name and url
339 * @return Position of last separator symbol prior to any regex symbols
341 protected int parseTargetAndLabel(int firstSep, int psqid, String link)
348 p = link.indexOf(SEP, sep + 1);
349 } while (p > sep && p < psqid);
350 // Assuming that the URL itself does not contain any SEP symbols
351 // sep now contains last pipe symbol position prior to any regex symbols
352 label = link.substring(0, sep);
353 if (label.indexOf(SEP) > -1)
355 // SEP terminated database name / www target at start of Label
356 target = label.substring(0, label.indexOf(SEP));
358 else if (label.indexOf(" ") > 2)
360 // space separated Label - matches database name
361 target = label.substring(0, label.indexOf(" "));
371 * Parse the URL part of the link string
374 * Link string containing database name and url
376 * Name of variable in url string (e.g. SEQUENCE_ID, SEQUENCE_NAME)
378 * Position of id or name in link string
380 * Position of separator in link string
382 protected void parseUrl(String link, String varName, int sqidPos, int sep)
384 urlPrefix = link.substring(sep + 1, sqidPos).trim();
386 // delimiter at start of regex: e.g. $SEQUENCE_ID=/
387 String startDelimiter = DELIM + varName + "=/";
389 // delimiter at end of regex: /=$
390 String endDelimiter = "/=" + DELIM;
392 int startLength = startDelimiter.length();
394 // Parse URL : Whole URL string first
395 int p = link.indexOf(endDelimiter, sqidPos + startLength);
397 if (link.indexOf(startDelimiter) == sqidPos
398 && (p > sqidPos + startLength))
400 // Extract Regex and suffix
401 urlSuffix = link.substring(p + endDelimiter.length());
402 regexReplace = link.substring(sqidPos + startLength, p);
405 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
406 + regexReplace + "/");
409 invalidMessage = "Invalid Regular Expression : '" + regexReplace
412 } catch (Exception e)
414 invalidMessage = "Invalid Regular Expression : '" + regexReplace
422 // verify format is really correct.
423 if (link.indexOf(DELIM + varName + DELIM) == sqidPos)
425 urlSuffix = link.substring(sqidPos + startLength - 1);
430 invalidMessage = "Warning: invalid regex structure for URL link : "
437 * Create a set of URL links for a sequence
440 * The sequence to create links for
442 * Map of links: key = id + SEP + link, value = [target, label, id,
445 public void createLinksFromSeq(final SequenceI seq,
446 Map<String, List<String>> linkset)
448 if (seq != null && dynamic)
450 createDynamicLinks(seq, linkset);
454 createStaticLink(linkset);
459 * Create a static URL link
462 * Map of links: key = id + SEP + link, value = [target, label, id,
465 protected void createStaticLink(Map<String, List<String>> linkset)
467 if (!linkset.containsKey(label + SEP + getUrl_prefix()))
469 // Add a non-dynamic link
470 linkset.put(label + SEP + getUrl_prefix(),
471 Arrays.asList(target, label, null, getUrl_prefix()));
476 * Create dynamic URL links
479 * The sequence to create links for
481 * Map of links: key = id + SEP + link, value = [target, label, id,
484 protected void createDynamicLinks(final SequenceI seq,
485 Map<String, List<String>> linkset)
487 // collect id string too
488 String id = seq.getName();
489 String descr = seq.getDescription();
490 if (descr != null && descr.length() < 1)
495 if (usesDBAccession()) // link is ID
497 // collect matching db-refs
498 DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
499 new String[] { target });
501 // if there are any dbrefs which match up with the link
504 for (int r = 0; r < dbr.length; r++)
506 // create Bare ID link for this URL
507 createBareURLLink(dbr[r].getAccessionId(), true, linkset);
511 else if (!usesDBAccession() && id != null) // link is name
513 // create Bare ID link for this URL
514 createBareURLLink(id, false, linkset);
517 // Create urls from description but only for URL links which are regex
519 if (descr != null && getRegexReplace() != null)
521 // create link for this URL from description where regex matches
522 createBareURLLink(descr, false, linkset);
527 * Create a bare URL Link
528 * Returns map where key = id + SEP + link, and value = [target, label, id, link]
530 protected void createBareURLLink(String id, Boolean combineLabel,
531 Map<String, List<String>> linkset)
533 String[] urls = makeUrls(id, true);
536 for (int u = 0; u < urls.length; u += 2)
538 if (!linkset.containsKey(urls[u] + SEP + urls[u + 1]))
540 String thisLabel = label;
543 // incorporate label with idstring
544 thisLabel = label + SEP + urls[u];
547 linkset.put(urls[u] + SEP + urls[u + 1],
548 Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
554 private static void testUrls(UrlLink ul, String idstring, String[] urls)
559 System.out.println("Created NO urls.");
563 System.out.println("Created " + (urls.length / 2) + " Urls.");
564 for (int uls = 0; uls < urls.length; uls += 2)
566 System.out.println("URL Replacement text : " + urls[uls]
567 + " : URL : " + urls[uls + 1]);
572 public static void main(String argv[])
574 String[] links = new String[] {
576 * "AlinkT|Target|http://foo.foo.soo/",
577 * "myUrl1|http://$SEQUENCE_ID=/[0-9]+/=$.someserver.org/foo",
578 * "myUrl2|http://$SEQUENCE_ID=/(([0-9]+).+([A-Za-z]+))/=$.someserver.org/foo"
580 * "myUrl3|http://$SEQUENCE_ID=/([0-9]+).+([A-Za-z]+)/=$.someserver.org/foo"
581 * , "myUrl4|target|http://$SEQUENCE_ID$.someserver.org/foo|too",
582 * "PF1|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(?:PFAM:)?(.+)/=$"
584 * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
586 * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
587 * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
589 "NESTED|http://nested/$" + DB_ACCESSION
590 + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
591 String[] idstrings = new String[] {
593 * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
594 * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
596 "Label:gi|9234|pdb|102L|A" };
597 // TODO: test the setLabel method.
598 for (int i = 0; i < links.length; i++)
600 UrlLink ul = new UrlLink(links[i]);
603 System.out.println("\n\n\n");
604 System.out.println("Link " + i + " " + links[i] + " : "
606 System.out.println(" pref : "
611 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
613 for (int ids = 0; ids < idstrings.length; ids++)
615 System.out.println("ID String : " + idstrings[ids]
616 + "\nWithout onlyIfMatches:");
617 String[] urls = ul.makeUrls(idstrings[ids], false);
618 testUrls(ul, idstrings[ids], urls);
619 System.out.println("With onlyIfMatches set.");
620 urls = ul.makeUrls(idstrings[ids], true);
621 testUrls(ul, idstrings[ids], urls);
626 System.err.println("Invalid URLLink : " + links[i] + " : "
627 + ul.getInvalidMessage());