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