Example usage for javax.script ScriptException ScriptException

List of usage examples for javax.script ScriptException ScriptException

Introduction

In this page you can find the example usage for javax.script ScriptException ScriptException.

Prototype

public ScriptException(Exception e) 

Source Link

Document

Creates a ScriptException wrapping an Exception thrown by an underlying interpreter.

Usage

From source file:org.fireflow.engine.modules.script.ScriptEngineHelper.java

@SuppressWarnings({ "restriction", "rawtypes", "unchecked" })
public static void assignOutputToVariable(WorkflowSession session, RuntimeContext runtimeContext,
        ProcessInstance processInstance, ActivityInstance activityInstance, List<Assignment> assignmentsList,
        Map<String, Object> contextVars) throws ScriptException {

    WorkflowSessionLocalImpl localSession = (WorkflowSessionLocalImpl) session;

    if (assignmentsList == null || assignmentsList.size() == 0)
        return;/*from ww w .  j a  va  2  s. c om*/

    Map<String, Object> result = resolveAssignments(runtimeContext, assignmentsList, contextVars);
    //System.out.println("===??Assignment is "+result);
    if (result == null)
        return;

    Map<String, Object> procInstVars = (Map<String, Object>) result
            .get(ScriptContextVariableNames.PROCESS_VARIABLES);
    if (procInstVars != null && procInstVars.size() > 0) {
        Iterator<String> keys = procInstVars.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                Object value = procInstVars.get(key);
                if (value instanceof Message) {
                    processInstance.setVariableValue(session, key, ((Message) value).getPayload(),
                            ((Message) value).getHeaders());
                } else {
                    processInstance.setVariableValue(session, key, value);
                }

            } catch (InvalidOperationException e) {
                throw new ScriptException(e);
            }
        }
    }

    Map<String, Object> actInstVars = (Map<String, Object>) result
            .get(ScriptContextVariableNames.ACTIVITY_VARIABLES);
    if (actInstVars != null && actInstVars.size() > 0) {
        Iterator<String> keys = actInstVars.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            try {
                Object value = actInstVars.get(key);
                if (value instanceof Message) {
                    activityInstance.setVariableValue(session, key, ((Message) value).getPayload(),
                            ((Message) value).getHeaders());
                } else {
                    activityInstance.setVariableValue(session, key, value);
                }

            } catch (InvalidOperationException e) {
                throw new ScriptException(e);
            }
        }
    }

    Map<String, Object> sessionAttrs = (Map<String, Object>) result
            .get(ScriptContextVariableNames.SESSION_ATTRIBUTES);
    if (sessionAttrs != null && sessionAttrs.size() > 0) {
        Iterator<String> keys = sessionAttrs.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            localSession.setAttribute(key, sessionAttrs.get(key));
        }
    }

}

From source file:org.icesquirrel.jsr223.IcesquirrelScriptEngine.java

