Example usage for javax.script ScriptContext ENGINE_SCOPE

List of usage examples for javax.script ScriptContext ENGINE_SCOPE

Introduction

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

Prototype

int ENGINE_SCOPE

To view the source code for javax.script ScriptContext ENGINE_SCOPE.

Click Source Link

Document

EngineScope attributes are visible during the lifetime of a single ScriptEngine and a set of attributes is maintained for each engine.

Usage

From source file:io.github.jeddict.jcode.util.FileUtil.java

/**
 * In-memory template api/*from   w w  w. ja  v  a  2s  .  c  o  m*/
 *
 * @param templateContent
 * @param values
 * @return
 */
public static String expandTemplateContent(String templateContent, Map<String, Object> values) {
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new StringReader(templateContent);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private ConsoleOutputBean eval(ScriptEngine engine, String evalScript, Map<String, ?> bindings,
        final ConsoleOutputBean consoleOutputBean) throws ScriptException {
    updateBindings(engine, ScriptContext.ENGINE_SCOPE, new HashMap<String, Object>() {
        {//from  ww  w  .j  ava  2s. c o m
            put("out", new PrintWriter(consoleOutputBean.getOut(), true));
            put("err", new PrintWriter(consoleOutputBean.getErr(), true));
        }
    });

    if (bindings != null && !bindings.isEmpty()) {
        updateBindings(engine, ScriptContext.ENGINE_SCOPE, bindings);
    }

    engine.getContext().setWriter(consoleOutputBean.getOut());
    engine.getContext().setErrorWriter(consoleOutputBean.getErr());
    engine.getContext().setReader(new NullReader(0));

    consoleOutputBean.setEvalResult(engine.eval(evalScript, engine.getContext()));

    return consoleOutputBean;
}

From source file:org.apache.nifi.processors.script.ExecuteScript.java

/**
 * Evaluates the given script body (or file) using the current session, context, and flowfile. The script
 * evaluation expects a FlowFile to be returned, in which case it will route the FlowFile to success. If a script
 * error occurs, the original FlowFile will be routed to failure. If the script succeeds but does not return a
 * FlowFile, the original FlowFile will be routed to no-flowfile
 *
 * @param context        the current process context
 * @param sessionFactory provides access to a {@link ProcessSessionFactory}, which
 *                       can be used for accessing FlowFiles, etc.
 * @throws ProcessException if the scripted processor's onTrigger() method throws an exception
 *///  w  ww .java  2  s.c  om
@Override
public void onTrigger(ProcessContext context, ProcessSessionFactory sessionFactory) throws ProcessException {
    synchronized (scriptingComponentHelper.isInitialized) {
        if (!scriptingComponentHelper.isInitialized.get()) {
            scriptingComponentHelper.createResources();
        }
    }
    ScriptEngine scriptEngine = scriptingComponentHelper.engineQ.poll();
    ComponentLog log = getLogger();
    if (scriptEngine == null) {
        // No engine available so nothing more to do here
        return;
    }
    ProcessSession session = sessionFactory.createSession();
    try {

        try {
            Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
            if (bindings == null) {
                bindings = new SimpleBindings();
            }
            bindings.put("session", session);
            bindings.put("context", context);
            bindings.put("log", log);
            bindings.put("REL_SUCCESS", REL_SUCCESS);
            bindings.put("REL_FAILURE", REL_FAILURE);

            // Find the user-added properties and set them on the script
            for (Map.Entry<PropertyDescriptor, String> property : context.getProperties().entrySet()) {
                if (property.getKey().isDynamic()) {
                    // Add the dynamic property bound to its full PropertyValue to the script engine
                    if (property.getValue() != null) {
                        bindings.put(property.getKey().getName(), context.getProperty(property.getKey()));
                    }
                }
            }

            scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

            // Execute any engine-specific configuration before the script is evaluated
            ScriptEngineConfigurator configurator = scriptingComponentHelper.scriptEngineConfiguratorMap
                    .get(scriptingComponentHelper.getScriptEngineName().toLowerCase());

            // Evaluate the script with the configurator (if it exists) or the engine
            if (configurator != null) {
                configurator.eval(scriptEngine, scriptToRun, scriptingComponentHelper.getModules());
            } else {
                scriptEngine.eval(scriptToRun);
            }

            // Commit this session for the user. This plus the outermost catch statement mimics the behavior
            // of AbstractProcessor. This class doesn't extend AbstractProcessor in order to share a base
            // class with InvokeScriptedProcessor
            session.commit();
        } catch (ScriptException e) {
            throw new ProcessException(e);
        }
    } catch (final Throwable t) {
        // Mimic AbstractProcessor behavior here
        getLogger().error("{} failed to process due to {}; rolling back session", new Object[] { this, t });
        session.rollback(true);
        throw t;
    } finally {
        scriptingComponentHelper.engineQ.offer(scriptEngine);
    }
}

From source file:nl.geodienstencentrum.maven.plugin.sass.AbstractSassMojo.java

/**
 * Execute the Sass Compilation Ruby Script.
 *
 * @param sassScript/*  w  ww .  j a v a 2 s . co m*/
 *            the sass script
 * @throws MojoExecutionException
 *             the mojo execution exception
 * @throws MojoFailureException
 *             the mojo failure exception
 */
protected void executeSassScript(final String sassScript) throws MojoExecutionException, MojoFailureException {
    if (this.skip) {
        return;
    }

    final Log log = this.getLog();
    System.setProperty("org.jruby.embed.localcontext.scope", "threadsafe");

    log.debug("Execute Sass Ruby script:\n\n" + sassScript + "\n\n");
    final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    final ScriptEngine jruby = scriptEngineManager.getEngineByName("jruby");
    try {
        final CompilerCallback compilerCallback = new CompilerCallback(log);
        jruby.getBindings(ScriptContext.ENGINE_SCOPE).put("compiler_callback", compilerCallback);
        jruby.eval(sassScript);
        if (this.failOnError && compilerCallback.hadError()) {
            throw new MojoFailureException("Sass compilation encountered errors (see above for details).");
        }
    } catch (final ScriptException e) {
        throw new MojoExecutionException("Failed to execute Sass ruby script:\n" + sassScript, e);
    }
    log.debug("\n");
}

From source file:org.apache.nifi.scripting.ScriptFactory.java

private void updateEngine() throws IOException, ScriptException {
    final String extension = getExtension(scriptFileName);
    // if engine is thread safe, it's being reused...if it's a JrubyEngine it
    File scriptFile = new File(this.scriptFileName);
    ScriptEngine scriptEngine = engineFactory.getNewEngine(scriptFile, extension);
    scriptText = getScriptText(scriptFile, extension);
    Map<String, Object> localThreadVariables = new HashMap<>();
    String loggerVariableKey = getVariableName("GLOBAL", "logger", extension);
    localThreadVariables.put(loggerVariableKey, logger);
    String propertiesVariableKey = getVariableName("INSTANCE", "properties", extension);
    localThreadVariables.put(propertiesVariableKey, new HashMap<String, String>());
    localThreadVariables.put(ScriptEngine.FILENAME, scriptFileName);
    if (scriptEngine instanceof Compilable) {
        Bindings bindings = new SimpleBindings(localThreadVariables);
        scriptEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        compiledScript = ((Compilable) scriptEngine).compile(scriptText);
    }// w w  w . j av a 2s  . c  om
    logger.debug("Updating Engine!!");
}

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");
    }/*from ww  w  . ja v  a 2s . c om*/
    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:fr.ens.transcriptome.corsen.calc.CorsenHistoryResults.java

