2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
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
10 * of the License, or (at your option) any later version.
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.
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.
21 package jalview.ws.rest;
23 import jalview.datamodel.SequenceI;
24 import jalview.io.packed.DataProvider.JvDataType;
25 import jalview.ws.rest.params.Alignment;
26 import jalview.ws.rest.params.AnnotationFile;
27 import jalview.ws.rest.params.SeqGroupIndexVector;
30 import java.util.ArrayList;
31 import java.util.HashMap;
32 import java.util.Hashtable;
33 import java.util.List;
35 import java.util.NoSuchElementException;
36 import java.util.StringTokenizer;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
40 public class RestServiceDescription
43 * create a new rest service description ready to be configured
45 public RestServiceDescription()
59 public RestServiceDescription(String action, String description,
60 String name, String postUrl, String urlSuffix,
61 Map<String, InputType> inputParams, boolean hseparable,
62 boolean vseparable, char gapCharacter)
65 this.details = new UIinfo();
66 details.Action = action == null ? "" : action;
67 details.description = description == null ? "" : description;
68 details.Name = name == null ? "" : name;
69 this.postUrl = postUrl == null ? "" : postUrl;
70 this.urlSuffix = urlSuffix == null ? "" : urlSuffix;
71 if (inputParams != null)
73 this.inputParams = inputParams;
75 this.hseparable = hseparable;
76 this.vseparable = vseparable;
77 this.gapCharacter = gapCharacter;
80 public boolean equals(Object o)
82 if (o == null || !(o instanceof RestServiceDescription))
86 RestServiceDescription other = (RestServiceDescription) o;
87 boolean diff = (gapCharacter != other.gapCharacter);
88 diff |= vseparable != other.vseparable;
89 diff |= hseparable != other.hseparable;
90 diff |= !(urlSuffix == null && other.urlSuffix == null || (urlSuffix != null
91 && other.urlSuffix != null && urlSuffix.equals(other.urlSuffix)));
92 // TODO - robust diff that includes constants and reordering of URL
93 // diff |= !(postUrl.equals(other.postUrl));
94 // diff |= !inputParams.equals(other.inputParams);
95 diff |= !details.Name.equals(other.details.Name);
96 diff |= !details.Action.equals(other.details.Action);
97 diff |= !details.description.equals(other.details.description);
102 * Service UI Info { Action, Specific Name of Service, Brief Description }
107 public String getAction()
112 public void setAction(String action)
117 public String getName()
122 public void setName(String name)
127 public String getDescription()
132 public void setDescription(String description)
134 this.description = description;
144 public UIinfo details = new UIinfo();
146 public String getAction()
148 return details.getAction();
151 public void setAction(String action)
153 details.setAction(action);
156 public String getName()
158 return details.getName();
161 public void setName(String name)
163 details.setName(name);
166 public String getDescription()
168 return details.getDescription();
171 public void setDescription(String description)
173 details.setDescription(description);
181 public String getPostUrl()
186 public void setPostUrl(String postUrl)
188 this.postUrl = postUrl;
191 public String getUrlSuffix()
196 public void setUrlSuffix(String urlSuffix)
198 this.urlSuffix = urlSuffix;
201 public Map<String, InputType> getInputParams()
206 public void setInputParams(Map<String, InputType> inputParams)
208 this.inputParams = inputParams;
211 public void setHseparable(boolean hseparable)
213 this.hseparable = hseparable;
216 public void setVseparable(boolean vseparable)
218 this.vseparable = vseparable;
221 public void setGapCharacter(char gapCharacter)
223 this.gapCharacter = gapCharacter;
227 * suffix that should be added to any url used if it does not already end in
233 * input info given as key/value pairs - mapped to post arguments
235 Map<String, InputType> inputParams = new HashMap<String, InputType>();
238 * assigns the given inputType it to its corresponding input parameter token
243 public void setInputParam(InputType it)
245 inputParams.put(it.token, it);
249 * remove the given input type it from the set of service input parameters.
253 public void removeInputParam(InputType it)
255 inputParams.remove(it.token);
259 * service requests alignment data
264 * service requests alignment and/or seuqence annotationo data
269 * service requests partitions defined over input (alignment) data
271 boolean partitiondata;
274 * process ths input data and set the appropriate shorthand flags describing
275 * the input the service wants
277 public void setInvolvesFlags()
279 aligndata = inputInvolves(Alignment.class);
280 annotdata = inputInvolves(AnnotationFile.class);
281 partitiondata = inputInvolves(SeqGroupIndexVector.class);
285 * Service return info { alignment, annotation file (loaded back on to
286 * alignment), tree (loaded back on to alignment), sequence annotation -
287 * loaded back on to alignment), text report, pdb structures with sequence
293 * Start with bare minimum: input is alignment + groups on alignment
299 private String invalidMessage = null;
302 * parse the given linkString of the form '<label>|<url>|separator
303 * char[|optional sequence separator char]' into parts. url may contain a
304 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
305 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
306 * $SEQUENCES<=optional regex=>$.
310 public RestServiceDescription(String link)
312 StringBuffer warnings = new StringBuffer();
313 if (!configureFromEncodedString(link, warnings))
315 if (warnings.length() > 0)
317 invalidMessage = warnings.toString();
322 public RestServiceDescription(RestServiceDescription toedit)
324 // Rather then do the above, we cheat and use our human readable
325 // serialization code to clone everything
326 this(toedit.toString());
328 * if (toedit == null) { return; } /** urlSuffix = toedit.urlSuffix; postUrl
329 * = toedit.postUrl; hseparable = toedit.hseparable; vseparable =
330 * toedit.vseparable; gapCharacter = toedit.gapCharacter; details = new
331 * RestServiceDescription.UIinfo(); details.Action = toedit.details.Action;
332 * details.description = toedit.details.description; details.Name =
333 * toedit.details.Name; for (InputType itype: toedit.inputParams.values()) {
334 * inputParams.put(itype.token, itype.clone());
338 // TODO Implement copy constructor NOW*/
342 * @return the invalidMessage
344 public String getInvalidMessage()
346 return invalidMessage;
350 * Check if URL string was parsed properly.
352 * @return boolean - if false then <code>getInvalidMessage</code> returns an
355 public boolean isValid()
357 return invalidMessage == null;
360 private static boolean debug = false;
363 * parse the string into a list
367 * @return elements separated by separator
369 public static String[] separatorListToArray(String list, String separator)
371 int seplen = separator.length();
372 if (list == null || list.equals("") || list.equals(separator))
376 java.util.ArrayList<String> jv = new ArrayList<String>();
377 int cp = 0, pos, escape;
378 boolean wasescaped = false, wasquoted = false;
379 String lstitem = null;
380 while ((pos = list.indexOf(separator, cp)) >= cp)
383 escape = (pos > 0 && list.charAt(pos - 1) == '\\') ? -1 : 0;
384 if (wasescaped || wasquoted)
386 // append to previous pos
387 jv.set(jv.size() - 1,
388 lstitem = lstitem + separator
389 + list.substring(cp, pos + escape));
393 jv.add(lstitem = list.substring(cp, pos + escape));
396 wasescaped = escape == -1;
397 // last separator may be in an unmatched quote
398 wasquoted = (java.util.regex.Pattern.matches(".*='[^']*(?!')",
401 if (cp < list.length())
403 String c = list.substring(cp);
404 if (wasescaped || wasquoted)
406 // append final separator
407 jv.set(jv.size() - 1, lstitem + separator + c);
411 if (!c.equals(separator))
419 String[] v = jv.toArray(new String[jv.size()]);
423 System.err.println("Array from '" + separator
424 + "' separated List:\n" + v.length);
425 for (int i = 0; i < v.length; i++)
427 System.err.println("item " + i + " '" + v[i] + "'");
434 System.err.println("Empty Array from '" + separator
435 + "' separated List");
441 * concatenate the list with separator
445 * @return concatenated string
447 public static String arrayToSeparatorList(String[] list, String separator)
449 StringBuffer v = new StringBuffer();
450 if (list != null && list.length > 0)
452 for (int i = 0, iSize = list.length; i < iSize; i++)
460 // TODO - escape any separator values in list[i]
466 System.err.println("Returning '" + separator
467 + "' separated List:\n");
468 System.err.println(v);
474 System.err.println("Returning empty '" + separator
475 + "' separated List\n");
477 return "" + separator;
481 * parse a string containing a list of service properties and configure the
482 * service description
485 * param warnings a StringBuffer that any warnings about invalid
486 * content will be appended to.
488 private boolean configureFromServiceInputProperties(String propList,
489 StringBuffer warnings)
491 String[] props = separatorListToArray(propList, ",");
497 boolean valid = true;
499 int l = warnings.length();
501 for (String prop : props)
503 if ((i = prop.indexOf("=")) > -1)
505 val = prop.substring(i + 1);
506 if (val.startsWith("\'") && val.endsWith("\'"))
508 val = val.substring(1, val.length() - 1);
510 prop = prop.substring(0, i);
513 if (prop.equals("hseparable"))
517 if (prop.equals("vseparable"))
521 if (prop.equals("gapCharacter"))
523 if (val == null || val.length() == 0 || val.length() > 1)
526 warnings.append((warnings.length() > 0 ? "\n" : "")
527 + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
532 gapCharacter = val.charAt(0);
535 if (prop.equals("returns"))
537 _configureOutputFormatFrom(val, warnings);
540 // return true if valid is true and warning buffer was not appended to.
541 return valid && (l == warnings.length());
544 private String _genOutputFormatString()
547 if (resultData == null)
551 for (JvDataType type : resultData)
553 if (buff.length() > 0)
557 buff += type.toString();
562 private void _configureOutputFormatFrom(String outstring,
563 StringBuffer warnings)
565 if (outstring.indexOf(";") == -1)
567 // we add a token, for simplicity
568 outstring = outstring + ";";
570 StringTokenizer st = new StringTokenizer(outstring, ";");
572 resultData = new ArrayList<JvDataType>();
573 while (st.hasMoreTokens())
577 resultData.add(JvDataType.valueOf(tok = st.nextToken()));
578 } catch (NoSuchElementException x)
580 warnings.append("Invalid result type: '" + tok
581 + "' (must be one of: ");
583 for (JvDataType vl : JvDataType.values())
585 warnings.append(sep);
586 warnings.append(vl.toString());
589 warnings.append(" separated by semi-colons)\n");
594 private String getServiceIOProperties()
596 ArrayList<String> vls = new ArrayList<String>();
599 vls.add("hseparable");
604 vls.add("vseparable");
607 vls.add(new String("gapCharacter='" + gapCharacter + "'"));
608 vls.add(new String("returns='" + _genOutputFormatString() + "'"));
609 return arrayToSeparatorList(vls.toArray(new String[0]), ",");
612 public String toString()
614 StringBuffer result = new StringBuffer();
616 result.append(details.Name);
618 result.append(details.Action);
620 if (details.description != null)
622 result.append(details.description);
625 // list job input flags
627 result.append(getServiceIOProperties());
628 // list any additional cgi parameters needed for result retrieval
629 if (urlSuffix != null && urlSuffix.length() > 0)
632 result.append(urlSuffix);
635 result.append(getInputParamEncodedUrl());
636 return result.toString();
640 * processes a service encoded as a string (as generated by
641 * RestServiceDescription.toString()) Note - this will only use the first
642 * service definition encountered in the string to configure the service.
646 * - 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);
663 * processes the given list from position p, attempting to configure the
664 * service from it. Service lists are formed by concatenating individual
665 * stringified services. The first character of a stringified service is '|',
666 * enabling this, and the parser will ignore empty fields in a '|' separated
667 * list when they fall outside a service definition.
674 protected int parseServiceList(String[] list, StringBuffer warnings, int p)
676 boolean invalid = false;
677 // look for the first non-empty position - expect it to be service name
678 while (list[p] != null && list[p].trim().length() == 0)
682 details.Name = list[p];
683 details.Action = list[p + 1];
684 details.description = list[p + 2];
685 invalid |= !configureFromServiceInputProperties(list[p + 3], warnings);
686 if (list.length - p > 5 && list[p + 5] != null
687 && list[p + 5].trim().length() > 5)
689 urlSuffix = list[p + 4];
690 invalid |= !configureFromInputParamEncodedUrl(list[p + 5], warnings);
695 if (list.length - p > 4 && list[p + 4] != null
696 && list[p + 4].trim().length() > 5)
699 invalid |= !configureFromInputParamEncodedUrl(list[p + 4], warnings);
703 return invalid ? -1 : p;
707 * @return string representation of the input parameters, their type and
708 * constraints, appended to the service's base submission URL
710 private String getInputParamEncodedUrl()
712 StringBuffer url = new StringBuffer();
713 if (postUrl == null || postUrl.length() < 5)
719 char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
720 boolean consts = true;
723 for (Map.Entry<String, InputType> param : inputParams.entrySet())
725 List<String> vals = param.getValue().getURLEncodedParameter();
726 if (param.getValue().isConstant())
730 url.append(appendChar);
732 url.append(param.getValue().token);
733 if (vals.size() == 1)
736 url.append(vals.get(0));
744 url.append(appendChar);
746 url.append(param.getValue().token);
748 // write parameter set as $TOKENPREFIX:csv list of params$ for this
751 url.append(param.getValue().getURLtokenPrefix());
753 url.append(arrayToSeparatorList(vals.toArray(new String[0]),
760 // toggle consts and repeat until !consts is false:
761 } while (!(consts = !consts));
762 return url.toString();
766 * parse the service URL and input parameters from the given encoded URL
767 * string and configure the RestServiceDescription from it.
772 * @return true if URL parsed correctly. false means the configuration failed.
774 private boolean configureFromInputParamEncodedUrl(String ipurl,
775 StringBuffer warnings)
777 boolean valid = true;
779 String url = new String();
780 Matcher prms = Pattern.compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$")
782 Map<String, InputType> iparams = new Hashtable<String, InputType>();
786 if (lastp < prms.start(0))
788 url += ipurl.substring(lastp, prms.start(0));
789 lastp = prms.end(0) + 1;
791 String sep = prms.group(1);
792 String tok = prms.group(2);
793 String iprm = prms.group(3);
794 int colon = iprm.indexOf(":");
795 String iprmparams = "";
798 iprmparams = iprm.substring(colon + 1);
799 iprm = iprm.substring(0, colon);
801 valid = parseTypeString(prms.group(0), tok, iprm, iprmparams,
808 URL u = new URL(url);
810 inputParams = iparams;
811 } catch (Exception e)
813 warnings.append("Failed to parse '" + url + "' as a URL.\n");
820 public static Class[] getInputTypes()
822 // TODO - find a better way of maintaining this classlist
824 { jalview.ws.rest.params.Alignment.class,
825 jalview.ws.rest.params.AnnotationFile.class,
826 SeqGroupIndexVector.class,
827 jalview.ws.rest.params.SeqIdVector.class,
828 jalview.ws.rest.params.SeqVector.class,
829 jalview.ws.rest.params.Tree.class };
832 public static boolean parseTypeString(String fullstring, String tok,
833 String iprm, String iprmparams, Map<String, InputType> iparams,
834 StringBuffer warnings)
836 boolean valid = true;
838 for (Class type : getInputTypes())
842 jinput = (InputType) (type.getConstructor().newInstance(null));
843 if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
845 ArrayList<String> al = new ArrayList<String>();
846 for (String prprm : separatorListToArray(iprmparams, ","))
848 // hack to ensure that strings like "sep=','" containing unescaped
849 // commas as values are concatenated
850 al.add(prprm.trim());
852 if (!jinput.configureFromURLtokenString(al, warnings))
855 warnings.append("Failed to parse '" + fullstring + "' as a "
856 + jinput.getURLtokenPrefix() + " input tag.\n");
861 iparams.put(tok, jinput);
867 } catch (Throwable thr)
876 * covenience method to generate the id and sequence string vector from a set
877 * of seuqences using each sequence's getName() and getSequenceAsString()
881 * @return String[][] {{sequence ids},{sequence strings}}
883 public static String[][] formStrings(SequenceI[] seqs)
885 String[][] idset = new String[2][seqs.length];
886 for (int i = 0; i < seqs.length; i++)
888 idset[0][i] = seqs[i].getName();
889 idset[1][i] = seqs[i].getSequenceAsString();
895 * can this service be run on the visible portion of an alignment regardless
896 * of hidden boundaries ?
898 boolean hseparable = false;
900 boolean vseparable = false;
902 public boolean isHseparable()
911 public boolean isVseparable()
917 * search the input types for an instance of the given class
919 * @param <validInput.inputType> class1
922 public boolean inputInvolves(Class<?> class1)
924 assert (InputType.class.isAssignableFrom(class1));
925 for (InputType val : inputParams.values())
927 if (class1.isAssignableFrom(val.getClass()))
935 char gapCharacter = '-';
939 * @return the preferred gap character for alignments input/output by this
942 public char getGapCharacter()
947 public String getDecoratedResultUrl(String jobId)
949 // TODO: correctly write ?/& appropriate to result URL format.
950 return jobId + urlSuffix;
953 private List<JvDataType> resultData = new ArrayList<JvDataType>();
958 * TODO: Extend to optionally specify relative/absolute url where data of this
959 * type can be retrieved from
963 public void addResultDatatype(JvDataType dt)
965 if (resultData == null)
967 resultData = new ArrayList<JvDataType>();
972 public boolean removeRsultDatatype(JvDataType dt)
974 if (resultData != null)
976 return resultData.remove(dt);
981 public List<JvDataType> getResultDataTypes()
987 * parse a concatenated list of rest service descriptions into an array
990 * @return zero or more services.
992 * if the services are improperly encoded.
994 public static List<RestServiceDescription> parseDescriptions(
995 String services) throws Exception
997 String[] list = separatorListToArray(services, "|");
998 List<RestServiceDescription> svcparsed = new ArrayList<RestServiceDescription>();
999 int p = 0, lastp = 0;
1000 StringBuffer warnings = new StringBuffer();
1003 RestServiceDescription rsd = new RestServiceDescription();
1004 p = rsd.parseServiceList(list, warnings, lastp = p);
1005 if (p > lastp && rsd.isValid())
1011 throw new Exception(
1012 "Failed to parse user defined RSBS services from :"
1014 + "\nFirst error was encountered at token " + lastp
1015 + " starting " + list[lastp] + ":\n"
1016 + rsd.getInvalidMessage());
1018 } while (p < lastp && p < list.length - 1);