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 susbstituted. Usage
45 private String url_suffix, url_prefix, target, label, regexReplace;
47 private boolean dynamic = false;
49 private boolean uses_db_accession = false;
51 private String invalidMessage = null;
54 * parse the given linkString of the form '<label>|<url>' into parts url may
55 * contain a string $SEQUENCE_ID<=optional regex=>$ where <=optional regex=>
56 * must be of the form =/<perl style regex>/=$
60 public UrlLink(String link)
62 int sep = link.indexOf("|");
63 int psqid = link.indexOf("$" + DB_ACCESSION);
64 int nsqid = link.indexOf("$" + SEQUENCE_ID);
68 uses_db_accession = true;
70 sep = parseTargetAndLabel(sep, psqid, link);
72 parseUrl(link, DB_ACCESSION, psqid, sep);
77 sep = parseTargetAndLabel(sep, nsqid, link);
79 parseUrl(link, SEQUENCE_ID, nsqid, sep);
83 target = link.substring(0, sep);
84 sep = link.lastIndexOf("|");
85 label = link.substring(0, sep);
86 url_prefix = link.substring(sep + 1).trim();
87 regexReplace = null; // implies we trim any prefix if necessary //
88 // regexReplace=".*\\|?(.*)";
93 target = target.trim();
94 target = target.toUpperCase(); // DBRefEntry uppercases DB names
95 // NB getCanonicalName might be better but does not currently change case
99 * @return the url_suffix
101 public String getUrl_suffix()
107 * @return the url_prefix
109 public String getUrl_prefix()
117 public String getTarget()
125 public String getLabel()
131 * @return the regexReplace
133 public String getRegexReplace()
139 * @return the invalidMessage
141 public String getInvalidMessage()
143 return invalidMessage;
147 * Check if URL string was parsed properly.
149 * @return boolean - if false then <code>getInvalidMessage</code> returns an
152 public boolean isValid()
154 return invalidMessage == null;
158 * return one or more URL strings by applying regex to the given idstring
161 * @param onlyIfMatches
162 * - when true url strings are only made if regex is defined and
164 * @return String[] { part of idstring substituted, full substituted url , ..
165 * next part, next url..}
167 public String[] makeUrls(String idstring, boolean onlyIfMatches)
171 if (regexReplace != null)
173 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
174 + regexReplace + "/");
175 if (rg.search(idstring))
177 int ns = rg.numSubs();
181 return new String[] { rg.stringMatched(),
182 url_prefix + rg.stringMatched() + url_suffix };
184 * else if (ns==1) { // take only subgroup match return new String[]
185 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
191 for (int s = 0; s <= rg.numSubs(); s++)
193 System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
194 + " : " + rg.matchedTo(s) + " : '"
195 + rg.stringMatched(s) + "'");
197 // try to collate subgroup matches
198 Vector subs = new Vector();
199 // have to loop through submatches, collating them at top level
204 if (s + 1 <= ns && rg.matchedTo(s) > -1
205 && rg.matchedTo(s + 1) > -1
206 && rg.matchedTo(s + 1) < rg.matchedTo(s))
208 // s is top level submatch. search for submatches enclosed by
212 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
214 if (rg.matchedFrom(r) > -1)
216 mtch += rg.stringMatched(r);
220 if (mtch.length() > 0)
222 subs.addElement(mtch);
223 subs.addElement(url_prefix + mtch + url_suffix);
229 if (rg.matchedFrom(s) > -1)
231 subs.addElement(rg.stringMatched(s));
232 subs.addElement(url_prefix + rg.stringMatched(s)
239 String[] res = new String[subs.size()];
240 for (int r = 0, rs = subs.size(); r < rs; r++)
242 res[r] = (String) subs.elementAt(r);
244 subs.removeAllElements();
253 /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
254 if (idstring.indexOf("|") > -1)
256 idstring = idstring.substring(idstring.lastIndexOf("|") + 1);
259 // just return simple url substitution.
260 return new String[] { idstring, url_prefix + idstring + url_suffix };
264 return new String[] { "", url_prefix };
269 public String toString()
271 String var = (uses_db_accession ? DB_ACCESSION : SEQUENCE_ID);
276 + (dynamic ? ("$" + var + ((regexReplace != null) ? "="
277 + regexReplace + "=$" : "$")) : "")
278 + ((url_suffix == null) ? "" : url_suffix);
284 * Location of first occurrence of separator in link string
286 * Position of sequence id or name in link string
288 * Link string containing database name and url
289 * @return Position of last separator symbol prior to any regex symbols
291 protected int parseTargetAndLabel(int firstSep, int psqid, String link)
298 p = link.indexOf("|", sep + 1);
299 } while (p > sep && p < psqid);
300 // Assuming that the URL itself does not contain any '|' symbols
301 // sep now contains last pipe symbol position prior to any regex symbols
302 label = link.substring(0, sep);
303 if (label.indexOf("|") > -1)
305 // | terminated database name / www target at start of Label
306 target = label.substring(0, label.indexOf("|"));
308 else if (label.indexOf(" ") > 2)
310 // space separated Label - matches database name
311 target = label.substring(0, label.indexOf(" "));
321 * Parse the URL part of the link string
324 * Link string containing database name and url
326 * Name of variable in url string (e.g. SEQUENCE_ID, SEQUENCE_NAME)
328 * Position of id or name in link string
330 * Position of separator in link string
332 protected void parseUrl(String link, String varName, int sqidPos, int sep)
334 url_prefix = link.substring(sep + 1, sqidPos).trim();
336 // delimiter at start of regex: e.g. $SEQUENCE_ID=/
337 String startDelimiter = "$" + varName + "=/";
339 // delimiter at end of regex: /=$
340 String endDelimiter = "/=$";
342 int startLength = startDelimiter.length();
344 // Parse URL : Whole URL string first
345 int p = link.indexOf(endDelimiter, sqidPos + startLength);
347 if (link.indexOf(startDelimiter) == sqidPos
348 && (p > sqidPos + startLength))
350 // Extract Regex and suffix
351 url_suffix = link.substring(p + endDelimiter.length());
352 regexReplace = link.substring(sqidPos + startLength, p);
355 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
356 + regexReplace + "/");
359 invalidMessage = "Invalid Regular Expression : '" + regexReplace
362 } catch (Exception e)
364 invalidMessage = "Invalid Regular Expression : '" + regexReplace
372 // verify format is really correct.
373 if (link.indexOf("$" + varName + "$") == sqidPos)
375 url_suffix = link.substring(sqidPos + startLength - 1);
380 invalidMessage = "Warning: invalid regex structure for URL link : "
387 * Create a set of URL links for a sequence
390 * The sequence to create links for
392 * Map of links: key = id | link, value = [target, label, id, link]
394 public void createLinksFromSeq(final SequenceI seq,
395 Map<String, List<String>> linkset)
397 if (seq != null && dynamic)
399 createDynamicLinks(seq, linkset);
403 createStaticLink(linkset);
408 * Create a static URL link
411 * Map of links: key = id | link, value = [target, label, id, link]
413 protected void createStaticLink(Map<String, List<String>> linkset)
415 if (!linkset.containsKey(label + "|" + getUrl_prefix()))
417 // Add a non-dynamic link
418 linkset.put(label + "|" + getUrl_prefix(),
419 Arrays.asList(target, label, null, getUrl_prefix()));
424 * Create dynamic URL links
427 * The sequence to create links for
429 * Map of links: key = id | link, value = [target, label, id, link]
431 protected void createDynamicLinks(final SequenceI seq,
432 Map<String, List<String>> linkset)
434 // collect id string too
435 String id = seq.getName();
436 String descr = seq.getDescription();
437 if (descr != null && descr.length() < 1)
442 if (usesDBAccession()) // link is ID
444 // collect matching db-refs
445 DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
446 new String[] { target });
448 // if there are any dbrefs which match up with the link
451 for (int r = 0; r < dbr.length; r++)
453 // create Bare ID link for this URL
454 createBareURLLink(dbr[r].getAccessionId(), true, linkset);
458 else if (!usesDBAccession() && id != null) // link is name
460 // create Bare ID link for this URL
461 createBareURLLink(id, false, linkset);
464 // Create urls from description but only for URL links which are regex
466 if (descr != null && getRegexReplace() != null)
468 // create link for this URL from description where regex matches
469 createBareURLLink(descr, false, linkset);
474 * Create a bare URL Link
475 * Returns map where key = id | link, and value = [target, label, id, link]
477 protected void createBareURLLink(String id, Boolean combineLabel,
478 Map<String, List<String>> linkset)
480 String[] urls = makeUrls(id, true);
483 for (int u = 0; u < urls.length; u += 2)
485 if (!linkset.containsKey(urls[u] + "|" + urls[u + 1]))
487 String thisLabel = label;
490 // incorporate label with idstring
491 thisLabel = label + "|" + urls[u];
494 linkset.put(urls[u] + "|" + urls[u + 1],
495 Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
501 private static void testUrls(UrlLink ul, String idstring, String[] urls)
506 System.out.println("Created NO urls.");
510 System.out.println("Created " + (urls.length / 2) + " Urls.");
511 for (int uls = 0; uls < urls.length; uls += 2)
513 System.out.println("URL Replacement text : " + urls[uls]
514 + " : URL : " + urls[uls + 1]);
519 public static void main(String argv[])
521 String[] links = new String[] {
523 * "AlinkT|Target|http://foo.foo.soo/",
524 * "myUrl1|http://$SEQUENCE_ID=/[0-9]+/=$.someserver.org/foo",
525 * "myUrl2|http://$SEQUENCE_ID=/(([0-9]+).+([A-Za-z]+))/=$.someserver.org/foo"
527 * "myUrl3|http://$SEQUENCE_ID=/([0-9]+).+([A-Za-z]+)/=$.someserver.org/foo"
528 * , "myUrl4|target|http://$SEQUENCE_ID$.someserver.org/foo|too",
529 * "PF1|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(?:PFAM:)?(.+)/=$"
531 * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
533 * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
534 * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
536 "NESTED|http://nested/$" + DB_ACCESSION
537 + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
538 String[] idstrings = new String[] {
540 * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
541 * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
543 "Label:gi|9234|pdb|102L|A" };
544 // TODO: test the setLabel method.
545 for (int i = 0; i < links.length; i++)
547 UrlLink ul = new UrlLink(links[i]);
550 System.out.println("\n\n\n");
551 System.out.println("Link " + i + " " + links[i] + " : "
553 System.out.println(" pref : "
558 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
560 for (int ids = 0; ids < idstrings.length; ids++)
562 System.out.println("ID String : " + idstrings[ids]
563 + "\nWithout onlyIfMatches:");
564 String[] urls = ul.makeUrls(idstrings[ids], false);
565 testUrls(ul, idstrings[ids], urls);
566 System.out.println("With onlyIfMatches set.");
567 urls = ul.makeUrls(idstrings[ids], true);
568 testUrls(ul, idstrings[ids], urls);
573 System.err.println("Invalid URLLink : " + links[i] + " : "
574 + ul.getInvalidMessage());
579 public boolean isDynamic()
584 public boolean usesDBAccession()
586 return uses_db_accession;
589 public void setLabel(String newlabel)
591 this.label = newlabel;