@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {

    SquirrelInterpretedScript sis = new SquirrelInterpretedScript();

    /*/*from w w w. ja  va  2s  .c  o m*/
     * If the global bindings is already a SquirrelTable, use that directly.
     * A squirrel table is kind of compatible with a bindings object, except
     * the key may be an Object instead of a string.
     */
    Bindings bindings = context.getBindings(ScriptContext.GLOBAL_SCOPE);
    if (bindings instanceof BindingsAdapter) {
        sis.setRootTable(((BindingsAdapter) bindings).getTable());
    } else {
        // Otherwise copy global bindings into our root table
        for (Entry<String, Object> s : bindings.entrySet()) {
            bind(sis, s);
        }
    }

    // Now the engine scoped bindings. If these are already a squirrel
    // table, add them as
    // a delegate, otherwise copy
    Bindings engBindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
    SquirrelTable addedDelegate = null;
    if (engBindings instanceof BindingsAdapter) {
        BindingsAdapter ba = (BindingsAdapter) engBindings;
        if (ba.getTable() != sis.getRootTable()) {
            SquirrelTable pt = sis.setRootTable(ba.getTable());
            if (pt != null && !ba.getTable().getDelegates().contains(pt)) {
                ba.getTable().addDelegate(pt);
                addedDelegate = pt;
            }
        }
    } else {
        for (Entry<String, Object> s : engBindings.entrySet()) {
            bind(sis, s);
        }
    }

    SquirrelRuntime runtime = SquirrelRuntime.getDefaultRuntime();
    SquirrelExecutionContext ctx = null;
    if (!SquirrelExecutionContext.is()) {
        ctx = new SquirrelExecutionContext();
        ctx.start(sis.getRootTable(), runtime, new SquirrelInterpretedProcessor());
    }

    try {
        try {
            // TODO encoding
            sis.execute(new ReaderInputStream(reader));
        } catch (SquirrelException se) {
            // TODO line number etc
            throw new ScriptException(se);
        } catch (Exception e) {
            // TODO line number etc
            throw new ScriptException(e);
        }
        Object result = sis.getResult();
        if (result instanceof SquirrelObjectWrapper) {
            return ((SquirrelObjectWrapper) result).getObject();
        }
        return result;
    } finally {
        if (addedDelegate != null) {
            sis.getRootTable().removeDelegate(addedDelegate);
        }
        if (ctx != null) {
            ctx.stop();
        }
    }
}

From source file:org.jahia.utils.ScriptEngineUtils.java

private ScriptEngine getScriptEngineFrom(String nameOrExtension, boolean fromExtension) throws ScriptException {
    ScriptEngine scriptEngine = fromExtension ? enginesManager.getEngineByExtension(nameOrExtension)
            : enginesManager.getEngineByName(nameOrExtension);

    if (scriptEngine == null) {
        throw new ScriptException(
                "Script engine not found for " + (fromExtension ? "extension: " : "name: ") + nameOrExtension);
    }//w  w  w . j a  va  2s .  c  o m
    initEngine(scriptEngine);
    return scriptEngine;
}

From source file:org.jgentleframework.integration.scripting.ScriptingInstantiationInterceptor.java

@Override
public Object instantiate(ObjectInstantiation oi) throws Throwable {

    Object result = null;/*w w  w. ja  v  a  2 s  .  co m*/
    Class<?> target = oi.getTargetClass();
    Definition definition = this.definitionManager.getDefinition(target);
    if (definition.isAnnotationPresent(ScriptingInject.class)) {
        if (!target.isInterface()) {
            if (log.isFatalEnabled()) {
                log.fatal("Could not binding to Scripting service",
                        new ScriptException("Target class must be a interface!"));
            }
        }
        final ScriptingInject scriptingInject = definition.getAnnotation(ScriptingInject.class);
        Object previous = oi.getPreviousResult();
        if (previous == null) {
            ScriptEngineManager engineManager = new ScriptEngineManager();
            ScriptEngine engine = engineManager.getEngineByName(scriptingInject.lang().getType());
            if (engine == null) {
                if (log.isFatalEnabled()) {
                    log.fatal(
                            "Script engine with name : " + scriptingInject.lang().getType() + " is not found!",
                            new ScriptException("Script engine with name : " + scriptingInject.lang().getType()
                                    + " is not found!"));
                }
                throw new ScriptException(
                        "Script engine with name : " + scriptingInject.lang().getType() + " is not found!");
            }
            File parentFile = null;
            if (!(PathType.CLASSPATH.equals(scriptingInject.pathType())
                    || PathType.CLASSPATH.equals(scriptingInject.pathType()))) {
                parentFile = new File(scriptingInject.pathType().getType());
            }
            File sourceFile = null;
            if (parentFile != null) {
                sourceFile = new File(parentFile, scriptingInject.scriptFile());
            } else {
                if (PathType.CLASSPATH.equals(scriptingInject.pathType())) {
                    sourceFile = new File(ScriptingInstantiationInterceptor.class
                            .getResource(scriptingInject.scriptFile()).toURI());
                } else {
                    sourceFile = new File(scriptingInject.scriptFile());
                }
            }
            engine.eval(new FileReader(sourceFile));
            Invocable inv = (Invocable) engine;
            final Object scriptObject = inv.getInterface(target);
            result = scriptObject;
            final Enhancer enhancer = new Enhancer();
            enhancer.setInterfaces(new Class<?>[] { target });
            enhancer.setCallback(new MethodInterceptor() {
                @Override
                public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy)
                        throws Throwable {

                    if (method.getName().equals("hashCode")) {
                        final int prime = 31;
                        int result = 1;
                        result = prime * result + super.hashCode();
                        result = prime * result + enhancer.hashCode();
                        return result;
                    } else {
                        MethodInvocation invocation = new BasicMethodInvocation(obj, method, args);
                        return invoke(invocation, scriptObject);
                    }
                }

                protected Object invoke(MethodInvocation invocation, Object stub) throws NoSuchMethodException,
                        IllegalArgumentException, IllegalAccessException, InvocationTargetException {

                    Object result = null;
                    Method method = null;
                    Method methodType = invocation.getMethod();
                    Class<?> clazz = stub.getClass();
                    Class<?>[] classType = ReflectUtils.getClassTypeOf(invocation.getArguments());
                    method = ReflectUtils.getSupportedMethod(clazz, methodType.getName(), classType);
                    result = method.invoke(stub, invocation.getArguments());
                    return result;
                }
            });
            if (oi.args() != null && oi.argTypes() != null)
                result = enhancer.create(oi.argTypes(), oi.args());
            else
                result = enhancer.create();
            oi.setPreviousResult(result);
        } else {
            if (log.isFatalEnabled()) {
                log.fatal(
                        "Does not support multible Instantiation Interceptor "
                                + "conjointly with Scripting Instantiation",
                        new ScriptException("Does not support multible Instantiation Interceptor!"));
            }
        }
        return oi.proceed();
    } else {
        if (log.isWarnEnabled()) {
            log.warn("The target interface is not annotated with [" + ScriptingInject.class + "]");
        }
    }
    return result;
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

