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:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Map<String, Object> contextVars, Writer writer)
        throws ScriptException {
    try {/*from w ww. j  av  a2 s  .  c om*/
        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.jahia.services.render.filter.MarkedForDeletionFilter.java

protected String getTemplateOutput(RenderContext renderContext, Resource resource) {
    String out = StringUtils.EMPTY;
    try {/* ww  w.j ava2  s .  com*/
        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:org.hbird.business.scripting.bean.ScriptExecutor.java

/**
 * Method to evaluate whether all required input parameters have been set.
 * //from   www.ja  va2  s  .co  m
 * @return True if all input parameters have been bound to the engine. Else false.
 */
protected boolean ready() {
    for (String parameter : component.inputBinding.values()) {
        if (engine.getBindings(ScriptContext.ENGINE_SCOPE).containsKey(parameter) == false) {
            LOG.debug("Script '" + component.getName() + "' Still missing dependency '" + parameter + "'.");
            return false;
        }
    }

    return true;
}

From source file:org.graphwalker.machines.ExtendedFiniteStateMachine.java

@Override
public boolean hasInternalVariables() {
    if (jsEngine != null) {
        return !jsEngine.getBindings(ScriptContext.ENGINE_SCOPE).isEmpty();
    } else if (beanShellEngine != null) {
        return beanShellEngine.getNameSpace().getVariableNames().length > 1;
    }//from w w w . ja v  a  2s.c  om
    return false;
}

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);// w w w . ja v a2 s  . c  o  m
    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:org.apache.sling.pipes.PipeBindings.java

public Bindings getBindings() {
    return scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
}

From source file:de.xwic.appkit.webbase.editors.EditorContext.java

/**
 * @param input//from   w  w  w. j  a v a  2s. com
 * @throws ConfigurationException
 * @throws EntityModelException
 */
public EditorContext(GenericEditorInput input, String langId)
        throws ConfigurationException, EntityModelException {
    this.input = input;
    this.config = input.getConfig();
    this.bundle = config.getEntityType().getDomain().getBundle(langId);
    this.model = EntityModelFactory.createModel(input.getEntity());
    this.dirty = input.getEntity().getId() == 0; // is a new entity.

    DAO<?> dao = DAOSystem.findDAOforEntity(config.getEntityType().getClassname());
    this.editable = dao.hasRight(input.getEntity(), "UPDATE") && !input.getEntity().isDeleted()
            && !(input.getEntity() instanceof IHistory);

    scriptEngine = ScriptEngineProvider.instance()
            .createEngine("Editor(" + config.getEntityType().getId() + ":" + config.getId() + ")");
    Bindings bindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
    bindings.put("entity", model);
    bindings.put("bundle", bundle);
    bindings.put("ctx", this);

    try {
        if (config.getGlobalScript() != null && !config.getGlobalScript().trim().isEmpty()) {
            scriptEngine.eval(config.getGlobalScript());
        }
    } catch (ScriptException se) {
        initErrors.add("ScriptException in GlobalScript for editor configuration (" + se + ")");
        log.error("Error evaluating global script in Editor(" + config.getEntityType() + ":" + config.getId()
                + ")", se);
    }
    final String entityType = getEntityDescriptor().getClassname();
    final List<IEditorListenerFactory> listenerExtensions = EditorExtensionUtils
            .getExtensions(EP_EDITOR_LISTENER, entityType);
    for (IEditorListenerFactory listenerExtension : listenerExtensions) {
        EditorListener editorListener = listenerExtension.createListener();
        addEditorListener(editorListener);
    }
}

From source file:org.omegat.gui.scripting.ScriptRunner.java

/**
 * Execute a script with a given engine and bindings.
 * /*  w w  w  .  j a va  2  s.c o m*/
 * @param script
 *            The script in string form
 * @param engine
 *            The engine
 * @param additionalBindings
 *            A map of bindings that will be included along with other
 *            bindings
 * @return The evaluation result
 * @throws ScriptException
 */
public static Object executeScript(String script, ScriptEngine engine, Map<String, Object> additionalBindings)
        throws ScriptException {
    // logResult(StaticUtils.format(OStrings.getString("SCW_SELECTED_LANGUAGE"),
    // engine.getFactory().getEngineName()));
    Bindings bindings = engine.createBindings();
    bindings.put(VAR_PROJECT, Core.getProject());
    bindings.put(VAR_EDITOR, Core.getEditor());
    bindings.put(VAR_GLOSSARY, Core.getGlossary());
    bindings.put(VAR_MAINWINDOW, Core.getMainWindow());
    bindings.put(VAR_CORE, Core.class);

    if (additionalBindings != null) {
        bindings.putAll(additionalBindings);
    }
    engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    Object result = engine.eval(script);
    if (engine instanceof Invocable) {
        invokeGuiScript((Invocable) engine);
    }
    return result;
}

From source file:org.graphwalker.machines.ExtendedFiniteStateMachine.java

public Set<Entry<String, Object>> getCurrentJsEngineData() {
    Bindings bindings = jsEngine.getBindings(ScriptContext.ENGINE_SCOPE);
    return bindings.entrySet();
}