Example usage for javax.script SimpleScriptContext SimpleScriptContext

List of usage examples for javax.script SimpleScriptContext SimpleScriptContext

Introduction

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

Prototype

public SimpleScriptContext() 

Source Link

Document

Create a SimpleScriptContext .

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 {/*from   ww  w  .  ja  v  a 2  s .co  m*/
            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:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;/* w ww .ja  v a2s.  co m*/
    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);
                }
            }
        }
    }
}

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);/*from ww  w .  j  a  v a 2s  . c o m*/
    }
    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:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Writer writer) throws ScriptException {
    try {//from  ww w  .j a va2 s .c  o 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:org.jahia.services.render.filter.MarkedForDeletionFilter.java

protected String getTemplateOutput(RenderContext renderContext, Resource resource) {
    String out = StringUtils.EMPTY;
    try {/*from   w w w.  jav a  2s .  co m*/
        String template = getTemplateContent();
        resolvedTemplate = null;

        if (StringUtils.isEmpty(template)) {
            return StringUtils.EMPTY;
        }

        ScriptEngine engine = ScriptEngineUtils.getInstance().scriptEngine(templateExtension);
        ScriptContext ctx = new SimpleScriptContext();
        ctx.setWriter(new StringWriter());
        Bindings bindings = engine.createBindings();
        bindings.put("renderContext", renderContext);
        bindings.put("resource", resource);
        final ResourceBundle bundle = ResourceBundles.getInternal(renderContext.getUILocale());
        bindings.put("bundle", bundle);
        bindings.put("i18n", LazyMap.decorate(new HashMap<String, String>(2), new Transformer() {
            public Object transform(Object input) {
                String value = null;
                String key = String.valueOf(input);
                try {
                    value = bundle.getString(key);
                } catch (MissingResourceException e) {
                    value = key;
                }
                return value;
            }
        }));

        ctx.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

        engine.eval(template, ctx);
        out = ((StringWriter) ctx.getWriter()).getBuffer().toString();

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
    return out;
}

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

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars, Writer writer)
        throws ScriptException {
    try {//  www.  j  a v a 2  s  . com
        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:org.nuxeo.automation.scripting.internals.AutomationScriptingServiceImpl.java

@Override
public void run(String script, CoreSession session) throws ScriptException, OperationException {
    ScriptEngine engine = engines.get();
    engine.setContext(new SimpleScriptContext());
    engine.eval(getJSWrapper());/*from w ww . j  av a  2s .co m*/

    // Initialize Operation Context
    if (operationContext == null) {
        operationContext = operationContexts.get();
        operationContext.setCoreSession(session);
    }

    // Injecting Automation Mapper 'automation'
    AutomationMapper automationMapper = new AutomationMapper(session, operationContext);
    engine.put(AutomationScriptingConstants.AUTOMATION_MAPPER_KEY, automationMapper);

    // Inject operation context vars in 'Context'
    engine.put(AutomationScriptingConstants.AUTOMATION_CTX_KEY, automationMapper.ctx.getVars());
    // Session injection
    engine.put("Session", automationMapper.ctx.getCoreSession());
    // User injection
    PrincipalWrapper principalWrapper = new PrincipalWrapper(
            (NuxeoPrincipal) automationMapper.ctx.getPrincipal());
    engine.put("CurrentUser", principalWrapper);
    engine.put("currentUser", principalWrapper);
    // Env Properties injection
    engine.put("Env", Framework.getProperties());
    // DateWrapper injection
    engine.put("CurrentDate", new DateWrapper());
    // Workflow variables injection
    if (automationMapper.ctx.get(Constants.VAR_WORKFLOW) != null) {
        engine.put(Constants.VAR_WORKFLOW, automationMapper.ctx.get(Constants.VAR_WORKFLOW));
    }
    if (automationMapper.ctx.get(Constants.VAR_WORKFLOW_NODE) != null) {
        engine.put(Constants.VAR_WORKFLOW_NODE, automationMapper.ctx.get(Constants.VAR_WORKFLOW_NODE));
    }

    // Helpers injection
    ContextService contextService = Framework.getService(ContextService.class);
    Map<String, ContextHelper> helperFunctions = contextService.getHelperFunctions();
    for (String helperFunctionsId : helperFunctions.keySet()) {
        engine.put(helperFunctionsId, helperFunctions.get(helperFunctionsId));
    }
    engine.eval(script);
}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.internal.ScriptConsolePlugin.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final String contentType = getContentType(req);
    resp.setContentType(contentType);/*from   w ww. j av  a  2  s . com*/
    if (contentType.startsWith("text/")) {
        resp.setCharacterEncoding("UTF-8");
    }
    final String script = getCodeValue(req);
    final Bindings bindings = new SimpleBindings();
    final PrintWriter pw = resp.getWriter();
    final ScriptHelper osgi = new ScriptHelper(getBundleContext());
    final Writer errorWriter = new LogWriter(log);
    final Reader reader = new StringReader(script);
    //Populate bindings
    bindings.put("request", req);
    bindings.put("reader", reader);
    bindings.put("response", resp);
    bindings.put("out", pw);
    bindings.put("osgi", osgi);

    //Also expose the bundleContext to simplify scripts interaction with the
    //enclosing OSGi container
    bindings.put("bundleContext", getBundleContext());

    final String lang = WebConsoleUtil.getParameter(req, "lang");
    final boolean webClient = "webconsole".equals(WebConsoleUtil.getParameter(req, "client"));

    SimpleScriptContext sc = new SimpleScriptContext();
    sc.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    sc.setWriter(pw);
    sc.setErrorWriter(errorWriter);
    sc.setReader(reader);

    try {
        log.log(LogService.LOG_DEBUG, "Executing script" + script);
        eval(script, lang, sc);
    } catch (Throwable t) {
        if (!webClient) {
            resp.setStatus(500);
        }
        pw.println(exceptionToString(t));
        log.log(LogService.LOG_ERROR, "Error in executing script", t);
    } finally {
        if (osgi != null) {
            osgi.cleanup();
        }
    }
}

From source file:it.geosolutions.geobatch.action.scripting.ScriptingAction.java

/**
 * Default execute method.../*from  w  w  w  .j  a va  2  s.  com*/
 */
@SuppressWarnings("unchecked")
public Queue<FileSystemEvent> execute(Queue<FileSystemEvent> events) throws ActionException {
    try {

        listenerForwarder.started();

        // //
        // data flow configuration and dataStore name must not be null.
        // //
        if (configuration == null) {
            throw new ActionException(this, "Configuration is null.");
        }

        final String scriptName = it.geosolutions.tools.commons.file.Path
                .findLocation(configuration.getScriptFile(), getConfigDir().getAbsolutePath());
        if (scriptName == null)
            throw new ActionException(this,
                    "Unable to locate the script file name: " + configuration.getScriptFile());

        final File script = new File(scriptName);

        /**
         * Dynamic class-loading ...
         */
        listenerForwarder.setTask("dynamic class loading ...");
        final String moduleFolder = new File(script.getParentFile(), "jars").getAbsolutePath();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Runtime class-loading from moduleFolder -> " + moduleFolder);
        }

        final File moduleDirectory = new File(moduleFolder);
        try {
            addFile(moduleDirectory.getParentFile());
            addFile(moduleDirectory);
        } catch (IOException e) {
            throw new ActionException(this, e.getLocalizedMessage(), e);
        }
        final String classpath = System.getProperty("java.class.path");
        final File[] moduleFiles = moduleDirectory.listFiles();
        if (moduleFiles != null) {
            for (File moduleFile : moduleFiles) {
                final String name = moduleFile.getName();
                if (name.endsWith(".jar")) {
                    if (classpath.indexOf(name) == -1) {
                        try {
                            if (LOGGER.isInfoEnabled())
                                LOGGER.info("Adding: " + name);
                            addFile(moduleFile);
                        } catch (IOException e) {
                            throw new ActionException(this, e.getLocalizedMessage(), e);
                        }
                    }
                }
            }
        }
        /**
         * Evaluating script ...
         */
        listenerForwarder.setTask("evaluating script ...");

        // Now, pass a different script context
        final ScriptContext newContext = new SimpleScriptContext();
        final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

        // add variables to the new engineScope
        //         engineScope.put("eventList", events);
        //         engineScope.put("runningContext", getRunningContext());

        // add properties as free vars in script
        final Map<String, Object> props = configuration.getProperties();
        if (props != null) {
            final Set<Entry<String, Object>> set = props.entrySet();
            final Iterator<Entry<String, Object>> it = set.iterator();
            while (it.hasNext()) {
                final Entry<String, ?> prop = it.next();
                if (prop == null) {
                    continue;
                }
                if (LOGGER.isInfoEnabled())
                    LOGGER.info(" Adding script property: " + prop.getKey() + " : " + prop.getValue());
                engineScope.put(prop.getKey(), prop.getValue());
            }
        }
        // read the script
        FileReader reader = null;
        try {
            reader = new FileReader(script);
            engine.eval(reader, engineScope);
        } catch (FileNotFoundException e) {
            throw new ActionException(this, e.getLocalizedMessage(), e);
        } finally {
            IOUtils.closeQuietly(reader);
        }

        final Invocable inv = (Invocable) engine;

        listenerForwarder.setTask("Executing script: " + script.getName());

        // check for incoming event list
        if (events == null) {
            throw new ActionException(this, "Unable to start the script using a null incoming list of events");
        }

        // call the script
        final Map<String, Object> argsMap = new HashedMap();
        argsMap.put(ScriptingAction.CONFIG_KEY, configuration);
        argsMap.put(ScriptingAction.TEMPDIR_KEY, getTempDir());
        argsMap.put(ScriptingAction.CONFIGDIR_KEY, getConfigDir());
        argsMap.put(ScriptingAction.EVENTS_KEY, events);
        argsMap.put(ScriptingAction.LISTENER_KEY, listenerForwarder);

        final Map<String, Object> mapOut = (Map<String, Object>) inv.invokeFunction("execute",
                new Object[] { argsMap });

        // checking output
        final Queue<FileSystemEvent> ret = new LinkedList<FileSystemEvent>();
        if (mapOut == null) {
            if (LOGGER.isWarnEnabled()) {
                LOGGER.warn("Caution returned map from script " + configuration.getScriptFile()
                        + " is null.\nSimulating an empty return list.");
            }
            return ret;
        }

        final Object obj = mapOut.get(ScriptingAction.RETURN_KEY);
        if (obj == null) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Caution returned object from script " + configuration.getScriptFile()
                        + " is null.\nPassing an empty list to the next action!");
            }
            return ret;
        }

        if (obj instanceof List) {
            final List<Object> list = (List<Object>) obj;
            for (final Object out : list) {
                if (out == null) {
                    if (LOGGER.isWarnEnabled()) {
                        LOGGER.warn("Caution returned object from script " + configuration.getScriptFile()
                                + " is null.\nContinue with the next one.");
                    }
                    continue;
                }

                if (out instanceof FileSystemEvent) {
                    FileSystemEvent ev = (FileSystemEvent) out;
                    ret.add(ev);
                } else if (out instanceof File) {
                    ret.add(new FileSystemEvent((File) out, FileSystemEventType.FILE_ADDED));
                } else {
                    final File file = new File(out.toString());
                    if (!file.exists() && LOGGER.isWarnEnabled()) {
                        LOGGER.warn("Caution returned object from script " + configuration.getScriptFile()
                                + " do not points to an existent file!");
                    }
                    ret.add(new FileSystemEvent(file, FileSystemEventType.FILE_ADDED));
                }
            }
        } else {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Caution returned object from script " + configuration.getScriptFile()
                        + " is not a valid List.\nPassing an empty list to the next action!");
            }
            return ret;
        }
        listenerForwarder.setTask("Completed");
        listenerForwarder.completed();

        return ret;

    } catch (Exception t) {
        listenerForwarder.setTask("Completed with errors");
        listenerForwarder.failed(t);
        throw new ActionException(this, t.getMessage(), t);
    } finally {
        engine = null;
        factory = null;
    }
}