/**
 * Calc the custom value.//from  ww w.  j a  v  a2s .  c o m
 * @param cr CorsenResults
 * @return the custom value
 */
private double calcCustomValue(final CorsenResult cr) {

    if (this.script == null)
        return Double.NaN;

    Map<Particle3D, Distance> in = cr.getMinDistances();

    long inCount = 0;
    long outCount = 0;

    for (Map.Entry<Particle3D, Distance> e : in.entrySet()) {

        final Particle3D particle = e.getKey();
        final long intensity = particle.getIntensity();
        final Distance distance = e.getValue();

        inCount += intensity;

        final Bindings b = this.script.getEngine().getBindings(ScriptContext.ENGINE_SCOPE);

        b.put("i", intensity);
        b.put("d", distance.getDistance());

        try {

            Object o = this.script.eval();

            if (o instanceof Boolean && ((Boolean) o) == true)
                outCount += intensity;

        } catch (ScriptException e1) {
        }
    }

    return (double) outCount / (double) inCount;
}

From source file:org.labkey.nashorn.NashornController.java

private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine;// www.  ja v a 2s.c  o m
    ScriptContext context;

    Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() {
        @Override
        @NotNull
        public ScriptEngine call() throws Exception {
            NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
            ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" });
            return engine;
        }
    };

    if (useSession) {
        HttpServletRequest req = getViewContext().getRequest();
        engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext);
    } else {
        engine = createContext.call();
    }

    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext()));

    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine
    // some docs mention enginScope.get("nashorn.global"), but that is also null
    if (null == globalScope)
        globalScope = (Bindings) engineScope.get("nashorn.global");
    if (null == globalScope)
        globalScope = engineScope;
    globalScope.put("console", new Console());

    return new Pair<>(engine, engine.getContext());
}

From source file:com.hypersocket.upgrade.UpgradeServiceImpl.java

private ScriptEngine buildEngine(Map<String, Object> beans, URL script, ScriptContext context)
        throws ScriptException, IOException {
    // Create a new scope for the beans
    Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE);
    for (String key : beans.keySet()) {
        engineScope.put(key, beans.get(key));
    }//w  ww. j  a v  a2s  .  c o m
    engineScope.put("ctx", springContext);

    // Execute the script
    String name = script.getPath();
    int idx;
    if ((idx = name.indexOf("/")) > -1) {
        name = name.substring(idx + 1);
    }
    if ((idx = name.lastIndexOf(".")) > -1) {
        name = name.substring(idx + 1);
    }
    ScriptEngine engine = manager.getEngineByExtension(name);
    if (engine == null) {
        throw new IOException("No scripting engine found for " + name);
    }
    return engine;
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (VERBOSE_LOADING) {
        log.info("Loading Script: " + file.getAbsolutePath());
    }/*from w  w  w  . j  av a2 s. c  om*/

    if (PURGE_ERROR_LOG) {
        String name = file.getAbsolutePath() + ".error.log";
        File errorLog = new File(name);
        if (errorLog.isFile()) {
            errorLog.delete();
        }
    }

    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);

        setCurrentLoadingScript(file);
        ScriptContext ctx = engine.getContext();
        try {
            engine.setContext(context);
            if (USE_COMPILED_CACHE) {
                CompiledScript cs = _cache.loadCompiledScript(engine, file);
                cs.eval(context);
            } else {
                Compilable eng = (Compilable) engine;
                CompiledScript cs = eng.compile(reader);
                cs.eval(context);
            }
        } finally {
            engine.setContext(ctx);
            setCurrentLoadingScript(null);
            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }
    } else {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);
        setCurrentLoadingScript(file);
        try {
            engine.eval(reader, context);
        } finally {
            setCurrentLoadingScript(null);
            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }

    }
}