List of usage examples for javax.script ScriptException ScriptException
public ScriptException(Exception e)
ScriptException
wrapping an Exception
thrown by an underlying interpreter. From source file:org.apache.synapse.mediators.bsf.NashornJavaScriptMessageContext.java
/** * Returns the parsed xml document./*from ww w. j a v a 2s . c om*/ * @param text xml string or document needed to be parser * @return parsed document */ public Document parseXml(String text) throws ScriptException { InputSource sax = new InputSource(new java.io.StringReader(text)); DOMParser parser = new DOMParser(); Document doc; try { parser.parse(sax); doc = parser.getDocument(); doc.getDocumentElement().normalize(); } catch (SAXException | IOException e) { ScriptException scriptException = new ScriptException("Failed to parse provided xml"); scriptException.initCause(e); throw scriptException; } return doc; }
From source file:org.apache.synapse.mediators.bsf.NashornJavaScriptMessageContext.java
/** * Saves the payload of this message context as a JSON payload. * * @param jsonPayload Javascript native object to be set as the message body * @throws ScriptException in case of creating a JSON object out of * the javascript native object. *///from w ww. j a v a 2 s .co m public void setPayloadJSON(Object jsonPayload) throws ScriptException { org.apache.axis2.context.MessageContext messageContext; messageContext = ((Axis2MessageContext) mc).getAxis2MessageContext(); byte[] json = { '{', '}' }; if (jsonPayload instanceof String) { json = jsonPayload.toString().getBytes(); } else if (jsonPayload != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); serializeJSON(jsonPayload, out); json = out.toByteArray(); } catch (IOException | ScriptException e) { logger.error("#setPayloadJSON. Could not retrieve bytes from JSON object.", e); } } // save this JSON object as the new payload. try { JsonUtil.getNewJsonPayload(messageContext, json, 0, json.length, true, true); } catch (AxisFault axisFault) { throw new ScriptException(axisFault); } Object jsonObject = scriptEngine.eval(JsonUtil.newJavaScriptSourceReader(messageContext)); setJsonObject(mc, jsonObject); }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
/** * {@inheritDoc}//from w w w.ja v a 2 s. c om */ @Override public Object eval(final String script, final ScriptContext context) throws ScriptException { try { final String val = (String) context.getAttribute(KEY_REFERENCE_TYPE, ScriptContext.ENGINE_SCOPE); ReferenceBundle bundle = ReferenceBundle.getHardBundle(); if (val != null && val.length() > 0) { if (val.equalsIgnoreCase(REFERENCE_TYPE_SOFT)) { bundle = ReferenceBundle.getSoftBundle(); } else if (val.equalsIgnoreCase(REFERENCE_TYPE_WEAK)) { bundle = ReferenceBundle.getWeakBundle(); } else if (val.equalsIgnoreCase(REFERENCE_TYPE_PHANTOM)) { bundle = ReferenceBundle.getPhantomBundle(); } } globalClosures.setBundle(bundle); } catch (ClassCastException cce) { /*ignore.*/ } try { registerBindingTypes(context); final Class clazz = getScriptClass(script); if (null == clazz) throw new ScriptException("Script class is null"); return eval(clazz, context); } catch (Exception e) { throw new ScriptException(e); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
/** * {@inheritDoc}//from w w w . j av a2 s . c o m */ @Override public CompiledScript compile(final String scriptSource) throws ScriptException { try { return new GroovyCompiledScript(this, getScriptClass(scriptSource)); } catch (Exception e) { throw new ScriptException(e); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
Object eval(final Class scriptClass, final ScriptContext context) throws ScriptException { final Binding binding = new Binding(context.getBindings(ScriptContext.ENGINE_SCOPE)) { @Override/*from w w w . j ava2 s . c o m*/ public Object getVariable(String name) { synchronized (context) { int scope = context.getAttributesScope(name); if (scope != -1) { return context.getAttribute(name, scope); } // Redirect script output to context writer, if out var is not already provided if ("out".equals(name)) { final Writer writer = context.getWriter(); if (writer != null) { return (writer instanceof PrintWriter) ? (PrintWriter) writer : new PrintWriter(writer, true); } } // Provide access to engine context, if context var is not already provided if ("context".equals(name)) { return context; } } throw new MissingPropertyException(name, getClass()); } @Override public void setVariable(String name, Object value) { synchronized (context) { int scope = context.getAttributesScope(name); if (scope == -1) { scope = ScriptContext.ENGINE_SCOPE; } context.setAttribute(name, value, scope); } } }; try { // if this class is not an instance of Script, it's a full-blown class then simply return that class if (!Script.class.isAssignableFrom(scriptClass)) { return scriptClass; } else { final Script scriptObject = InvokerHelper.createScript(scriptClass, binding); for (Method m : scriptClass.getMethods()) { final String name = m.getName(); globalClosures.put(name, new MethodClosure(scriptObject, name)); } final MetaClass oldMetaClass = scriptObject.getMetaClass(); scriptObject.setMetaClass(new DelegatingMetaClass(oldMetaClass) { @Override public Object invokeMethod(final Object object, final String name, final Object args) { if (args == null) { return invokeMethod(object, name, MetaClassHelper.EMPTY_ARRAY); } else if (args instanceof Tuple) { return invokeMethod(object, name, ((Tuple) args).toArray()); } else if (args instanceof Object[]) { return invokeMethod(object, name, (Object[]) args); } else { return invokeMethod(object, name, new Object[] { args }); } } @Override public Object invokeMethod(final Object object, final String name, final Object args[]) { try { return super.invokeMethod(object, name, args); } catch (MissingMethodException mme) { return callGlobal(name, args, context); } } @Override public Object invokeStaticMethod(final Object object, final String name, final Object args[]) { try { return super.invokeStaticMethod(object, name, args); } catch (MissingMethodException mme) { return callGlobal(name, args, context); } } }); final Object o = scriptObject.run(); // if interpreter mode is enable then local vars of the script are promoted to engine scope bindings. if (interpreterModeEnabled) { final Map<String, Object> localVars = (Map<String, Object>) context .getAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME); if (localVars != null) { localVars.entrySet().forEach(e -> { // closures need to be cached for later use if (e.getValue() instanceof Closure) globalClosures.put(e.getKey(), (Closure) e.getValue()); context.setAttribute(e.getKey(), e.getValue(), ScriptContext.ENGINE_SCOPE); }); // get rid of the temporary collected vars context.removeAttribute(COLLECTED_BOUND_VARS_MAP_VARNAME, ScriptContext.ENGINE_SCOPE); localVars.clear(); } } return o; } } catch (Exception e) { throw new ScriptException(e); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
private Object invokeImpl(final Object thiz, final String name, final Object args[]) throws ScriptException, NoSuchMethodException { if (name == null) { throw new NullPointerException("Method name can not be null"); }// w w w.ja v a 2 s . c o m try { if (thiz != null) { return InvokerHelper.invokeMethod(thiz, name, args); } } catch (MissingMethodException mme) { throw new NoSuchMethodException(mme.getMessage()); } catch (Exception e) { throw new ScriptException(e); } return callGlobal(name, args); }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java
private String readFully(final Reader reader) throws ScriptException { final char arr[] = new char[8192]; final StringBuilder buf = new StringBuilder(); int numChars; try {/* w w w . j a v a 2s. c o m*/ while ((numChars = reader.read(arr, 0, arr.length)) > 0) { buf.append(arr, 0, numChars); } } catch (IOException exp) { throw new ScriptException(exp); } return buf.toString(); }
From source file:org.fireflow.engine.invocation.impl.AbsServiceInvoker.java
public static Map<String, Object> resolveInputAssignments(RuntimeContext runtimeContext, WorkflowSession session, ProcessInstance processInstance, ActivityInstance activityInstance, ServiceBinding serviceBinding, ServiceDef service) throws ScriptException { List<Assignment> inputAssignmentList = serviceBinding.getInputAssignments(); // OperationDef operation = serviceBinding.getOperation(); // List<Input> inputs = operation.getInputs(); Map<String, Object> contextVars = ScriptEngineHelper.fulfillScriptContext(session, runtimeContext, processInstance, activityInstance); //?xmlinputxmlorg.w3c.dom.Document Map<String, Object> inputsContext = new HashMap<String, Object>(); for (Assignment assignment : inputAssignmentList) { Expression toExpression = assignment.getTo(); if (toExpression.getName() == null || toExpression.getName().trim().equals("")) { throw new ScriptException( "The name of the assignment's To-Expression can NOT be empty. More information : the body of the To-Expression is '" + toExpression.getBody() + "';the activity id is " + activityInstance.getNodeId()); }//from w w w . j a v a 2 s . c om if (toExpression.getDataType() != null && !NameSpaces.JAVA.getUri().equals(toExpression.getDataType().getNamespaceURI()) && inputsContext.get(toExpression.getName()) == null) { Document doc = initDocument(service.getXmlSchemaCollection(), toExpression.getDataType()); inputsContext.put(toExpression.getName(), doc); } } contextVars.put(ScriptContextVariableNames.INPUTS, inputsContext); Map<String, Object> inputParamValues = ScriptEngineHelper.resolveInputParameters(runtimeContext, serviceBinding.getInputAssignments(), contextVars); return inputParamValues; }
From source file:org.fireflow.engine.invocation.impl.AbsServiceInvoker.java
/** * ?Schemaorg.w3c.dom.Document;// w w w . ja va2 s . co m * TODO SchemaChoice???? * @param xmlSchemaCollection * @param elementQName * @return */ protected static Document initDocument(XmlSchemaCollection xmlSchemaCollection, QName rootElementQName) throws ScriptException { try { Document doc = DOMInitializer.generateDocument(xmlSchemaCollection, rootElementQName); return doc; } catch (ParserConfigurationException e) { throw new ScriptException(e); } }
From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java
public static Map<String, Object> resolveAssignments(RuntimeContext runtimeContext, List<Assignment> assignments, Map<String, Object> contextVars) throws ScriptException { if (assignments == null || assignments.size() == 0) { return null; }//from ww w .ja v a 2 s.com Map<String, Object> jxpathRoot = new HashMap<String, Object>(); if (contextVars.get(ScriptContextVariableNames.INPUTS) != null) { jxpathRoot.put(ScriptContextVariableNames.INPUTS, contextVars.get(ScriptContextVariableNames.INPUTS)); } else { jxpathRoot.put(ScriptContextVariableNames.INPUTS, new HashMap<String, Object>()); } if (contextVars.get(ScriptContextVariableNames.OUTPUTS) != null) { jxpathRoot.put(ScriptContextVariableNames.OUTPUTS, contextVars.get(ScriptContextVariableNames.OUTPUTS)); } else { jxpathRoot.put(ScriptContextVariableNames.OUTPUTS, new HashMap<String, Object>()); } jxpathRoot.put(ScriptContextVariableNames.PROCESS_VARIABLES, new HashMap<String, Object>()); jxpathRoot.put(ScriptContextVariableNames.ACTIVITY_VARIABLES, new HashMap<String, Object>()); jxpathRoot.put(ScriptContextVariableNames.SESSION_ATTRIBUTES, new HashMap<String, Object>()); for (Assignment assignment : assignments) { Expression fromExpression = assignment.getFrom(); Object obj = evaluateExpression(runtimeContext, fromExpression, contextVars); if (fromExpression.getDataType() != null && obj != null) { try { obj = JavaDataTypeConvertor.dataTypeConvert(fromExpression.getDataType(), obj, null); } catch (ClassCastException e) { throw new ScriptException(e); } catch (ClassNotFoundException e) { throw new ScriptException(e); } } // TODO To ?JXpath??? Expression toExpression = assignment.getTo(); QName dataType = toExpression.getDataType(); if (dataType != null && dataType.getNamespaceURI().equals(NameSpaces.JAVA.getUri()) && obj != null) {// ?? try { obj = JavaDataTypeConvertor.dataTypeConvert(dataType, obj, null); } catch (ClassCastException e) { throw new ScriptException(e); } catch (ClassNotFoundException e) { throw new ScriptException(e); } } else { // XSD?? //TODO (?)datestring if (obj instanceof java.util.Date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); obj = df.format((java.util.Date) obj); } } JXPathContext jxpathContext = JXPathContext.newContext(jxpathRoot); jxpathContext.setFactory(w3cDomFactory); Map<String, String> nsMap = toExpression.getNamespaceMap(); Iterator<String> prefixIterator = nsMap.keySet().iterator(); while (prefixIterator.hasNext()) { String prefix = prefixIterator.next(); String nsUri = nsMap.get(prefix); jxpathContext.registerNamespace(prefix, nsUri); } //? jxpathContext.createPathAndSetValue(toExpression.getBody(), obj); } return jxpathRoot; }