diff options
| author | Andrew Branson <andrew.branson@cern.ch> | 2012-05-30 08:37:45 +0200 |
|---|---|---|
| committer | Andrew Branson <andrew.branson@cern.ch> | 2012-05-30 08:37:45 +0200 |
| commit | b086f57f56bf0eb9dab9cf321a0f69aaaae84347 (patch) | |
| tree | 8e6e26e8b7eed6abad7a17b093bdbb55c5e6b1ba /src/main/java/com/c2kernel/scripting/Script.java | |
| parent | 22088ae8d2d5ff390518dbe1c4372325ffb3a647 (diff) | |
Initial Maven Conversion
Diffstat (limited to 'src/main/java/com/c2kernel/scripting/Script.java')
| -rw-r--r-- | src/main/java/com/c2kernel/scripting/Script.java | 456 |
1 files changed, 456 insertions, 0 deletions
diff --git a/src/main/java/com/c2kernel/scripting/Script.java b/src/main/java/com/c2kernel/scripting/Script.java new file mode 100644 index 0000000..7e40003 --- /dev/null +++ b/src/main/java/com/c2kernel/scripting/Script.java @@ -0,0 +1,456 @@ +package com.c2kernel.scripting;
+
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import javax.script.Bindings;
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineFactory;
+import javax.script.ScriptEngineManager;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+import org.w3c.dom.Text;
+import org.xml.sax.InputSource;
+
+import com.c2kernel.common.ObjectNotFoundException;
+import com.c2kernel.entity.agent.Job;
+import com.c2kernel.entity.proxy.AgentProxy;
+import com.c2kernel.entity.proxy.ItemProxy;
+import com.c2kernel.utils.LocalObjectLoader;
+import com.c2kernel.utils.Logger;
+
+/**************************************************************************
+ *
+ * $Revision: 1.25 $
+ * $Date: 2005/10/05 07:39:37 $
+ *
+ * Copyright (C) 2003 CERN - European Organization for Nuclear Research
+ * All rights reserved.
+ **************************************************************************/
+public class Script
+{
+ String mScript = "";
+ String mName;
+ String mVersion;
+ HashMap<String, Parameter> mInputParams = new HashMap<String, Parameter>();
+ HashMap<String, Parameter> mAllInputParams = new HashMap<String, Parameter>();
+ HashMap<String, Parameter> mOutputParams = new HashMap<String, Parameter>();
+ ArrayList<Script> mIncludes = new ArrayList<Script>();
+ ScriptEngine engine;
+ Bindings beans;
+
+ /**
+ * Loads script xml and parses it for script source, parameters and output specifications.
+ * First tries to load the script from resource path /scriptFiles/scriptName_scriptVersion.xml
+ * If not found tries to find item at /desc/ScriptDesc/scriptName and load Viewpoint scriptVersion from it.
+ *
+ * For the specification of script xml, see the Script schema from resources.
+ *
+ * @param scriptName - name of the script
+ * @param scriptVersion - named version of the script (must be numbered viewpoint)
+ * @throws ScriptParsingException - when script not found (ScriptLoadingException) or xml is invalid (ScriptParsingException)
+ */
+ public Script(String scriptName, int scriptVersion, Bindings context) throws ScriptingEngineException
+ {
+ this(scriptName, scriptVersion);
+ beans = context;
+
+ }
+
+ public Script(String scriptName, int scriptVersion) throws ScriptingEngineException
+ {
+ mName = scriptName;
+ mVersion = String.valueOf(scriptVersion);
+ if (!scriptName.equals(""))
+ setScript(mName, mVersion);
+ }
+
+ /**
+ * Creates a script executor for the supplied expression, bypassing the xml parsing bit
+ * Output class is forced to an object.
+ */
+ public Script(String lang, String expr, Class<?> returnType) throws ScriptingEngineException
+ {
+ mName = "<expr>";
+ setScriptEngine(lang);
+ mVersion = "";
+ addOutput(null, returnType);
+ mScript = expr;
+ }
+
+ public Script(String lang, String expr) throws ScriptingEngineException
+ {
+ this(lang, expr, Object.class);
+ }
+
+ public Script(ItemProxy object, AgentProxy subject, Job job) throws ScriptingEngineException
+ {
+ this(job.getActPropString("ScriptName"), job.getActPropString("ScriptVersion") == null ? -1 : Integer.parseInt(job.getActPropString("ScriptVersion")));
+ // set enviroment - this needs to be well documented for script developers
+ if (!mInputParams.containsKey("item"))
+ addInputParam("item", ItemProxy.class);
+ setInputParamValue("item", object);
+
+ if (!mInputParams.containsKey("agent"))
+ addInputParam("agent", AgentProxy.class);
+ setInputParamValue("agent", subject);
+
+ if (!mInputParams.containsKey("job"))
+ addInputParam("job", Job.class);
+ setInputParamValue("job", job);
+
+ if (!mOutputParams.containsKey("errors"))
+ addOutput("errors", ErrorInfo.class);
+ }
+
+ public void setScriptEngine(String lang) {
+ engine = new ScriptEngineManager().getEngineByName(lang);
+ beans = engine.createBindings();
+ }
+
+ public void setScript(String scriptName, String scriptVersion) throws ScriptingEngineException
+ {
+ try
+ {
+ mName = scriptName;
+ mVersion = scriptVersion;
+ parseScriptXML(LocalObjectLoader.getScript(scriptName, scriptVersion));
+ }
+ catch (ObjectNotFoundException e)
+ {
+ throw new ScriptingEngineException("Script "+scriptName+" not found");
+ }
+ }
+
+ /**
+ * Extracts script data from script xml.
+ *
+ * @param scriptXML
+ * @throws ScriptParsingException - when script is invalid
+ */
+ private void parseScriptXML(String scriptXML) throws ScriptParsingException, ParameterException
+ {
+ Document scriptDoc = null;
+
+ // get the DOM document from the XML
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ try
+ {
+ DocumentBuilder domBuilder = factory.newDocumentBuilder();
+ scriptDoc = domBuilder.parse(new InputSource(new StringReader(scriptXML)));
+ }
+ catch (Exception ex)
+ {
+ throw new ScriptParsingException("Error parsing Script XML : " + ex.toString());
+ }
+
+ Element root = scriptDoc.getDocumentElement();
+ NodeList scriptNodes = root.getChildNodes();
+ for (int i = 0; i < scriptNodes.getLength(); i++)
+ {
+ Element currentParam;
+ String paramName;
+
+ try
+ {
+ currentParam = (Element) scriptNodes.item(i);
+ }
+ catch (ClassCastException ex)
+ {
+ // not an element, skip
+ continue;
+ }
+ paramName = currentParam.getTagName();
+ Logger.msg(9, "Script.parseScriptXML() - Found element " + paramName);
+
+ // Process script parameters
+
+ // input parameter
+ if (paramName.equals("param"))
+ {
+ if (!(currentParam.hasAttribute("name") && currentParam.hasAttribute("type")))
+ throw new ScriptParsingException("Script Input Param incomplete, must have name and type");
+ addInputParam(currentParam.getAttribute("name"), currentParam.getAttribute("type"));
+ }
+
+ //load output type
+ else if (paramName.equals("output"))
+ {
+ if (!currentParam.hasAttribute("type"))
+ throw new ScriptParsingException("Script Output declaration incomplete, must have type");
+ addOutput(currentParam.getAttribute("name"), currentParam.getAttribute("type"));
+ }
+
+ //load any included scripts
+ else if (paramName.equals("include"))
+ {
+ if (!(currentParam.hasAttribute("name") && currentParam.hasAttribute("version")))
+ throw new ScriptParsingException("Script include declaration incomplete, must have name and version");
+ String includeName = currentParam.getAttribute("name");
+ String includeVersion = currentParam.getAttribute("version");
+ try {
+ Script includedScript = new Script(includeName, Integer.parseInt(includeVersion), beans);
+ mIncludes.add(includedScript);
+ for (Parameter includeParam : includedScript.getInputParams().values()) {
+ addIncludedInputParam(includeParam.getName(), includeParam.getType());
+ }
+ } catch (NumberFormatException e) {
+ throw new ScriptParsingException("Invalid version in imported script "+includeName+"_"+includeVersion);
+ } catch (ScriptingEngineException e) {
+ throw new ScriptParsingException("Error parsing imported script "+includeName+"_"+includeVersion+": "+e.getMessage());
+ }
+
+
+ }
+ //load Script
+ else if (paramName.equals("script"))
+ {
+ if (!currentParam.hasAttribute("language"))
+ throw new ScriptParsingException("Script data incomplete, must specify scripting language");
+ Logger.msg(6, "Script.parseScriptXML() - Script Language: " + currentParam.getAttribute("language"));
+ setScriptEngine(currentParam.getAttribute("language"));
+
+ // get script source
+ NodeList scriptChildNodes = currentParam.getChildNodes();
+ if (scriptChildNodes.getLength() != 1)
+ throw new ScriptParsingException("More than one child element found under script tag. Script characters may need escaping - suggest convert to CDATA section");
+ if (scriptChildNodes.item(0) instanceof Text)
+ mScript = ((Text) scriptChildNodes.item(0)).getData();
+ else
+ throw new ScriptParsingException("Child element of script tag was not text");
+ Logger.msg(6, "Script.parseScriptXML() - script:" + mScript);
+ }
+ }
+ }
+
+ protected void addInputParam(String name, String type) throws ParameterException
+ {
+ try
+ {
+ addInputParam(name, Class.forName(type));
+ }
+ catch (ClassNotFoundException ex)
+ {
+ throw new ParameterException("Input parameter " + name + " specifies class " + type + " which was not found.");
+ }
+ }
+
+ protected void addInputParam(String name, Class<?> type) throws ParameterException
+ {
+ Parameter inputParam = new Parameter(name, type);
+
+
+
+ Logger.msg(6, "ScriptExecutor.parseScriptXML() - declared parameter " + name + " (" + type + ")");
+ //add parameter to hashtable
+ mInputParams.put(inputParam.getName(), inputParam);
+ mAllInputParams.put(inputParam.getName(), inputParam);
+
+ }
+
+ protected void addIncludedInputParam(String name, Class<?> type) throws ParameterException
+ {
+ // check if we already have it
+ if (mAllInputParams.containsKey(name)) {
+ Parameter existingParam = mAllInputParams.get(name);
+ // check the types match
+ if (existingParam.getType() == type)
+ return; // matches
+ else // error
+ throw new ParameterException("Parameter conflict. Parameter'"+name+"' is declared as "
+ +existingParam.getType().getName()+" is declared in another script as "+type.getName());
+ }
+
+ Parameter inputParam = new Parameter(name);
+ inputParam.setType(type);
+
+ //add parameter to hashtable
+ mAllInputParams.put(inputParam.getName(), inputParam);
+
+ }
+
+ protected void addOutput(String name, String type) throws ParameterException
+ {
+ try
+ {
+ addOutput(name, Class.forName(type));
+ }
+ catch (ClassNotFoundException ex) {
+ throw new ParameterException("Output parameter " + name + " specifies class " + type + " which was not found.");
+ }
+ }
+
+ protected void addOutput(String name, Class<?> type) throws ParameterException
+ {
+ String outputName = name;
+
+ Parameter outputParam = new Parameter(name, type);
+
+ if (mOutputParams.containsKey(outputName))
+ throw new ParameterException("Output parameter '"+outputName+"' declared more than once.");
+
+ mOutputParams.put(outputName, outputParam);
+
+ }
+
+ /**
+ * Gets all declared parameters
+ * @return HashMap of String (name), com.c2kernel.scripting.Parameter (param)
+ * @see com.c2kernel.scripting.Parameter
+ */
+ public HashMap<String, Parameter> getInputParams()
+ {
+ return mInputParams;
+ }
+
+ /**
+ * Gets all declared parameters, including those of imported scripts
+ * @return HashMap of String (name), com.c2kernel.scripting.Parameter (param)
+ * @see com.c2kernel.scripting.Parameter
+ */
+ public HashMap<String, Parameter> getAllInputParams()
+ {
+ return mAllInputParams;
+ }
+
+ /**
+ * Submits an input parameter to the script. Must be declared by name and type in the script XML.
+ *
+ * @param name - input parameter name from the script xml
+ * @param value - object to use for this parameter
+ * @throws ParameterException - name not found or wrong type
+ */
+ public void setInputParamValue(String name, Object value) throws ParameterException
+ {
+ Parameter param = mInputParams.get(name);
+
+ if (!mAllInputParams.containsKey(name))
+ throw new ParameterException("Parameter " + name + " not found in parameter list");
+
+ if (param != null) { // param is in this script
+ if (value.getClass() != param.getType())
+ throw new ParameterException(
+ "Parameter " + name + " is wrong type \n" + "Required: " + param.getType().toString() + "\n" + "Supplied: " + value.getClass().toString());
+ beans.put(name, value);
+ Logger.msg(7, "Script.setInputParamValue() - " + name + ": " + value.toString());
+ param.setInitialised(true);
+ }
+
+ // pass param down to child scripts
+ for (Script importScript : mIncludes) {
+ importScript.setInputParamValue(name, value);
+ }
+ }
+
+ /**
+ * Executes the script with the submitted parameters. All declared input parametes should have been set first.
+ *
+ * @return The return value depends on the way the output type was declared in the script xml.
+ * <ul><li>If there was no output class declared then null is returned
+ * <li>If a class was declared, but not named, then the object returned by the script is checked
+ * to be of that type, then returned.
+ * <li>If the output value was named and typed, then an object of that class is created and
+ * passed to the script as an input parameter. The script should set this before it returns.
+ * </ul>
+ * @throws ScriptingEngineException - input parameters weren't set, there was an error executing the script, or the output was invalid
+ */
+ public Object execute() throws ScriptingEngineException
+ {
+
+ // check input params
+ StringBuffer missingParams = new StringBuffer();
+ for (Parameter thisParam : mInputParams.values()) {
+ if (!thisParam.getInitialised())
+ missingParams.append(thisParam.getName()).append("\n");
+ }
+ // croak if any missing
+ if (missingParams.length() > 0)
+ throw new ScriptingEngineException("Execution aborted, the following declared parameters were not set: \n" + missingParams.toString());
+
+ for (Parameter outputParam : mOutputParams.values()) {
+ if (outputParam.getName() == null) continue; // If the name is null then it's the return type. don't pre-register it
+ Logger.msg(8, "Script.setOutput() - Initialising output bean '" + outputParam.getName() + "'");
+ Object emptyObject;
+ try {
+ emptyObject = outputParam.getType().newInstance();
+ } catch (Exception e) {
+ emptyObject = null;
+ }
+ beans.put(outputParam.getName(), emptyObject);
+
+ }
+
+ // execute the child scripts
+ for (Script importScript : mIncludes) {
+ importScript.execute();
+ }
+
+ // run the script
+ Object returnValue = null;
+ try
+ {
+ Logger.msg(7, "Script.execute() - Executing script");
+ if (engine == null)
+ throw new ScriptingEngineException("Script engine not set. Cannot execute scripts.");
+ returnValue = engine.eval(mScript, beans);
+ Logger.msg(8, "Script.execute() - script returned \"" + returnValue + "\"");
+ }
+ catch (Exception ex)
+ {
+ throw new ScriptingEngineException("Error executing script: " + ex.getMessage());
+ }
+
+ // if no outputs are defined, return null
+ if (mOutputParams.size() == 0) {
+ Logger.msg(4, "Script.execute() - No output params. Returning null.");
+ return null;
+ }
+
+ HashMap<String, Object> outputs = new HashMap<String, Object>();
+
+ for (Parameter outputParam : mOutputParams.values()) {
+ String outputName = outputParam.getName();
+ Object outputValue;
+ if (outputName == null)
+ outputValue = returnValue;
+ else
+ outputValue = beans.get(outputParam.getName());
+ Logger.msg(4, "Script.execute() - Output parameter "+outputName+"="+(outputValue==null?"null":outputValue.toString()));
+
+ // check the class
+ if (outputValue!=null && !(outputParam.getType().isInstance(outputValue)))
+ throw new ScriptingEngineException(
+ "Script output "+outputName+" was not null or instance of " + outputParam.getType().getName() + ", it was a " + outputValue.getClass().getName());
+
+ Logger.msg(8, "Script.execute() - output "+outputValue);
+ if (mOutputParams.size() == 1) {
+ Logger.msg(6, "Script.execute() - only one parameter, returning "+(outputValue==null?"null":outputValue.toString()));
+ return outputValue;
+ }
+ outputs.put(outputParam.getName(), outputValue);
+ }
+
+ return outputs;
+ }
+
+ /**
+ * Resets the scripting enviroment, clearing all state and parameters for another execution.
+ */
+ public void reset()
+ {
+ for (Parameter parameter : mInputParams.values())
+ parameter.setInitialised(false);
+ beans = engine.createBindings();
+ }
+
+ static public void main(String[] args) {
+ for(ScriptEngineFactory sef: new ScriptEngineManager().getEngineFactories()) {
+ System.out.println(sef.getEngineName()+" v"+sef.getEngineVersion()+" using "+sef.getLanguageName()+" v"+sef.getLanguageVersion());
+ }
+ }
+}
|
