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.nuxeo.runtime.scripting.ScriptingComponent.java

@Override
public CompiledScript compile(String path) throws ScriptException {
    ScriptEngine engine = getEngineByFileName(path);
    if (engine != null) {
        if (engine instanceof Compilable) {
            try {
                Reader reader = new FileReader(getScriptFile(path));
                try {
                    return ((Compilable) engine).compile(reader);
                } finally {
                    reader.close();//from  www .  jav a  2s.  c om
                }
            } catch (IOException e) {
                throw new ScriptException(e);
            }
        } else {
            throw new ScriptException(
                    "Script Engine " + engine.getFactory().getEngineName() + " is not compilable");
        }
    } else {
        throw new ScriptException("No suitable script engine found for the file " + path);
    }
}

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

@Override
public Object eval(String path) throws ScriptException {
    ScriptEngine engine = getEngineByFileName(path);
    if (engine != null) {
        try {//from w w w.j a  va  2s  . c  o m
            Reader reader = new FileReader(getScriptFile(path));
            try {
                return engine.eval(reader);
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    } else {
        throw new ScriptException("No script engine was found for the file: " + path);
    }
}

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

@Override
public Object eval(String path, ScriptContext ctx) throws ScriptException {
    ScriptEngine engine = getEngineByFileName(path);
    if (engine != null) {
        try {/*from w ww.j  a  v  a  2 s .c  o m*/
            Reader reader = new FileReader(getScriptFile(path));
            try {
                return engine.eval(reader, ctx);
            } finally {
                reader.close();
            }
        } catch (IOException e) {
            throw new ScriptException(e);
        }
    } else {
        throw new ScriptException("No script engine was found for the file: " + path);
    }
}

From source file:org.ow2.parserve.PARServeEngine.java

@Override
public Object eval(String script, ScriptContext ctx) throws ScriptException {
    // Transfer all bindings from context into the rengine env
    if (ctx == null) {
        throw new ScriptException("No script context specified");
    }/* w  w w .  ja v a 2 s  .co m*/
    Bindings bindings = ctx.getBindings(ScriptContext.ENGINE_SCOPE);
    if (bindings == null) {
        throw new ScriptException("No bindings specified in the script context");
    }

    serverEval = false;
    Map<String, Serializable> jobVariables = (Map<String, Serializable>) bindings
            .get(SchedulerConstants.VARIABLES_BINDING_NAME);
    if (jobVariables != null) {
        serverEval = "true".equals(jobVariables.get(PARSERVE_SERVEREVAL));
    }

    Map<String, String> resultMetadata = (Map<String, String>) bindings
            .get(SchedulerConstants.RESULT_METADATA_VARIABLE);

    engine = new PARServeConnection(Rsession.newInstanceTry("Script", rServeConf), serverEval);

    try {

        initializeTailer(bindings, ctx);
        Object resultValue = null;

        if (!serverEval) {
            prepareExecution(ctx, bindings);
        }
        // if there is an exception during the parsing, a ScriptException is immediately thrown
        engine.checkParsing(script, ctx);

        // otherwise each step is followed till the end
        REXP rexp = engine.engineEval(script, ctx);

        resultValue = retrieveResultVariable(ctx, bindings, rexp);

        retrieveOtherVariable(SelectionScript.RESULT_VARIABLE, ctx, bindings);

        retrieveOtherVariable(FlowScript.loopVariable, ctx, bindings);
        retrieveOtherVariable(FlowScript.branchSelectionVariable, ctx, bindings);
        retrieveOtherVariable(FlowScript.replicateRunsVariable, ctx, bindings);

        if (!serverEval) {
            this.updateJobVariables(jobVariables, ctx);
            this.updateResultMetadata(resultMetadata, ctx);
        }

        // server evaluation is for one task only, it must not be propagated
        if (serverEval) {
            jobVariables.put(PARSERVE_SERVEREVAL, "false");
        }

        return resultValue;
    } catch (Exception ex) {
        engine.writeExceptionToError(ex, ctx);
        throw new ScriptException(ex.getMessage());
    } finally {
        engine.terminateOutput(ctx);

        if (!serverEval) {
            engine.engineEval("setwd('" + Utils.toRpath(System.getProperty("java.io.tmpdir")) + "')", ctx);
        }
        engine.end();

        terminateTailer();

        if (!serverEval) {
            // PRC-32 A ScriptException() must be thrown if the script calls stop() function
            ScriptException toThrow = null;
            if (lastErrorMessage != null) {
                toThrow = new ScriptException(lastErrorMessage);
            }
            if (toThrow != null) {
                throw toThrow;
            }
        }
    }
}

From source file:org.ow2.parserve.PARServeEngine.java

/**
 * Initialize the Tailer thread used to read R output
 *//* w  w  w.jav a 2  s.c om*/
private void initializeTailer(Bindings bindings, ScriptContext ctx) throws ScriptException {
    if (!serverEval) {
        try {
            Tailer tailer = null;
            outputFile = createOuputFile(bindings);

            listener = new PARScriptTailerListener(ctx.getWriter());
            tailer = new Tailer(outputFile, listener, TAILER_PERIOD, false, true);

            tailerThread = new Thread(tailer, "PARServeEngine Tailer");
            tailerThread.setDaemon(true);
            tailerThread.start();

            engine.initializeOutput(outputFile, ctx);

        } catch (Exception e) {
            logger.error("Error during tailer init:", e);
            throw new ScriptException(e);
        }
    }
}

From source file:org.ow2.parserve.PARServeEngine.java

@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
    String s;//from  w w  w  . j a v  a  2s . co  m
    try {
        s = CharStreams.toString(reader);
    } catch (IOException ex) {
        throw new ScriptException(ex);
    }
    return eval(s, context);
}

From source file:org.ow2.proactive.scheduler.task.java.JavaClassScriptEngine.java

@Override
public Object eval(String userExecutableClassName, ScriptContext context) throws ScriptException {

    try {//  ww w.  ja v  a  2  s.com
        JavaExecutable javaExecutable = getExecutable(userExecutableClassName);

        JavaStandaloneExecutableInitializer execInitializer = new JavaStandaloneExecutableInitializer();
        PrintStream output = new PrintStream(new WriterOutputStream(context.getWriter()), true);
        execInitializer.setOutputSink(output);
        PrintStream error = new PrintStream(new WriterOutputStream(context.getErrorWriter()), true);
        execInitializer.setErrorSink(error);

        Map<String, byte[]> propagatedVariables = null;
        if (context.getAttribute(SchedulerConstants.VARIABLES_BINDING_NAME) != null) {
            propagatedVariables = SerializationUtil.serializeVariableMap(
                    ((VariablesMap) context.getAttribute(SchedulerConstants.VARIABLES_BINDING_NAME))
                            .getPropagatedVariables());
            execInitializer.setPropagatedVariables(propagatedVariables);
        } else {
            execInitializer.setPropagatedVariables(Collections.<String, byte[]>emptyMap());
        }

        if (context.getAttribute(Script.ARGUMENTS_NAME) != null) {
            execInitializer.setSerializedArguments(
                    (Map<String, byte[]>) ((Serializable[]) context.getAttribute(Script.ARGUMENTS_NAME))[0]);
        } else {
            execInitializer.setSerializedArguments(Collections.<String, byte[]>emptyMap());
        }

        if (context.getAttribute(SchedulerConstants.CREDENTIALS_VARIABLE) != null) {
            execInitializer.setThirdPartyCredentials(
                    (Map<String, String>) context.getAttribute(SchedulerConstants.CREDENTIALS_VARIABLE));
        } else {
            execInitializer.setThirdPartyCredentials(Collections.<String, String>emptyMap());
        }

        if (context.getAttribute(SchedulerConstants.MULTI_NODE_TASK_NODESURL_BINDING_NAME) != null) {
            List<String> nodesURLs = (List<String>) context
                    .getAttribute(SchedulerConstants.MULTI_NODE_TASK_NODESURL_BINDING_NAME);
            execInitializer.setNodesURL(nodesURLs);
        } else {
            execInitializer.setNodesURL(Collections.<String>emptyList());
        }

        javaExecutable.internalInit(execInitializer, context);

        Serializable execute = javaExecutable
                .execute((TaskResult[]) context.getAttribute(SchedulerConstants.RESULTS_VARIABLE));

        if (propagatedVariables != null) {
            ((Map<String, Serializable>) context.getAttribute(SchedulerConstants.VARIABLES_BINDING_NAME))
                    .putAll(javaExecutable.getVariables());
        }

        output.close();
        error.close();
        return execute;

    } catch (Throwable e) {
        throw new ScriptException(new TaskException(getStackTraceAsString(e), e));
    }
}

From source file:org.ow2.proactive.scheduler.task.java.JavaClassScriptEngine.java

@Override
public Object eval(Reader reader, ScriptContext context) throws ScriptException {
    try {/* www. j  a v  a2s.c  o m*/
        return eval(IOUtils.toString(reader), context);
    } catch (IOException e) {
        throw new ScriptException(e);
    }
}

From source file:org.rhq.bindings.ScriptEngineFactory.java

/**
 * This method is similar to the {@link #getScriptEngine(String, PackageFinder, StandardBindings)} method
 * but additionally applies a security wrapper on the returned script engine so that the scripts execute
 * with the provided java permissions.//from w w w .  j av a  2 s.  c o m
 * 
 * @see #getScriptEngine(String, PackageFinder, StandardBindings)
 */
public static ScriptEngine getSecuredScriptEngine(final String language, final PackageFinder packageFinder,
        final StandardBindings bindings, final PermissionCollection permissions)
        throws ScriptException, IOException {
    CodeSource src = new CodeSource(new URL("http://rhq-project.org/scripting"), (Certificate[]) null);
    ProtectionDomain scriptDomain = new ProtectionDomain(src, permissions);
    AccessControlContext ctx = new AccessControlContext(new ProtectionDomain[] { scriptDomain });
    try {
        return AccessController.doPrivileged(new PrivilegedExceptionAction<ScriptEngine>() {
            @Override
            public ScriptEngine run() throws Exception {
                //This might seem a bit excessive but is necessary due to the 
                //change in security handling in the rhino script engine
                //that occured in Java6u27 (due to a CVE desribed here:
                //https://bugzilla.redhat.com/show_bug.cgi?id=CVE-2011-3544)

                //In Java 6u26 and earlier, it was enough to wrap a script engine
                //in the sandbox and everything would work.

                //Java 6u27 introduced new behavior where the rhino script engine
                //remembers the access control context with which it has been 
                //constructed and combines that with the callers protection domain
                //when a script is executed. Because this class has all perms and
                //all the code in RHQ that called ScriptEngine.eval* also
                //had all perms, the scripts would never be sandboxed even if the call
                //was pushed through the SandboxedScriptEngine.

                //This means that the below wrapping is necessary for the security
                //to work in java6 pre u27 while the surrounding privileged block 
                //is necessary for the security to be applied in java6 u27 and later.
                return new SandboxedScriptEngine(getScriptEngine(language, packageFinder, bindings),
                        permissions);
            }
        }, ctx);
    } catch (PrivilegedActionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else if (cause instanceof ScriptException) {
            throw (ScriptException) cause;
        } else {
            throw new ScriptException(e);
        }
    }
}

From source file:org.structr.core.script.StructrScriptEngine.java

@Override
public Object eval(final String script, final ScriptContext context) throws ScriptException {

    try {/* w w  w .  ja v  a2s  .  co  m*/

        final ActionContext actionContext = (ActionContext) get("_actionContext");
        final GraphObject entity = (GraphObject) get("_entity");

        return Functions.evaluate(actionContext, entity, script);

    } catch (FrameworkException fex) {

        // wrap FrameworkException in ScriptException and re-throw
        throw new ScriptException(fex);
    }
}