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