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.SEQUENCE_ID;
24 import static jalview.util.UrlConstants.SEQUENCE_NAME;
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_seq_id = 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("$" + SEQUENCE_ID);
64 int nsqid = link.indexOf("$" + SEQUENCE_NAME);
70 sep = parseTargetAndLabel(sep, psqid, link);
72 parseUrl(link, SEQUENCE_ID, psqid, sep);
77 sep = parseTargetAndLabel(sep, nsqid, link);
79 parseUrl(link, SEQUENCE_NAME, 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);
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_seq_id ? SEQUENCE_ID : SEQUENCE_NAME);
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);
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 : "
392 public void createLinksFromSeq(final SequenceI seq,
393 Map<String, List<String>> linkset)
395 if (seq != null && dynamic)
397 createDynamicLinks(seq, linkset);
401 createStaticLink(linkset);
406 * Create a static URL link
410 public void createStaticLink(Map<String, List<String>> linkset)
412 if (!linkset.containsKey(label + "|" + getUrl_prefix()))
414 // Add a non-dynamic link
415 linkset.put(label + "|" + getUrl_prefix(),
416 Arrays.asList(target, label, null, getUrl_prefix()));
421 * Create a dynamic URL link
426 public void createDynamicLinks(final SequenceI seq,
427 Map<String, List<String>> linkset)
429 // collect id string too
430 String id = seq.getName();
431 String descr = seq.getDescription();
432 if (descr != null && descr.length() < 1)
437 if (usesSeqId()) // link is ID
439 // collect matching db-refs
440 DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
441 new String[] { target });
443 // if there are any dbrefs which match up with the link
446 for (int r = 0; r < dbr.length; r++)
448 // create Bare ID link for this URL
449 createBareURLLink(dbr[r].getAccessionId(), linkset, true);
453 else if (!usesSeqId() && id != null) // link is name
455 // create Bare ID link for this URL
456 createBareURLLink(id, linkset, false);
459 // Create urls from description but only for URL links which are regex
461 if (descr != null && getRegexReplace() != null)
463 // create link for this URL from description where regex matches
464 createBareURLLink(descr, linkset, false);
469 * Create a bare URL Link
471 protected void createBareURLLink(String id,
472 Map<String, List<String>> linkset, Boolean combineLabel)
474 String[] urls = makeUrls(id, true);
477 for (int u = 0; u < urls.length; u += 2)
479 if (!linkset.containsKey(urls[u] + "|" + urls[u + 1]))
481 String thisLabel = label;
484 thisLabel = label + "|" + urls[u];
487 linkset.put(urls[u] + "|" + urls[u + 1],
488 Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
494 private static void testUrls(UrlLink ul, String idstring, String[] urls)
499 System.out.println("Created NO urls.");
503 System.out.println("Created " + (urls.length / 2) + " Urls.");
504 for (int uls = 0; uls < urls.length; uls += 2)
506 System.out.println("URL Replacement text : " + urls[uls]
507 + " : URL : " + urls[uls + 1]);
512 public static void main(String argv[])
514 String[] links = new String[] {
516 * "AlinkT|Target|http://foo.foo.soo/",
517 * "myUrl1|http://$SEQUENCE_ID=/[0-9]+/=$.someserver.org/foo",
518 * "myUrl2|http://$SEQUENCE_ID=/(([0-9]+).+([A-Za-z]+))/=$.someserver.org/foo"
520 * "myUrl3|http://$SEQUENCE_ID=/([0-9]+).+([A-Za-z]+)/=$.someserver.org/foo"
521 * , "myUrl4|target|http://$SEQUENCE_ID$.someserver.org/foo|too",
522 * "PF1|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(?:PFAM:)?(.+)/=$"
524 * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
526 * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
527 * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
529 "NESTED|http://nested/$" + SEQUENCE_ID
530 + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
531 String[] idstrings = new String[] {
533 * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
534 * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
536 "Label:gi|9234|pdb|102L|A" };
537 // TODO: test the setLabel method.
538 for (int i = 0; i < links.length; i++)
540 UrlLink ul = new UrlLink(links[i]);
543 System.out.println("\n\n\n");
544 System.out.println("Link " + i + " " + links[i] + " : "
546 System.out.println(" pref : "
551 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
553 for (int ids = 0; ids < idstrings.length; ids++)
555 System.out.println("ID String : " + idstrings[ids]
556 + "\nWithout onlyIfMatches:");
557 String[] urls = ul.makeUrls(idstrings[ids], false);
558 testUrls(ul, idstrings[ids], urls);
559 System.out.println("With onlyIfMatches set.");
560 urls = ul.makeUrls(idstrings[ids], true);
561 testUrls(ul, idstrings[ids], urls);
566 System.err.println("Invalid URLLink : " + links[i] + " : "
567 + ul.getInvalidMessage());
572 public boolean isDynamic()
577 public boolean usesSeqId()
582 public void setLabel(String newlabel)
584 this.label = newlabel;