X-Git-Url: http://source.jalview.org/gitweb/?a=blobdiff_plain;ds=sidebyside;f=src%2Fjalview%2Fws%2Frest%2FRestServiceDescription.java;h=553340691905684f4814b79d2ccebb49f4516548;hb=06de78be50c3934158fa1d35ec92ad86b54e959f;hp=6794a8d2420a03d689f063e66eb180233fc24ea9;hpb=c762d9525db36ffd5d3fca49fb5e7d506d13401a;p=jalview.git
diff --git a/src/jalview/ws/rest/RestServiceDescription.java b/src/jalview/ws/rest/RestServiceDescription.java
index 6794a8d..5533406 100644
--- a/src/jalview/ws/rest/RestServiceDescription.java
+++ b/src/jalview/ws/rest/RestServiceDescription.java
@@ -1,37 +1,56 @@
/*
- * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
- * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
+ * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
+ * Copyright (C) $$Year-Rel$$ The Jalview Authors
*
* This file is part of Jalview.
*
* Jalview is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
- *
+ * as published by the Free Software Foundation, either version 3
+ * of the License, or (at your option) any later version.
+ *
* Jalview is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR
* PURPOSE. See the GNU General Public License for more details.
*
- * You should have received a copy of the GNU General Public License along with Jalview. If not, see .
+ * You should have received a copy of the GNU General Public License
+ * along with Jalview. If not, see .
+ * The Jalview Authors are detailed in the 'AUTHORS' file.
*/
package jalview.ws.rest;
-
import jalview.datamodel.SequenceI;
-import jalview.util.GroupUrlLink.UrlStringTooLongException;
-import jalview.util.Platform;
+import jalview.io.packed.DataProvider.JvDataType;
+import jalview.util.StringUtils;
import jalview.ws.rest.params.Alignment;
import jalview.ws.rest.params.AnnotationFile;
import jalview.ws.rest.params.SeqGroupIndexVector;
+import java.net.URL;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
+import java.util.List;
import java.util.Map;
-
+import java.util.NoSuchElementException;
+import java.util.StringTokenizer;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
public class RestServiceDescription
{
+ private static final Pattern PARAM_ENCODED_URL_PATTERN = Pattern
+ .compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$");
+
+ /**
+ * create a new rest service description ready to be configured
+ */
+ public RestServiceDescription()
+ {
+
+ }
+
/**
* @param details
* @param postUrl
@@ -41,142 +60,249 @@ public class RestServiceDescription
* @param vseparable
* @param gapCharacter
*/
- public RestServiceDescription(String action,String description,String name, String postUrl,
- String urlSuffix, Map inputParams,
- boolean hseparable, boolean vseparable, char gapCharacter)
+ public RestServiceDescription(String action, String description,
+ String name, String postUrl, String urlSuffix,
+ Map inputParams, boolean hseparable,
+ boolean vseparable, char gapCharacter)
{
super();
this.details = new UIinfo();
- details.Action= action;
- details.description = description;
- details.Name = name;
- this.postUrl = postUrl;
- this.urlSuffix = urlSuffix;
- this.inputParams = inputParams;
+ details.Action = action == null ? "" : action;
+ details.description = description == null ? "" : description;
+ details.Name = name == null ? "" : name;
+ this.postUrl = postUrl == null ? "" : postUrl;
+ this.urlSuffix = urlSuffix == null ? "" : urlSuffix;
+ if (inputParams != null)
+ {
+ this.inputParams = inputParams;
+ }
this.hseparable = hseparable;
this.vseparable = vseparable;
this.gapCharacter = gapCharacter;
}
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (o == null || !(o instanceof RestServiceDescription))
+ {
+ return false;
+ }
+ RestServiceDescription other = (RestServiceDescription) o;
+ boolean diff = (gapCharacter != other.gapCharacter);
+ diff |= vseparable != other.vseparable;
+ diff |= hseparable != other.hseparable;
+ diff |= !(urlSuffix == null && other.urlSuffix == null
+ || (urlSuffix != null && other.urlSuffix != null
+ && urlSuffix.equals(other.urlSuffix)));
+ // TODO - robust diff that includes constants and reordering of URL
+ // diff |= !(postUrl.equals(other.postUrl));
+ // diff |= !inputParams.equals(other.inputParams);
+ diff |= !details.Name.equals(other.details.Name);
+ diff |= !details.Action.equals(other.details.Action);
+ diff |= !details.description.equals(other.details.description);
+ return !diff;
+ }
+
/**
* Service UI Info { Action, Specific Name of Service, Brief Description }
*/
-
- public class UIinfo {
+
+ public class UIinfo
+ {
+ public String getAction()
+ {
+ return Action;
+ }
+
+ public void setAction(String action)
+ {
+ Action = action;
+ }
+
+ public String getName()
+ {
+ return Name;
+ }
+
+ public void setName(String name)
+ {
+ Name = name;
+ }
+
+ public String getDescription()
+ {
+ return description;
+ }
+
+ public void setDescription(String description)
+ {
+ this.description = description;
+ }
+
String Action;
+
String Name;
+
String description;
}
- UIinfo details = new UIinfo();
-
- /** Service base URL
+
+ public UIinfo details = new UIinfo();
+
+ public String getAction()
+ {
+ return details.getAction();
+ }
+
+ public void setAction(String action)
+ {
+ details.setAction(action);
+ }
+
+ public String getName()
+ {
+ return details.getName();
+ }
+
+ public void setName(String name)
+ {
+ details.setName(name);
+ }
+
+ public String getDescription()
+ {
+ return details.getDescription();
+ }
+
+ public void setDescription(String description)
+ {
+ details.setDescription(description);
+ }
+
+ /**
+ * Service base URL
*/
String postUrl;
+
+ public String getPostUrl()
+ {
+ return postUrl;
+ }
+
+ public void setPostUrl(String postUrl)
+ {
+ this.postUrl = postUrl;
+ }
+
+ public String getUrlSuffix()
+ {
+ return urlSuffix;
+ }
+
+ public void setUrlSuffix(String urlSuffix)
+ {
+ this.urlSuffix = urlSuffix;
+ }
+
+ public Map getInputParams()
+ {
+ return inputParams;
+ }
+
+ public void setInputParams(Map inputParams)
+ {
+ this.inputParams = inputParams;
+ }
+
+ public void setHseparable(boolean hseparable)
+ {
+ this.hseparable = hseparable;
+ }
+
+ public void setVseparable(boolean vseparable)
+ {
+ this.vseparable = vseparable;
+ }
+
+ public void setGapCharacter(char gapCharacter)
+ {
+ this.gapCharacter = gapCharacter;
+ }
+
/**
- * suffix that should be added to any url used if it does not already end in the suffix.
+ * suffix that should be added to any url used if it does not already end in
+ * the suffix.
*/
String urlSuffix;
-
- /***
- * modelling the io:
- * validation of input
- * { formatter for type, parser for type }
- *
- */
- /** input info given as key/value pairs - mapped to post arguments
- */
- Map inputParams=new HashMap();
- /**
- * service requests alignment data
- */
- boolean aligndata;
- /**
- * service requests alignment and/or seuqence annotationo data
- */
- boolean annotdata;
- /**
- * service requests partitions defined over input (alignment) data
- */
- boolean partitiondata;
-
+
/**
- * process ths input data and set the appropriate shorthand flags describing the input the service wants
+ * input info given as key/value pairs - mapped to post arguments
*/
- public void setInvolvesFlags() {
- aligndata = inputInvolves(Alignment.class);
- annotdata = inputInvolves(AnnotationFile.class);
- partitiondata = inputInvolves(SeqGroupIndexVector.class);
- }
+ Map inputParams = new HashMap();
- /** Service return info { alignment, annotation file (loaded back on to alignment), tree (loaded back on to alignment), sequence annotation - loaded back on to alignment), text report, pdb structures with sequence mapping )
+ /**
+ * assigns the given inputType it to its corresponding input parameter token
+ * it.token
*
- */
-
- /** Start with bare minimum: input is alignment + groups on alignment
- *
- * @author JimP
- *
+ * @param it
*/
+ public void setInputParam(InputType it)
+ {
+ inputParams.put(it.token, it);
+ }
/**
- * Helper class based on the UrlLink class which enables URLs to be
- * constructed from sequences or IDs associated with a group of sequences. URL
- * definitions consist of a pipe separated string containing a ||[|]. The url
- * construct includes regex qualified tokens which are replaced with seuqence
- * IDs ($SEQUENCE_IDS$) and/or seuqence regions ($SEQUENCES$) that are
- * extracted from the group. See UrlLink
for more information
- * about the approach, and the original implementation. Documentation to come.
- * Note - groupUrls can be very big!
+ * remove the given input type it from the set of service input parameters.
+ *
+ * @param it
*/
- private String url_prefix, target, label;
+ public void removeInputParam(InputType it)
+ {
+ inputParams.remove(it.token);
+ }
/**
- * these are all filled in order of the occurence of each token in the url
- * string template
+ * service requests alignment data
*/
- private String url_suffix[], separators[], regexReplace[];
-
- private String invalidMessage = null;
+ boolean aligndata;
/**
- * tokens that can be replaced in the URL.
+ * service requests alignment and/or seuqence annotationo data
*/
- private static String[] tokens;
+ boolean annotdata;
/**
- * position of each token (which can appear once only) in the url
+ * service requests partitions defined over input (alignment) data
*/
- private int[] segs;
+ boolean partitiondata;
/**
- * contains tokens in the order they appear in the URL template.
+ * process ths input data and set the appropriate shorthand flags describing
+ * the input the service wants
*/
- private String[] mtch;
- static
+ public void setInvolvesFlags()
{
- if (tokens == null)
- {
- tokens = new String[]
- { "SEQUENCEIDS", "SEQUENCES", "DATASETID" };
- }
+ aligndata = inputInvolves(Alignment.class);
+ annotdata = inputInvolves(AnnotationFile.class);
+ partitiondata = inputInvolves(SeqGroupIndexVector.class);
}
/**
- * test for GroupURLType bitfield (with default tokens)
- */
- public static final int SEQUENCEIDS = 1;
-
- /**
- * test for GroupURLType bitfield (with default tokens)
+ * Service return info { alignment, annotation file (loaded back on to
+ * alignment), tree (loaded back on to alignment), sequence annotation -
+ * loaded back on to alignment), text report, pdb structures with sequence
+ * mapping )
+ *
*/
- public static final int SEQUENCES = 2;
/**
- * test for GroupURLType bitfield (with default tokens)
+ * Start with bare minimum: input is alignment + groups on alignment
+ *
+ * @author JimP
+ *
*/
- public static final int DATASETID = 4;
- // private int idseg = -1, seqseg = -1;
+ private String invalidMessage = null;
/**
* parse the given linkString of the form '||separator
@@ -189,223 +315,33 @@ public class RestServiceDescription
*/
public RestServiceDescription(String link)
{
- int sep = link.indexOf("|");
- segs = new int[tokens.length];
- int ntoks = 0;
- for (int i = 0; i < segs.length; i++)
- {
- if ((segs[i] = link.indexOf("$" + tokens[i])) > -1)
- {
- ntoks++;
- }
- }
- // expect at least one token
- if (ntoks == 0)
- {
- invalidMessage = "Group URL string must contain at least one of ";
- for (int i = 0; i < segs.length; i++)
- {
- invalidMessage += " '$" + tokens[i] + "[=/regex=/]$'";
- }
- return;
- }
-
- int[] ptok = new int[ntoks + 1];
- String[] tmtch = new String[ntoks + 1];
- mtch = new String[ntoks];
- for (int i = 0, t = 0; i < segs.length; i++)
- {
- if (segs[i] > -1)
- {
- ptok[t] = segs[i];
- tmtch[t++] = tokens[i];
- }
- }
- ptok[ntoks] = link.length();
- tmtch[ntoks] = "$$$$$$$$$";
- jalview.util.QuickSort.sort(ptok, tmtch);
- for (int i = 0; i < ntoks; i++)
- {
- mtch[i] = tmtch[i]; // TODO: check order is ascending
- }
- /*
- * replaces the specific code below {}; if (psqids > -1 && pseqs > -1) { if
- * (psqids > pseqs) { idseg = 1; seqseg = 0;
- *
- * ptok = new int[] { pseqs, psqids, link.length() }; mtch = new String[] {
- * "$SEQUENCES", "$SEQUENCEIDS" }; } else { idseg = 0; seqseg = 1; ptok =
- * new int[] { psqids, pseqs, link.length() }; mtch = new String[] {
- * "$SEQUENCEIDS", "$SEQUENCES" }; } } else { if (psqids != -1) { idseg = 0;
- * ptok = new int[] { psqids, link.length() }; mtch = new String[] {
- * "$SEQUENCEIDS" }; } else { seqseg = 0; ptok = new int[] { pseqs,
- * link.length() }; mtch = new String[] { "$SEQUENCES" }; } }
- */
-
- int p = sep;
- // first get the label and target part before the first |
- do
- {
- sep = p;
- p = link.indexOf("|", sep + 1);
- } while (p > sep && p < ptok[0]);
- // Assuming that the URL itself does not contain any '|' symbols
- // sep now contains last pipe symbol position prior to any regex symbols
- label = link.substring(0, sep);
- if (label.indexOf("|") > -1)
+ StringBuffer warnings = new StringBuffer();
+ if (!configureFromEncodedString(link, warnings))
{
- // | terminated database name / www target at start of Label
- target = label.substring(0, label.indexOf("|"));
- }
- else if (label.indexOf(" ") > 2)
- {
- // space separated Label - matches database name
- target = label.substring(0, label.indexOf(" "));
- }
- else
- {
- target = label;
- }
- // Now Parse URL : Whole URL string first
- url_prefix = link.substring(sep + 1, ptok[0]);
- url_suffix = new String[mtch.length];
- regexReplace = new String[mtch.length];
- // and loop through tokens
- for (int pass = 0; pass < mtch.length; pass++)
- {
- int mlength = 3 + mtch[pass].length();
- if (link.indexOf("$" + mtch[pass] + "=/") == ptok[pass]
- && (p = link.indexOf("/=$", ptok[pass] + mlength)) > ptok[pass]
- + mlength)
- {
- // Extract Regex and suffix
- if (ptok[pass + 1] < p + 3)
- {
- // tokens are not allowed inside other tokens - e.g. inserting a
- // $sequences$ into the regex match for the sequenceid
- invalidMessage = "Token regexes cannot contain other regexes (did you terminate the $"
- + mtch[pass] + " regex with a '/=$' ?";
- return;
- }
- url_suffix[pass] = link.substring(p + 3, ptok[pass + 1]);
- regexReplace[pass] = link.substring(ptok[pass] + mlength, p);
- try
- {
- com.stevesoft.pat.Regex rg = com.stevesoft.pat.Regex.perlCode("/"
- + regexReplace[pass] + "/");
- if (rg == null)
- {
- invalidMessage = "Invalid Regular Expression : '"
- + regexReplace[pass] + "'\n";
- }
- } catch (Exception e)
- {
- invalidMessage = "Invalid Regular Expression : '"
- + regexReplace[pass] + "'\n";
- }
- }
- else
- {
- regexReplace[pass] = null;
- // verify format is really correct.
- if ((p = link.indexOf("$" + mtch[pass] + "$")) == ptok[pass])
- {
- url_suffix[pass] = link.substring(p + mtch[pass].length() + 2,
- ptok[pass + 1]);
- }
- else
- {
- invalidMessage = "Warning: invalid regex structure (after '"
- + mtch[0] + "') for URL link : " + link;
- }
- }
- }
- int pass = 0;
- separators = new String[url_suffix.length];
- String suffices = url_suffix[url_suffix.length - 1], lastsep = ",";
- // have a look in the last suffix for any more separators.
- while ((p = suffices.indexOf('|')) > -1)
- {
- separators[pass] = suffices.substring(p + 1);
- if (pass == 0)
- {
- // trim the original suffix string
- url_suffix[url_suffix.length - 1] = suffices.substring(0, p);
- }
- else
+ if (warnings.length() > 0)
{
- lastsep = (separators[pass - 1] = separators[pass - 1].substring(0,
- p));
+ invalidMessage = warnings.toString();
}
- suffices = separators[pass];
- pass++;
}
- if (pass > 0)
- {
- lastsep = separators[pass - 1];
- }
- // last separator is always used for all the remaining separators
- while (pass < separators.length)
- {
- separators[pass++] = lastsep;
- }
- }
-
- /**
- * @return the url_suffix
- */
- public String getUrl_suffix()
- {
- return url_suffix[url_suffix.length - 1];
}
- /**
- * @return the url_prefix
- */
- public String getUrl_prefix()
+ public RestServiceDescription(RestServiceDescription toedit)
{
- return url_prefix;
- }
-
- /**
- * @return the target
- */
- public String getTarget()
- {
- return target;
- }
-
- /**
- * @return the label
- */
- public String getLabel()
- {
- return label;
- }
-
- /**
- * @return the sequence ID regexReplace
- */
- public String getIDRegexReplace()
- {
- return _replaceFor(tokens[0]);
- }
-
- private String _replaceFor(String token)
- {
- for (int i = 0; i < mtch.length; i++)
- if (segs[i] > -1 && mtch[i].equals(token))
- {
- return regexReplace[i];
- }
- return null;
- }
-
- /**
- * @return the sequence ID regexReplace
- */
- public String getSeqRegexReplace()
- {
- return _replaceFor(tokens[1]);
+ // Rather then do the above, we cheat and use our human readable
+ // serialization code to clone everything
+ this(toedit.toString());
+ /**
+ * if (toedit == null) { return; } /** urlSuffix = toedit.urlSuffix; postUrl
+ * = toedit.postUrl; hseparable = toedit.hseparable; vseparable =
+ * toedit.vseparable; gapCharacter = toedit.gapCharacter; details = new
+ * RestServiceDescription.UIinfo(); details.Action = toedit.details.Action;
+ * details.description = toedit.details.description; details.Name =
+ * toedit.details.Name; for (InputType itype: toedit.inputParams.values()) {
+ * inputParams.put(itype.token, itype.clone());
+ *
+ * }
+ */
+ // TODO Implement copy constructor NOW*/
}
/**
@@ -427,408 +363,400 @@ public class RestServiceDescription
return invalidMessage == null;
}
-
- /**
- * gathers input into a hashtable
- *
- * @param idstrings
- * @param seqstrings
- * @param dsstring
- * @return
- */
- private Hashtable replacementArgs(String[] idstrings,
- String[] seqstrings, String dsstring)
- {
- Hashtable rstrings = new Hashtable();
- rstrings.put(tokens[0], idstrings);
- rstrings.put(tokens[1], seqstrings);
- rstrings.put(tokens[2], new String[]
- { dsstring });
- if (idstrings.length != seqstrings.length)
- {
- throw new Error(
- "idstrings and seqstrings contain one string each per sequence.");
- }
- return rstrings;
- }
-
-
-
-
/**
- * conditionally generate urls or stubs for a given input.
+ * parse a string containing a list of service properties and configure the
+ * service description
*
- * @param createFullUrl
- * set to false if you only want to test if URLs would be generated.
- * @param repstrings
- * @param onlyIfMatches
- * @return null if no url is generated. Object[] { int[] { number of matches
- * seqs }, boolean[] { which matched }, (if createFullUrl also has
- * StringBuffer[] { segment generated from inputs that is used in URL
- * }, String[] { url })}
- * @throws Exception
- * @throws UrlStringTooLongException
+ * @param propList
+ * param warnings a StringBuffer that any warnings about invalid
+ * content will be appended to.
*/
- protected Object[] makeUrlsIf(boolean createFullUrl,
- Hashtable repstrings, boolean onlyIfMatches) throws Exception
+ private boolean configureFromServiceInputProperties(String propList,
+ StringBuffer warnings)
{
- int pass = 0;
-
- // prepare string arrays in correct order to be assembled into URL input
- String[][] idseq = new String[mtch.length][]; // indexed by pass
- int mins = 0, maxs = 0; // allowed two values, 1 or n-sequences.
- for (int i = 0; i < mtch.length; i++)
+ String[] props = StringUtils.separatorListToArray(propList, ",");
+ if (props == null)
+ {
+ return true;
+ }
+ ;
+ boolean valid = true;
+ String val = null;
+ int l = warnings.length();
+ int i;
+ for (String prop : props)
{
- idseq[i] = (String[]) repstrings.get(mtch[i]);
- if (idseq[i].length >= 1)
+ if ((i = prop.indexOf("=")) > -1)
{
- if (mins == 0 && idseq[i].length == 1)
+ val = prop.substring(i + 1);
+ if (val.startsWith("\'") && val.endsWith("\'"))
{
- mins = 1;
+ val = val.substring(1, val.length() - 1);
}
- if (maxs < 2)
+ prop = prop.substring(0, i);
+ }
+
+ if (prop.equals("hseparable"))
+ {
+ hseparable = true;
+ }
+ if (prop.equals("vseparable"))
+ {
+ vseparable = true;
+ }
+ if (prop.equals("gapCharacter"))
+ {
+ if (val == null || val.length() == 0 || val.length() > 1)
{
- maxs = idseq[i].length;
+ valid = false;
+ warnings.append((warnings.length() > 0 ? "\n" : "")
+ + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
+ + val + "'"));
}
else
{
- if (maxs != idseq[i].length)
- {
- throw new Error(
- "Cannot have mixed length replacement vectors. Replacement vector for "
- + (mtch[i]) + " is " + idseq[i].length
- + " strings long, and have already seen a "
- + maxs + " length vector.");
- }
+ gapCharacter = val.charAt(0);
}
}
- else
+ if (prop.equals("returns"))
{
- throw new Error(
- "Cannot have zero length vector of replacement strings - either 1 value or n values.");
+ _configureOutputFormatFrom(val, warnings);
}
}
- // iterate through input, collating segments to be inserted into url
- StringBuffer matched[] = new StringBuffer[idseq.length];
- // and precompile regexes
- com.stevesoft.pat.Regex[] rgxs = new com.stevesoft.pat.Regex[matched.length];
- for (pass = 0; pass < matched.length; pass++)
- {
- matched[pass] = new StringBuffer();
- if (regexReplace[pass] != null)
- {
- rgxs[pass] = com.stevesoft.pat.Regex.perlCode("/"
- + regexReplace[pass] + "/");
- }
- else
+ // return true if valid is true and warning buffer was not appended to.
+ return valid && (l == warnings.length());
+ }
+
+ private String _genOutputFormatString()
+ {
+ String buff = "";
+ if (resultData == null)
+ {
+ return "";
+ }
+ for (JvDataType type : resultData)
+ {
+ if (buff.length() > 0)
{
- rgxs[pass] = null;
+ buff += ";";
}
+ buff += type.toString();
}
- // tot up the invariant lengths for this url
- int urllength = url_prefix.length();
- for (pass = 0; pass < matched.length; pass++)
+ return buff;
+ }
+
+ private void _configureOutputFormatFrom(String outstring,
+ StringBuffer warnings)
+ {
+ if (outstring.indexOf(";") == -1)
{
- urllength += url_suffix[pass].length();
+ // we add a token, for simplicity
+ outstring = outstring + ";";
}
-
- // flags to record which of the input sequences were actually used to
- // generate the
- // url
- boolean[] thismatched = new boolean[maxs];
- int seqsmatched = 0;
- for (int sq = 0; sq < maxs; sq++)
- {
- // initialise flag for match
- thismatched[sq] = false;
- StringBuffer[] thematches = new StringBuffer[rgxs.length];
- for (pass = 0; pass < rgxs.length; pass++)
+ StringTokenizer st = new StringTokenizer(outstring, ";");
+ String tok = "";
+ resultData = new ArrayList();
+ while (st.hasMoreTokens())
+ {
+ try
{
- thematches[pass] = new StringBuffer(); // initialise - in case there are
- // no more
- // matches.
- // if a regex is provided, then it must match for all sequences in all
- // tokens for it to be considered.
- if (idseq[pass].length <= sq)
- {
- // no more replacement strings to try for this token
- continue;
- }
- if (rgxs[pass] != null)
- {
- com.stevesoft.pat.Regex rg = rgxs[pass];
- int rematchat = 0;
- // concatenate all matches of re in the given string!
- while (rg.searchFrom(idseq[pass][sq], rematchat))
- {
- rematchat = rg.matchedTo();
- thismatched[sq] |= true;
- urllength += rg.charsMatched(); // count length
- if ((urllength + 32) > Platform.getMaxCommandLineLength())
- {
- throw new Exception("urllength");
- }
-
- if (!createFullUrl)
- {
- continue; // don't bother making the URL replacement text.
- }
- // do we take the cartesian products of the substituents ?
- int ns = rg.numSubs();
- if (ns == 0)
- {
- thematches[pass].append(rg.stringMatched());// take whole regex
- }
- /*
- * else if (ns==1) { // take only subgroup match return new String[]
- * { rg.stringMatched(1), url_prefix+rg.stringMatched(1)+url_suffix
- * }; }
- */
- // deal with multiple submatch case - for moment we do the simplest
- // - concatenate the matched regions, instead of creating a complete
- // list for each alternate match over all sequences.
- // TODO: specify a 'replace pattern' - next refinement
- else
- {
- // debug
- /*
- * for (int s = 0; s <= rg.numSubs(); s++) {
- * System.err.println("Sub " + s + " : " + rg.matchedFrom(s) +
- * " : " + rg.matchedTo(s) + " : '" + rg.stringMatched(s) + "'");
- * }
- */
- // try to collate subgroup matches
- StringBuffer subs = new StringBuffer();
- // have to loop through submatches, collating them at top level
- // match
- int s = 0; // 1;
- while (s <= ns)
- {
- if (s + 1 <= ns && rg.matchedTo(s) > -1
- && rg.matchedTo(s + 1) > -1
- && rg.matchedTo(s + 1) < rg.matchedTo(s))
- {
- // s is top level submatch. search for submatches enclosed by
- // this one
- int r = s + 1;
- StringBuffer rmtch = new StringBuffer();
- while (r <= ns && rg.matchedTo(r) <= rg.matchedTo(s))
- {
- if (rg.matchedFrom(r) > -1)
- {
- rmtch.append(rg.stringMatched(r));
- }
- r++;
- }
- if (rmtch.length() > 0)
- {
- subs.append(rmtch); // simply concatenate
- }
- s = r;
- }
- else
- {
- if (rg.matchedFrom(s) > -1)
- {
- subs.append(rg.stringMatched(s)); // concatenate
- }
- s++;
- }
- }
- thematches[pass].append(subs);
- }
- }
- }
- else
- {
- // are we only supposed to take regex matches ?
- if (!onlyIfMatches)
- {
- thismatched[sq] |= true;
- urllength += idseq[pass][sq].length(); // tot up length
- if (createFullUrl)
- {
- thematches[pass] = new StringBuffer(idseq[pass][sq]); // take
- // whole
- // string -
- // regardless - probably not a
- // good idea!
- /*
- * TODO: do some boilerplate trimming of the fields to make them
- * sensible e.g. trim off any 'prefix' in the id string (see
- * UrlLink for the below) - pre 2.4 Jalview behaviour if
- * (idstring.indexOf("|") > -1) { idstring =
- * idstring.substring(idstring.lastIndexOf("|") + 1); }
- */
- }
-
- }
- }
- }
-
- // check if we are going to add this sequence's results ? all token
- // replacements must be valid for this to happen!
- // (including single value replacements - eg. dataset name)
- if (thismatched[sq])
+ resultData.add(JvDataType.valueOf(tok = st.nextToken()));
+ } catch (NoSuchElementException x)
{
- if (createFullUrl)
+ warnings.append(
+ "Invalid result type: '" + tok + "' (must be one of: ");
+ String sep = "";
+ for (JvDataType vl : JvDataType.values())
{
- for (pass = 0; pass < matched.length; pass++)
- {
- if (idseq[pass].length > 1 && matched[pass].length() > 0)
- {
- matched[pass].append(separators[pass]);
- }
- matched[pass].append(thematches[pass]);
- }
+ warnings.append(sep);
+ warnings.append(vl.toString());
+ sep = " ,";
}
- seqsmatched++;
+ warnings.append(" separated by semi-colons)\n");
}
}
- // finally, if any sequences matched, then form the URL and return
- if (seqsmatched == 0 || (createFullUrl && matched[0].length() == 0))
+ }
+
+ private String getServiceIOProperties()
+ {
+ ArrayList vls = new ArrayList();
+ if (isHseparable())
{
- // no matches - no url generated
- return null;
+ vls.add("hseparable");
}
- // check if we are beyond the feasible command line string limit for this
- // platform
- if ((urllength + 32) > Platform.getMaxCommandLineLength())
+ ;
+ if (isVseparable())
{
- throw new Exception("urllength");
+ vls.add("vseparable");
}
- if (!createFullUrl)
+ ;
+ vls.add(new String("gapCharacter='" + gapCharacter + "'"));
+ vls.add(new String("returns='" + _genOutputFormatString() + "'"));
+ return StringUtils.arrayToSeparatorList(vls.toArray(new String[0]),
+ ",");
+ }
+
+ public String toString()
+ {
+ StringBuffer result = new StringBuffer();
+ result.append("|");
+ result.append(details.Name);
+ result.append('|');
+ result.append(details.Action);
+ result.append('|');
+ if (details.description != null)
{
- // just return the essential info about what the URL would be generated
- // from
- return new Object[]
- { new int[]
- { seqsmatched }, thismatched };
+ result.append(details.description);
}
- // otherwise, create the URL completely.
-
- StringBuffer submiturl = new StringBuffer();
- submiturl.append(url_prefix);
- for (pass = 0; pass < matched.length; pass++)
+ ;
+ // list job input flags
+ result.append('|');
+ result.append(getServiceIOProperties());
+ // list any additional cgi parameters needed for result retrieval
+ if (urlSuffix != null && urlSuffix.length() > 0)
{
- submiturl.append(matched[pass]);
- if (url_suffix[pass] != null)
- {
- submiturl.append(url_suffix[pass]);
- }
+ result.append('|');
+ result.append(urlSuffix);
}
-
- return new Object[]
- { new int[]
- { seqsmatched }, thismatched, matched, new String[]
- { submiturl.toString() } };
+ result.append('|');
+ result.append(getInputParamEncodedUrl());
+ return result.toString();
}
/**
+ * processes a service encoded as a string (as generated by
+ * RestServiceDescription.toString()) Note - this will only use the first
+ * service definition encountered in the string to configure the service.
*
- * @param urlstub
- * @return number of distinct sequence (id or seuqence) replacements predicted
- * for this stub
+ * @param encoding
+ * @param warnings
+ * - where warning messages are reported.
+ * @return true if configuration was parsed successfully.
*/
- public int getNumberInvolved(Object[] urlstub)
+ public boolean configureFromEncodedString(String encoding,
+ StringBuffer warnings)
{
- return ((int[]) urlstub[0])[0]; // returns seqsmatched from
- // makeUrlsIf(false,...)
+ String[] list = StringUtils.separatorListToArray(encoding, "|");
+
+ int nextpos = parseServiceList(list, warnings, 0);
+ if (nextpos > 0)
+ {
+ return true;
+ }
+ return false;
}
/**
- * get token types present in this url as a bitfield indicating presence of
- * each token from tokens (LSB->MSB).
+ * processes the given list from position p, attempting to configure the
+ * service from it. 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.
*
- * @return groupURL class as integer
+ * @param list
+ * @param warnings
+ * @param p
+ * @return
*/
- public int getGroupURLType()
+ protected int parseServiceList(String[] list, StringBuffer warnings,
+ int p)
{
- int r = 0;
- for (int pass = 0; pass < tokens.length; pass++)
+ boolean invalid = false;
+ // look for the first non-empty position - expect it to be service name
+ while (list[p] != null && list[p].trim().length() == 0)
{
- for (int i = 0; i < mtch.length; i++)
+ p++;
+ }
+ details.Name = list[p];
+ details.Action = list[p + 1];
+ details.description = list[p + 2];
+ invalid |= !configureFromServiceInputProperties(list[p + 3], warnings);
+ if (list.length - p > 5 && list[p + 5] != null
+ && list[p + 5].trim().length() > 5)
+ {
+ urlSuffix = list[p + 4];
+ invalid |= !configureFromInputParamEncodedUrl(list[p + 5], warnings);
+ p += 6;
+ }
+ else
+ {
+ if (list.length - p > 4 && list[p + 4] != null
+ && list[p + 4].trim().length() > 5)
{
- if (mtch[i].equals(tokens[pass]))
- {
- r += 1 << pass;
- }
+ urlSuffix = null;
+ invalid |= !configureFromInputParamEncodedUrl(list[p + 4],
+ warnings);
+ p += 5;
}
}
- return r;
+ return invalid ? -1 : p;
}
- public String toString()
+ /**
+ * @return string representation of the input parameters, their type and
+ * constraints, appended to the service's base submission URL
+ */
+ private String getInputParamEncodedUrl()
{
- StringBuffer result = new StringBuffer();
- result.append(label + "|" + url_prefix);
- int r;
- for (r = 0; r < url_suffix.length; r++)
+ StringBuffer url = new StringBuffer();
+ if (postUrl == null || postUrl.length() < 5)
{
- result.append("$");
- result.append(mtch[r]);
- if (regexReplace[r] != null)
- {
- result.append("=/");
- result.append(regexReplace[r]);
- result.append("/=");
- }
- result.append("$");
- result.append(url_suffix[r]);
+ return "";
}
- for (r = 0; r < separators.length; r++)
+
+ url.append(postUrl);
+ char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
+ boolean consts = true;
+ do
{
- result.append("|");
- result.append(separators[r]);
- }
- return result.toString();
+ for (Map.Entry param : inputParams.entrySet())
+ {
+ List vals = param.getValue().getURLEncodedParameter();
+ if (param.getValue().isConstant())
+ {
+ if (consts)
+ {
+ url.append(appendChar);
+ appendChar = '&';
+ url.append(param.getValue().token);
+ if (vals.size() == 1)
+ {
+ url.append("=");
+ url.append(vals.get(0));
+ }
+ }
+ }
+ else
+ {
+ if (!consts)
+ {
+ url.append(appendChar);
+ appendChar = '&';
+ url.append(param.getValue().token);
+ url.append("=");
+ // write parameter set as $TOKENPREFIX:csv list of params$ for this
+ // input param
+ url.append("$");
+ url.append(param.getValue().getURLtokenPrefix());
+ url.append(":");
+ url.append(StringUtils.arrayToSeparatorList(
+ vals.toArray(new String[0]), ","));
+ url.append("$");
+ }
+ }
+
+ }
+ // toggle consts and repeat until !consts is false:
+ } while (!(consts = !consts));
+ return url.toString();
}
/**
- * report stats about the generated url string given an input set
+ * parse the service URL and input parameters from the given encoded URL
+ * string and configure the RestServiceDescription from it.
*
- * @param ul
- * @param idstring
- * @param url
+ * @param ipurl
+ * @param warnings
+ * where any warnings
+ * @return true if URL parsed correctly. false means the configuration failed.
*/
- private static void testUrls(RestServiceDescription
- ul, String[][] idstring,
- Object[] url)
+ private boolean configureFromInputParamEncodedUrl(String ipurl,
+ StringBuffer warnings)
{
-
- if (url == null)
+ boolean valid = true;
+ int lastp = 0;
+ String url = new String();
+ Matcher prms = PARAM_ENCODED_URL_PATTERN.matcher(ipurl);
+ Map iparams = new Hashtable();
+ InputType jinput;
+ while (prms.find())
{
- System.out.println("Created NO urls.");
+ if (lastp < prms.start(0))
+ {
+ url += ipurl.substring(lastp, prms.start(0));
+ lastp = prms.end(0) + 1;
+ }
+ String sep = prms.group(1);
+ String tok = prms.group(2);
+ String iprm = prms.group(3);
+ int colon = iprm.indexOf(":");
+ String iprmparams = "";
+ if (colon > -1)
+ {
+ iprmparams = iprm.substring(colon + 1);
+ iprm = iprm.substring(0, colon);
+ }
+ valid = parseTypeString(prms.group(0), tok, iprm, iprmparams, iparams,
+ warnings);
}
- else
+ if (valid)
{
- System.out.println("Created a url from " + ((int[]) url[0])[0]
- + "out of " + idstring[0].length + " sequences.");
- System.out.println("Sequences that did not match:");
- for (int sq = 0; sq < idstring[0].length; sq++)
+ try
{
- if (!((boolean[]) url[1])[sq])
- {
- System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
- + idstring[1][sq]);
- }
- }
- System.out.println("Sequences that DID match:");
- for (int sq = 0; sq < idstring[0].length; sq++)
+ URL u = new URL(url);
+ postUrl = url;
+ inputParams = iparams;
+ } catch (Exception e)
{
- if (((boolean[]) url[1])[sq])
- {
- System.out.println("Seq " + sq + ": " + idstring[0][sq] + "\t: "
- + idstring[1][sq]);
- }
+ warnings.append("Failed to parse '" + url + "' as a URL.\n");
+ valid = false;
}
- System.out.println("The generated URL:");
- System.out.println(((String[]) url[3])[0]);
}
+ return valid;
}
- public static void main(String argv[])
+ public static Class[] getInputTypes()
{
+ // TODO - find a better way of maintaining this classlist
+ return new Class[] { jalview.ws.rest.params.Alignment.class,
+ jalview.ws.rest.params.AnnotationFile.class,
+ SeqGroupIndexVector.class, jalview.ws.rest.params.SeqIdVector.class,
+ jalview.ws.rest.params.SeqVector.class,
+ jalview.ws.rest.params.Tree.class };
+ }
+
+ public static boolean parseTypeString(String fullstring, String tok,
+ String iprm, String iprmparams, Map iparams,
+ StringBuffer warnings)
+ {
+ boolean valid = true;
+ InputType jinput;
+ for (Class type : getInputTypes())
+ {
+ try
+ {
+ jinput = (InputType) (type.getConstructor().newInstance());
+ if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
+ {
+ ArrayList al = new ArrayList();
+ for (String prprm : StringUtils.separatorListToArray(iprmparams,
+ ","))
+ {
+ // hack to ensure that strings like "sep=','" containing unescaped
+ // commas as values are concatenated
+ al.add(prprm.trim());
+ }
+ if (!jinput.configureFromURLtokenString(al, warnings))
+ {
+ valid = false;
+ warnings.append("Failed to parse '" + fullstring + "' as a "
+ + jinput.getURLtokenPrefix() + " input tag.\n");
+ }
+ else
+ {
+ jinput.token = tok;
+ iparams.put(tok, jinput);
+ valid = true;
+ }
+ break;
+ }
+
+ } catch (Throwable thr)
+ {
+ }
+ ;
+ }
+ return valid;
}
/**
@@ -850,41 +778,39 @@ public class RestServiceDescription
return idset;
}
- public void setLabel(String newlabel)
- {
- this.label = newlabel;
- }
-
/**
- * can this service be run on the visible portion of an alignment regardless of hidden boundaries ?
+ * can this service be run on the visible portion of an alignment regardless
+ * of hidden boundaries ?
*/
- boolean hseparable=false;
- boolean vseparable=false;
-
+ boolean hseparable = false;
+
+ boolean vseparable = false;
+
public boolean isHseparable()
{
- // TODO Auto-generated method stub
return hseparable;
}
+
/**
*
* @return
*/
public boolean isVseparable()
{
- // TODO Auto-generated method stub
- return hseparable;
+ return vseparable;
}
/**
* search the input types for an instance of the given class
- * @param class1
+ *
+ * @param
+ * class1
* @return
*/
public boolean inputInvolves(Class> class1)
{
- assert(InputType.class.isAssignableFrom(class1));
- for (InputType val:inputParams.values())
+ assert (InputType.class.isAssignableFrom(class1));
+ for (InputType val : inputParams.values())
{
if (class1.isAssignableFrom(val.getClass()))
{
@@ -893,10 +819,13 @@ public class RestServiceDescription
}
return false;
}
+
char gapCharacter = '-';
+
/**
*
- * @return the preferred gap character for alignments input/output by this service
+ * @return the preferred gap character for alignments input/output by this
+ * service
*/
public char getGapCharacter()
{
@@ -906,6 +835,76 @@ public class RestServiceDescription
public String getDecoratedResultUrl(String jobId)
{
// TODO: correctly write ?/& appropriate to result URL format.
- return jobId+urlSuffix;
+ return jobId + urlSuffix;
}
+
+ private List resultData = new ArrayList();
+
+ /**
+ *
+ *
+ * TODO: Extend to optionally specify relative/absolute url where data of this
+ * type can be retrieved from
+ *
+ * @param dt
+ */
+ public void addResultDatatype(JvDataType dt)
+ {
+ if (resultData == null)
+ {
+ resultData = new ArrayList();
+ }
+ resultData.add(dt);
+ }
+
+ public boolean removeRsultDatatype(JvDataType dt)
+ {
+ if (resultData != null)
+ {
+ return resultData.remove(dt);
+ }
+ return false;
+ }
+
+ public List getResultDataTypes()
+ {
+ return resultData;
+ }
+
+ /**
+ * parse a concatenated list of rest service descriptions into an array
+ *
+ * @param services
+ * @return zero or more services.
+ * @throws exceptions
+ * if the services are improperly encoded.
+ */
+ public static List parseDescriptions(
+ String services) throws Exception
+ {
+ String[] list = StringUtils.separatorListToArray(services, "|");
+ List svcparsed = new ArrayList();
+ int p = 0, lastp = 0;
+ StringBuffer warnings = new StringBuffer();
+ do
+ {
+ RestServiceDescription rsd = new RestServiceDescription();
+ p = rsd.parseServiceList(list, warnings, lastp = p);
+ if (p > lastp && rsd.isValid())
+ {
+ svcparsed.add(rsd);
+ }
+ else
+ {
+ 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());
+ }
+ } while (p < lastp && p < list.length - 1);
+ return svcparsed;
+ }
+
}