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;
29 import jalview.ws.rest.params.SeqIdVector;
30 import jalview.ws.rest.params.SeqVector;
31 import jalview.ws.rest.params.Tree;
34 import java.util.ArrayList;
35 import java.util.HashMap;
36 import java.util.Hashtable;
37 import java.util.List;
39 import java.util.NoSuchElementException;
40 import java.util.StringTokenizer;
41 import java.util.regex.Matcher;
42 import java.util.regex.Pattern;
44 public class RestServiceDescription
46 private static final Pattern PARAM_ENCODED_URL_PATTERN = Pattern.compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$");
49 * create a new rest service description ready to be configured
51 public RestServiceDescription()
65 public RestServiceDescription(String action, String description,
66 String name, String postUrl, String urlSuffix,
67 Map<String, InputType> inputParams, boolean hseparable,
68 boolean vseparable, char gapCharacter)
71 this.details = new UIinfo();
72 details.Action = action == null ? "" : action;
73 details.description = description == null ? "" : description;
74 details.Name = name == null ? "" : name;
75 this.postUrl = postUrl == null ? "" : postUrl;
76 this.urlSuffix = urlSuffix == null ? "" : urlSuffix;
77 if (inputParams != null)
79 this.inputParams = inputParams;
81 this.hseparable = hseparable;
82 this.vseparable = vseparable;
83 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 == null && other.urlSuffix == null || (urlSuffix != null
98 && other.urlSuffix != null && 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);
109 * Service UI Info { Action, Specific Name of Service, Brief Description }
114 public String getAction()
119 public void setAction(String action)
124 public String getName()
129 public void setName(String name)
134 public String getDescription()
139 public void setDescription(String description)
141 this.description = description;
151 public UIinfo details = new UIinfo();
153 public String getAction()
155 return details.getAction();
158 public void setAction(String action)
160 details.setAction(action);
163 public String getName()
165 return details.getName();
168 public void setName(String name)
170 details.setName(name);
173 public String getDescription()
175 return details.getDescription();
178 public void setDescription(String description)
180 details.setDescription(description);
188 public String getPostUrl()
193 public void setPostUrl(String postUrl)
195 this.postUrl = postUrl;
198 public String getUrlSuffix()
203 public void setUrlSuffix(String urlSuffix)
205 this.urlSuffix = urlSuffix;
208 public Map<String, InputType> getInputParams()
213 public void setInputParams(Map<String, InputType> inputParams)
215 this.inputParams = inputParams;
218 public void setHseparable(boolean hseparable)
220 this.hseparable = hseparable;
223 public void setVseparable(boolean vseparable)
225 this.vseparable = vseparable;
228 public void setGapCharacter(char gapCharacter)
230 this.gapCharacter = gapCharacter;
234 * suffix that should be added to any url used if it does not already end in
240 * input info given as key/value pairs - mapped to post arguments
242 Map<String, InputType> inputParams = new HashMap<String, InputType>();
245 * assigns the given inputType it to its corresponding input parameter token
250 public void setInputParam(InputType it)
252 inputParams.put(it.token, it);
256 * remove the given input type it from the set of service input parameters.
260 public void removeInputParam(InputType it)
262 inputParams.remove(it.token);
266 * service requests alignment data
271 * service requests alignment and/or seuqence annotationo data
276 * service requests partitions defined over input (alignment) data
278 boolean partitiondata;
281 * process ths input data and set the appropriate shorthand flags describing
282 * the input the service wants
284 public void setInvolvesFlags()
286 aligndata = inputInvolves(Alignment.class);
287 annotdata = inputInvolves(AnnotationFile.class);
288 partitiondata = inputInvolves(SeqGroupIndexVector.class);
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
300 * Start with bare minimum: input is alignment + groups on alignment
306 private String invalidMessage = null;
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=>$.
317 public RestServiceDescription(String link)
319 StringBuffer warnings = new StringBuffer();
320 if (!configureFromEncodedString(link, warnings))
322 if (warnings.length() > 0)
324 invalidMessage = warnings.toString();
329 public RestServiceDescription(RestServiceDescription toedit)
331 // Rather then do the above, we cheat and use our human readable
332 // serialization code to clone everything
333 this(toedit.toString());
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());
345 // TODO Implement copy constructor NOW*/
349 * @return the invalidMessage
351 public String getInvalidMessage()
353 return invalidMessage;
357 * Check if URL string was parsed properly.
359 * @return boolean - if false then <code>getInvalidMessage</code> returns an
362 public boolean isValid()
364 return invalidMessage == null;
368 * parse a string containing a list of service properties and configure the
369 * service description
372 * param warnings a StringBuffer that any warnings about invalid
373 * content will be appended to.
375 private boolean configureFromServiceInputProperties(String propList,
376 StringBuffer warnings)
378 String[] props = StringUtils.separatorListToArray(propList, ",");
384 boolean valid = true;
386 int l = warnings.length();
388 for (String prop : props)
390 if ((i = prop.indexOf("=")) > -1)
392 val = prop.substring(i + 1);
393 if (val.startsWith("\'") && val.endsWith("\'"))
395 val = val.substring(1, val.length() - 1);
397 prop = prop.substring(0, i);
400 if (prop.equals("hseparable"))
404 if (prop.equals("vseparable"))
408 if (prop.equals("gapCharacter"))
410 if (val == null || val.length() == 0 || val.length() > 1)
413 warnings.append((warnings.length() > 0 ? "\n" : "")
414 + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
419 gapCharacter = val.charAt(0);
422 if (prop.equals("returns"))
424 _configureOutputFormatFrom(val, warnings);
427 // return true if valid is true and warning buffer was not appended to.
428 return valid && (l == warnings.length());
431 private String _genOutputFormatString()
434 if (resultData == null)
438 for (JvDataType type : resultData)
440 if (buff.length() > 0)
444 buff += type.toString();
449 private void _configureOutputFormatFrom(String outstring,
450 StringBuffer warnings)
452 if (outstring.indexOf(";") == -1)
454 // we add a token, for simplicity
455 outstring = outstring + ";";
457 StringTokenizer st = new StringTokenizer(outstring, ";");
459 resultData = new ArrayList<JvDataType>();
460 while (st.hasMoreTokens())
464 resultData.add(JvDataType.valueOf(tok = st.nextToken()));
465 } catch (NoSuchElementException x)
467 warnings.append("Invalid result type: '" + tok
468 + "' (must be one of: ");
470 for (JvDataType vl : JvDataType.values())
472 warnings.append(sep);
473 warnings.append(vl.toString());
476 warnings.append(" separated by semi-colons)\n");
481 private String getServiceIOProperties()
483 ArrayList<String> vls = new ArrayList<String>();
486 vls.add("hseparable");
491 vls.add("vseparable");
494 vls.add(new String("gapCharacter='" + gapCharacter + "'"));
495 vls.add(new String("returns='" + _genOutputFormatString() + "'"));
496 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, int p)
563 boolean invalid = false;
564 // look for the first non-empty position - expect it to be service name
565 while (list[p] != null && list[p].trim().length() == 0)
569 details.Name = list[p];
570 details.Action = list[p + 1];
571 details.description = list[p + 2];
572 invalid |= !configureFromServiceInputProperties(list[p + 3], warnings);
573 if (list.length - p > 5 && list[p + 5] != null
574 && list[p + 5].trim().length() > 5)
576 urlSuffix = list[p + 4];
577 invalid |= !configureFromInputParamEncodedUrl(list[p + 5], warnings);
582 if (list.length - p > 4 && list[p + 4] != null
583 && list[p + 4].trim().length() > 5)
586 invalid |= !configureFromInputParamEncodedUrl(list[p + 4], warnings);
590 return invalid ? -1 : p;
594 * @return string representation of the input parameters, their type and
595 * constraints, appended to the service's base submission URL
597 private String getInputParamEncodedUrl()
599 StringBuffer url = new StringBuffer();
600 if (postUrl == null || postUrl.length() < 5)
606 char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
607 boolean consts = true;
610 for (Map.Entry<String, InputType> param : inputParams.entrySet())
612 List<String> vals = param.getValue().getURLEncodedParameter();
613 if (param.getValue().isConstant())
617 url.append(appendChar);
619 url.append(param.getValue().token);
620 if (vals.size() == 1)
623 url.append(vals.get(0));
631 url.append(appendChar);
633 url.append(param.getValue().token);
635 // write parameter set as $TOKENPREFIX:csv list of params$ for this
638 url.append(param.getValue().getURLtokenPrefix());
640 url.append(StringUtils.arrayToSeparatorList(vals.toArray(new String[0]),
647 // toggle consts and repeat until !consts is false:
648 } while (!(consts = !consts));
649 return url.toString();
653 * parse the service URL and input parameters from the given encoded URL
654 * string and configure the RestServiceDescription from it.
659 * @return true if URL parsed correctly. false means the configuration failed.
661 private boolean configureFromInputParamEncodedUrl(String ipurl,
662 StringBuffer warnings)
664 boolean valid = true;
666 String url = new String();
667 Matcher prms = PARAM_ENCODED_URL_PATTERN
669 Map<String, InputType> iparams = new Hashtable<String, InputType>();
673 if (lastp < prms.start(0))
675 url += ipurl.substring(lastp, prms.start(0));
676 lastp = prms.end(0) + 1;
678 String sep = prms.group(1);
679 String tok = prms.group(2);
680 String iprm = prms.group(3);
681 int colon = iprm.indexOf(":");
682 String iprmparams = "";
685 iprmparams = iprm.substring(colon + 1);
686 iprm = iprm.substring(0, colon);
688 valid = parseTypeString(prms.group(0), tok, iprm, iprmparams,
695 URL u = new URL(url);
697 inputParams = iparams;
698 } catch (Exception e)
700 warnings.append("Failed to parse '" + url + "' as a URL.\n");
707 public static Class[] getInputTypes()
709 // TODO - find a better way of maintaining this classlist
711 { Alignment.class, AnnotationFile.class,
712 SeqGroupIndexVector.class,
713 SeqIdVector.class, SeqVector.class, 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, ","))
732 // hack to ensure that strings like "sep=','" containing unescaped
733 // commas as values are concatenated
734 al.add(prprm.trim());
736 if (!jinput.configureFromURLtokenString(al, warnings))
739 warnings.append("Failed to parse '" + fullstring + "' as a "
740 + jinput.getURLtokenPrefix() + " input tag.\n");
745 iparams.put(tok, jinput);
751 } catch (Throwable thr)
760 * covenience method to generate the id and sequence string vector from a set
761 * of seuqences using each sequence's getName() and getSequenceAsString()
765 * @return String[][] {{sequence ids},{sequence strings}}
767 public static String[][] formStrings(SequenceI[] seqs)
769 String[][] idset = new String[2][seqs.length];
770 for (int i = 0; i < seqs.length; i++)
772 idset[0][i] = seqs[i].getName();
773 idset[1][i] = seqs[i].getSequenceAsString();
779 * can this service be run on the visible portion of an alignment regardless
780 * of hidden boundaries ?
782 boolean hseparable = false;
784 boolean vseparable = false;
786 public boolean isHseparable()
795 public boolean isVseparable()
801 * search the input types for an instance of the given class
803 * @param <validInput.inputType> class1
806 public boolean inputInvolves(Class<?> class1)
808 assert (InputType.class.isAssignableFrom(class1));
809 for (InputType val : inputParams.values())
811 if (class1.isAssignableFrom(val.getClass()))
819 char gapCharacter = '-';
823 * @return the preferred gap character for alignments input/output by this
826 public char getGapCharacter()
831 public String getDecoratedResultUrl(String jobId)
833 // TODO: correctly write ?/& appropriate to result URL format.
834 return jobId + urlSuffix;
837 private List<JvDataType> resultData = new ArrayList<JvDataType>();
842 * TODO: Extend to optionally specify relative/absolute url where data of this
843 * type can be retrieved from
847 public void addResultDatatype(JvDataType dt)
849 if (resultData == null)
851 resultData = new ArrayList<JvDataType>();
856 public boolean removeRsultDatatype(JvDataType dt)
858 if (resultData != null)
860 return resultData.remove(dt);
865 public List<JvDataType> getResultDataTypes()
871 * parse a concatenated list of rest service descriptions into an array
874 * @return zero or more services.
876 * if the services are improperly encoded.
878 public static List<RestServiceDescription> parseDescriptions(
879 String services) throws Exception
881 String[] list = StringUtils.separatorListToArray(services, "|");
882 List<RestServiceDescription> svcparsed = new ArrayList<RestServiceDescription>();
883 int p = 0, lastp = 0;
884 StringBuffer warnings = new StringBuffer();
887 RestServiceDescription rsd = new RestServiceDescription();
888 p = rsd.parseServiceList(list, warnings, lastp = p);
889 if (p > lastp && rsd.isValid())
896 "Failed to parse user defined RSBS services from :"
898 + "\nFirst error was encountered at token " + lastp
899 + " starting " + list[lastp] + ":\n"
900 + rsd.getInvalidMessage());
902 } while (p < lastp && p < list.length - 1);