2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.6)
3 * Copyright (C) 2010 J Procter, AM Waterhouse, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
18 package jalview.ws.rest;
20 import jalview.datamodel.SequenceI;
21 import jalview.io.packed.DataProvider;
22 import jalview.io.packed.SimpleDataProvider;
23 import jalview.io.packed.DataProvider.JvDataType;
24 import jalview.util.GroupUrlLink.UrlStringTooLongException;
25 import jalview.util.Platform;
26 import jalview.ws.rest.params.Alignment;
27 import jalview.ws.rest.params.AnnotationFile;
28 import jalview.ws.rest.params.JobConstant;
29 import jalview.ws.rest.params.SeqGroupIndexVector;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.Hashtable;
35 import java.util.List;
37 import java.util.NoSuchElementException;
38 import java.util.StringTokenizer;
39 import java.util.Vector;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
43 import javax.swing.JViewport;
45 import com.stevesoft.pat.Regex;
46 import com.sun.org.apache.xml.internal.serialize.OutputFormat.DTD;
47 import com.sun.tools.doclets.internal.toolkit.util.DocFinder.Output;
49 public class RestServiceDescription
60 public RestServiceDescription(String action, String description,
61 String name, String postUrl, String urlSuffix,
62 Map<String, InputType> inputParams, boolean hseparable,
63 boolean vseparable, char gapCharacter)
66 this.details = new UIinfo();
67 details.Action = action;
68 details.description = description;
70 this.postUrl = postUrl;
71 this.urlSuffix = urlSuffix;
72 this.inputParams = inputParams;
73 this.hseparable = hseparable;
74 this.vseparable = vseparable;
75 this.gapCharacter = gapCharacter;
78 public boolean equals(Object o)
80 if (o == null || !(o instanceof RestServiceDescription))
84 RestServiceDescription other = (RestServiceDescription) o;
85 boolean diff = (gapCharacter != other.gapCharacter);
86 diff |= vseparable != other.vseparable;
87 diff |= hseparable != other.hseparable;
88 diff |= !(urlSuffix.equals(other.urlSuffix));
89 // TODO - robust diff that includes constants and reordering of URL
90 // diff |= !(postUrl.equals(other.postUrl));
91 // diff |= !inputParams.equals(other.inputParams);
92 diff |= !details.Name.equals(other.details.Name);
93 diff |= !details.Action.equals(other.details.Action);
94 diff |= !details.description.equals(other.details.description);
99 * Service UI Info { Action, Specific Name of Service, Brief Description }
104 public String getAction()
109 public void setAction(String action)
114 public String getName()
119 public void setName(String name)
124 public String getDescription()
129 public void setDescription(String description)
131 this.description = description;
141 public UIinfo details = new UIinfo();
143 public String getAction()
145 return details.getAction();
148 public void setAction(String action)
150 details.setAction(action);
153 public String getName()
155 return details.getName();
158 public void setName(String name)
160 details.setName(name);
163 public String getDescription()
165 return details.getDescription();
168 public void setDescription(String description)
170 details.setDescription(description);
178 public String getPostUrl()
183 public void setPostUrl(String postUrl)
185 this.postUrl = postUrl;
188 public String getUrlSuffix()
193 public void setUrlSuffix(String urlSuffix)
195 this.urlSuffix = urlSuffix;
198 public Map<String, InputType> getInputParams()
203 public void setInputParams(Map<String, InputType> inputParams)
205 this.inputParams = inputParams;
208 public void setHseparable(boolean hseparable)
210 this.hseparable = hseparable;
213 public void setVseparable(boolean vseparable)
215 this.vseparable = vseparable;
218 public void setGapCharacter(char gapCharacter)
220 this.gapCharacter = gapCharacter;
224 * suffix that should be added to any url used if it does not already end in
230 * input info given as key/value pairs - mapped to post arguments
232 Map<String, InputType> inputParams = new HashMap<String,InputType>();
235 * assigns the given inputType it to its corresponding input parameter token
240 public void setInputParam(InputType it)
242 inputParams.put(it.token, it);
246 * remove the given input type it from the set of service input parameters.
250 public void removeInputParam(InputType it)
252 inputParams.remove(it.token);
256 * service requests alignment data
261 * service requests alignment and/or seuqence annotationo data
266 * service requests partitions defined over input (alignment) data
268 boolean partitiondata;
271 * process ths input data and set the appropriate shorthand flags describing
272 * the input the service wants
274 public void setInvolvesFlags()
276 aligndata = inputInvolves(Alignment.class);
277 annotdata = inputInvolves(AnnotationFile.class);
278 partitiondata = inputInvolves(SeqGroupIndexVector.class);
282 * Service return info { alignment, annotation file (loaded back on to
283 * alignment), tree (loaded back on to alignment), sequence annotation -
284 * loaded back on to alignment), text report, pdb structures with sequence
290 * Start with bare minimum: input is alignment + groups on alignment
296 private String invalidMessage = null;
299 * parse the given linkString of the form '<label>|<url>|separator
300 * char[|optional sequence separator char]' into parts. url may contain a
301 * string $SEQUENCEIDS<=optional regex=>$ where <=optional regex=> must be of
302 * the form =/<perl style regex>/=$ or $SEQUENCES<=optional regex=>$ or
303 * $SEQUENCES<=optional regex=>$.
307 public RestServiceDescription(String link)
309 StringBuffer warnings = new StringBuffer();
310 if (!configureFromEncodedString(link, warnings))
312 if (warnings.length() > 0)
314 invalidMessage = warnings.toString();
319 public RestServiceDescription(RestServiceDescription toedit)
321 // Rather then do the above, we cheat and use our human readable serialization code to clone everything
322 this(toedit.toString());
329 urlSuffix = toedit.urlSuffix;
330 postUrl = toedit.postUrl;
331 hseparable = toedit.hseparable;
332 vseparable = toedit.vseparable;
333 gapCharacter = toedit.gapCharacter;
334 details = new RestServiceDescription.UIinfo();
335 details.Action = toedit.details.Action;
336 details.description = toedit.details.description;
337 details.Name = toedit.details.Name;
338 for (InputType itype: toedit.inputParams.values())
340 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;
367 private static boolean debug = false;
370 * parse the string into a list
374 * @return elements separated by separator
376 public static String[] separatorListToArray(String list, String separator)
378 int seplen = separator.length();
379 if (list == null || list.equals("") || list.equals(separator))
381 java.util.ArrayList<String> jv = new ArrayList<String>();
382 int cp = 0, pos, escape;
383 boolean wasescaped = false;
384 String lstitem = null;
385 while ((pos = list.indexOf(separator, cp)) >= cp)
387 escape = (pos>0 && list.charAt(pos - 1) == '\\') ? -1 : 0;
390 // append to previous pos
391 jv.set(jv.size() - 1,
392 lstitem = lstitem + separator
393 + list.substring(cp, pos + escape));
398 jv.add(lstitem = list.substring(cp, pos + escape));
401 wasescaped = escape == -1;
403 if (cp < list.length())
405 String c = list.substring(cp);
408 // append final separator
409 jv.set(jv.size() - 1, lstitem + separator + c);
413 if (!c.equals(separator))
421 String[] v = jv.toArray(new String[jv.size()]);
425 System.err.println("Array from '" + separator
426 + "' separated List:\n" + v.length);
427 for (int i = 0; i < v.length; i++)
429 System.err.println("item " + i + " '" + v[i] + "'");
436 System.err.println("Empty Array from '" + separator
437 + "' separated List");
443 * concatenate the list with separator
447 * @return concatenated string
449 public static String arrayToSeparatorList(String[] list, String separator)
451 StringBuffer v = new StringBuffer();
452 if (list != null && list.length > 0)
454 for (int i = 0, iSize = list.length; i < iSize; i++)
462 // TODO - escape any separator values in list[i]
468 System.err.println("Returning '" + separator
469 + "' separated List:\n");
470 System.err.println(v);
476 System.err.println("Returning empty '" + separator
477 + "' separated List\n");
479 return "" + separator;
483 * parse a string containing a list of service properties and configure the
484 * service description
487 * param warnings a StringBuffer that any warnings about invalid
488 * content will be appended to.
490 private boolean configureFromServiceInputProperties(String propList,
491 StringBuffer warnings)
493 String[] props = separatorListToArray(propList, ",");
502 for (String prop : props)
504 if ((i = prop.indexOf("=")) > -1)
506 val = prop.substring(i + 1);
507 if (val.startsWith("\'") && val.endsWith("\'"))
509 val = val.substring(1, val.length() - 1);
511 prop = prop.substring(0, i);
514 if (prop.equals("hseparable"))
518 if (prop.equals("vseparable"))
522 if (prop.equals("gapCharacter"))
524 if (val == null || val.length()==0 || val.length() > 1)
527 warnings.append((warnings.length() > 0 ? "\n" : "")
528 + ("Invalid service property: gapCharacter=' ' (single character) - was given '"
533 gapCharacter = val.charAt(0);
536 if (prop.equals("returns"))
538 int l=warnings.length();
539 _configureOutputFormatFrom(val, warnings);
540 valid = (l!=warnings.length());
546 private String _genOutputFormatString()
549 if (resultData==null)
553 for (JvDataType type : resultData)
555 if (buff.length() > 0)
559 buff += type.toString();
564 private void _configureOutputFormatFrom(String outstring,
565 StringBuffer warnings)
567 if (outstring.indexOf(";")==-1) {
568 // we add a token, for simplicity
569 outstring = outstring+";";
571 StringTokenizer st = new StringTokenizer(outstring, ";");
573 resultData = new ArrayList<JvDataType>();
574 while (st.hasMoreTokens())
578 resultData.add(JvDataType.valueOf(tok = st.nextToken()));
579 } catch (NoSuchElementException x)
581 warnings.append("Invalid result type: '" + tok
582 + "' (must be one of: ");
584 for (JvDataType vl : JvDataType.values())
586 warnings.append(sep);
587 warnings.append(vl.toString());
590 warnings.append(" separated by semi-colons)\n");
595 private String getServiceIOProperties()
597 String[] vls = new String[]
598 { isHseparable() ? "hseparable" : "",
599 isVseparable() ? "vseparable" : "",
600 (new String("gapCharacter='" + gapCharacter + "'")),
601 (new String("returns='" + _genOutputFormatString() + "'")) };
603 return arrayToSeparatorList(vls, ",");
606 public String toString()
608 StringBuffer result = new StringBuffer();
609 result.append(details.Name);
611 result.append(details.Action);
613 if (details.description != null)
615 result.append(details.description);
618 // list job input flags
620 result.append(getServiceIOProperties());
621 // list any additional cgi parameters needed for result retrieval
622 if (urlSuffix != null && urlSuffix.length() > 0)
625 result.append(urlSuffix);
628 result.append(getInputParamEncodedUrl());
629 return result.toString();
632 public boolean configureFromEncodedString(String encoding,
633 StringBuffer warnings)
635 boolean invalid = false;
636 String[] list = separatorListToArray(encoding, "|");
637 details.Name = list[0];
638 details.Action = list[1];
639 details.description = list[2];
640 invalid|=!configureFromServiceInputProperties(list[3], warnings);
644 invalid |= !configureFromInputParamEncodedUrl(list[5], warnings);
649 invalid |= !configureFromInputParamEncodedUrl(list[4], warnings);
655 * @return string representation of the input parameters, their type and
656 * constraints, appended to the service's base submission URL
658 private String getInputParamEncodedUrl()
660 StringBuffer url = new StringBuffer();
661 if (postUrl == null || postUrl.length() < 5)
667 char appendChar = (postUrl.indexOf("?") > -1) ? '&' : '?';
668 boolean consts = true;
671 for (Map.Entry<String, InputType> param : inputParams.entrySet())
673 List<String> vals = param.getValue().getURLEncodedParameter();
674 if (param.getValue().isConstant())
678 url.append(appendChar);
680 url.append(param.getValue().token);
681 if (vals.size() == 1)
684 url.append(vals.get(0));
692 url.append(appendChar);
694 url.append(param.getValue().token);
696 // write parameter set as $TOKENPREFIX:csv list of params$ for this
699 url.append(param.getValue().getURLtokenPrefix());
701 url.append(arrayToSeparatorList(vals.toArray(new String[0]),
708 // toggle consts and repeat until !consts is false:
709 } while (!(consts = !consts));
710 return url.toString();
714 * parse the service URL and input parameters from the given encoded URL
715 * string and configure the RestServiceDescription from it.
720 * @return true if URL parsed correctly. false means the configuration failed.
722 private boolean configureFromInputParamEncodedUrl(String ipurl,
723 StringBuffer warnings)
725 boolean valid = true;
727 String url = new String();
728 Matcher prms = Pattern.compile("([?&])([A-Za-z0-9_]+)=\\$([^$]+)\\$")
730 Map<String, InputType> iparams = new Hashtable<String, InputType>();
734 if (lastp < prms.start(0))
736 url += ipurl.substring(lastp, prms.start(0));
737 lastp = prms.end(0) + 1;
739 String sep = prms.group(1);
740 String tok = prms.group(2);
741 String iprm = prms.group(3);
742 int colon = iprm.indexOf(":");
743 String iprmparams = "";
746 iprmparams = iprm.substring(colon + 1);
747 iprm = iprm.substring(0, colon);
749 valid = parseTypeString(prms.group(0), tok, iprm, iprmparams, iparams, warnings);
755 URL u = new URL(url);
757 inputParams = iparams;
758 } catch (Exception e)
760 warnings.append("Failed to parse '" + url + "' as a URL.\n");
767 public static boolean parseTypeString(String fullstring, String tok, String iprm, String iprmparams,
768 Map<String, InputType> iparams, StringBuffer warnings)
772 // TODO - find a better way of maintaining this classlist
773 for (Class type : new Class[]
774 { jalview.ws.rest.params.Alignment.class,
775 jalview.ws.rest.params.AnnotationFile.class,
776 SeqGroupIndexVector.class,
777 jalview.ws.rest.params.SeqIdVector.class,
778 jalview.ws.rest.params.SeqVector.class,
779 jalview.ws.rest.params.Tree.class })
783 jinput = (InputType) (type.getConstructor().newInstance(null));
784 if (iprm.equalsIgnoreCase(jinput.getURLtokenPrefix()))
786 ArrayList<String> al = new ArrayList<String>();
787 for (String prprm : separatorListToArray(iprmparams, ","))
789 al.add(prprm.trim());
791 if (!jinput.configureFromURLtokenString(al, warnings))
794 warnings.append("Failed to parse '" + fullstring
795 + "' as a " + jinput.getURLtokenPrefix()
801 iparams.put(tok, jinput);
807 } catch (Throwable thr)
816 public static void main(String argv[])
818 if (argv.length == 0)
820 if (!testRsdExchange("Test using default Shmmr service",
821 RestClient.makeShmmrRestClient().service))
823 System.err.println("default test failed.");
827 System.err.println("default test passed.");
833 for (String svc : argv)
835 p += testRsdExchange("Test " + (++i), svc) ? 1 : 0;
837 System.err.println("" + p + " out of " + i + " tests passed.");
842 private static boolean testRsdExchange(String desc, String servicestring)
846 RestServiceDescription newService = new RestServiceDescription(
848 if (!newService.isValid())
850 throw new Error("Failed to create service from '" + servicestring
851 + "'.\n" + newService.getInvalidMessage());
853 return testRsdExchange(desc, newService);
854 } catch (Throwable x)
856 System.err.println("Failed for service (" + desc + "): "
863 private static boolean testRsdExchange(String desc,
864 RestServiceDescription service)
868 String fromservicetostring = service.toString();
869 RestServiceDescription newService = new RestServiceDescription(
870 fromservicetostring);
871 if (!newService.isValid())
873 throw new Error("Failed to create service from '"
874 + fromservicetostring + "'.\n"
875 + newService.getInvalidMessage());
878 if (!service.equals(newService))
880 System.err.println("Failed for service (" + desc + ").");
881 System.err.println("Original service and parsed service differ.");
882 System.err.println("Original: " + fromservicetostring);
883 System.err.println("Parsed : " + newService.toString());
886 } catch (Throwable x)
888 System.err.println("Failed for service (" + desc + "): "
889 + service.toString());
897 * covenience method to generate the id and sequence string vector from a set
898 * of seuqences using each sequence's getName() and getSequenceAsString()
902 * @return String[][] {{sequence ids},{sequence strings}}
904 public static String[][] formStrings(SequenceI[] seqs)
906 String[][] idset = new String[2][seqs.length];
907 for (int i = 0; i < seqs.length; i++)
909 idset[0][i] = seqs[i].getName();
910 idset[1][i] = seqs[i].getSequenceAsString();
916 * can this service be run on the visible portion of an alignment regardless
917 * of hidden boundaries ?
919 boolean hseparable = false;
921 boolean vseparable = false;
923 public boolean isHseparable()
932 public boolean isVseparable()
938 * search the input types for an instance of the given class
940 * @param <validInput.inputType> class1
943 public boolean inputInvolves(Class<?> class1)
945 assert (InputType.class.isAssignableFrom(class1));
946 for (InputType val : inputParams.values())
948 if (class1.isAssignableFrom(val.getClass()))
956 char gapCharacter = '-';
960 * @return the preferred gap character for alignments input/output by this
963 public char getGapCharacter()
968 public String getDecoratedResultUrl(String jobId)
970 // TODO: correctly write ?/& appropriate to result URL format.
971 return jobId + urlSuffix;
974 private List<JvDataType> resultData=new ArrayList<JvDataType>();
979 * TODO: Extend to optionally specify relative/absolute url where data of this
980 * type can be retrieved from
984 public void addResultDatatype(JvDataType dt)
986 if (resultData == null)
988 resultData = new ArrayList<JvDataType>();
993 public boolean removeRsultDatatype(JvDataType dt)
995 if (resultData != null)
997 return resultData.remove(dt);
1002 public List<JvDataType> getResultDataTypes()