Example usage for javax.script Bindings putAll

List of usage examples for javax.script Bindings putAll

Introduction

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

Prototype

public void putAll(Map<? extends String, ? extends Object> toMerge);

Source Link

Document

Adds all the mappings in a given Map to this Bindings .

Usage

From source file:de.ingrid.iplug.ckan.utils.ScriptEngine.java

/**
 * Execute the given scripts with the given parameters
 * @param scripts The script files// w  w w .  j a va 2s.c o  m
 * @param parameters The parameters
 * @param compile Boolean indicating whether to compile the script or not
 * @return Map with the absolute paths of the scripts as keys and the execution results as values
 * If an execution returns null, the result will not be added
 * @throws Exception
 */
public static Map<String, Object> execute(Resource[] scripts, Map<String, Object> parameters, boolean compile)
        throws Exception {

    Map<Integer, Bindings> bindings = new Hashtable<Integer, Bindings>();
    Map<String, Object> results = new Hashtable<String, Object>();

    for (Resource script : scripts) {
        // get the engine for the script
        javax.script.ScriptEngine engine = getEngine(script);

        // initialize/get the bindings
        if (!bindings.containsKey(engine.hashCode())) {
            Bindings newBindings = engine.createBindings();
            newBindings.putAll(parameters);
            bindings.put(engine.hashCode(), newBindings);
        }
        Bindings curBindings = bindings.get(engine.hashCode());

        // execute the script
        CompiledScript compiledScript = null;
        Object result = null;
        if (compile && (compiledScript = getCompiledScript(script)) != null) {
            result = compiledScript.eval(curBindings);
        } else {
            result = engine.eval(new InputStreamReader(script.getInputStream()), curBindings);
        }
        if (result != null) {
            results.put(script.getFilename(), result);
        }
    }
    return results;
}

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

