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