JAL-1807 explicit imports (jalview.util)
[jalview.git] / src / jalview / util / GroupUrlLink.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.datamodel.Sequence;
24 import jalview.datamodel.SequenceI;
25
26 import java.util.Hashtable;
27
28 import com.stevesoft.pat.Regex;
29
30 public class GroupUrlLink
31 {
32   public class UrlStringTooLongException extends Exception
33   {
34     public UrlStringTooLongException(int lng)
35     {
36       urlLength = lng;
37     }
38
39     public int urlLength;
40
41     public String toString()
42     {
43       return "Generated url is estimated to be too long (" + urlLength
44               + ")";
45     }
46   }
47
48   /**
49    * Helper class based on the UrlLink class which enables URLs to be
50    * constructed from sequences or IDs associated with a group of sequences. URL
51    * definitions consist of a pipe separated string containing a <label>|<url
52    * construct>|<separator character>[|<sequence separator character>]. The url
53    * construct includes regex qualified tokens which are replaced with seuqence
54    * IDs ($SEQUENCE_IDS$) and/or seuqence regions ($SEQUENCES$) that are
55    * extracted from the group. See <code>UrlLink</code> for more information
56    * about the approach, and the original implementation. Documentation to come.
57    * Note - groupUrls can be very big!
58    */
59   private String url_prefix, target, label;
60
61   /**
62    * these are all filled in order of the occurence of each token in the url
63    * string template
64    */
65   private String url_suffix[], separators[], regexReplace[];
66
67   private String invalidMessage = null;
68
69   /**
70    * tokens that can be replaced in the URL.
71    */
72   private static String[] tokens;
73
74   /**
75    * position of each token (which can appear once only) in the url
76    */
77   private int[] segs;
78
79   /**
80    * contains tokens in the order they appear in the URL template.
81    */
82   private String[] mtch;
83   static
84   {
85     if (tokens == null)
86     {
87       tokens = new String[]
88       { "SEQUENCEIDS", "SEQUENCES", "DATASETID" };
89     }
90   }
91
92   /**
93    * test for GroupURLType bitfield (with default tokens)
94    */
95   public static final int SEQUENCEIDS = 1;
96
97   /**
98    * test for GroupURLType bitfield (with default tokens)
99    */
100   public static final int SEQUENCES = 2;
101
102   /**
103    * test for GroupURLType bitfield (with default tokens)
104    */
105   public static final int DATASETID = 4;
106
107   // private int idseg = -1, seqseg = -1;
108
109   /**
110    * parse the given linkString of the form '<label>|<url>|separator
111    * char[|optional sequence separator char]' into parts. url may contain a
112    * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
113    * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
114    * $SEQUENCES<=optional regex=>$.
115    * 
116    * @param link
117    */
118   public GroupUrlLink(String link)
119   {
120     int sep = link.indexOf("|");
121     segs = new int[tokens.length];
122     int ntoks = 0;
123     for (int i = 0; i < segs.length; i++)
124     {
125       if ((segs[i] = link.indexOf("$" + tokens[i])) > -1)
126       {
127         ntoks++;
128       }
129     }
130     // expect at least one token
131     if (ntoks == 0)
132     {
133       invalidMessage = "Group URL string must contain at least one of ";
134       for (int i = 0; i < segs.length; i++)
135       {
136         invalidMessage += " '$" + tokens[i] + "[=/regex=/]$'";
137       }
138       return;
139     }
140
141     int[] ptok = new int[ntoks + 1];
142     String[] tmtch = new String[ntoks + 1];
143     mtch = new String[ntoks];
144     for (int i = 0, t = 0; i < segs.length; i++)
145     {
146       if (segs[i] > -1)
147       {
148         ptok[t] = segs[i];
149         tmtch[t++] = tokens[i];
150       }
151     }
152     ptok[ntoks] = link.length();
153     tmtch[ntoks] = "$$$$$$$$$";
154     QuickSort.sortInt(ptok, tmtch);
155     for (int i = 0; i < ntoks; i++)
156     {
157       mtch[i] = tmtch[i]; // TODO: check order is ascending
158     }
159     /*
160      * replaces the specific code below {}; if (psqids > -1 && pseqs > -1) { if
161      * (psqids > pseqs) { idseg = 1; seqseg = 0;
162      * 
163      * ptok = new int[] { pseqs, psqids, link.length() }; mtch = new String[] {
164      * "$SEQUENCES", "$SEQUENCEIDS" }; } else { idseg = 0; seqseg = 1; ptok =
165      * new int[] { psqids, pseqs, link.length() }; mtch = new String[] {
166      * "$SEQUENCEIDS", "$SEQUENCES" }; } } else { if (psqids != -1) { idseg = 0;
167      * ptok = new int[] { psqids, link.length() }; mtch = new String[] {
168      * "$SEQUENCEIDS" }; } else { seqseg = 0; ptok = new int[] { pseqs,
169      * link.length() }; mtch = new String[] { "$SEQUENCES" }; } }
170      */
171
172     int p = sep;
173     // first get the label and target part before the first |
174     do
175     {
176       sep = p;
177       p = link.indexOf("|", sep + 1);
178     } while (p > sep && p < ptok[0]);
179     // Assuming that the URL itself does not contain any '|' symbols
180     // sep now contains last pipe symbol position prior to any regex symbols
181     label = link.substring(0, sep);
182     if (label.indexOf("|") > -1)
183     {
184       // | terminated database name / www target at start of Label
185       target = label.substring(0, label.indexOf("|"));
186     }
187     else if (label.indexOf(" ") > 2)
188     {
189       // space separated Label - matches database name
190       target = label.substring(0, label.indexOf(" "));
191     }
192     else
193     {
194       target = label;
195     }
196     // Now Parse URL : Whole URL string first
197     url_prefix = link.substring(sep + 1, ptok[0]);
198     url_suffix = new String[mtch.length];
199     regexReplace = new String[mtch.length];
200     // and loop through tokens
201     for (int pass = 0; pass < mtch.length; pass++)
202     {
203       int mlength = 3 + mtch[pass].length();
204       if (link.indexOf("$" + mtch[pass] + "=/") == ptok[pass]
205               && (p = link.indexOf("/=$", ptok[pass] + mlength)) > ptok[pass]
206                       + mlength)
207       {
208         // Extract Regex and suffix
209         if (ptok[pass + 1] < p + 3)
210         {
211           // tokens are not allowed inside other tokens - e.g. inserting a
212           // $sequences$ into the regex match for the sequenceid
213           invalidMessage = "Token regexes cannot contain other regexes (did you terminate the $"
214                   + mtch[pass] + " regex with a '/=$' ?";
215           return;
216         }
217         url_suffix[pass] = link.substring(p + 3, ptok[pass + 1]);
218         regexReplace[pass] = link.substring(ptok[pass] + mlength, p);
219         try
220         {
221           Regex rg = Regex.perlCode("/"
222                   + regexReplace[pass] + "/");
223           if (rg == null)
224           {
225             invalidMessage = "Invalid Regular Expression : '"
226                     + regexReplace[pass] + "'\n";
227           }
228         } catch (Exception e)
229         {
230           invalidMessage = "Invalid Regular Expression : '"
231                   + regexReplace[pass] + "'\n";
232         }
233       }
234       else
235       {
236         regexReplace[pass] = null;
237         // verify format is really correct.
238         if ((p = link.indexOf("$" + mtch[pass] + "$")) == ptok[pass])
239         {
240           url_suffix[pass] = link.substring(p + mtch[pass].length() + 2,
241                   ptok[pass + 1]);
242         }
243         else
244         {
245           invalidMessage = "Warning: invalid regex structure (after '"
246                   + mtch[0] + "') for URL link : " + link;
247         }
248       }
249     }
250     int pass = 0;
251     separators = new String[url_suffix.length];
252     String suffices = url_suffix[url_suffix.length - 1], lastsep = ",";
253     // have a look in the last suffix for any more separators.
254     while ((p = suffices.indexOf('|')) > -1)
255     {
256       separators[pass] = suffices.substring(p + 1);
257       if (pass == 0)
258       {
259         // trim the original suffix string
260         url_suffix[url_suffix.length - 1] = suffices.substring(0, p);
261       }
262       else
263       {
264         lastsep = (separators[pass - 1] = separators[pass - 1].substring(0,
265                 p));
266       }
267       suffices = separators[pass];
268       pass++;
269     }
270     if (pass > 0)
271     {
272       lastsep = separators[pass - 1];
273     }
274     // last separator is always used for all the remaining separators
275     while (pass < separators.length)
276     {
277       separators[pass++] = lastsep;
278     }
279   }
280
281   /**
282    * @return the url_suffix
283    */
284   public String getUrl_suffix()
285   {
286     return url_suffix[url_suffix.length - 1];
287   }
288
289   /**
290    * @return the url_prefix
291    */
292   public String getUrl_prefix()
293   {
294     return url_prefix;
295   }
296
297   /**
298    * @return the target
299    */
300   public String getTarget()
301   {
302     return target;
303   }
304
305   /**
306    * @return the label
307    */
308   public String getLabel()
309   {
310     return label;
311   }
312
313   /**
314    * @return the sequence ID regexReplace
315    */
316   public String getIDRegexReplace()
317   {
318     return _replaceFor(tokens[0]);
319   }
320
321   private String _replaceFor(String token)
322   {
323     for (int i = 0; i < mtch.length; i++)
324     {
325       if (segs[i] > -1 && mtch[i].equals(token))
326       {
327         return regexReplace[i];
328       }
329     }
330     return null;
331   }
332
333   /**
334    * @return the sequence ID regexReplace
335    */
336   public String getSeqRegexReplace()
337   {
338     return _replaceFor(tokens[1]);
339   }
340
341   /**
342    * @return the invalidMessage
343    */
344   public String getInvalidMessage()
345   {
346     return invalidMessage;
347   }
348
349   /**
350    * Check if URL string was parsed properly.
351    * 
352    * @return boolean - if false then <code>getInvalidMessage</code> returns an
353    *         error message
354    */
355   public boolean isValid()
356   {
357     return invalidMessage == null;
358   }
359
360   /**
361    * return one or more URL strings by applying regex to the given idstring
362    * 
363    * @param idstrings
364    *          array of id strings to pass to service
365    * @param seqstrings
366    *          array of seq strings to pass to service
367    * @param onlyIfMatches
368    *          - when true url strings are only made if regex is defined and
369    *          matches for all qualified tokens in groupURL - TODO: consider if
370    *          onlyIfMatches is really a useful parameter!
371    * @return null or Object[] { int[] { number of seqs substituted},boolean[] {
372    *         which seqs were substituted }, StringBuffer[] { substituted lists
373    *         for each token }, String[] { url } }
374    * @throws UrlStringTooLongException
375    */
376   public Object[] makeUrls(String[] idstrings, String[] seqstrings,
377           String dsstring, boolean onlyIfMatches)
378           throws UrlStringTooLongException
379   {
380     Hashtable rstrings = replacementArgs(idstrings, seqstrings, dsstring);
381     return makeUrls(rstrings, onlyIfMatches);
382   }
383
384   /**
385    * gathers input into a hashtable
386    * 
387    * @param idstrings
388    * @param seqstrings
389    * @param dsstring
390    * @return
391    */
392   private Hashtable replacementArgs(String[] idstrings,
393           String[] seqstrings, String dsstring)
394   {
395     Hashtable rstrings = new Hashtable();
396     rstrings.put(tokens[0], idstrings);
397     rstrings.put(tokens[1], seqstrings);
398     rstrings.put(tokens[2], new String[]
399     { dsstring });
400     if (idstrings.length != seqstrings.length)
401     {
402       throw new Error(MessageManager.getString("error.idstring_seqstrings_only_one_per_sequence"));
403     }
404     return rstrings;
405   }
406
407   public Object[] makeUrls(Hashtable repstrings, boolean onlyIfMatches)
408           throws UrlStringTooLongException
409   {
410     return makeUrlsIf(true, repstrings, onlyIfMatches);
411   }
412
413   /**
414    * 
415    * @param ids
416    * @param seqstr
417    * @param string
418    * @param b
419    * @return URL stub objects ready to pass to constructFrom
420    * @throws UrlStringTooLongException
421    */
422   public Object[] makeUrlStubs(String[] ids, String[] seqstr,
423           String string, boolean b) throws UrlStringTooLongException
424   {
425     Hashtable rstrings = replacementArgs(ids, seqstr, string);
426     Object[] stubs = makeUrlsIf(false, rstrings, b);
427     if (stubs != null)
428     {
429       return new Object[]
430       { stubs[0], stubs[1], rstrings, new boolean[]
431       { b } };
432     }
433     // TODO Auto-generated method stub
434     return null;
435   }
436
437   /**
438    * generate the URL for the given URL stub object array returned from
439    * makeUrlStubs
440    * 
441    * @param stubs
442    * @return URL string.
443    * @throws UrlStringTooLongException
444    */
445   public String constructFrom(Object[] stubs)
446           throws UrlStringTooLongException
447   {
448     Object[] results = makeUrlsIf(true, (Hashtable) stubs[2],
449             ((boolean[]) stubs[3])[0]);
450     return ((String[]) results[3])[0];
451   }
452
453   /**
454    * conditionally generate urls or stubs for a given input.
455    * 
456    * @param createFullUrl
457    *          set to false if you only want to test if URLs would be generated.
458    * @param repstrings
459    * @param onlyIfMatches
460    * @return null if no url is generated. Object[] { int[] { number of matches
461    *         seqs }, boolean[] { which matched }, (if createFullUrl also has
462    *         StringBuffer[] { segment generated from inputs that is used in URL
463    *         }, String[] { url })}
464    * @throws UrlStringTooLongException
465    */
466   protected Object[] makeUrlsIf(boolean createFullUrl,
467           Hashtable repstrings, boolean onlyIfMatches)
468           throws UrlStringTooLongException
469   {
470     int pass = 0;
471
472     // prepare string arrays in correct order to be assembled into URL input
473     String[][] idseq = new String[mtch.length][]; // indexed by pass
474     int mins = 0, maxs = 0; // allowed two values, 1 or n-sequences.
475     for (int i = 0; i < mtch.length; i++)
476     {
477       idseq[i] = (String[]) repstrings.get(mtch[i]);
478       if (idseq[i].length >= 1)
479       {
480         if (mins == 0 && idseq[i].length == 1)
481         {
482           mins = 1;
483         }
484         if (maxs < 2)
485         {
486           maxs = idseq[i].length;
487         }
488         else
489         {
490           if (maxs != idseq[i].length)
491           {
492             throw new Error(MessageManager.formatMessage("error.cannot_have_mixed_length_replacement_vectors",
493                                 new String[]{(mtch[i]), Integer.valueOf(idseq[i].length).toString(),Integer.valueOf(maxs).toString()}));
494           }
495         }
496       }
497       else
498       {
499         throw new Error(MessageManager.getString("error.cannot_have_zero_length_vector_replacement_strings"));
500       }
501     }
502     // iterate through input, collating segments to be inserted into url
503     StringBuffer matched[] = new StringBuffer[idseq.length];
504     // and precompile regexes
505     Regex[] rgxs = new Regex[matched.length];
506     for (pass = 0; pass < matched.length; pass++)
507     {
508       matched[pass] = new StringBuffer();
509       if (regexReplace[pass] != null)
510       {
511         rgxs[pass] = Regex.perlCode("/"
512                 + regexReplace[pass] + "/");
513       }
514       else
515       {
516         rgxs[pass] = null;
517       }
518     }
519     // tot up the invariant lengths for this url
520     int urllength = url_prefix.length();
521     for (pass = 0; pass < matched.length; pass++)
522     {
523       urllength += url_suffix[pass].length();
524     }
525
526     // flags to record which of the input sequences were actually used to
527     // generate the
528     // url
529     boolean[] thismatched = new boolean[maxs];
530     int seqsmatched = 0;
531     for (int sq = 0; sq < maxs; sq++)
532     {
533       // initialise flag for match
534       thismatched[sq] = false;
535       StringBuffer[] thematches = new StringBuffer[rgxs.length];
536       for (pass = 0; pass < rgxs.length; pass++)
537       {
538         thematches[pass] = new StringBuffer(); // initialise - in case there are
539                                                // no more
540         // matches.
541         // if a regex is provided, then it must match for all sequences in all
542         // tokens for it to be considered.
543         if (idseq[pass].length <= sq)
544         {
545           // no more replacement strings to try for this token
546           continue;
547         }
548         if (rgxs[pass] != null)
549         {
550           Regex rg = rgxs[pass];
551           int rematchat = 0;
552           // concatenate all matches of re in the given string!
553           while (rg.searchFrom(idseq[pass][sq], rematchat))
554           {
555             rematchat = rg.matchedTo();
556             thismatched[sq] |= true;
557             urllength += rg.charsMatched(); // count length
558             if ((urllength + 32) > Platform.getMaxCommandLineLength())
559             {
560               throw new UrlStringTooLongException(urllength);
561             }
562
563             if (!createFullUrl)
564             {
565               continue; // don't bother making the URL replacement text.
566             }
567             // do we take the cartesian products of the substituents ?
568             int ns = rg.numSubs();
569             if (ns == 0)
570             {
571               thematches[pass].append(rg.stringMatched());// take whole regex
572             }
573             /*
574              * else if (ns==1) { // take only subgroup match return new String[]
575              * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
576              * }; }
577              */
578             // deal with multiple submatch case - for moment we do the simplest
579             // - concatenate the matched regions, instead of creating a complete
580             // list for each alternate match over all sequences.
581             // TODO: specify a 'replace pattern' - next refinement
582             else
583             {
584               // debug
585               /*
586                * for (int s = 0; s <= rg.numSubs(); s++) {
587                * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
588                * " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
589                * }
590                */
591               // try to collate subgroup matches
592               StringBuffer subs = new StringBuffer();
593               // have to loop through submatches, collating them at top level
594               // match
595               int s = 0; // 1;
596               while (s <= ns)
597               {
598                 if (s + 1 <= ns && rg.matchedTo(s) > -1
599                         && rg.matchedTo(s + 1) > -1
600                         && rg.matchedTo(s + 1) < rg.matchedTo(s))
601                 {
602                   // s is top level submatch. search for submatches enclosed by
603                   // this one
604                   int r = s + 1;
605                   StringBuffer rmtch = new StringBuffer();
606                   while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
607                   {
608                     if (rg.matchedFrom(r) > -1)
609                     {
610                       rmtch.append(rg.stringMatched(r));
611                     }
612                     r++;
613                   }
614                   if (rmtch.length() > 0)
615                   {
616                     subs.append(rmtch); // simply concatenate
617                   }
618                   s = r;
619                 }
620                 else
621                 {
622                   if (rg.matchedFrom(s) > -1)
623                   {
624                     subs.append(rg.stringMatched(s)); // concatenate
625                   }
626                   s++;
627                 }
628               }
629               thematches[pass].append(subs);
630             }
631           }
632         }
633         else
634         {
635           // are we only supposed to take regex matches ?
636           if (!onlyIfMatches)
637           {
638             thismatched[sq] |= true;
639             urllength += idseq[pass][sq].length(); // tot up length
640             if (createFullUrl)
641             {
642               thematches[pass] = new StringBuffer(idseq[pass][sq]); // take
643                                                                     // whole
644                                                                     // string -
645               // regardless - probably not a
646               // good idea!
647               /*
648                * TODO: do some boilerplate trimming of the fields to make them
649                * sensible e.g. trim off any 'prefix' in the id string (see
650                * UrlLink for the below) - pre 2.4 Jalview behaviour if
651                * (idstring.indexOf("|") > -1) { idstring =
652                * idstring.substring(idstring.lastIndexOf("|") + 1); }
653                */
654             }
655
656           }
657         }
658       }
659
660       // check if we are going to add this sequence's results ? all token
661       // replacements must be valid for this to happen!
662       // (including single value replacements - eg. dataset name)
663       if (thismatched[sq])
664       {
665         if (createFullUrl)
666         {
667           for (pass = 0; pass < matched.length; pass++)
668           {
669             if (idseq[pass].length > 1 && matched[pass].length() > 0)
670             {
671               matched[pass].append(separators[pass]);
672             }
673             matched[pass].append(thematches[pass]);
674           }
675         }
676         seqsmatched++;
677       }
678     }
679     // finally, if any sequences matched, then form the URL and return
680     if (seqsmatched == 0 || (createFullUrl && matched[0].length() == 0))
681     {
682       // no matches - no url generated
683       return null;
684     }
685     // check if we are beyond the feasible command line string limit for this
686     // platform
687     if ((urllength + 32) > Platform.getMaxCommandLineLength())
688     {
689       throw new UrlStringTooLongException(urllength);
690     }
691     if (!createFullUrl)
692     {
693       // just return the essential info about what the URL would be generated
694       // from
695       return new Object[]
696       { new int[]
697       { seqsmatched }, thismatched };
698     }
699     // otherwise, create the URL completely.
700
701     StringBuffer submiturl = new StringBuffer();
702     submiturl.append(url_prefix);
703     for (pass = 0; pass < matched.length; pass++)
704     {
705       submiturl.append(matched[pass]);
706       if (url_suffix[pass] != null)
707       {
708         submiturl.append(url_suffix[pass]);
709       }
710     }
711
712     return new Object[]
713     { new int[]
714     { seqsmatched }, thismatched, matched, new String[]
715     { submiturl.toString() } };
716   }
717
718   /**
719    * 
720    * @param urlstub
721    * @return number of distinct sequence (id or seuqence) replacements predicted
722    *         for this stub
723    */
724   public int getNumberInvolved(Object[] urlstub)
725   {
726     return ((int[]) urlstub[0])[0]; // returns seqsmatched from
727                                     // makeUrlsIf(false,...)
728   }
729
730   /**
731    * get token types present in this url as a bitfield indicating presence of
732    * each token from tokens (LSB->MSB).
733    * 
734    * @return groupURL class as integer
735    */
736   public int getGroupURLType()
737   {
738     int r = 0;
739     for (int pass = 0; pass < tokens.length; pass++)
740     {
741       for (int i = 0; i < mtch.length; i++)
742       {
743         if (mtch[i].equals(tokens[pass]))
744         {
745           r += 1 << pass;
746         }
747       }
748     }
749     return r;
750   }
751
752   public String toString()
753   {
754     StringBuffer result = new StringBuffer();
755     result.append(label + "|" + url_prefix);
756     int r;
757     for (r = 0; r < url_suffix.length; r++)
758     {
759       result.append("$");
760       result.append(mtch[r]);
761       if (regexReplace[r] != null)
762       {
763         result.append("=/");
764         result.append(regexReplace[r]);
765         result.append("/=");
766       }
767       result.append("$");
768       result.append(url_suffix[r]);
769     }
770     for (r = 0; r < separators.length; r++)
771     {
772       result.append("|");
773       result.append(separators[r]);
774     }
775     return result.toString();
776   }
777
778   /**
779    * report stats about the generated url string given an input set
780    * 
781    * @param ul
782    * @param idstring
783    * @param url
784    */
785   private static void testUrls(GroupUrlLink ul, String[][] idstring,
786           Object[] url)
787   {
788
789     if (url == null)
790     {
791       System.out.println("Created NO urls.");
792     }
793     else
794     {
795       System.out.println("Created a url from " + ((int[]) url[0])[0]
796               + "out of " + idstring[0].length + " sequences.");
797       System.out.println("Sequences that did not match:");
798       for (int sq = 0; sq < idstring[0].length; sq++)
799       {
800         if (!((boolean[]) url[1])[sq])
801         {
802           System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
803                   + idstring[1][sq]);
804         }
805       }
806       System.out.println("Sequences that DID match:");
807       for (int sq = 0; sq < idstring[0].length; sq++)
808       {
809         if (((boolean[]) url[1])[sq])
810         {
811           System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
812                   + idstring[1][sq]);
813         }
814       }
815       System.out.println("The generated URL:");
816       System.out.println(((String[]) url[3])[0]);
817     }
818   }
819
820   public static void main(String argv[])
821   {
822     // note - JAL-1383 - these services are all dead
823     String[] links = new String[]
824     {
825         "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
826         "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=linkInDatasetFromJalview&input=$SEQUENCES$&inputType=1|,",
827         "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCEIDS$&inputType=0|,",
828         "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Enfin%20Default%20Workflow&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
829         "EnVision2|IDS|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=linkInDatasetFromJalview&input=$SEQUENCEIDS$&inputType=0|,",
830         "EnVision2|Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=$SEQUENCEIDS$&datasetName=$DATASETID$&input=$SEQUENCES$&inputType=1|,",
831         "EnVision2 Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Default&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCES=/([a-zA-Z]+)/=$&inputType=1|,",
832         "EnVision2 Seqs|http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?workflow=Default&datasetName=JalviewSeqs$DATASETID$&input=$SEQUENCES=/[A-Za-z]+/=$&inputType=1|,"
833     /*
834      * http://www.ebi.ac.uk/enfin-srv/envision2/pages/linkin.jsf?input=P38389,P38398
835      * &inputType=0&workflow=Enfin%20Default%20Workflow&datasetName=
836      * linkInDatasetFromPRIDE
837      */
838     };
839
840     SequenceI[] seqs = new SequenceI[]
841     { new Sequence("StupidLabel:gi|9234|pdb|102L|A",
842             "asdiasdpasdpadpwpadasdpaspdw"), };
843     String[][] seqsandids = formStrings(seqs);
844     for (int i = 0; i < links.length; i++)
845     {
846       GroupUrlLink ul = new GroupUrlLink(links[i]);
847       if (ul.isValid())
848       {
849         System.out.println("\n\n\n");
850         System.out.println("Link " + i + " " + links[i] + " : "
851                 + ul.toString());
852         System.out.println(" pref : " + ul.getUrl_prefix());
853         System.out.println(" IdReplace : " + ul.getIDRegexReplace());
854         System.out.println(" SeqReplace : " + ul.getSeqRegexReplace());
855         System.out.println(" Suffixes : " + ul.getUrl_suffix());
856
857         System.out
858                 .println("<insert input id and sequence strings here> Without onlyIfMatches:");
859         Object[] urls;
860         try
861         {
862           urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset",
863                   false);
864           testUrls(ul, seqsandids, urls);
865         } catch (UrlStringTooLongException ex)
866         {
867           System.out.println("too long exception " + ex);
868         }
869         System.out
870                 .println("<insert input id and sequence strings here> With onlyIfMatches set:");
871         try
872         {
873           urls = ul.makeUrls(seqsandids[0], seqsandids[1], "mydataset",
874                   true);
875           testUrls(ul, seqsandids, urls);
876         } catch (UrlStringTooLongException ex)
877         {
878           System.out.println("too long exception " + ex);
879         }
880       }
881       else
882       {
883         System.err.println("Invalid URLLink : " + links[i] + " : "
884                 + ul.getInvalidMessage());
885       }
886     }
887   }
888
889   /**
890    * covenience method to generate the id and sequence string vector from a set
891    * of seuqences using each sequence's getName() and getSequenceAsString()
892    * method
893    * 
894    * @param seqs
895    * @return String[][] {{sequence ids},{sequence strings}}
896    */
897   public static String[][] formStrings(SequenceI[] seqs)
898   {
899     String[][] idset = new String[2][seqs.length];
900     for (int i = 0; i < seqs.length; i++)
901     {
902       idset[0][i] = seqs[i].getName();
903       idset[1][i] = seqs[i].getSequenceAsString();
904     }
905     return idset;
906   }
907
908   public void setLabel(String newlabel)
909   {
910     this.label = newlabel;
911   }
912
913 }