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