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:org.jahia.tools.patches.GroovyPatcher.java

public static void executeScripts(Resource[] scripts) {
    long timer = System.currentTimeMillis();
    logger.info("Found new patch scripts {}. Executing...", StringUtils.join(scripts));

    for (Resource script : scripts) {
        try {// www  . j  av a  2 s.c  om
            long timerSingle = System.currentTimeMillis();
            String scriptContent = getContent(script);
            if (StringUtils.isNotEmpty(scriptContent)) {
                ScriptEngine engine = getEngine();
                ScriptContext ctx = new SimpleScriptContext();
                ctx.setWriter(new StringWriter());
                Bindings bindings = engine.createBindings();
                bindings.put("log", new LoggerWrapper(logger, logger.getName(), ctx.getWriter()));
                ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

                engine.eval(scriptContent, ctx);
                String result = ((StringWriter) ctx.getWriter()).getBuffer().toString();
                logger.info("Execution of script {} took {} ms with result:\n{}", new String[] {
                        script.toString(), String.valueOf(System.currentTimeMillis() - timerSingle), result });
            } else {
                logger.warn("Content of the script {} is either empty or cannot be read. Skipping.");
            }
            rename(script, ".installed");
        } catch (Exception e) {
            logger.error("Execution of script " + script + " failed with error: " + e.getMessage(), e);
            rename(script, ".failed");
        }
    }

    logger.info("Execution took {} ms", (System.currentTimeMillis() - timer));
}

From source file:io.github.jeddict.jcode.parser.ejs.EJSParser.java

