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 * @return the url_suffix
109 public String getUrl_suffix()
115 * @return the url_prefix
117 public String getUrl_prefix()
125 public String getTarget()
133 public String getLabel()
139 * @return the regexReplace
141 public String getRegexReplace()
147 * @return the invalidMessage
149 public String getInvalidMessage()
151 return invalidMessage;
155 * Check if URL string was parsed properly.
157 * @return boolean - if false then <code>getInvalidMessage</code> returns an
160 public boolean isValid()
162 return invalidMessage == null;
167 * @return whether link is dynamic
169 public boolean isDynamic()
176 * @return whether link uses DB Accession id
178 public boolean usesDBAccession()
180 return usesDBaccession;
188 public void setLabel(String newlabel)
190 this.label = newlabel;
194 * return one or more URL strings by applying regex to the given idstring
197 * @param onlyIfMatches
198 * - when true url strings are only made if regex is defined and
200 * @return String[] { part of idstring substituted, full substituted url , ..
201 * next part, next url..}
203 public String[] makeUrls(String idstring, boolean onlyIfMatches)
207 if (regexReplace != null)
209 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
210 + regexReplace + "/");
211 if (rg.search(idstring))
213 int ns = rg.numSubs();
217 return new String[] { rg.stringMatched(),
218 urlPrefix + rg.stringMatched() + urlSuffix };
220 * else if (ns==1) { // take only subgroup match return new String[]
221 * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
227 for (int s = 0; s <= rg.numSubs(); s++)
229 System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
230 + " : " + rg.matchedTo(s) + " : '"
231 + rg.stringMatched(s) + "'");
233 // try to collate subgroup matches
234 Vector subs = new Vector();
235 // have to loop through submatches, collating them at top level
240 if (s + 1 <= ns && rg.matchedTo(s) > -1
241 && rg.matchedTo(s + 1) > -1
242 && rg.matchedTo(s + 1) < rg.matchedTo(s))
244 // s is top level submatch. search for submatches enclosed by
248 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
250 if (rg.matchedFrom(r) > -1)
252 mtch += rg.stringMatched(r);
256 if (mtch.length() > 0)
258 subs.addElement(mtch);
259 subs.addElement(urlPrefix + mtch + urlSuffix);
265 if (rg.matchedFrom(s) > -1)
267 subs.addElement(rg.stringMatched(s));
268 subs.addElement(urlPrefix + rg.stringMatched(s)
275 String[] res = new String[subs.size()];
276 for (int r = 0, rs = subs.size(); r < rs; r++)
278 res[r] = (String) subs.elementAt(r);
280 subs.removeAllElements();
289 /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
290 if (idstring.indexOf(SEP) > -1)
292 idstring = idstring.substring(idstring.lastIndexOf(SEP) + 1);
295 // just return simple url substitution.
296 return new String[] { idstring, urlPrefix + idstring + urlSuffix };
300 return new String[] { "", urlPrefix };
305 public String toString()
307 String var = (usesDBaccession ? DB_ACCESSION : SEQUENCE_ID);
312 + (dynamic ? (DELIM + var + ((regexReplace != null) ? "="
313 + regexReplace + "=" + DELIM : DELIM)) : "")
314 + ((urlSuffix == null) ? "" : urlSuffix);
320 * Location of first occurrence of separator in link string
322 * Position of sequence id or name in link string
324 * Link string containing database name and url
325 * @return Position of last separator symbol prior to any regex symbols
327 protected int parseTargetAndLabel(int firstSep, int psqid, String link)
334 p = link.indexOf(SEP, sep + 1);
335 } while (p > sep && p < psqid);
336 // Assuming that the URL itself does not contain any SEP symbols
337 // sep now contains last pipe symbol position prior to any regex symbols
338 label = link.substring(0, sep);
339 if (label.indexOf(SEP) > -1)
341 // SEP terminated database name / www target at start of Label
342 target = label.substring(0, label.indexOf(SEP));
344 else if (label.indexOf(" ") > 2)
346 // space separated Label - matches database name
347 target = label.substring(0, label.indexOf(" "));
357 * Parse the URL part of the link string
360 * Link string containing database name and url
362 * Name of variable in url string (e.g. SEQUENCE_ID, SEQUENCE_NAME)
364 * Position of id or name in link string
366 * Position of separator in link string
368 protected void parseUrl(String link, String varName, int sqidPos, int sep)
370 urlPrefix = link.substring(sep + 1, sqidPos).trim();
372 // delimiter at start of regex: e.g. $SEQUENCE_ID=/
373 String startDelimiter = DELIM + varName + "=/";
375 // delimiter at end of regex: /=$
376 String endDelimiter = "/=" + DELIM;
378 int startLength = startDelimiter.length();
380 // Parse URL : Whole URL string first
381 int p = link.indexOf(endDelimiter, sqidPos + startLength);
383 if (link.indexOf(startDelimiter) == sqidPos
384 && (p > sqidPos + startLength))
386 // Extract Regex and suffix
387 urlSuffix = link.substring(p + endDelimiter.length());
388 regexReplace = link.substring(sqidPos + startLength, p);
391 com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
392 + regexReplace + "/");
395 invalidMessage = "Invalid Regular Expression : '" + regexReplace
398 } catch (Exception e)
400 invalidMessage = "Invalid Regular Expression : '" + regexReplace
408 // verify format is really correct.
409 if (link.indexOf(DELIM + varName + DELIM) == sqidPos)
411 urlSuffix = link.substring(sqidPos + startLength - 1);
416 invalidMessage = "Warning: invalid regex structure for URL link : "
423 * Create a set of URL links for a sequence
426 * The sequence to create links for
428 * Map of links: key = id + SEP + link, value = [target, label, id,
431 public void createLinksFromSeq(final SequenceI seq,
432 Map<String, List<String>> linkset)
434 if (seq != null && dynamic)
436 createDynamicLinks(seq, linkset);
440 createStaticLink(linkset);
445 * Create a static URL link
448 * Map of links: key = id + SEP + link, value = [target, label, id,
451 protected void createStaticLink(Map<String, List<String>> linkset)
453 if (!linkset.containsKey(label + SEP + getUrl_prefix()))
455 // Add a non-dynamic link
456 linkset.put(label + SEP + getUrl_prefix(),
457 Arrays.asList(target, label, null, getUrl_prefix()));
462 * Create dynamic URL links
465 * The sequence to create links for
467 * Map of links: key = id + SEP + link, value = [target, label, id,
470 protected void createDynamicLinks(final SequenceI seq,
471 Map<String, List<String>> linkset)
473 // collect id string too
474 String id = seq.getName();
475 String descr = seq.getDescription();
476 if (descr != null && descr.length() < 1)
481 if (usesDBAccession()) // link is ID
483 // collect matching db-refs
484 DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
485 new String[] { target });
487 // if there are any dbrefs which match up with the link
490 for (int r = 0; r < dbr.length; r++)
492 // create Bare ID link for this URL
493 createBareURLLink(dbr[r].getAccessionId(), true, linkset);
497 else if (!usesDBAccession() && id != null) // link is name
499 // create Bare ID link for this URL
500 createBareURLLink(id, false, linkset);
503 // Create urls from description but only for URL links which are regex
505 if (descr != null && getRegexReplace() != null)
507 // create link for this URL from description where regex matches
508 createBareURLLink(descr, false, linkset);
513 * Create a bare URL Link
514 * Returns map where key = id + SEP + link, and value = [target, label, id, link]
516 protected void createBareURLLink(String id, Boolean combineLabel,
517 Map<String, List<String>> linkset)
519 String[] urls = makeUrls(id, true);
522 for (int u = 0; u < urls.length; u += 2)
524 if (!linkset.containsKey(urls[u] + SEP + urls[u + 1]))
526 String thisLabel = label;
529 // incorporate label with idstring
530 thisLabel = label + SEP + urls[u];
533 linkset.put(urls[u] + SEP + urls[u + 1],
534 Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
540 private static void testUrls(UrlLink ul, String idstring, String[] urls)
545 System.out.println("Created NO urls.");
549 System.out.println("Created " + (urls.length / 2) + " Urls.");
550 for (int uls = 0; uls < urls.length; uls += 2)
552 System.out.println("URL Replacement text : " + urls[uls]
553 + " : URL : " + urls[uls + 1]);
558 public static void main(String argv[])
560 String[] links = new String[] {
562 * "AlinkT|Target|http://foo.foo.soo/",
563 * "myUrl1|http://$SEQUENCE_ID=/[0-9]+/=$.someserver.org/foo",
564 * "myUrl2|http://$SEQUENCE_ID=/(([0-9]+).+([A-Za-z]+))/=$.someserver.org/foo"
566 * "myUrl3|http://$SEQUENCE_ID=/([0-9]+).+([A-Za-z]+)/=$.someserver.org/foo"
567 * , "myUrl4|target|http://$SEQUENCE_ID$.someserver.org/foo|too",
568 * "PF1|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(?:PFAM:)?(.+)/=$"
570 * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
572 * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
573 * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
575 "NESTED|http://nested/$" + DB_ACCESSION
576 + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
577 String[] idstrings = new String[] {
579 * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
580 * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
582 "Label:gi|9234|pdb|102L|A" };
583 // TODO: test the setLabel method.
584 for (int i = 0; i < links.length; i++)
586 UrlLink ul = new UrlLink(links[i]);
589 System.out.println("\n\n\n");
590 System.out.println("Link " + i + " " + links[i] + " : "
592 System.out.println(" pref : "
597 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
599 for (int ids = 0; ids < idstrings.length; ids++)
601 System.out.println("ID String : " + idstrings[ids]
602 + "\nWithout onlyIfMatches:");
603 String[] urls = ul.makeUrls(idstrings[ids], false);
604 testUrls(ul, idstrings[ids], urls);
605 System.out.println("With onlyIfMatches set.");
606 urls = ul.makeUrls(idstrings[ids], true);
607 testUrls(ul, idstrings[ids], urls);
612 System.err.println("Invalid URLLink : " + links[i] + " : "
613 + ul.getInvalidMessage());