/**
 * Loads an script application./* w  w  w.j a v a2s  . co m*/
 *
 * @param aAppName The application name
 * @param aAppPath The application home path
 * @param aHotLoad
 * @return
 * @throws Exception
 */
private void loadApp(final String aAppName, String aAppPath, boolean aHotLoad) throws Exception {
    // notifying before app reload event here
    BaseScriptApp lScript = mApps.get(aAppName);
    if (null != lScript) {
        lScript.notifyEvent(BaseScriptApp.EVENT_BEFORE_APP_RELOAD, new Object[] { aHotLoad });
        if (!aHotLoad) {
            destroyAppBeans(lScript);
        }
    }

    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");

    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);

    // support hot app load
    if (aHotLoad && mApps.containsKey(aAppName)) {
        try {
            // loading app
            mApps.get(aAppName).eval(lBootstrap.getPath());
        } catch (ScriptException lEx) {
            mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
            mApps.remove(aAppName);
            throw new ScriptException(lEx.getMessage());
        }
    } else {
        LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
        ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

        final ScriptEngine lScriptApp;
        if ("js".equals(lExt)) {
            // making "nashorn" the default engine for JavaScript
            if (null != lManager.getEngineByName("nashorn")) {
                lScriptApp = lManager.getEngineByName("nashorn");
            } else {
                lScriptApp = lManager.getEngineByExtension(lExt);
            }
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }

        // crating the high level script app instance
        if ("js".equals(lExt)) {
            mApps.put(aAppName, new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader));
        } else {
            String lMsg = "The extension '" + lExt + "' is not currently supported!";
            mLog.error(lMsg);
            throw new Exception(lMsg);
        }

        final BaseScriptApp lApp = mApps.get(aAppName);
        // loading application into security sandbox
        Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                try {
                    // loading app
                    lApp.eval(lBootstrap.getPath());
                    return null;
                } catch (Exception lEx) {
                    mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
                    mApps.remove(aAppName);
                    throw new RuntimeException(lEx);
                }
            }
        });
    }

    // notifying app loaded event
    mApps.get(aAppName).notifyEvent(BaseScriptApp.EVENT_APP_LOADED, new Object[] { aHotLoad });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application loaded successfully!");
    }
}