public static void expandTemplate(Reader reader, Writer writer, Map<String, Object> values,
        Charset targetEncoding) throws IOException {
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    bind.putAll(values);
    bind.put(ENCODING_PROPERTY_NAME, targetEncoding.name());

    try {/*  w  w w . j a va 2  s .com*/
        eng.getContext().setWriter(writer);
        eng.eval(reader);
    } catch (ScriptException ex) {
        throw new IOException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

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

public static String expandTemplate(String inputTemplatePath, Map<String, Object> values) {
    InputStream contentStream = loadResource(inputTemplatePath);
    StringWriter writer = new StringWriter();
    ScriptEngine eng = getScriptEngine();
    Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    if (values != null) {
        bind.putAll(values);
    }/* w  ww. jav a 2 s . c o  m*/
    bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
    eng.getContext().setWriter(writer);
    Reader is = new InputStreamReader(contentStream);
    try {
        eng.eval(is);
    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }

    return writer.toString();
}

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

/**
 * In-memory template api//from   w  w  w .  ja v  a2 s  .  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:io.lavagna.service.ApiHooksService.java

private static void executeScript(String name, CompiledScript script, Map<String, Object> scope) {
    try {//from ww w . j  a  v a 2s .c o  m
        ScriptContext newContext = new SimpleScriptContext();
        Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
        engineScope.putAll(scope);
        engineScope.put("log", LOG);
        engineScope.put("GSON", Json.GSON);
        engineScope.put("restTemplate", new RestTemplate());
        script.eval(newContext);
    } catch (ScriptException ex) {
        LOG.warn("Error while executing script " + name, ex);
    }
}

From source file:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars, Writer writer)
        throws ScriptException {
    try {//w w  w. jav  a  2 s  . c o m
        ScriptEngine scriptEngine = getEngine();
        SimpleScriptContext simpleScriptContext = new SimpleScriptContext();
        Bindings bindings = scriptEngine.createBindings();
        bindings.putAll(contextVars);
        simpleScriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        executePreExecuteScripts(simpleScriptContext);
        simpleScriptContext.setWriter(writer);
        CompiledScript compiledScript = getCachedScript(script);
        Object object = compiledScript.eval(simpleScriptContext);
        writer.flush();
        if (object == null)
            return bindings;
        return object;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars) throws ScriptException {
    try {//  w  ww . ja va  2 s .  co m
        ScriptEngine scriptEngine = getEngine();
        Bindings bindings = scriptEngine.createBindings();
        ScriptContext scriptContext = new SimpleScriptContext();
        scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
        bindings.putAll(contextVars);
        executePreExecuteScripts(scriptContext);
        CompiledScript compiledScript = getCachedScript(script);
        Object object = compiledScript.eval(scriptContext);
        if (object == null)
            return bindings;
        return object;
    } catch (javax.script.ScriptException e) {
        throw new ScriptException(e);
    }
}

From source file:com.qwazr.webapps.transaction.ControllerManager.java

private void handleJavascript(WebappTransaction transaction, File controllerFile)
        throws IOException, ScriptException, PrivilegedActionException {
    WebappHttpResponse response = transaction.getResponse();
    response.setHeader("Cache-Control", "max-age=0, no-cache, no-store");
    Bindings bindings = scriptEngine.createBindings();
    IOUtils.CloseableList closeables = new IOUtils.CloseableList();
    bindings.put("console", new ScriptConsole());
    bindings.put("request", transaction.getRequest());
    bindings.put("response", transaction.getResponse());
    bindings.put("session", transaction.getRequest().getSession());
    bindings.putAll(transaction.getRequest().getAttributes());
    FileReader fileReader = new FileReader(controllerFile);
    try {//from ww  w  . j av  a2  s.  com
        ScriptUtils.evalScript(scriptEngine, RestrictedAccessControlContext.INSTANCE, fileReader, bindings);
    } finally {
        fileReader.close();
    }
}

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

@SuppressWarnings({ "SameParameterValue" })
private void updateBindings(ScriptEngine engine, int scope, Map<String, ?> mergeValues) {
    Bindings bindings = engine.getContext().getBindings(scope);
    if (bindings == null) {
        bindings = engine.createBindings();
        engine.getContext().setBindings(bindings, scope);
    }// www . j av a 2  s .c om
    bindings.putAll(mergeValues);
}

From source file:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

@Override
public boolean execute(TestData data, TestResult result, final boolean debug) {
    // Interpret the file
    testData = data;//from  www. ja v  a  2s . co  m
    testResult = result;

    if (debug) {
        testScriptBreakPointEventHandler.addTestScriptBreakpointListener(scriptBreakpoint);
    }

    try {
        Bindings bindings = engine.createBindings();
        engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

        engine.eval("import sys as __sys");
        engine.eval("if not globals().has_key('__initModules'):\n" + "  __initModules = __sys.modules.keys()\n"
                + "else:\n" + "  for m in __sys.modules.keys():\n" + "    if m not in __initModules:\n"
                + "      del __sys.modules[m]", globalBindings);

        // add all global bindinds
        bindings.putAll(globalBindings);

        if (testSuite != null) {
            // add pythonlib subdirectories of test script directory up to test suites directory, to python path
            List<String> additionalPythonPath = getAdditionalPythonPath();
            String pythonPathScript = "";
            for (String pythonlib : additionalPythonPath) {
                pythonPathScript += "__sys.path.append(r'" + pythonlib + "')\n";
            }
            engine.eval(pythonPathScript);
        }

        // reset doStep count / step id / step name stacks
        engine.eval("doStep.countStack = [0]\n" + "doStep.stepIdStack = []\n" + "doStep.stepNameStack = []\n");

        // add testAPI, testData and scriptBreakpoint to bindings
        bindings.put("this", this);
        engine.eval("testAPI = __TestAPIWrapper(this)");
        bindings.remove("__TestAPIWrapper");
        bindings.remove("this");
        bindings.put("testData", scriptTestData);
        bindings.put("DoubleWithPrecision", DoubleWithPrecision.class);
        bindings.put("QTasteException", QTasteException.class);
        bindings.put("QTasteDataException", QTasteDataException.class);
        bindings.put("QTasteTestFailException", QTasteTestFailException.class);
        bindings.put("__scriptBreakpoint", scriptBreakpoint);
        globalBindings.put("testScript", this);

        // create QTaste module with testAPI, testData, DoubleWithPrecision, doStep, doSteps, doSubStep, logger and Status
        engine.eval("class __QTaste_Module:\n" + "    def __init__(self):\n"
                + "        self.importTestScript= importTestScript\n"
                + "        self.isInTestScriptImport= isInTestScriptImport\n"
                + "        self.testAPI= testAPI\n" + "        self.testData = testData\n"
                + "        self.DoubleWithPrecision = DoubleWithPrecision\n" + "        self.doStep = doStep\n"
                + "        self.doSteps = doSteps\n" + "        self.doSubStep = doStep\n"
                + "        self.doSubSteps = doSteps\n" + "        self.logger = logger\n"
                + "        self.Status = Status\n" + "        self.QTasteException = QTasteException\n"
                + "        self.QTasteDataException = QTasteDataException\n"
                + "        self.QTasteTestFailException = QTasteTestFailException\n"
                + "__sys.modules['qtaste'] = __QTaste_Module()");

        // remove testAPI, testData, DoubleWithPrecision, doStep, doSteps, logger and Status from bindinds
        bindings.remove("__QTaste_Module");
        bindings.remove("importTestScript");
        bindings.remove("isCalledFromMainTestScript");
        bindings.remove("testAPI");
        bindings.remove("testData");
        bindings.remove("DoubleWithPrecision");
        bindings.remove("doStep");
        bindings.remove("doSteps");
        bindings.remove("logger");
        bindings.remove("Status");
        bindings.remove("QTasteException");
        bindings.remove("QTasteDataException");
        bindings.remove("QTasteTestFailException");

        // Check if test was aborted by user before execute testscript.py
        if (TestEngine.isAbortedByUser()) {
            return false;
        }

        if (!debug) {
            engine.eval("execfile(r'" + fileName + "', globals())");
        } else {
            // execute in debugger
            engine.eval(scriptDebuggerClassCode);
            engine.eval("__debugger = __ScriptDebugger()");
            bindings.remove("__bdb");
            bindings.remove("__ScriptDebugger");
            for (Breakpoint b : breakPointEventHandler.getBreakpoints()) {
                engine.eval("__debugger.set_break(r'" + b.getFileName() + "', " + b.getLineIndex() + ")");
            }
            engine.eval("__debugger.runcall(execfile, r'" + fileName + "', globals())");
        }
    } catch (ScriptException e) {
        handleScriptException(e, result);
    } finally {
        if (debug) {
            testScriptBreakPointEventHandler.removeTestScriptBreakpointListener(scriptBreakpoint);
        }
    }
    return true;
}