private ScriptEngine createEngine() {
    CompiledScript cscript;//from   ww  w.  j  a  v a2s.  co m
    Bindings bindings;
    ScriptEngine scriptEngine = new NashornScriptEngineFactory().getScriptEngine("--language=es6");//engine = new ScriptEngineManager().getEngineByName("nashorn");
    try {
        try {
            if (base == null) {
                base = IOUtils.toString(EJSParser.class.getClassLoader()
                        .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/base.js"), "UTF-8");
            }
            if (ejs == null) {
                ejs = IOUtils.toString(EJSParser.class.getClassLoader()
                        .getResourceAsStream("io/github/jeddict/jcode/parser/ejs/resources/ejs.js"), "UTF-8");
            }
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        }

        scriptEngine.eval(base);
        Compilable compilingEngine = (Compilable) scriptEngine;
        cscript = compilingEngine.compile(ejs);
        bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        cscript.eval(bindings);
        scriptEngine.eval(scripts.toString());

        for (Map<String, Object> context : contexts) {
            context.keySet().stream().forEach((key) -> {
                try {
                    bindings.put(key, context.get(key));
                    if (context.get(key) instanceof Collection) {
                        scriptEngine.eval(String.format("%s = Java.from(%s);", key, key));
                    }
                } catch (ScriptException ex) {
                    Exceptions.printStackTrace(ex);
                }
            });
        }

    } catch (ScriptException ex) {
        Exceptions.printStackTrace(ex);
    }
    return scriptEngine;
}

From source file:org.apache.camel.builder.script.ScriptBuilder.java

/**
 * Sets the attribute on the context so that it is available to the script
 * as a variable in the {@link ScriptContext#ENGINE_SCOPE}
 *
 * @param name the name of the attribute
 * @param value the attribute value/* w w  w.j av a2  s  . com*/
 * @return this builder
 */
public ScriptBuilder attribute(String name, Object value) {
    getScriptContext().setAttribute(name, value, ScriptContext.ENGINE_SCOPE);
    return this;
}

From source file:org.xwiki.rendering.internal.macro.ctsreport.CTSDataMacro.java

@Override
public List<Block> execute(Object unusedParameters, String content, MacroTransformationContext context)
        throws MacroExecutionException {
    // We consider the content as containing wiki syntax so we parse it and render it with the Plain text parser.
    XDOM xdom = this.contentParser.parse(content, context, true, false);
    DefaultWikiPrinter printer = new DefaultWikiPrinter();
    this.plainTextRenderer.render(xdom, printer);
    String parsedContent = printer.toString();

    // Parse the results
    TestParser parser = new TestParser();
    List<Result> results = new ArrayList<Result>();
    for (String resultLine : parsedContent.split("[\\r\\n]+")) {
        results.add(parser.parse(resultLine));
    }// w w  w .j ava2  s .  c  o m

    // Bind 2 variables in the Script Context so that they can be used by Script macros
    ScriptContext scriptContext = getScriptContext();
    if (scriptContext != null) {
        ResultExtractor extractor = new ResultExtractor();
        Set<String> testNames = extractor.extractByTestName(results);
        scriptContext.setAttribute("ctsTestNames", testNames, ScriptContext.ENGINE_SCOPE);
        Map<String, Pair<Set<Test>, Set<Test>>> tests = extractor.extractBySyntax(results);
        extractor.normalize(testNames, tests);
        scriptContext.setAttribute("ctsTests", tests, ScriptContext.ENGINE_SCOPE);
    } else {
        this.logger.warn("Script Context not found in the Execution Context. CTS Data variable not bound!");
    }

    return Collections.emptyList();
}

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

@Override
public Object execute(Script<CompiledScript> script, Writer writer) throws ScriptException {
    try {//from   w  w w .  ja v  a2 s  . co  m
        ScriptEngine scriptEngine = getEngine();
        CompiledScript compiledScript = getCachedScript(script);
        SimpleScriptContext simpleScriptContext = new SimpleScriptContext();
        executePreExecuteScripts(simpleScriptContext);
        simpleScriptContext.setWriter(writer);
        Object object = compiledScript.eval(simpleScriptContext);
        writer.flush();
        if (object == null)
            return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        return object;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:tk.elevenk.restfulrobot.testsuite.TestSuite.java

/**
 * Runs the test cases in the test suite
 *//*ww  w .  j  a va2s.  c  o  m*/
public void executeTestCases() {

    // initialize variables
    this.passes = this.failures = this.errors = 0;
    this.id = this.toString();
    this.timestamp = new Timestamp(Calendar.getInstance().getTime().getTime()).toString();
    long testSuiteTime = System.nanoTime();

    // add this test suite to the reporter if it has test cases
    if (this.testCases != null && this.testCases.size() > 0) {
        reporter.addTestSuite(this);

        // prepare the engine
        engine.put("DataPool", this.dataPool);
    }

    // loop through each test case and run them
    for (TestCase testCase : testCases) {

        // set current test case in data pool
        dataPool.setCurrentTestCase(testCase);

        // set the test suite of the test case to this suite
        testCase.setTestSuite(this);

        // add api definitions to script engine
        engine.put("Test", testCase);
        engine.put("Request", testCase.request);
        engine.put("Response", testCase.response);
        engine.put("defaults", null);
        engine.put("none", null);

        // set logger based on test case that is running
        logger = LogManager.getLogger(testCase.getClass().getName());
        logger.info("Starting test case of type " + testCase.getTestType());

        // run test script
        try {
            testCase.runTest(engine);
        } catch (Exception e) {
            logger.error(ExceptionUtils.getStackTrace(e));
        }
        // remove test case from engine context after completed
        engine.getBindings(ScriptContext.ENGINE_SCOPE).remove("Test");

    }

    // set runtime of test suite
    runtime = (System.nanoTime() - testSuiteTime) / RestfulRobot.TIME_DIVISOR;

}

From source file:org.jahia.services.render.scripting.JSR223Script.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display/*from w  ww  .  ja va2s.c o  m*/
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    ScriptEngine scriptEngine = null;

    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(view.getModule().getChainedClassLoader());

    try {
        scriptEngine = ScriptEngineUtils.getInstance().scriptEngine(view.getFileExtension());

        if (scriptEngine != null) {
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            Enumeration<?> attrNamesEnum = context.getRequest().getAttributeNames();
            while (attrNamesEnum.hasMoreElements()) {
                String currentAttributeName = (String) attrNamesEnum.nextElement();
                if (!"".equals(currentAttributeName)) {
                    bindings.put(currentAttributeName, context.getRequest().getAttribute(currentAttributeName));
                }
            }
            bindings.put("params", context.getRequest().getParameterMap());
            Reader scriptContent = null;
            try {
                InputStream scriptInputStream = getViewInputStream();
                if (scriptInputStream != null) {
                    scriptContent = new InputStreamReader(scriptInputStream);
                    scriptContext.setWriter(new StringWriter());
                    scriptContext.setErrorWriter(new StringWriter());
                    // The following binding is necessary for Javascript, which doesn't offer a console by default.
                    bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                    scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                            ScriptContext.GLOBAL_SCOPE);

                    scriptEngine.eval(scriptContent, scriptContext);

                    StringWriter writer = (StringWriter) scriptContext.getWriter();
                    return writer.toString().trim();
                } else {
                    throw new RenderException(
                            "Error while retrieving input stream for the resource " + view.getPath());
                }
            } catch (ScriptException e) {
                throw new RenderException("Error while executing script " + view.getPath(), e);
            } catch (IOException e) {
                throw new RenderException(
                        "Error while retrieving input stream for the resource " + view.getPath(), e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }

    } catch (ScriptException e) {
        logger.error(e.getMessage(), e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }

    return null;
}

From source file:org.xwiki.job.handler.internal.question.QuestionJobResourceReferenceHandler.java

@Override
public void handle(ParentResourceReference reference) throws ResourceReferenceHandlerException {
    List<String> jobId = reference.getPathSegments();

    Job job = this.executor.getJob(jobId);
    if (job == null) {
        throw new ResourceReferenceHandlerException("Cannot find any running job with id " + jobId);
    }//from   w  ww.  j a va 2s. com

    Object question = job.getStatus().getQuestion();
    if (question == null) {
        throw new ResourceReferenceHandlerException("The job with id " + jobId + " does not have any question");
    }

    Request request = this.container.getRequest();

    String prefix = "question/";
    String contentType = "text/html; charset=utf-8";

    // POST request means answer
    if (request instanceof ServletRequest) {
        HttpServletRequest httpRequest = ((ServletRequest) request).getHttpServletRequest();

        if (httpRequest.getMethod().equals("POST")) {
            String token = httpRequest.getParameter("form_token");

            // TODO: should probably move this check in some filter triggered by an annotation
            if (this.csrf.isTokenValid(token)) {
                answer(httpRequest, job, jobId, question);

                prefix = "answer/";
                contentType = "application/json";
            } else {
                // TODO: Throw some exception
            }
        }
    }

    String jobType = job.getType();

    // Provide informations about the job to the template
    this.scriptContextManager.getCurrentScriptContext().setAttribute("job", job, ScriptContext.ENGINE_SCOPE);

    String[] templates = getTemplates(question.getClass(), jobType, prefix);
    if (!tryTemplates(contentType, templates)) {
        throw new ResourceReferenceHandlerException("Cannot find any template for the job with id" + jobId
                + " (" + Arrays.toString(templates) + ")");
    }
}

From source file:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;/* w w  w  .  j  a v a 2  s .  c om*/
    boolean isAbsolutePath = false;
    if (map.containsKey(JOB_SCRIPT_ABSOLUTE_PATH)) {
        isAbsolutePath = true;
        jobScriptPath = map.getString(JOB_SCRIPT_ABSOLUTE_PATH);
    } else {
        jobScriptPath = map.getString(JOB_SCRIPT_PATH);
    }
    logger.info("Start executing JSR223 script job {}", jobScriptPath);

    ScriptEngine scriptEngine = ScriptEngineUtils.getInstance()
            .scriptEngine(FilenameUtils.getExtension(jobScriptPath));
    if (scriptEngine != null) {
        ScriptContext scriptContext = new SimpleScriptContext();
        final Bindings bindings = new SimpleBindings();
        bindings.put("jobDataMap", map);

        InputStream scriptInputStream;
        if (!isAbsolutePath) {
            scriptInputStream = JahiaContextLoaderListener.getServletContext()
                    .getResourceAsStream(jobScriptPath);
        } else {
            scriptInputStream = FileUtils.openInputStream(new File(jobScriptPath));
        }
        if (scriptInputStream != null) {
            Reader scriptContent = null;
            try {
                scriptContent = new InputStreamReader(scriptInputStream);
                StringWriter out = new StringWriter();
                scriptContext.setWriter(out);
                // The following binding is necessary for Javascript, which doesn't offer a console by default.
                bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                        ScriptContext.GLOBAL_SCOPE);
                scriptEngine.eval(scriptContent, scriptContext);
                map.put(JOB_SCRIPT_OUTPUT, out.toString());
                logger.info("...JSR-223 script job {} execution finished", jobScriptPath);
            } catch (ScriptException e) {
                logger.error("Error during execution of the JSR-223 script job " + jobScriptPath
                        + " execution failed with error " + e.getMessage(), e);
                throw new Exception("Error during execution of script " + jobScriptPath, e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }
    }
}