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