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