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