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