JAL-2316 Restructure identifiers.org download
[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    * @return the url_suffix
108    */
109   public String getUrl_suffix()
110   {
111     return urlSuffix;
112   }
113
114   /**
115    * @return the url_prefix
116    */
117   public String getUrl_prefix()
118   {
119     return urlPrefix;
120   }
121
122   /**
123    * @return the target
124    */
125   public String getTarget()
126   {
127     return target;
128   }
129
130   /**
131    * @return the label
132    */
133   public String getLabel()
134   {
135     return label;
136   }
137
138   public String getUrlWithToken()
139   {
140     String var = (usesDBaccession ? DB_ACCESSION : SEQUENCE_ID);
141
142     return urlPrefix
143             + (dynamic ? (DELIM + var + ((regexReplace != null) ? "="
144                     + regexReplace + "=" + DELIM : DELIM)) : "")
145             + ((urlSuffix == null) ? "" : urlSuffix);
146   }
147
148   /**
149    * @return the regexReplace
150    */
151   public String getRegexReplace()
152   {
153     return regexReplace;
154   }
155
156   /**
157    * @return the invalidMessage
158    */
159   public String getInvalidMessage()
160   {
161     return invalidMessage;
162   }
163
164   /**
165    * Check if URL string was parsed properly.
166    * 
167    * @return boolean - if false then <code>getInvalidMessage</code> returns an
168    *         error message
169    */
170   public boolean isValid()
171   {
172     return invalidMessage == null;
173   }
174
175   /**
176    * 
177    * @return whether link is dynamic
178    */
179   public boolean isDynamic()
180   {
181     return dynamic;
182   }
183
184   /**
185    * 
186    * @return whether link uses DB Accession id
187    */
188   public boolean usesDBAccession()
189   {
190     return usesDBaccession;
191   }
192
193   /**
194    * Set the label
195    * 
196    * @param newlabel
197    */
198   public void setLabel(String newlabel)
199   {
200     this.label = newlabel;
201   }
202
203   /**
204    * return one or more URL strings by applying regex to the given idstring
205    * 
206    * @param idstring
207    * @param onlyIfMatches
208    *          - when true url strings are only made if regex is defined and
209    *          matches
210    * @return String[] { part of idstring substituted, full substituted url , ..
211    *         next part, next url..}
212    */
213   public String[] makeUrls(String idstring, boolean onlyIfMatches)
214   {
215     if (dynamic)
216     {
217       if (regexReplace != null)
218       {
219         com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
220                 + regexReplace + "/");
221         if (rg.search(idstring))
222         {
223           int ns = rg.numSubs();
224           if (ns == 0)
225           {
226             // take whole regex
227             return new String[] { rg.stringMatched(),
228                 urlPrefix + rg.stringMatched() + urlSuffix };
229           } /*
230              * else if (ns==1) { // take only subgroup match return new String[]
231              * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
232              * }; }
233              */
234           else
235           {
236             // debug
237             for (int s = 0; s <= rg.numSubs(); s++)
238             {
239               System.err.println("Sub " + s + " : " + rg.matchedFrom(s)
240                       + " : " + rg.matchedTo(s) + " : '"
241                       + rg.stringMatched(s) + "'");
242             }
243             // try to collate subgroup matches
244             Vector subs = new Vector();
245             // have to loop through submatches, collating them at top level
246             // match
247             int s = 0; // 1;
248             while (s <= ns)
249             {
250               if (s + 1 <= ns && rg.matchedTo(s) > -1
251                       && rg.matchedTo(s + 1) > -1
252                       && rg.matchedTo(s + 1) < rg.matchedTo(s))
253               {
254                 // s is top level submatch. search for submatches enclosed by
255                 // this one
256                 int r = s + 1;
257                 String mtch = "";
258                 while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
259                 {
260                   if (rg.matchedFrom(r) > -1)
261                   {
262                     mtch += rg.stringMatched(r);
263                   }
264                   r++;
265                 }
266                 if (mtch.length() > 0)
267                 {
268                   subs.addElement(mtch);
269                   subs.addElement(urlPrefix + mtch + urlSuffix);
270                 }
271                 s = r;
272               }
273               else
274               {
275                 if (rg.matchedFrom(s) > -1)
276                 {
277                   subs.addElement(rg.stringMatched(s));
278                   subs.addElement(urlPrefix + rg.stringMatched(s)
279                           + urlSuffix);
280                 }
281                 s++;
282               }
283             }
284
285             String[] res = new String[subs.size()];
286             for (int r = 0, rs = subs.size(); r < rs; r++)
287             {
288               res[r] = (String) subs.elementAt(r);
289             }
290             subs.removeAllElements();
291             return res;
292           }
293         }
294         if (onlyIfMatches)
295         {
296           return null;
297         }
298       }
299       /* Otherwise - trim off any 'prefix' - pre 2.4 Jalview behaviour */
300       if (idstring.indexOf(SEP) > -1)
301       {
302         idstring = idstring.substring(idstring.lastIndexOf(SEP) + 1);
303       }
304
305       // just return simple url substitution.
306       return new String[] { idstring, urlPrefix + idstring + urlSuffix };
307     }
308     else
309     {
310       return new String[] { "", urlPrefix };
311     }
312   }
313
314   @Override
315   public String toString()
316   {
317     return label + SEP + getUrlWithToken();
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 }