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
96 || (urlSuffix != null && other.urlSuffix != null
97 && 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;
367 * parse a string containing a list of service properties and configure the
368 * service description
371 * param warnings a StringBuffer that any warnings about invalid
372 * content will be appended to.
374 private boolean configureFromServiceInputProperties(String propList,
375 StringBuffer warnings)
377 String[] props = StringUtils.separatorListToArray(propList, ",");
383 boolean valid = true;
385 int l = warnings.length();
387 for (String prop : props)
389 if ((i = prop.indexOf("=")) > -1)
391 val = prop.substring(i + 1);
392 if (val.startsWith("\'") && val.endsWith("\'"))
394 val = val.substring(1, val.length() - 1);
396 prop = prop.substring(0, i);
399 if (prop.equals("hseparable"))
403 if (prop.equals("vseparable"))
407 if (prop.equals("gapCharacter"))
409 if (val == null || val.length() == 0 || val.length() > 1)
412 warnings.append((warnings.length() > 0 ? "\n" : "")
413 + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
418 gapCharacter = val.charAt(0);
421 if (prop.equals("returns"))
423 _configureOutputFormatFrom(val, warnings);
426 // return true if valid is true and warning buffer was not appended to.
427 return valid && (l == warnings.length());
430 private String _genOutputFormatString()
433 if (resultData == null)
437 for (JvDataType type : resultData)
439 if (buff.length() > 0)
443 buff += type.toString();
448 private void _configureOutputFormatFrom(String outstring,
449 StringBuffer warnings)
451 if (outstring.indexOf(";") == -1)
453 // we add a token, for simplicity
454 outstring = outstring + ";";
456 StringTokenizer st = new StringTokenizer(outstring, ";");
458 resultData = new ArrayList<JvDataType>();
459 while (st.hasMoreTokens())
463 resultData.add(JvDataType.valueOf(tok = st.nextToken()));
464 } catch (NoSuchElementException x)
467 "Invalid result type: '" + tok + "' (must be one of: ");
469 for (JvDataType vl : JvDataType.values())
471 warnings.append(sep);
472 warnings.append(vl.toString());
475 warnings.append(" separated by semi-colons)\n");
480 private String getServiceIOProperties()
482 ArrayList<String> vls = new ArrayList<String>();
485 vls.add("hseparable");
490 vls.add("vseparable");
493 vls.add(new String("gapCharacter='" + gapCharacter + "'"));
494 vls.add(new String("returns='" + _genOutputFormatString() + "'"));
495 return StringUtils.arrayToSeparatorList(vls.toArray(new String[0]),
499 public String toString()
501 StringBuffer result = new StringBuffer();
503 result.append(details.Name);
505 result.append(details.Action);
507 if (details.description != null)
509 result.append(details.description);
512 // list job input flags
514 result.append(getServiceIOProperties());
515 // list any additional cgi parameters needed for result retrieval
516 if (urlSuffix != null && urlSuffix.length() > 0)
519 result.append(urlSuffix);
522 result.append(getInputParamEncodedUrl());
523 return result.toString();
527 * processes a service encoded as a string (as generated by
528 * RestServiceDescription.toString()) Note - this will only use the first
529 * service definition encountered in the string to configure the service.
533 * - where warning messages are reported.
534 * @return true if configuration was parsed successfully.
536 public boolean configureFromEncodedString(String encoding,
537 StringBuffer warnings)
539 String[] list = StringUtils.separatorListToArray(encoding, "|");
541 int nextpos = parseServiceList(list, warnings, 0);
550 * processes the given list from position p, attempting to configure the
551 * service from it. Service lists are formed by concatenating individual
552 * stringified services. The first character of a stringified service is '|',
553 * enabling this, and the parser will ignore empty fields in a '|' separated
554 * list when they fall outside a service definition.
561 protected int parseServiceList(String[] list, StringBuffer warnings,
564 boolean invalid = false;
565 // look for the first non-empty position - expect it to be service name
566 while (list[p] != null && list[p].trim().length() == 0)
570 details.Name = list[p];
571 details.Action = list[p + 1];
572 details.description = list[p + 2];
573 invalid |= !configureFromServiceInputProperties(list[p + 3], warnings);
574 if (list.length - p > 5 && list[p + 5] != null
575 && list[p + 5].trim().length() > 5)
577 urlSuffix = list[p + 4];
578 invalid |= !configureFromInputParamEncodedUrl(list[p + 5], warnings);
583 if (list.length - p > 4 && list[p + 4] != null
584 && list[p + 4].trim().length() > 5)
587 invalid |= !configureFromInputParamEncodedUrl(list[p + 4],
592 return invalid ? -1 : p;
596 * @return string representation of the input parameters, their type and
597 * constraints, appended to the service's base submission URL
599 private String getInputParamEncodedUrl()
601 StringBuffer url = new StringBuffer();
602 if (postUrl == null || postUrl.length() < 5)
608 char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
609 boolean consts = true;
612 for (Map.Entry<String, InputType> param : inputParams.entrySet())
614 List<String> vals = param.getValue().getURLEncodedParameter();
615 if (param.getValue().isConstant())
619 url.append(appendChar);
621 url.append(param.getValue().token);
622 if (vals.size() == 1)
625 url.append(vals.get(0));
633 url.append(appendChar);
635 url.append(param.getValue().token);
637 // write parameter set as $TOKENPREFIX:csv list of params$ for this
640 url.append(param.getValue().getURLtokenPrefix());
642 url.append(StringUtils.arrayToSeparatorList(
643 vals.toArray(new String[0]), ","));
649 // toggle consts and repeat until !consts is false:
650 } while (!(consts = !consts));
651 return url.toString();
655 * parse the service URL and input parameters from the given encoded URL
656 * string and configure the RestServiceDescription from it.
661 * @return true if URL parsed correctly. false means the configuration failed.
663 private boolean configureFromInputParamEncodedUrl(String ipurl,
664 StringBuffer warnings)
666 boolean valid = true;
668 String url = new String();
669 Matcher prms = PARAM_ENCODED_URL_PATTERN.matcher(ipurl);
670 Map<String, InputType> iparams = new Hashtable<String, InputType>();
674 if (lastp < prms.start(0))
676 url += ipurl.substring(lastp, prms.start(0));
677 lastp = prms.end(0) + 1;
679 String sep = prms.group(1);
680 String tok = prms.group(2);
681 String iprm = prms.group(3);
682 int colon = iprm.indexOf(":");
683 String iprmparams = "";
686 iprmparams = iprm.substring(colon + 1);
687 iprm = iprm.substring(0, colon);
689 valid = parseTypeString(prms.group(0), tok, iprm, iprmparams, iparams,
696 URL u = new URL(url);
698 inputParams = iparams;
699 } catch (Exception e)
701 warnings.append("Failed to parse '" + url + "' as a URL.\n");
708 public static Class[] getInputTypes()
710 // TODO - find a better way of maintaining this classlist
711 return new Class[] { jalview.ws.rest.params.Alignment.class,
712 jalview.ws.rest.params.AnnotationFile.class,
713 SeqGroupIndexVector.class, jalview.ws.rest.params.SeqIdVector.class,
714 jalview.ws.rest.params.SeqVector.class,
715 jalview.ws.rest.params.Tree.class };
718 public static boolean parseTypeString(String fullstring, String tok,
719 String iprm, String iprmparams, Map<String, InputType> iparams,
720 StringBuffer warnings)
722 boolean valid = true;
724 for (Class type : getInputTypes())
728 jinput = (InputType) (type.getConstructor().newInstance());
729 if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
731 ArrayList<String> al = new ArrayList<String>();
732 for (String prprm : StringUtils.separatorListToArray(iprmparams,
735 // hack to ensure that strings like "sep=','" containing unescaped
736 // commas as values are concatenated
737 al.add(prprm.trim());
739 if (!jinput.configureFromURLtokenString(al, warnings))
742 warnings.append("Failed to parse '" + fullstring + "' as a "
743 + jinput.getURLtokenPrefix() + " input tag.\n");
748 iparams.put(tok, jinput);
754 } catch (Throwable thr)
763 * covenience method to generate the id and sequence string vector from a set
764 * of seuqences using each sequence's getName() and getSequenceAsString()
768 * @return String[][] {{sequence ids},{sequence strings}}
770 public static String[][] formStrings(SequenceI[] seqs)
772 String[][] idset = new String[2][seqs.length];
773 for (int i = 0; i < seqs.length; i++)
775 idset[0][i] = seqs[i].getName();
776 idset[1][i] = seqs[i].getSequenceAsString();
782 * can this service be run on the visible portion of an alignment regardless
783 * of hidden boundaries ?
785 boolean hseparable = false;
787 boolean vseparable = false;
789 public boolean isHseparable()
798 public boolean isVseparable()
804 * search the input types for an instance of the given class
806 * @param <validInput.inputType>
810 public boolean inputInvolves(Class<?> class1)
812 assert (InputType.class.isAssignableFrom(class1));
813 for (InputType val : inputParams.values())
815 if (class1.isAssignableFrom(val.getClass()))
823 char gapCharacter = '-';
827 * @return the preferred gap character for alignments input/output by this
830 public char getGapCharacter()
835 public String getDecoratedResultUrl(String jobId)
837 // TODO: correctly write ?/& appropriate to result URL format.
838 return jobId + urlSuffix;
841 private List<JvDataType> resultData = new ArrayList<JvDataType>();
846 * TODO: Extend to optionally specify relative/absolute url where data of this
847 * type can be retrieved from
851 public void addResultDatatype(JvDataType dt)
853 if (resultData == null)
855 resultData = new ArrayList<JvDataType>();
860 public boolean removeRsultDatatype(JvDataType dt)
862 if (resultData != null)
864 return resultData.remove(dt);
869 public List<JvDataType> getResultDataTypes()
875 * parse a concatenated list of rest service descriptions into an array
878 * @return zero or more services.
880 * if the services are improperly encoded.
882 public static List<RestServiceDescription> parseDescriptions(
883 String services) throws Exception
885 String[] list = StringUtils.separatorListToArray(services, "|");
886 List<RestServiceDescription> svcparsed = new ArrayList<RestServiceDescription>();
887 int p = 0, lastp = 0;
888 StringBuffer warnings = new StringBuffer();
891 RestServiceDescription rsd = new RestServiceDescription();
892 p = rsd.parseServiceList(list, warnings, lastp = p);
893 if (p > lastp && rsd.isValid())
900 "Failed to parse user defined RSBS services from :"
902 + "\nFirst error was encountered at token " + lastp
903 + " starting " + list[lastp] + ":\n"
904 + rsd.getInvalidMessage());
906 } while (p < lastp && p < list.length - 1);