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
5 * This file is part of Jalview.
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.
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.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.ws.rest;
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;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Hashtable;
35 import java.util.List;
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;
43 import javax.swing.JViewport;
45 import com.stevesoft.pat.Regex;
46 import com.sun.org.apache.xml.internal.serialize.OutputFormat.DTD;
48 public class RestServiceDescription
51 * create a new rest service description ready to be configured
53 public RestServiceDescription()
66 public RestServiceDescription(String action, String description,
67 String name, String postUrl, String urlSuffix,
68 Map<String, InputType> inputParams, boolean hseparable,
69 boolean vseparable, char gapCharacter)
72 this.details = new UIinfo();
73 details.Action = action == null ? "" : action;
74 details.description = description == null ? "" : description;
75 details.Name = name == null ? "" : name;
76 this.postUrl = postUrl == null ? "" : postUrl;
77 this.urlSuffix = urlSuffix == null ? "" : urlSuffix;
78 if (inputParams != null)
80 this.inputParams = inputParams;
82 this.hseparable = hseparable;
83 this.vseparable = vseparable;
84 this.gapCharacter = gapCharacter;
87 public boolean equals(Object o)
89 if (o == null || !(o instanceof RestServiceDescription))
93 RestServiceDescription other = (RestServiceDescription) o;
94 boolean diff = (gapCharacter != other.gapCharacter);
95 diff |= vseparable != other.vseparable;
96 diff |= hseparable != other.hseparable;
97 diff |= !(urlSuffix.equals(other.urlSuffix));
98 // TODO - robust diff that includes constants and reordering of URL
99 // diff |= !(postUrl.equals(other.postUrl));
100 // diff |= !inputParams.equals(other.inputParams);
101 diff |= !details.Name.equals(other.details.Name);
102 diff |= !details.Action.equals(other.details.Action);
103 diff |= !details.description.equals(other.details.description);
108 * Service UI Info { Action, Specific Name of Service, Brief Description }
113 public String getAction()
118 public void setAction(String action)
123 public String getName()
128 public void setName(String name)
133 public String getDescription()
138 public void setDescription(String description)
140 this.description = description;
150 public UIinfo details = new UIinfo();
152 public String getAction()
154 return details.getAction();
157 public void setAction(String action)
159 details.setAction(action);
162 public String getName()
164 return details.getName();
167 public void setName(String name)
169 details.setName(name);
172 public String getDescription()
174 return details.getDescription();
177 public void setDescription(String description)
179 details.setDescription(description);
187 public String getPostUrl()
192 public void setPostUrl(String postUrl)
194 this.postUrl = postUrl;
197 public String getUrlSuffix()
202 public void setUrlSuffix(String urlSuffix)
204 this.urlSuffix = urlSuffix;
207 public Map<String, InputType> getInputParams()
212 public void setInputParams(Map<String, InputType> inputParams)
214 this.inputParams = inputParams;
217 public void setHseparable(boolean hseparable)
219 this.hseparable = hseparable;
222 public void setVseparable(boolean vseparable)
224 this.vseparable = vseparable;
227 public void setGapCharacter(char gapCharacter)
229 this.gapCharacter = gapCharacter;
233 * suffix that should be added to any url used if it does not already end in
239 * input info given as key/value pairs - mapped to post arguments
241 Map<String, InputType> inputParams = new HashMap<String, InputType>();
244 * assigns the given inputType it to its corresponding input parameter token
249 public void setInputParam(InputType it)
251 inputParams.put(it.token, it);
255 * remove the given input type it from the set of service input parameters.
259 public void removeInputParam(InputType it)
261 inputParams.remove(it.token);
265 * service requests alignment data
270 * service requests alignment and/or seuqence annotationo data
275 * service requests partitions defined over input (alignment) data
277 boolean partitiondata;
280 * process ths input data and set the appropriate shorthand flags describing
281 * the input the service wants
283 public void setInvolvesFlags()
285 aligndata = inputInvolves(Alignment.class);
286 annotdata = inputInvolves(AnnotationFile.class);
287 partitiondata = inputInvolves(SeqGroupIndexVector.class);
291 * Service return info { alignment, annotation file (loaded back on to
292 * alignment), tree (loaded back on to alignment), sequence annotation -
293 * loaded back on to alignment), text report, pdb structures with sequence
299 * Start with bare minimum: input is alignment + groups on alignment
305 private String invalidMessage = null;
308 * parse the given linkString of the form '<label>|<url>|separator
309 * char[|optional sequence separator char]' into parts. url may contain a
310 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
311 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
312 * $SEQUENCES<=optional regex=>$.
316 public RestServiceDescription(String link)
318 StringBuffer warnings = new StringBuffer();
319 if (!configureFromEncodedString(link, warnings))
321 if (warnings.length() > 0)
323 invalidMessage = warnings.toString();
328 public RestServiceDescription(RestServiceDescription toedit)
330 // Rather then do the above, we cheat and use our human readable
331 // serialization code to clone everything
332 this(toedit.toString());
334 * if (toedit == null) { return; } /** urlSuffix = toedit.urlSuffix; postUrl
335 * = toedit.postUrl; hseparable = toedit.hseparable; vseparable =
336 * toedit.vseparable; gapCharacter = toedit.gapCharacter; details = new
337 * RestServiceDescription.UIinfo(); details.Action = toedit.details.Action;
338 * details.description = toedit.details.description; details.Name =
339 * toedit.details.Name; for (InputType itype: toedit.inputParams.values()) {
340 * inputParams.put(itype.token, itype.clone());
344 // TODO Implement copy constructor NOW*/
348 * @return the invalidMessage
350 public String getInvalidMessage()
352 return invalidMessage;
356 * Check if URL string was parsed properly.
358 * @return boolean - if false then <code>getInvalidMessage</code> returns an
361 public boolean isValid()
363 return invalidMessage == null;
366 private static boolean debug = false;
369 * parse the string into a list
373 * @return elements separated by separator
375 public static String[] separatorListToArray(String list, String separator)
377 int seplen = separator.length();
378 if (list == null || list.equals("") || list.equals(separator))
380 java.util.ArrayList<String> jv = new ArrayList<String>();
381 int cp = 0, pos, escape;
382 boolean wasescaped = false,wasquoted=false;
383 String lstitem = null;
384 while ((pos = list.indexOf(separator, cp)) >= cp)
387 escape = (pos > 0 && list.charAt(pos - 1) == '\\') ? -1 : 0;
388 if (wasescaped || wasquoted)
390 // append to previous pos
391 jv.set(jv.size() - 1,
392 lstitem = lstitem + separator
393 + list.substring(cp, pos + escape));
398 jv.add(lstitem = list.substring(cp, pos + escape));
401 wasescaped = escape == -1;
404 // last separator may be in an unmatched quote
405 if (java.util.regex.Pattern.matches("('[^']*')*[^']*'",lstitem))
412 if (cp < list.length())
414 String c = list.substring(cp);
415 if (wasescaped || wasquoted)
417 // append final separator
418 jv.set(jv.size() - 1, lstitem + separator + c);
422 if (!c.equals(separator))
430 String[] v = jv.toArray(new String[jv.size()]);
434 System.err.println("Array from '" + separator
435 + "' separated List:\n" + v.length);
436 for (int i = 0; i < v.length; i++)
438 System.err.println("item " + i + " '" + v[i] + "'");
445 System.err.println("Empty Array from '" + separator
446 + "' separated List");
452 * concatenate the list with separator
456 * @return concatenated string
458 public static String arrayToSeparatorList(String[] list, String separator)
460 StringBuffer v = new StringBuffer();
461 if (list != null && list.length > 0)
463 for (int i = 0, iSize = list.length; i < iSize; i++)
471 // TODO - escape any separator values in list[i]
477 System.err.println("Returning '" + separator
478 + "' separated List:\n");
479 System.err.println(v);
485 System.err.println("Returning empty '" + separator
486 + "' separated List\n");
488 return "" + separator;
492 * parse a string containing a list of service properties and configure the
493 * service description
496 * param warnings a StringBuffer that any warnings about invalid
497 * content will be appended to.
499 private boolean configureFromServiceInputProperties(String propList,
500 StringBuffer warnings)
502 String[] props = separatorListToArray(propList, ",");
508 boolean valid = true;
510 int l = warnings.length();
512 for (String prop : props)
514 if ((i = prop.indexOf("=")) > -1)
516 val = prop.substring(i + 1);
517 if (val.startsWith("\'") && val.endsWith("\'"))
519 val = val.substring(1, val.length() - 1);
521 prop = prop.substring(0, i);
524 if (prop.equals("hseparable"))
528 if (prop.equals("vseparable"))
532 if (prop.equals("gapCharacter"))
534 if (val == null || val.length() == 0 || val.length() > 1)
537 warnings.append((warnings.length() > 0 ? "\n" : "")
538 + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
543 gapCharacter = val.charAt(0);
546 if (prop.equals("returns"))
548 _configureOutputFormatFrom(val, warnings);
551 // return true if valid is true and warning buffer was not appended to.
552 return valid && (l == warnings.length());
555 private String _genOutputFormatString()
558 if (resultData == null)
562 for (JvDataType type : resultData)
564 if (buff.length() > 0)
568 buff += type.toString();
573 private void _configureOutputFormatFrom(String outstring,
574 StringBuffer warnings)
576 if (outstring.indexOf(";") == -1)
578 // we add a token, for simplicity
579 outstring = outstring + ";";
581 StringTokenizer st = new StringTokenizer(outstring, ";");
583 resultData = new ArrayList<JvDataType>();
584 while (st.hasMoreTokens())
588 resultData.add(JvDataType.valueOf(tok = st.nextToken()));
589 } catch (NoSuchElementException x)
591 warnings.append("Invalid result type: '" + tok
592 + "' (must be one of: ");
594 for (JvDataType vl : JvDataType.values())
596 warnings.append(sep);
597 warnings.append(vl.toString());
600 warnings.append(" separated by semi-colons)\n");
605 private String getServiceIOProperties()
607 ArrayList<String> vls = new ArrayList<String>();
608 if (isHseparable()) { vls.add("hseparable");};
609 if (isVseparable()) { vls.add("vseparable");};
610 vls.add(new String("gapCharacter='" + gapCharacter + "'"));
611 vls.add(new String("returns='" + _genOutputFormatString() + "'"));
612 return arrayToSeparatorList(vls.toArray(new String[0]), ",");
615 public String toString()
617 StringBuffer result = new StringBuffer();
619 result.append(details.Name);
621 result.append(details.Action);
623 if (details.description != null)
625 result.append(details.description);
628 // list job input flags
630 result.append(getServiceIOProperties());
631 // list any additional cgi parameters needed for result retrieval
632 if (urlSuffix != null && urlSuffix.length() > 0)
635 result.append(urlSuffix);
638 result.append(getInputParamEncodedUrl());
639 return result.toString();
643 * processes a service encoded as a string (as generated by RestServiceDescription.toString())
644 * Note - this will only use the first service definition encountered in the string to configure the service.
646 * @param warnings - where warning messages are reported.
647 * @return true if configuration was parsed successfully.
649 public boolean configureFromEncodedString(String encoding,
650 StringBuffer warnings)
652 String[] list = separatorListToArray(encoding, "|");
654 int nextpos=parseServiceList(list,warnings, 0);
662 * processes the given list from position p, attempting to configure the service from it.
663 * 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.
669 protected int parseServiceList(String[] list, StringBuffer warnings, int p)
671 boolean invalid = false;
672 // look for the first non-empty position - expect it to be service name
673 while (list[p]!=null && list[p].trim().length()==0)
677 details.Name = list[p];
678 details.Action = list[p+1];
679 details.description = list[p+2];
680 invalid |= !configureFromServiceInputProperties(list[p+3], warnings);
681 if (list.length-p > 5 && list[p+5]!=null && list[p+5].trim().length()>5)
683 urlSuffix = list[p+4];
684 invalid |= !configureFromInputParamEncodedUrl(list[p+5], warnings);
689 if (list.length-p > 4 && list[p+4]!=null && list[p+4].trim().length()>5)
692 invalid |= !configureFromInputParamEncodedUrl(list[p+4], warnings);
696 return invalid ? -1 : p;
700 * @return string representation of the input parameters, their type and
701 * constraints, appended to the service's base submission URL
703 private String getInputParamEncodedUrl()
705 StringBuffer url = new StringBuffer();
706 if (postUrl == null || postUrl.length() < 5)
712 char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
713 boolean consts = true;
716 for (Map.Entry<String, InputType> param : inputParams.entrySet())
718 List<String> vals = param.getValue().getURLEncodedParameter();
719 if (param.getValue().isConstant())
723 url.append(appendChar);
725 url.append(param.getValue().token);
726 if (vals.size() == 1)
729 url.append(vals.get(0));
737 url.append(appendChar);
739 url.append(param.getValue().token);
741 // write parameter set as $TOKENPREFIX:csv list of params$ for this
744 url.append(param.getValue().getURLtokenPrefix());
746 url.append(arrayToSeparatorList(vals.toArray(new String[0]),
753 // toggle consts and repeat until !consts is false:
754 } while (!(consts = !consts));
755 return url.toString();
759 * parse the service URL and input parameters from the given encoded URL
760 * string and configure the RestServiceDescription from it.
765 * @return true if URL parsed correctly. false means the configuration failed.
767 private boolean configureFromInputParamEncodedUrl(String ipurl,
768 StringBuffer warnings)
770 boolean valid = true;
772 String url = new String();
773 Matcher prms = Pattern.compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$")
775 Map<String, InputType> iparams = new Hashtable<String, InputType>();
779 if (lastp < prms.start(0))
781 url += ipurl.substring(lastp, prms.start(0));
782 lastp = prms.end(0) + 1;
784 String sep = prms.group(1);
785 String tok = prms.group(2);
786 String iprm = prms.group(3);
787 int colon = iprm.indexOf(":");
788 String iprmparams = "";
791 iprmparams = iprm.substring(colon + 1);
792 iprm = iprm.substring(0, colon);
794 valid = parseTypeString(prms.group(0), tok, iprm, iprmparams,
801 URL u = new URL(url);
803 inputParams = iparams;
804 } catch (Exception e)
806 warnings.append("Failed to parse '" + url + "' as a URL.\n");
813 public static Class[] getInputTypes()
815 // TODO - find a better way of maintaining this classlist
817 { jalview.ws.rest.params.Alignment.class,
818 jalview.ws.rest.params.AnnotationFile.class,
819 SeqGroupIndexVector.class,
820 jalview.ws.rest.params.SeqIdVector.class,
821 jalview.ws.rest.params.SeqVector.class,
822 jalview.ws.rest.params.Tree.class };
825 public static boolean parseTypeString(String fullstring, String tok,
826 String iprm, String iprmparams, Map<String, InputType> iparams,
827 StringBuffer warnings)
829 boolean valid = true;
831 for (Class type : getInputTypes())
835 jinput = (InputType) (type.getConstructor().newInstance(null));
836 if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
838 ArrayList<String> al = new ArrayList<String>();
839 for (String prprm : separatorListToArray(iprmparams, ","))
841 // hack to ensure that strings like "sep=','" containing unescaped commas as values are concatenated
842 al.add(prprm.trim());
844 if (!jinput.configureFromURLtokenString(al, warnings))
847 warnings.append("Failed to parse '" + fullstring + "' as a "
848 + jinput.getURLtokenPrefix() + " input tag.\n");
853 iparams.put(tok, jinput);
859 } catch (Throwable thr)
867 public static void main(String argv[])
869 // test separator list
871 assert(separatorListToArray("foo=',',min='foo',max='1,2,3',fa=','", ",").length==4);
872 if (separatorListToArray("minsize='2', sep=','", ",").length==2)
877 } catch (AssertionError x)
879 System.err.println("separatorListToArray is faulty.");
881 if (argv.length == 0)
883 if (!testRsdExchange("Test using default Shmmr service",
884 RestClient.makeShmmrRestClient().service))
886 System.err.println("default test failed.");
890 System.err.println("default test passed.");
896 for (String svc : argv)
898 p += testRsdExchange("Test " + (++i), svc) ? 1 : 0;
900 System.err.println("" + p + " out of " + i + " tests passed.");
905 private static boolean testRsdExchange(String desc, String servicestring)
909 RestServiceDescription newService = new RestServiceDescription(
911 if (!newService.isValid())
913 throw new Error("Failed to create service from '" + servicestring
914 + "'.\n" + newService.getInvalidMessage());
916 return testRsdExchange(desc, newService);
917 } catch (Throwable x)
919 System.err.println("Failed for service (" + desc + "): "
926 private static boolean testRsdExchange(String desc,
927 RestServiceDescription service)
931 String fromservicetostring = service.toString();
932 RestServiceDescription newService = new RestServiceDescription(
933 fromservicetostring);
934 if (!newService.isValid())
936 throw new Error("Failed to create service from '"
937 + fromservicetostring + "'.\n"
938 + newService.getInvalidMessage());
941 if (!service.equals(newService))
943 System.err.println("Failed for service (" + desc + ").");
944 System.err.println("Original service and parsed service differ.");
945 System.err.println("Original: " + fromservicetostring);
946 System.err.println("Parsed : " + newService.toString());
949 } catch (Throwable x)
951 System.err.println("Failed for service (" + desc + "): "
952 + service.toString());
960 * covenience method to generate the id and sequence string vector from a set
961 * of seuqences using each sequence's getName() and getSequenceAsString()
965 * @return String[][] {{sequence ids},{sequence strings}}
967 public static String[][] formStrings(SequenceI[] seqs)
969 String[][] idset = new String[2][seqs.length];
970 for (int i = 0; i < seqs.length; i++)
972 idset[0][i] = seqs[i].getName();
973 idset[1][i] = seqs[i].getSequenceAsString();
979 * can this service be run on the visible portion of an alignment regardless
980 * of hidden boundaries ?
982 boolean hseparable = false;
984 boolean vseparable = false;
986 public boolean isHseparable()
995 public boolean isVseparable()
1001 * search the input types for an instance of the given class
1003 * @param <validInput.inputType> class1
1006 public boolean inputInvolves(Class<?> class1)
1008 assert (InputType.class.isAssignableFrom(class1));
1009 for (InputType val : inputParams.values())
1011 if (class1.isAssignableFrom(val.getClass()))
1019 char gapCharacter = '-';
1023 * @return the preferred gap character for alignments input/output by this
1026 public char getGapCharacter()
1028 return gapCharacter;
1031 public String getDecoratedResultUrl(String jobId)
1033 // TODO: correctly write ?/& appropriate to result URL format.
1034 return jobId + urlSuffix;
1037 private List<JvDataType> resultData = new ArrayList<JvDataType>();
1042 * TODO: Extend to optionally specify relative/absolute url where data of this
1043 * type can be retrieved from
1047 public void addResultDatatype(JvDataType dt)
1049 if (resultData == null)
1051 resultData = new ArrayList<JvDataType>();
1056 public boolean removeRsultDatatype(JvDataType dt)
1058 if (resultData != null)
1060 return resultData.remove(dt);
1065 public List<JvDataType> getResultDataTypes()
1071 * parse a concatenated list of rest service descriptions into an array
1073 * @return zero or more services.
1074 * @throws exceptions if the services are improperly encoded.
1076 public static List<RestServiceDescription> parseDescriptions(String services) throws Exception
1078 String[] list = separatorListToArray(services, "|");
1079 List<RestServiceDescription> svcparsed = new ArrayList<RestServiceDescription>();
1081 StringBuffer warnings=new StringBuffer();
1083 RestServiceDescription rsd = new RestServiceDescription();
1084 p=rsd.parseServiceList(list, warnings, lastp=p);
1085 if (p>lastp && rsd.isValid())
1089 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 } while (p<lastp && p<list.length-1);