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