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.util.StringUtils;
26 import jalview.ws.rest.params.Alignment;
27 import jalview.ws.rest.params.AnnotationFile;
28 import jalview.ws.rest.params.SeqGroupIndexVector;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.Hashtable;
34 import java.util.List;
36 import java.util.NoSuchElementException;
37 import java.util.StringTokenizer;
38 import java.util.regex.Matcher;
39 import java.util.regex.Pattern;
41 public class RestServiceDescription
43 private static final Pattern PARAM_ENCODED_URL_PATTERN = Pattern
44 .compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$");
47 * create a new rest service description ready to be configured
49 public RestServiceDescription()
63 public RestServiceDescription(String action, String description,
64 String name, String postUrl, String urlSuffix,
65 Map<String, InputType> inputParams, boolean hseparable,
66 boolean vseparable, char gapCharacter)
69 this.details = new UIinfo();
70 details.Action = action == null ? "" : action;
71 details.description = description == null ? "" : description;
72 details.Name = name == null ? "" : name;
73 this.postUrl = postUrl == null ? "" : postUrl;
74 this.urlSuffix = urlSuffix == null ? "" : urlSuffix;
75 if (inputParams != null)
77 this.inputParams = inputParams;
79 this.hseparable = hseparable;
80 this.vseparable = vseparable;
81 this.gapCharacter = gapCharacter;
85 public boolean equals(Object o)
87 if (o == null || !(o instanceof RestServiceDescription))
91 RestServiceDescription other = (RestServiceDescription) o;
92 boolean diff = (gapCharacter != other.gapCharacter);
93 diff |= vseparable != other.vseparable;
94 diff |= hseparable != other.hseparable;
95 diff |= !(urlSuffix == null && other.urlSuffix == null || (urlSuffix != null
96 && other.urlSuffix != null && urlSuffix.equals(other.urlSuffix)));
97 // TODO - robust diff that includes constants and reordering of URL
98 // diff |= !(postUrl.equals(other.postUrl));
99 // diff |= !inputParams.equals(other.inputParams);
100 diff |= !details.Name.equals(other.details.Name);
101 diff |= !details.Action.equals(other.details.Action);
102 diff |= !details.description.equals(other.details.description);
107 * Service UI Info { Action, Specific Name of Service, Brief Description }
112 public String getAction()
117 public void setAction(String action)
122 public String getName()
127 public void setName(String name)
132 public String getDescription()
137 public void setDescription(String description)
139 this.description = description;
149 public UIinfo details = new UIinfo();
151 public String getAction()
153 return details.getAction();
156 public void setAction(String action)
158 details.setAction(action);
161 public String getName()
163 return details.getName();
166 public void setName(String name)
168 details.setName(name);
171 public String getDescription()
173 return details.getDescription();
176 public void setDescription(String description)
178 details.setDescription(description);
186 public String getPostUrl()
191 public void setPostUrl(String postUrl)
193 this.postUrl = postUrl;
196 public String getUrlSuffix()
201 public void setUrlSuffix(String urlSuffix)
203 this.urlSuffix = urlSuffix;
206 public Map<String, InputType> getInputParams()
211 public void setInputParams(Map<String, InputType> inputParams)
213 this.inputParams = inputParams;
216 public void setHseparable(boolean hseparable)
218 this.hseparable = hseparable;
221 public void setVseparable(boolean vseparable)
223 this.vseparable = vseparable;
226 public void setGapCharacter(char gapCharacter)
228 this.gapCharacter = gapCharacter;
232 * suffix that should be added to any url used if it does not already end in
238 * input info given as key/value pairs - mapped to post arguments
240 Map<String, InputType> inputParams = new HashMap<String, InputType>();
243 * assigns the given inputType it to its corresponding input parameter token
248 public void setInputParam(InputType it)
250 inputParams.put(it.token, it);
254 * remove the given input type it from the set of service input parameters.
258 public void removeInputParam(InputType it)
260 inputParams.remove(it.token);
264 * service requests alignment data
269 * service requests alignment and/or seuqence annotationo data
274 * service requests partitions defined over input (alignment) data
276 boolean partitiondata;
279 * process ths input data and set the appropriate shorthand flags describing
280 * the input the service wants
282 public void setInvolvesFlags()
284 aligndata = inputInvolves(Alignment.class);
285 annotdata = inputInvolves(AnnotationFile.class);
286 partitiondata = inputInvolves(SeqGroupIndexVector.class);
290 * Service return info { alignment, annotation file (loaded back on to
291 * alignment), tree (loaded back on to alignment), sequence annotation -
292 * loaded back on to alignment), text report, pdb structures with sequence
298 * Start with bare minimum: input is alignment + groups on alignment
304 private String invalidMessage = null;
307 * parse the given linkString of the form '<label>|<url>|separator
308 * char[|optional sequence separator char]' into parts. url may contain a
309 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
310 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
311 * $SEQUENCES<=optional regex=>$.
315 public RestServiceDescription(String link)
317 StringBuffer warnings = new StringBuffer();
318 if (!configureFromEncodedString(link, warnings))
320 if (warnings.length() > 0)
322 invalidMessage = warnings.toString();
327 public RestServiceDescription(RestServiceDescription toedit)
329 // Rather then do the above, we cheat and use our human readable
330 // serialization code to clone everything
331 this(toedit.toString());
333 * if (toedit == null) { return; } /** urlSuffix = toedit.urlSuffix; postUrl
334 * = toedit.postUrl; hseparable = toedit.hseparable; vseparable =
335 * toedit.vseparable; gapCharacter = toedit.gapCharacter; details = new
336 * RestServiceDescription.UIinfo(); details.Action = toedit.details.Action;
337 * details.description = toedit.details.description; details.Name =
338 * toedit.details.Name; for (InputType itype: toedit.inputParams.values()) {
339 * inputParams.put(itype.token, itype.clone());
343 // TODO Implement copy constructor NOW*/
347 * @return the invalidMessage
349 public String getInvalidMessage()
351 return invalidMessage;
355 * Check if URL string was parsed properly.
357 * @return boolean - if false then <code>getInvalidMessage</code> returns an
360 public boolean isValid()
362 return invalidMessage == null;
366 * parse a string containing a list of service properties and configure the
367 * service description
370 * param warnings a StringBuffer that any warnings about invalid
371 * content will be appended to.
373 private boolean configureFromServiceInputProperties(String propList,
374 StringBuffer warnings)
376 String[] props = StringUtils.separatorListToArray(propList, ",");
382 boolean valid = true;
384 int l = warnings.length();
386 for (String prop : props)
388 if ((i = prop.indexOf("=")) > -1)
390 val = prop.substring(i + 1);
391 if (val.startsWith("\'") && val.endsWith("\'"))
393 val = val.substring(1, val.length() - 1);
395 prop = prop.substring(0, i);
398 if (prop.equals("hseparable"))
402 if (prop.equals("vseparable"))
406 if (prop.equals("gapCharacter"))
408 if (val == null || val.length() == 0 || val.length() > 1)
411 warnings.append((warnings.length() > 0 ? "\n" : "")
412 + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
417 gapCharacter = val.charAt(0);
420 if (prop.equals("returns"))
422 _configureOutputFormatFrom(val, warnings);
425 // return true if valid is true and warning buffer was not appended to.
426 return valid && (l == warnings.length());
429 private String _genOutputFormatString()
432 if (resultData == null)
436 for (JvDataType type : resultData)
438 if (buff.length() > 0)
442 buff += type.toString();
447 private void _configureOutputFormatFrom(String outstring,
448 StringBuffer warnings)
450 if (outstring.indexOf(";") == -1)
452 // we add a token, for simplicity
453 outstring = outstring + ";";
455 StringTokenizer st = new StringTokenizer(outstring, ";");
457 resultData = new ArrayList<JvDataType>();
458 while (st.hasMoreTokens())
462 resultData.add(JvDataType.valueOf(tok = st.nextToken()));
463 } catch (NoSuchElementException x)
465 warnings.append("Invalid result type: '" + tok
466 + "' (must be one of: ");
468 for (JvDataType vl : JvDataType.values())
470 warnings.append(sep);
471 warnings.append(vl.toString());
474 warnings.append(" separated by semi-colons)\n");
479 private String getServiceIOProperties()
481 ArrayList<String> vls = new ArrayList<String>();
484 vls.add("hseparable");
489 vls.add("vseparable");
492 vls.add(new String("gapCharacter='" + gapCharacter + "'"));
493 vls.add(new String("returns='" + _genOutputFormatString() + "'"));
495 .arrayToSeparatorList(vls.toArray(new String[0]), ",");
498 public String toString()
500 StringBuffer result = new StringBuffer();
502 result.append(details.Name);
504 result.append(details.Action);
506 if (details.description != null)
508 result.append(details.description);
511 // list job input flags
513 result.append(getServiceIOProperties());
514 // list any additional cgi parameters needed for result retrieval
515 if (urlSuffix != null && urlSuffix.length() > 0)
518 result.append(urlSuffix);
521 result.append(getInputParamEncodedUrl());
522 return result.toString();
526 * processes a service encoded as a string (as generated by
527 * RestServiceDescription.toString()) Note - this will only use the first
528 * service definition encountered in the string to configure the service.
532 * - where warning messages are reported.
533 * @return true if configuration was parsed successfully.
535 public boolean configureFromEncodedString(String encoding,
536 StringBuffer warnings)
538 String[] list = StringUtils.separatorListToArray(encoding, "|");
540 int nextpos = parseServiceList(list, warnings, 0);
549 * processes the given list from position p, attempting to configure the
550 * service from it. Service lists are formed by concatenating individual
551 * stringified services. The first character of a stringified service is '|',
552 * enabling this, and the parser will ignore empty fields in a '|' separated
553 * list when they fall outside a service definition.
560 protected int parseServiceList(String[] list, StringBuffer warnings, int p)
562 boolean invalid = false;
563 // look for the first non-empty position - expect it to be service name
564 while (list[p] != null && list[p].trim().length() == 0)
568 details.Name = list[p];
569 details.Action = list[p + 1];
570 details.description = list[p + 2];
571 invalid |= !configureFromServiceInputProperties(list[p + 3], warnings);
572 if (list.length - p > 5 && list[p + 5] != null
573 && list[p + 5].trim().length() > 5)
575 urlSuffix = list[p + 4];
576 invalid |= !configureFromInputParamEncodedUrl(list[p + 5], warnings);
581 if (list.length - p > 4 && list[p + 4] != null
582 && list[p + 4].trim().length() > 5)
585 invalid |= !configureFromInputParamEncodedUrl(list[p + 4], warnings);
589 return invalid ? -1 : p;
593 * @return string representation of the input parameters, their type and
594 * constraints, appended to the service's base submission URL
596 private String getInputParamEncodedUrl()
598 StringBuffer url = new StringBuffer();
599 if (postUrl == null || postUrl.length() < 5)
605 char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
606 boolean consts = true;
609 for (Map.Entry<String, InputType> param : inputParams.entrySet())
611 List<String> vals = param.getValue().getURLEncodedParameter();
612 if (param.getValue().isConstant())
616 url.append(appendChar);
618 url.append(param.getValue().token);
619 if (vals.size() == 1)
622 url.append(vals.get(0));
630 url.append(appendChar);
632 url.append(param.getValue().token);
634 // write parameter set as $TOKENPREFIX:csv list of params$ for this
637 url.append(param.getValue().getURLtokenPrefix());
639 url.append(StringUtils.arrayToSeparatorList(
640 vals.toArray(new String[0]), ","));
646 // toggle consts and repeat until !consts is false:
647 } while (!(consts = !consts));
648 return url.toString();
652 * parse the service URL and input parameters from the given encoded URL
653 * string and configure the RestServiceDescription from it.
658 * @return true if URL parsed correctly. false means the configuration failed.
660 private boolean configureFromInputParamEncodedUrl(String ipurl,
661 StringBuffer warnings)
663 boolean valid = true;
665 String url = new String();
666 Matcher prms = PARAM_ENCODED_URL_PATTERN.matcher(ipurl);
667 Map<String, InputType> iparams = new Hashtable<String, InputType>();
671 if (lastp < prms.start(0))
673 url += ipurl.substring(lastp, prms.start(0));
674 lastp = prms.end(0) + 1;
676 String sep = prms.group(1);
677 String tok = prms.group(2);
678 String iprm = prms.group(3);
679 int colon = iprm.indexOf(":");
680 String iprmparams = "";
683 iprmparams = iprm.substring(colon + 1);
684 iprm = iprm.substring(0, colon);
686 valid = parseTypeString(prms.group(0), tok, iprm, iprmparams,
693 URL u = new URL(url);
695 inputParams = iparams;
696 } catch (Exception e)
698 warnings.append("Failed to parse '" + url + "' as a URL.\n");
705 public static Class[] getInputTypes()
707 // TODO - find a better way of maintaining this classlist
708 return new Class[] { jalview.ws.rest.params.Alignment.class,
709 jalview.ws.rest.params.AnnotationFile.class,
710 SeqGroupIndexVector.class,
711 jalview.ws.rest.params.SeqIdVector.class,
712 jalview.ws.rest.params.SeqVector.class,
713 jalview.ws.rest.params.Tree.class };
716 public static boolean parseTypeString(String fullstring, String tok,
717 String iprm, String iprmparams, Map<String, InputType> iparams,
718 StringBuffer warnings)
720 boolean valid = true;
722 for (Class type : getInputTypes())
726 jinput = (InputType) (type.getConstructor().newInstance());
727 if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
729 ArrayList<String> al = new ArrayList<String>();
730 for (String prprm : StringUtils.separatorListToArray(iprmparams,
733 // hack to ensure that strings like "sep=','" containing unescaped
734 // commas as values are concatenated
735 al.add(prprm.trim());
737 if (!jinput.configureFromURLtokenString(al, warnings))
740 warnings.append("Failed to parse '" + fullstring + "' as a "
741 + jinput.getURLtokenPrefix() + " input tag.\n");
746 iparams.put(tok, jinput);
752 } catch (Throwable thr)
761 * covenience method to generate the id and sequence string vector from a set
762 * of seuqences using each sequence's getName() and getSequenceAsString()
766 * @return String[][] {{sequence ids},{sequence strings}}
768 public static String[][] formStrings(SequenceI[] seqs)
770 String[][] idset = new String[2][seqs.length];
771 for (int i = 0; i < seqs.length; i++)
773 idset[0][i] = seqs[i].getName();
774 idset[1][i] = seqs[i].getSequenceAsString();
780 * can this service be run on the visible portion of an alignment regardless
781 * of hidden boundaries ?
783 boolean hseparable = false;
785 boolean vseparable = false;
787 public boolean isHseparable()
796 public boolean isVseparable()
802 * search the input types for an instance of the given class
804 * @param <validInput.inputType> class1
807 public boolean inputInvolves(Class<?> class1)
809 assert (InputType.class.isAssignableFrom(class1));
810 for (InputType val : inputParams.values())
812 if (class1.isAssignableFrom(val.getClass()))
820 char gapCharacter = '-';
824 * @return the preferred gap character for alignments input/output by this
827 public char getGapCharacter()
832 public String getDecoratedResultUrl(String jobId)
834 // TODO: correctly write ?/& appropriate to result URL format.
835 return jobId + urlSuffix;
838 private List<JvDataType> resultData = new ArrayList<JvDataType>();
843 * TODO: Extend to optionally specify relative/absolute url where data of this
844 * type can be retrieved from
848 public void addResultDatatype(JvDataType dt)
850 if (resultData == null)
852 resultData = new ArrayList<JvDataType>();
857 public boolean removeRsultDatatype(JvDataType dt)
859 if (resultData != null)
861 return resultData.remove(dt);
866 public List<JvDataType> getResultDataTypes()
872 * parse a concatenated list of rest service descriptions into an array
875 * @return zero or more services.
877 * if the services are improperly encoded.
879 public static List<RestServiceDescription> parseDescriptions(
880 String services) throws Exception
882 String[] list = StringUtils.separatorListToArray(services, "|");
883 List<RestServiceDescription> svcparsed = new ArrayList<RestServiceDescription>();
884 int p = 0, lastp = 0;
885 StringBuffer warnings = new StringBuffer();
888 RestServiceDescription rsd = new RestServiceDescription();
889 p = rsd.parseServiceList(list, warnings, lastp = p);
890 if (p > lastp && rsd.isValid())
897 "Failed to parse user defined RSBS services from :"
899 + "\nFirst error was encountered at token " + lastp
900 + " starting " + list[lastp] + ":\n"
901 + rsd.getInvalidMessage());
903 } while (p < lastp && p < list.length - 1);