update author list in license for (JAL-826)
[jalview.git] / src / jalview / ws / rest / RestServiceDescription.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.ws.rest;
19
20 import jalview.datamodel.SequenceI;
21 import jalview.io.packed.DataProvider;
22 import jalview.io.packed.SimpleDataProvider;
23 import jalview.io.packed.DataProvider.JvDataType;
24 import jalview.util.GroupUrlLink.UrlStringTooLongException;
25 import jalview.util.Platform;
26 import jalview.ws.rest.params.Alignment;
27 import jalview.ws.rest.params.AnnotationFile;
28 import jalview.ws.rest.params.JobConstant;
29 import jalview.ws.rest.params.SeqGroupIndexVector;
30
31 import java.net.URL;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Hashtable;
35 import java.util.List;
36 import java.util.Map;
37 import java.util.NoSuchElementException;
38 import java.util.StringTokenizer;
39 import java.util.Vector;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42
43 import javax.swing.JViewport;
44
45 import com.stevesoft.pat.Regex;
46 import com.sun.org.apache.xml.internal.serialize.OutputFormat.DTD;
47 import com.sun.tools.doclets.internal.toolkit.util.DocFinder.Output;
48
49 public class RestServiceDescription
50 {
51   /**
52    * create a new rest service description ready to be configured
53    */
54   public RestServiceDescription()
55   {
56     
57   }
58   /**
59    * @param details
60    * @param postUrl
61    * @param urlSuffix
62    * @param inputParams
63    * @param hseparable
64    * @param vseparable
65    * @param gapCharacter
66    */
67   public RestServiceDescription(String action, String description,
68           String name, String postUrl, String urlSuffix,
69           Map<String, InputType> inputParams, boolean hseparable,
70           boolean vseparable, char gapCharacter)
71   {
72     super();
73     this.details = new UIinfo();
74     details.Action = action == null ? "" : action;
75     details.description = description == null ? "" : description;
76     details.Name = name == null ? "" : name;
77     this.postUrl = postUrl == null ? "" : postUrl;
78     this.urlSuffix = urlSuffix == null ? "" : urlSuffix;
79     if (inputParams != null)
80     {
81       this.inputParams = inputParams;
82     }
83     this.hseparable = hseparable;
84     this.vseparable = vseparable;
85     this.gapCharacter = gapCharacter;
86   }
87
88   public boolean equals(Object o)
89   {
90     if (o == null || !(o instanceof RestServiceDescription))
91     {
92       return false;
93     }
94     RestServiceDescription other = (RestServiceDescription) o;
95     boolean diff = (gapCharacter != other.gapCharacter);
96     diff |= vseparable != other.vseparable;
97     diff |= hseparable != other.hseparable;
98     diff |= !(urlSuffix.equals(other.urlSuffix));
99     // TODO - robust diff that includes constants and reordering of URL
100     // diff |= !(postUrl.equals(other.postUrl));
101     // diff |= !inputParams.equals(other.inputParams);
102     diff |= !details.Name.equals(other.details.Name);
103     diff |= !details.Action.equals(other.details.Action);
104     diff |= !details.description.equals(other.details.description);
105     return !diff;
106   }
107
108   /**
109    * Service UI Info { Action, Specific Name of Service, Brief Description }
110    */
111
112   public class UIinfo
113   {
114     public String getAction()
115     {
116       return Action;
117     }
118
119     public void setAction(String action)
120     {
121       Action = action;
122     }
123
124     public String getName()
125     {
126       return Name;
127     }
128
129     public void setName(String name)
130     {
131       Name = name;
132     }
133
134     public String getDescription()
135     {
136       return description;
137     }
138
139     public void setDescription(String description)
140     {
141       this.description = description;
142     }
143
144     String Action;
145
146     String Name;
147
148     String description;
149   }
150
151   public UIinfo details = new UIinfo();
152
153   public String getAction()
154   {
155     return details.getAction();
156   }
157
158   public void setAction(String action)
159   {
160     details.setAction(action);
161   }
162
163   public String getName()
164   {
165     return details.getName();
166   }
167
168   public void setName(String name)
169   {
170     details.setName(name);
171   }
172
173   public String getDescription()
174   {
175     return details.getDescription();
176   }
177
178   public void setDescription(String description)
179   {
180     details.setDescription(description);
181   }
182
183   /**
184    * Service base URL
185    */
186   String postUrl;
187
188   public String getPostUrl()
189   {
190     return postUrl;
191   }
192
193   public void setPostUrl(String postUrl)
194   {
195     this.postUrl = postUrl;
196   }
197
198   public String getUrlSuffix()
199   {
200     return urlSuffix;
201   }
202
203   public void setUrlSuffix(String urlSuffix)
204   {
205     this.urlSuffix = urlSuffix;
206   }
207
208   public Map<String, InputType> getInputParams()
209   {
210     return inputParams;
211   }
212
213   public void setInputParams(Map<String, InputType> inputParams)
214   {
215     this.inputParams = inputParams;
216   }
217
218   public void setHseparable(boolean hseparable)
219   {
220     this.hseparable = hseparable;
221   }
222
223   public void setVseparable(boolean vseparable)
224   {
225     this.vseparable = vseparable;
226   }
227
228   public void setGapCharacter(char gapCharacter)
229   {
230     this.gapCharacter = gapCharacter;
231   }
232
233   /**
234    * suffix that should be added to any url used if it does not already end in
235    * the suffix.
236    */
237   String urlSuffix;
238
239   /**
240    * input info given as key/value pairs - mapped to post arguments
241    */
242   Map<String, InputType> inputParams = new HashMap<String, InputType>();
243
244   /**
245    * assigns the given inputType it to its corresponding input parameter token
246    * it.token
247    * 
248    * @param it
249    */
250   public void setInputParam(InputType it)
251   {
252     inputParams.put(it.token, it);
253   }
254
255   /**
256    * remove the given input type it from the set of service input parameters.
257    * 
258    * @param it
259    */
260   public void removeInputParam(InputType it)
261   {
262     inputParams.remove(it.token);
263   }
264
265   /**
266    * service requests alignment data
267    */
268   boolean aligndata;
269
270   /**
271    * service requests alignment and/or seuqence annotationo data
272    */
273   boolean annotdata;
274
275   /**
276    * service requests partitions defined over input (alignment) data
277    */
278   boolean partitiondata;
279
280   /**
281    * process ths input data and set the appropriate shorthand flags describing
282    * the input the service wants
283    */
284   public void setInvolvesFlags()
285   {
286     aligndata = inputInvolves(Alignment.class);
287     annotdata = inputInvolves(AnnotationFile.class);
288     partitiondata = inputInvolves(SeqGroupIndexVector.class);
289   }
290
291   /**
292    * Service return info { alignment, annotation file (loaded back on to
293    * alignment), tree (loaded back on to alignment), sequence annotation -
294    * loaded back on to alignment), text report, pdb structures with sequence
295    * mapping )
296    * 
297    */
298
299   /**
300    * Start with bare minimum: input is alignment + groups on alignment
301    * 
302    * @author JimP
303    * 
304    */
305
306   private String invalidMessage = null;
307
308   /**
309    * parse the given linkString of the form '<label>|<url>|separator
310    * char[|optional sequence separator char]' into parts. url may contain a
311    * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
312    * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
313    * $SEQUENCES<=optional regex=>$.
314    * 
315    * @param link
316    */
317   public RestServiceDescription(String link)
318   {
319     StringBuffer warnings = new StringBuffer();
320     if (!configureFromEncodedString(link, warnings))
321     {
322       if (warnings.length() > 0)
323       {
324         invalidMessage = warnings.toString();
325       }
326     }
327   }
328
329   public RestServiceDescription(RestServiceDescription toedit)
330   {
331     // Rather then do the above, we cheat and use our human readable
332     // serialization code to clone everything
333     this(toedit.toString());
334     /**
335      * if (toedit == null) { return; } /** urlSuffix = toedit.urlSuffix; postUrl
336      * = toedit.postUrl; hseparable = toedit.hseparable; vseparable =
337      * toedit.vseparable; gapCharacter = toedit.gapCharacter; details = new
338      * RestServiceDescription.UIinfo(); details.Action = toedit.details.Action;
339      * details.description = toedit.details.description; details.Name =
340      * toedit.details.Name; for (InputType itype: toedit.inputParams.values()) {
341      * inputParams.put(itype.token, itype.clone());
342      * 
343      * }
344      */
345     // TODO Implement copy constructor NOW*/
346   }
347
348   /**
349    * @return the invalidMessage
350    */
351   public String getInvalidMessage()
352   {
353     return invalidMessage;
354   }
355
356   /**
357    * Check if URL string was parsed properly.
358    * 
359    * @return boolean - if false then <code>getInvalidMessage</code> returns an
360    *         error message
361    */
362   public boolean isValid()
363   {
364     return invalidMessage == null;
365   }
366
367   private static boolean debug = false;
368
369   /**
370    * parse the string into a list
371    * 
372    * @param list
373    * @param separator
374    * @return elements separated by separator
375    */
376   public static String[] separatorListToArray(String list, String separator)
377   {
378     int seplen = separator.length();
379     if (list == null || list.equals("") || list.equals(separator))
380       return null;
381     java.util.ArrayList<String> jv = new ArrayList<String>();
382     int cp = 0, pos, escape;
383     boolean wasescaped = false,wasquoted=false;
384     String lstitem = null;
385     while ((pos = list.indexOf(separator, cp)) >= cp)
386     {
387       
388       escape = (pos > 0 && list.charAt(pos - 1) == '\\') ? -1 : 0;
389       if (wasescaped || wasquoted)
390       {
391         // append to previous pos
392         jv.set(jv.size() - 1,
393                 lstitem = lstitem + separator
394                         + list.substring(cp, pos + escape));
395
396       }
397       else
398       {
399         jv.add(lstitem = list.substring(cp, pos + escape));
400       }
401       cp = pos + seplen;
402       wasescaped = escape == -1;
403       if (!wasescaped)
404       {
405         // last separator may be in an unmatched quote
406         if (java.util.regex.Pattern.matches("('[^']*')*[^']*'",lstitem))
407         {
408           wasquoted=true;
409         }
410       }
411       
412     }
413     if (cp < list.length())
414     {
415       String c = list.substring(cp);
416       if (wasescaped || wasquoted)
417       {
418         // append final separator
419         jv.set(jv.size() - 1, lstitem + separator + c);
420       }
421       else
422       {
423         if (!c.equals(separator))
424         {
425           jv.add(c);
426         }
427       }
428     }
429     if (jv.size() > 0)
430     {
431       String[] v = jv.toArray(new String[jv.size()]);
432       jv.clear();
433       if (debug)
434       {
435         System.err.println("Array from '" + separator
436                 + "' separated List:\n" + v.length);
437         for (int i = 0; i < v.length; i++)
438         {
439           System.err.println("item " + i + " '" + v[i] + "'");
440         }
441       }
442       return v;
443     }
444     if (debug)
445     {
446       System.err.println("Empty Array from '" + separator
447               + "' separated List");
448     }
449     return null;
450   }
451
452   /**
453    * concatenate the list with separator
454    * 
455    * @param list
456    * @param separator
457    * @return concatenated string
458    */
459   public static String arrayToSeparatorList(String[] list, String separator)
460   {
461     StringBuffer v = new StringBuffer();
462     if (list != null && list.length > 0)
463     {
464       for (int i = 0, iSize = list.length; i < iSize; i++)
465       {
466         if (list[i] != null)
467         {
468           if (v.length() > 0)
469           {
470             v.append(separator);
471           }
472           // TODO - escape any separator values in list[i]
473           v.append(list[i]);
474         }
475       }
476       if (debug)
477       {
478         System.err.println("Returning '" + separator
479                 + "' separated List:\n");
480         System.err.println(v);
481       }
482       return v.toString();
483     }
484     if (debug)
485     {
486       System.err.println("Returning empty '" + separator
487               + "' separated List\n");
488     }
489     return "" + separator;
490   }
491
492   /**
493    * parse a string containing a list of service properties and configure the
494    * service description
495    * 
496    * @param propList
497    *          param warnings a StringBuffer that any warnings about invalid
498    *          content will be appended to.
499    */
500   private boolean configureFromServiceInputProperties(String propList,
501           StringBuffer warnings)
502   {
503     String[] props = separatorListToArray(propList, ",");
504     if (props == null)
505     {
506       return true;
507     }
508     ;
509     boolean valid = true;
510     String val = null;
511     int l = warnings.length();
512     int i;
513     for (String prop : props)
514     {
515       if ((i = prop.indexOf("=")) > -1)
516       {
517         val = prop.substring(i + 1);
518         if (val.startsWith("\'") && val.endsWith("\'"))
519         {
520           val = val.substring(1, val.length() - 1);
521         }
522         prop = prop.substring(0, i);
523       }
524
525       if (prop.equals("hseparable"))
526       {
527         hseparable = true;
528       }
529       if (prop.equals("vseparable"))
530       {
531         vseparable = true;
532       }
533       if (prop.equals("gapCharacter"))
534       {
535         if (val == null || val.length() == 0 || val.length() > 1)
536         {
537           valid = false;
538           warnings.append((warnings.length() > 0 ? "\n" : "")
539                   + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
540                           + val + "'"));
541         }
542         else
543         {
544           gapCharacter = val.charAt(0);
545         }
546       }
547       if (prop.equals("returns"))
548       {
549         _configureOutputFormatFrom(val, warnings);
550       }
551     }
552     // return true if valid is true and warning buffer was not appended to.
553     return valid && (l == warnings.length());
554   }
555
556   private String _genOutputFormatString()
557   {
558     String buff = "";
559     if (resultData == null)
560     {
561       return "";
562     }
563     for (JvDataType type : resultData)
564     {
565       if (buff.length() > 0)
566       {
567         buff += ";";
568       }
569       buff += type.toString();
570     }
571     return buff;
572   }
573
574   private void _configureOutputFormatFrom(String outstring,
575           StringBuffer warnings)
576   {
577     if (outstring.indexOf(";") == -1)
578     {
579       // we add a token, for simplicity
580       outstring = outstring + ";";
581     }
582     StringTokenizer st = new StringTokenizer(outstring, ";");
583     String tok = "";
584     resultData = new ArrayList<JvDataType>();
585     while (st.hasMoreTokens())
586     {
587       try
588       {
589         resultData.add(JvDataType.valueOf(tok = st.nextToken()));
590       } catch (NoSuchElementException x)
591       {
592         warnings.append("Invalid result type: '" + tok
593                 + "' (must be one of: ");
594         String sep = "";
595         for (JvDataType vl : JvDataType.values())
596         {
597           warnings.append(sep);
598           warnings.append(vl.toString());
599           sep = " ,";
600         }
601         warnings.append(" separated by semi-colons)\n");
602       }
603     }
604   }
605
606   private String getServiceIOProperties()
607   {
608     ArrayList<String> vls = new ArrayList<String>();
609     if (isHseparable()) { vls.add("hseparable");};
610     if (isVseparable()) { vls.add("vseparable");};
611     vls.add(new String("gapCharacter='" + gapCharacter + "'"));
612     vls.add(new String("returns='" + _genOutputFormatString() + "'"));
613     return arrayToSeparatorList(vls.toArray(new String[0]), ",");
614   }
615
616   public String toString()
617   {
618     StringBuffer result = new StringBuffer();
619     result.append("|");
620     result.append(details.Name);
621     result.append('|');
622     result.append(details.Action);
623     result.append('|');
624     if (details.description != null)
625     {
626       result.append(details.description);
627     }
628     ;
629     // list job input flags
630     result.append('|');
631     result.append(getServiceIOProperties());
632     // list any additional cgi parameters needed for result retrieval
633     if (urlSuffix != null && urlSuffix.length() > 0)
634     {
635       result.append('|');
636       result.append(urlSuffix);
637     }
638     result.append('|');
639     result.append(getInputParamEncodedUrl());
640     return result.toString();
641   }
642
643   /**
644    * processes a service encoded as a string (as generated by RestServiceDescription.toString())
645    * Note - this will only use the first service definition encountered in the string to configure the service.
646    * @param encoding
647    * @param warnings - where warning messages are reported.
648    * @return true if configuration was parsed successfully. 
649    */
650   public boolean configureFromEncodedString(String encoding,
651           StringBuffer warnings)
652   {
653     String[] list = separatorListToArray(encoding, "|");
654     
655     int nextpos=parseServiceList(list,warnings, 0);
656     if (nextpos>0)
657     {
658       return true;
659     }
660     return false;
661   }
662   /**
663    * processes the given list from position p, attempting to configure the service from it.
664    * Service lists are formed by concatenating individual stringified services. The first character of a stringified service is '|', enabling this, and the parser will ignore empty fields in a '|' separated list when they fall outside a service definition.
665    * @param list
666    * @param warnings
667    * @param p
668    * @return
669    */
670   protected int parseServiceList(String[] list, StringBuffer warnings, int p)
671   {
672     boolean invalid = false;
673     // look for the first non-empty position - expect it to be service name
674     while (list[p]!=null && list[p].trim().length()==0)
675     {
676       p++;
677     }
678     details.Name = list[p];
679     details.Action = list[p+1];
680     details.description = list[p+2];
681     invalid |= !configureFromServiceInputProperties(list[p+3], warnings);
682     if (list.length-p > 5 && list[p+5]!=null && list[p+5].trim().length()>5)
683     {
684       urlSuffix = list[p+4];
685       invalid |= !configureFromInputParamEncodedUrl(list[p+5], warnings);
686       p+=6;
687     }
688     else
689     {
690       if (list.length-p > 4 && list[p+4]!=null && list[p+4].trim().length()>5)
691       {
692         urlSuffix = null;
693         invalid |= !configureFromInputParamEncodedUrl(list[p+4], warnings);
694         p+=5;
695       }
696     }
697     return invalid ? -1 : p;
698   }
699   
700   /**
701    * @return string representation of the input parameters, their type and
702    *         constraints, appended to the service's base submission URL
703    */
704   private String getInputParamEncodedUrl()
705   {
706     StringBuffer url = new StringBuffer();
707     if (postUrl == null || postUrl.length() < 5)
708     {
709       return "";
710     }
711
712     url.append(postUrl);
713     char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
714     boolean consts = true;
715     do
716     {
717       for (Map.Entry<String, InputType> param : inputParams.entrySet())
718       {
719         List<String> vals = param.getValue().getURLEncodedParameter();
720         if (param.getValue().isConstant())
721         {
722           if (consts)
723           {
724             url.append(appendChar);
725             appendChar = '&';
726             url.append(param.getValue().token);
727             if (vals.size() == 1)
728             {
729               url.append("=");
730               url.append(vals.get(0));
731             }
732           }
733         }
734         else
735         {
736           if (!consts)
737           {
738             url.append(appendChar);
739             appendChar = '&';
740             url.append(param.getValue().token);
741             url.append("=");
742             // write parameter set as $TOKENPREFIX:csv list of params$ for this
743             // input param
744             url.append("$");
745             url.append(param.getValue().getURLtokenPrefix());
746             url.append(":");
747             url.append(arrayToSeparatorList(vals.toArray(new String[0]),
748                     ","));
749             url.append("$");
750           }
751         }
752
753       }
754       // toggle consts and repeat until !consts is false:
755     } while (!(consts = !consts));
756     return url.toString();
757   }
758
759   /**
760    * parse the service URL and input parameters from the given encoded URL
761    * string and configure the RestServiceDescription from it.
762    * 
763    * @param ipurl
764    * @param warnings
765    *          where any warnings
766    * @return true if URL parsed correctly. false means the configuration failed.
767    */
768   private boolean configureFromInputParamEncodedUrl(String ipurl,
769           StringBuffer warnings)
770   {
771     boolean valid = true;
772     int lastp = 0;
773     String url = new String();
774     Matcher prms = Pattern.compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$")
775             .matcher(ipurl);
776     Map<String, InputType> iparams = new Hashtable<String, InputType>();
777     InputType jinput;
778     while (prms.find())
779     {
780       if (lastp < prms.start(0))
781       {
782         url += ipurl.substring(lastp, prms.start(0));
783         lastp = prms.end(0) + 1;
784       }
785       String sep = prms.group(1);
786       String tok = prms.group(2);
787       String iprm = prms.group(3);
788       int colon = iprm.indexOf(":");
789       String iprmparams = "";
790       if (colon > -1)
791       {
792         iprmparams = iprm.substring(colon + 1);
793         iprm = iprm.substring(0, colon);
794       }
795       valid = parseTypeString(prms.group(0), tok, iprm, iprmparams,
796               iparams, warnings);
797     }
798     if (valid)
799     {
800       try
801       {
802         URL u = new URL(url);
803         postUrl = url;
804         inputParams = iparams;
805       } catch (Exception e)
806       {
807         warnings.append("Failed to parse '" + url + "' as a URL.\n");
808         valid = false;
809       }
810     }
811     return valid;
812   }
813
814   public static Class[] getInputTypes()
815   {
816     // TODO - find a better way of maintaining this classlist
817     return new Class[]
818     { jalview.ws.rest.params.Alignment.class,
819         jalview.ws.rest.params.AnnotationFile.class,
820         SeqGroupIndexVector.class,
821         jalview.ws.rest.params.SeqIdVector.class,
822         jalview.ws.rest.params.SeqVector.class,
823         jalview.ws.rest.params.Tree.class };
824   }
825
826   public static boolean parseTypeString(String fullstring, String tok,
827           String iprm, String iprmparams, Map<String, InputType> iparams,
828           StringBuffer warnings)
829   {
830     boolean valid = true;
831     InputType jinput;
832     for (Class type : getInputTypes())
833     {
834       try
835       {
836         jinput = (InputType) (type.getConstructor().newInstance(null));
837         if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
838         {
839           ArrayList<String> al = new ArrayList<String>();
840           for (String prprm : separatorListToArray(iprmparams, ","))
841           {
842             // hack to ensure that strings like "sep=','" containing unescaped commas as values are concatenated
843             al.add(prprm.trim());
844           }
845           if (!jinput.configureFromURLtokenString(al, warnings))
846           {
847             valid = false;
848             warnings.append("Failed to parse '" + fullstring + "' as a "
849                     + jinput.getURLtokenPrefix() + " input tag.\n");
850           }
851           else
852           {
853             jinput.token = tok;
854             iparams.put(tok, jinput);
855             valid = true;
856           }
857           break;
858         }
859
860       } catch (Throwable thr)
861       {
862       }
863       ;
864     }
865     return valid;
866   }
867
868   public static void main(String argv[])
869   {
870     // test separator list
871     try {
872       assert(separatorListToArray("foo=',',min='foo',max='1,2,3',fa=','", ",").length==4);
873       if (separatorListToArray("minsize='2', sep=','", ",").length==2)
874       {
875         assert(false);
876       }
877       
878     } catch (AssertionError x)
879     {
880       System.err.println("separatorListToArray is faulty.");
881     }
882     if (argv.length == 0)
883     {
884       if (!testRsdExchange("Test using default Shmmr service",
885               RestClient.makeShmmrRestClient().service))
886       {
887         System.err.println("default test failed.");
888       }
889       else
890       {
891         System.err.println("default test passed.");
892       }
893     }
894     else
895     {
896       int i = 0, p = 0;
897       for (String svc : argv)
898       {
899         p += testRsdExchange("Test " + (++i), svc) ? 1 : 0;
900       }
901       System.err.println("" + p + " out of " + i + " tests passed.");
902
903     }
904   }
905
906   private static boolean testRsdExchange(String desc, String servicestring)
907   {
908     try
909     {
910       RestServiceDescription newService = new RestServiceDescription(
911               servicestring);
912       if (!newService.isValid())
913       {
914         throw new Error("Failed to create service from '" + servicestring
915                 + "'.\n" + newService.getInvalidMessage());
916       }
917       return testRsdExchange(desc, newService);
918     } catch (Throwable x)
919     {
920       System.err.println("Failed for service (" + desc + "): "
921               + servicestring);
922       x.printStackTrace();
923       return false;
924     }
925   }
926
927   private static boolean testRsdExchange(String desc,
928           RestServiceDescription service)
929   {
930     try
931     {
932       String fromservicetostring = service.toString();
933       RestServiceDescription newService = new RestServiceDescription(
934               fromservicetostring);
935       if (!newService.isValid())
936       {
937         throw new Error("Failed to create service from '"
938                 + fromservicetostring + "'.\n"
939                 + newService.getInvalidMessage());
940       }
941
942       if (!service.equals(newService))
943       {
944         System.err.println("Failed for service (" + desc + ").");
945         System.err.println("Original service and parsed service differ.");
946         System.err.println("Original: " + fromservicetostring);
947         System.err.println("Parsed  : " + newService.toString());
948         return false;
949       }
950     } catch (Throwable x)
951     {
952       System.err.println("Failed for service (" + desc + "): "
953               + service.toString());
954       x.printStackTrace();
955       return false;
956     }
957     return true;
958   }
959
960   /**
961    * covenience method to generate the id and sequence string vector from a set
962    * of seuqences using each sequence's getName() and getSequenceAsString()
963    * method
964    * 
965    * @param seqs
966    * @return String[][] {{sequence ids},{sequence strings}}
967    */
968   public static String[][] formStrings(SequenceI[] seqs)
969   {
970     String[][] idset = new String[2][seqs.length];
971     for (int i = 0; i < seqs.length; i++)
972     {
973       idset[0][i] = seqs[i].getName();
974       idset[1][i] = seqs[i].getSequenceAsString();
975     }
976     return idset;
977   }
978
979   /**
980    * can this service be run on the visible portion of an alignment regardless
981    * of hidden boundaries ?
982    */
983   boolean hseparable = false;
984
985   boolean vseparable = false;
986
987   public boolean isHseparable()
988   {
989     return hseparable;
990   }
991
992   /**
993    * 
994    * @return
995    */
996   public boolean isVseparable()
997   {
998     return vseparable;
999   }
1000
1001   /**
1002    * search the input types for an instance of the given class
1003    * 
1004    * @param <validInput.inputType> class1
1005    * @return
1006    */
1007   public boolean inputInvolves(Class<?> class1)
1008   {
1009     assert (InputType.class.isAssignableFrom(class1));
1010     for (InputType val : inputParams.values())
1011     {
1012       if (class1.isAssignableFrom(val.getClass()))
1013       {
1014         return true;
1015       }
1016     }
1017     return false;
1018   }
1019
1020   char gapCharacter = '-';
1021
1022   /**
1023    * 
1024    * @return the preferred gap character for alignments input/output by this
1025    *         service
1026    */
1027   public char getGapCharacter()
1028   {
1029     return gapCharacter;
1030   }
1031
1032   public String getDecoratedResultUrl(String jobId)
1033   {
1034     // TODO: correctly write ?/& appropriate to result URL format.
1035     return jobId + urlSuffix;
1036   }
1037
1038   private List<JvDataType> resultData = new ArrayList<JvDataType>();
1039
1040   /**
1041    * 
1042    * 
1043    * TODO: Extend to optionally specify relative/absolute url where data of this
1044    * type can be retrieved from
1045    * 
1046    * @param dt
1047    */
1048   public void addResultDatatype(JvDataType dt)
1049   {
1050     if (resultData == null)
1051     {
1052       resultData = new ArrayList<JvDataType>();
1053     }
1054     resultData.add(dt);
1055   }
1056
1057   public boolean removeRsultDatatype(JvDataType dt)
1058   {
1059     if (resultData != null)
1060     {
1061       return resultData.remove(dt);
1062     }
1063     return false;
1064   }
1065
1066   public List<JvDataType> getResultDataTypes()
1067   {
1068     return resultData;
1069   }
1070
1071   /**
1072    * parse a concatenated list of rest service descriptions into an array
1073    * @param services
1074    * @return zero or more services.
1075    * @throws exceptions if the services are improperly encoded.
1076    */
1077   public static List<RestServiceDescription> parseDescriptions(String services) throws Exception
1078   {
1079     String[] list = separatorListToArray(services, "|");
1080     List<RestServiceDescription> svcparsed = new ArrayList<RestServiceDescription>();
1081     int p=0,lastp=0;
1082     StringBuffer warnings=new StringBuffer();
1083     do {
1084       RestServiceDescription rsd = new RestServiceDescription();
1085       p=rsd.parseServiceList(list, warnings, lastp=p);
1086       if (p>lastp && rsd.isValid())
1087       {
1088         svcparsed.add(rsd);
1089       } else {
1090         throw new Exception("Failed to parse user defined RSBS services from :"+services+"\nFirst error was encountered at token "+lastp+" starting "+list[lastp]+":\n"+rsd.getInvalidMessage());
1091       }
1092     } while (p<lastp && p<list.length-1);
1093     return svcparsed;
1094   }
1095
1096 }