JAL-2282 Renamed internal use of sequence id / db accession for
[jalview.git] / src / jalview / util / UrlLink.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.util;
22
23 import static jalview.util.UrlConstants.DB_ACCESSION;
24 import static jalview.util.UrlConstants.SEQUENCE_ID;
25
26 import jalview.datamodel.DBRefEntry;
27 import jalview.datamodel.SequenceI;
28
29 import java.util.Arrays;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Vector;
33
34 public class UrlLink
35 {
36   /**
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
43    * documentation todo.
44    */
45   private String url_suffix, url_prefix, target, label, regexReplace;
46
47   private boolean dynamic = false;
48
49   private boolean uses_db_accession = false;
50
51   private String invalidMessage = null;
52
53   /**
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>/=$
57    * 
58    * @param link
59    */
60   public UrlLink(String link)
61   {
62     int sep = link.indexOf("|");
63     int psqid = link.indexOf("$" + DB_ACCESSION);
64     int nsqid = link.indexOf("$" + SEQUENCE_ID);
65     if (psqid > -1)
66     {
67       dynamic = true;
68       uses_db_accession = true;
69
70       sep = parseTargetAndLabel(sep, psqid, link);
71
72       parseUrl(link, DB_ACCESSION, psqid, sep);
73     }
74     else if (nsqid > -1)
75     {
76       dynamic = true;
77       sep = parseTargetAndLabel(sep, nsqid, link);
78
79       parseUrl(link, SEQUENCE_ID, nsqid, sep);
80     }
81     else
82     {
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=".*\\|?(.*)";
89       url_suffix = null;
90     }
91
92     label = label.trim();
93     target = target.trim();
94     target = target.toUpperCase(); // DBRefEntry uppercases DB names
95     // NB getCanonicalName might be better but does not currently change case
96   }
97
98   /**
99    * @return the url_suffix
100    */
101   public String getUrl_suffix()
102   {
103     return url_suffix;
104   }
105
106   /**
107    * @return the url_prefix
108    */
109   public String getUrl_prefix()
110   {
111     return url_prefix;
112   }
113
114   /**
115    * @return the target
116    */
117   public String getTarget()
118   {
119     return target;
120   }
121
122   /**
123    * @return the label
124    */
125   public String getLabel()
126   {
127     return label;
128   }
129
130   /**
131    * @return the regexReplace
132    */
133   public String getRegexReplace()
134   {
135     return regexReplace;
136   }
137
138   /**
139    * @return the invalidMessage
140    */
141   public String getInvalidMessage()
142   {
143     return invalidMessage;
144   }
145
146   /**
147    * Check if URL string was parsed properly.
148    * 
149    * @return boolean - if false then <code>getInvalidMessage</code> returns an
150    *         error message
151    */
152   public boolean isValid()
153   {
154     return invalidMessage == null;
155   }
156
157   /**
158    * return one or more URL strings by applying regex to the given idstring
159    * 
160    * @param idstring
161    * @param onlyIfMatches
162    *          - when true url strings are only made if regex is defined and
163    *          matches
164    * @return String[] { part of idstring substituted, full substituted url , ..
165    *         next part, next url..}
166    */
167   public String[] makeUrls(String idstring, boolean onlyIfMatches)
168   {
169     if (dynamic)
170     {
171       if (regexReplace != null)
172       {
173         com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
174                 + regexReplace + "/");
175         if (rg.search(idstring))
176         {
177           int ns = rg.numSubs();
178           if (ns == 0)
179           {
180             // take whole regex
181             return new String[] { rg.stringMatched(),
182                 url_prefix + rg.stringMatched() + url_suffix };
183           } /*
184              * else if (ns==1) { // take only subgroup match return new String[]
185              * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
186              * }; }
187              */
188           else
189           {
190             // debug
191             for (int s = 0; s <= rg.numSubs(); s++)
192             {
193               System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
194                       + " : " + rg.matchedTo(s) + " : '"
195                       + rg.stringMatched(s) + "'");
196             }
197             // try to collate subgroup matches
198             Vector subs = new Vector();
199             // have to loop through submatches, collating them at top level
200             // match
201             int s = 0; // 1;
202             while (s <= ns)
203             {
204               if (s + 1 <= ns && rg.matchedTo(s) > -1
205                       && rg.matchedTo(s + 1) > -1
206                       && rg.matchedTo(s + 1) < rg.matchedTo(s))
207               {
208                 // s is top level submatch. search for submatches enclosed by
209                 // this one
210                 int r = s + 1;
211                 String mtch = "";
212                 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
213                 {
214                   if (rg.matchedFrom(r) > -1)
215                   {
216                     mtch += rg.stringMatched(r);
217                   }
218                   r++;
219                 }
220                 if (mtch.length() > 0)
221                 {
222                   subs.addElement(mtch);
223                   subs.addElement(url_prefix + mtch + url_suffix);
224                 }
225                 s = r;
226               }
227               else
228               {
229                 if (rg.matchedFrom(s) > -1)
230                 {
231                   subs.addElement(rg.stringMatched(s));
232                   subs.addElement(url_prefix + rg.stringMatched(s)
233                           + url_suffix);
234                 }
235                 s++;
236               }
237             }
238
239             String[] res = new String[subs.size()];
240             for (int r = 0, rs = subs.size(); r < rs; r++)
241             {
242               res[r] = (String) subs.elementAt(r);
243             }
244             subs.removeAllElements();
245             return res;
246           }
247         }
248         if (onlyIfMatches)
249         {
250           return null;
251         }
252       }
253       /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
254       if (idstring.indexOf("|") > -1)
255       {
256         idstring = idstring.substring(idstring.lastIndexOf("|") + 1);
257       }
258
259       // just return simple url substitution.
260       return new String[] { idstring, url_prefix + idstring + url_suffix };
261     }
262     else
263     {
264       return new String[] { "", url_prefix };
265     }
266   }
267
268   @Override
269   public String toString()
270   {
271     String var = (uses_db_accession ? DB_ACCESSION : SEQUENCE_ID);
272
273     return label
274             + "|"
275             + url_prefix
276             + (dynamic ? ("$" + var + ((regexReplace != null) ? "="
277                     + regexReplace + "=$" : "$")) : "")
278             + ((url_suffix == null) ? "" : url_suffix);
279   }
280
281   /**
282    * 
283    * @param firstSep
284    *          Location of first occurrence of separator in link string
285    * @param psqid
286    *          Position of sequence id or name in link string
287    * @param link
288    *          Link string containing database name and url
289    * @return Position of last separator symbol prior to any regex symbols
290    */
291   protected int parseTargetAndLabel(int firstSep, int psqid, String link)
292   {
293     int p = firstSep;
294     int sep = firstSep;
295     do
296     {
297       sep = p;
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)
304     {
305       // | terminated database name / www target at start of Label
306       target = label.substring(0, label.indexOf("|"));
307     }
308     else if (label.indexOf(" ") > 2)
309     {
310       // space separated Label - matches database name
311       target = label.substring(0, label.indexOf(" "));
312     }
313     else
314     {
315       target = label;
316     }
317     return sep;
318   }
319
320   /**
321    * Parse the URL part of the link string
322    * 
323    * @param link
324    *          Link string containing database name and url
325    * @param varName
326    *          Name of variable in url string (e.g. SEQUENCE_ID, SEQUENCE_NAME)
327    * @param sqidPos
328    *          Position of id or name in link string
329    * @param sep
330    *          Position of separator in link string
331    */
332   protected void parseUrl(String link, String varName, int sqidPos, int sep)
333   {
334     url_prefix = link.substring(sep + 1, sqidPos).trim();
335
336     // delimiter at start of regex: e.g. $SEQUENCE_ID=/
337     String startDelimiter = "$" + varName + "=/";
338
339     // delimiter at end of regex: /=$
340     String endDelimiter = "/=$";
341
342     int startLength = startDelimiter.length();
343
344     // Parse URL : Whole URL string first
345     int p = link.indexOf(endDelimiter, sqidPos + startLength);
346
347     if (link.indexOf(startDelimiter) == sqidPos
348             && (p > sqidPos + startLength))
349     {
350       // Extract Regex and suffix
351       url_suffix = link.substring(p + endDelimiter.length());
352       regexReplace = link.substring(sqidPos + startLength, p);
353       try
354       {
355         com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
356                 + regexReplace + "/");
357         if (rg == null)
358         {
359           invalidMessage = "Invalid Regular Expression : '" + regexReplace
360                   + "'\n";
361         }
362       } catch (Exception e)
363       {
364         invalidMessage = "Invalid Regular Expression : '" + regexReplace
365                 + "'\n";
366       }
367     }
368     else
369     {
370       // no regex
371       regexReplace = null;
372       // verify format is really correct.
373       if (link.indexOf("$" + varName + "$") == sqidPos)
374       {
375         url_suffix = link.substring(sqidPos + startLength - 1);
376         regexReplace = null;
377       }
378       else
379       {
380         invalidMessage = "Warning: invalid regex structure for URL link : "
381                 + link;
382       }
383     }
384   }
385
386   /**
387    * Create a set of URL links for a sequence
388    * 
389    * @param seq
390    *          The sequence to create links for
391    * @param linkset
392    *          Map of links: key = id | link, value = [target, label, id, link]
393    */
394   public void createLinksFromSeq(final SequenceI seq,
395           Map<String, List<String>> linkset)
396   {
397     if (seq != null && dynamic)
398     {
399       createDynamicLinks(seq, linkset);
400     }
401     else
402     {
403       createStaticLink(linkset);
404     }
405   }
406
407   /**
408    * Create a static URL link
409    * 
410    * @param linkset
411    *          Map of links: key = id | link, value = [target, label, id, link]
412    */
413   protected void createStaticLink(Map<String, List<String>> linkset)
414   {
415     if (!linkset.containsKey(label + "|" + getUrl_prefix()))
416     {
417       // Add a non-dynamic link
418       linkset.put(label + "|" + getUrl_prefix(),
419               Arrays.asList(target, label, null, getUrl_prefix()));
420     }
421   }
422
423   /**
424    * Create dynamic URL links
425    * 
426    * @param seq
427    *          The sequence to create links for
428    * @param linkset
429    *          Map of links: key = id | link, value = [target, label, id, link]
430    */
431   protected void createDynamicLinks(final SequenceI seq,
432           Map<String, List<String>> linkset)
433   {
434     // collect id string too
435     String id = seq.getName();
436     String descr = seq.getDescription();
437     if (descr != null && descr.length() < 1)
438     {
439       descr = null;
440     }
441
442     if (usesDBAccession()) // link is ID
443     {
444       // collect matching db-refs
445       DBRefEntry[] dbr = DBRefUtils.selectRefs(seq.getDBRefs(),
446               new String[] { target });
447
448       // if there are any dbrefs which match up with the link
449       if (dbr != null)
450       {
451         for (int r = 0; r < dbr.length; r++)
452         {
453           // create Bare ID link for this URL
454           createBareURLLink(dbr[r].getAccessionId(), true, linkset);
455         }
456       }
457     }
458     else if (!usesDBAccession() && id != null) // link is name
459     {
460       // create Bare ID link for this URL
461       createBareURLLink(id, false, linkset);
462     }
463
464     // Create urls from description but only for URL links which are regex
465     // links
466     if (descr != null && getRegexReplace() != null)
467     {
468       // create link for this URL from description where regex matches
469       createBareURLLink(descr, false, linkset);
470     }
471   }
472
473   /*
474    * Create a bare URL Link
475    * Returns map where key = id | link, and value = [target, label, id, link]
476    */
477   protected void createBareURLLink(String id, Boolean combineLabel,
478           Map<String, List<String>> linkset)
479   {
480     String[] urls = makeUrls(id, true);
481     if (urls != null)
482     {
483       for (int u = 0; u < urls.length; u += 2)
484       {
485         if (!linkset.containsKey(urls[u] + "|" + urls[u + 1]))
486         {
487           String thisLabel = label;
488           if (combineLabel)
489           {
490             // incorporate label with idstring
491             thisLabel = label + "|" + urls[u];
492           }
493
494           linkset.put(urls[u] + "|" + urls[u + 1],
495                   Arrays.asList(target, thisLabel, urls[u], urls[u + 1]));
496         }
497       }
498     }
499   }
500
501   private static void testUrls(UrlLink ul, String idstring, String[] urls)
502   {
503
504     if (urls == null)
505     {
506       System.out.println("Created NO urls.");
507     }
508     else
509     {
510       System.out.println("Created " + (urls.length / 2) + " Urls.");
511       for (int uls = 0; uls < urls.length; uls += 2)
512       {
513         System.out.println("URL Replacement text : " + urls[uls]
514                 + " : URL : " + urls[uls + 1]);
515       }
516     }
517   }
518
519   public static void main(String argv[])
520   {
521     String[] links = new String[] {
522     /*
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"
526      * ,
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:)?(.+)/=$"
530      * ,
531      * "PF2|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/(PFAM:)?(.+)/=$"
532      * ,
533      * "PF3|http://us.expasy.org/cgi-bin/niceprot.pl?$SEQUENCE_ID=/PFAM:(.+)/=$"
534      * , "NOTFER|http://notfer.org/$SEQUENCE_ID=/(?<!\\s)(.+)/=$",
535      */
536     "NESTED|http://nested/$" + DB_ACCESSION
537             + "=/^(?:Label:)?(?:(?:gi\\|(\\d+))|([^:]+))/=$/nested" };
538     String[] idstrings = new String[] {
539     /*
540      * //"LGUL_human", //"QWIQW_123123", "uniprot|why_do+_12313_foo",
541      * //"123123312", "123123 ABCDE foo", "PFAM:PF23943",
542      */
543     "Label:gi|9234|pdb|102L|A" };
544     // TODO: test the setLabel method.
545     for (int i = 0; i < links.length; i++)
546     {
547       UrlLink ul = new UrlLink(links[i]);
548       if (ul.isValid())
549       {
550         System.out.println("\n\n\n");
551         System.out.println("Link " + i + " " + links[i] + " : "
552                 + ul.toString());
553         System.out.println(" pref : "
554                 + ul.getUrl_prefix()
555                 + "\n suf : "
556                 + ul.getUrl_suffix()
557                 + "\n : "
558                 + ((ul.getRegexReplace() != null) ? ul.getRegexReplace()
559                         : ""));
560         for (int ids = 0; ids < idstrings.length; ids++)
561         {
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);
569         }
570       }
571       else
572       {
573         System.err.println("Invalid URLLink : " + links[i] + " : "
574                 + ul.getInvalidMessage());
575       }
576     }
577   }
578
579   public boolean isDynamic()
580   {
581     return dynamic;
582   }
583
584   public boolean usesDBAccession()
585   {
586     return uses_db_accession;
587   }
588
589   public void setLabel(String newlabel)
590   {
591     this.label = newlabel;
592   }
593 }