From source file:org.mule.module.scripting.component.Scriptable.java

public Object runScript(Bindings bindings) throws ScriptException {
    Object result;/*from w w w. ja  va2 s  . c om*/
    try {
        RegistryLookupBindings registryLookupBindings = new RegistryLookupBindings(muleContext.getRegistry(),
                bindings);
        if (compiledScript != null) {
            result = compiledScript.eval(registryLookupBindings);
        } else {
            result = scriptEngine.eval(scriptText, registryLookupBindings);
        }

        // The result of the script can be returned directly or it can
        // be set as the variable "result".
        if (result == null) {
            result = registryLookupBindings.get("result");
        }
    } catch (ScriptException e) {
        // re-throw
        throw e;
    } catch (Exception ex) {
        throw new ScriptException(ex);
    }
    return result;
}

From source file:org.nuxeo.ecm.webengine.scripting.Scripting.java

public static CompiledScript compileScript(ScriptEngine engine, File file) throws ScriptException {
    if (engine instanceof Compilable) {
        Compilable comp = (Compilable) engine;
        try {/*  w ww  .  j  a v  a2 s.c  o m*/
            Reader reader = new FileReader(file);
            try {
                return comp.compile(reader);
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    } else {
        return null;
    }
}

From source file:org.nuxeo.ecm.webengine.scripting.Scripting.java

protected Object _runScript(ScriptFile script, Map<String, Object> args) throws Exception {
    SimpleBindings bindings = new SimpleBindings();
    if (args != null) {
        bindings.putAll(args);/*  w  ww.ja v a  2  s  . c om*/
    }
    String ext = script.getExtension();
    // check for a script engine
    ScriptEngine engine = getEngineManager().getEngineByExtension(ext);
    if (engine != null) {
        ScriptContext ctx = new SimpleScriptContext();
        ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        CompiledScript comp = getCompiledScript(engine, script.getFile()); // use cache for compiled scripts
        if (comp != null) {
            return comp.eval(ctx);
        } // compilation not supported - eval it on the fly
        try {
            Reader reader = new FileReader(script.getFile());
            try { // TODO use __result__ to pass return value for engine that doesn't returns like jython
                Object result = engine.eval(reader, ctx);
                if (result == null) {
                    result = bindings.get("__result__");
                }
                return result;
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    }
    return null;
}

From source file:org.nuxeo.ecm.webengine.security.guards.ScriptGuard.java

private CompiledScript compile(String type, String content) throws ScriptException {
    if (engine == null) {
        engine = Framework.getLocalService(WebEngine.class).getScripting().getEngineManager()
                .getEngineByName(type);//from ww w.  jav  a2s  .  c o m
    }
    if (engine != null) {
        if (engine instanceof Compilable) {
            return ((Compilable) engine).compile(content);
        } else {
            return null; // script is not compilable
        }
    } else {
        throw new ScriptException("No suitable script engine found for the file " + type);
    }
}

From source file:org.nuxeo.runtime.scripting.ScriptingComponent.java

@Override
public CompiledScript getScript(String name) throws ScriptException, IOException {
    ScriptDescriptor sd = scripts.get(name);
    if (sd != null) {
        if (sd.script != null) {
            return sd.script;
        }//w w w  . ja  va 2s  .  c om
        ScriptEngine engine = getEngineByFileName(sd.src);
        if (engine == null) {
            log.warn("Script engine not found for: " + sd.src);
        } else if (engine instanceof Compilable) {
            try {
                Reader reader = getReader(sd);
                try {
                    sd.script = ((Compilable) engine).compile(reader);
                    return sd.script;
                } finally {
                    reader.close();
                }
            } catch (ScriptException e) {
                throw new ScriptException(
                        "Script file was not found: " + sd.src + " when trying to load " + name);
            }
        } else {
            throw new ScriptException(
                    "Not a compilable scripting engine: " + engine.getFactory().getEngineName());
        }
    }
    return null;
}