Example usage for javax.script ScriptContext GLOBAL_SCOPE

List of usage examples for javax.script ScriptContext GLOBAL_SCOPE

Introduction

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

Prototype

int GLOBAL_SCOPE

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

Click Source Link

Document

GlobalScope attributes are visible to all engines created by same ScriptEngineFactory.

Usage

From source file:org.jahia.services.workflow.jbpm.custom.email.JBPMMailProducer.java

protected String evaluateExpression(WorkItem workItem, String scriptToExecute, JCRSessionWrapper session)
        throws RepositoryException, ScriptException {
    ScriptContext scriptContext = new SimpleScriptContext();
    if (bindings == null) {
        bindings = getBindings(workItem, session);
    }//w  w w . ja v a  2 s .  c  om
    scriptContext.setWriter(new StringWriter());
    scriptContext.setErrorWriter(new StringWriter());
    scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    scriptContext.setBindings(scriptContext.getBindings(ScriptContext.GLOBAL_SCOPE),
            ScriptContext.GLOBAL_SCOPE);
    scriptEngine.eval(scriptToExecute, scriptContext);
    String error = scriptContext.getErrorWriter().toString();
    if (error.length() > 0) {
        logger.error("Scripting error : " + error);
    }
    return scriptContext.getWriter().toString().trim();
}

From source file:org.jahia.services.render.filter.StaticAssetsFilter.java

private void addResources(RenderContext renderContext, org.jahia.services.render.Resource resource,
        Source source, OutputDocument outputDocument, String targetTag,
        Map<String, Map<String, Map<String, String>>> assetsByType) throws IOException, ScriptException {

    renderContext.getRequest().setAttribute(STATIC_ASSETS, assetsByType);
    Element element = source.getFirstElement(targetTag);
    String templateContent = getResolvedTemplate();
    if (element == null) {
        logger.warn("Trying to add resources to output but didn't find {} tag", targetTag);
        return;//from   w  w  w.j av a  2  s  . c  o  m
    }

    if (templateContent != null) {

        final EndTag headEndTag = element.getEndTag();
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(templateExtension);
        ScriptContext scriptContext = new AssetsScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        bindings.put("contextJsParameters", getContextJsParameters(assetsByType, renderContext));

        if (aggregateAndCompress && resource.getWorkspace().equals("live")) {
            Map<String, Map<String, String>> cssAssets = assetsByType.get("css");
            if (cssAssets != null) {
                assetsByType.put("css", aggregate(cssAssets, "css"));
            }
            Map<String, Map<String, String>> javascriptAssets = assetsByType.get("javascript");
            if (javascriptAssets != null) {
                Map<String, Map<String, String>> scripts = new LinkedHashMap<String, Map<String, String>>(
                        javascriptAssets);
                Map<String, Map<String, String>> newScripts = aggregate(javascriptAssets, "js");
                assetsByType.put("javascript", newScripts);
                scripts.keySet().removeAll(newScripts.keySet());
                assetsByType.put("aggregatedjavascript", scripts);
            }
        } else if (addLastModifiedDate) {
            addLastModified(assetsByType);
        }

        bindings.put(TARGET_TAG, targetTag);
        bindings.put("renderContext", renderContext);
        bindings.put("resource", resource);
        bindings.put("contextPath", renderContext.getRequest().getContextPath());
        scriptContext.setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
        // The following binding is necessary for Javascript, which doesn't offer a console by default.
        bindings.put("out", new PrintWriter(scriptContext.getWriter()));
        scriptEngine.eval(templateContent, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String staticsAsset = writer.toString();

        if (StringUtils.isNotBlank(staticsAsset)) {
            outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1,
                    "\n" + AggregateCacheFilter.removeCacheTags(staticsAsset) + "\n<");
        }
    }

    // workaround for ie9 in gxt/gwt
    // renderContext.isEditMode() means that gwt is loaded, for contribute, edit or studio
    if (isEnforceIECompatibilityMode(renderContext)) {
        int idx = element.getBegin() + element.toString().indexOf(">");
        String str = ">\n<meta http-equiv=\"X-UA-Compatible\" content=\""
                + SettingsBean.getInstance().getInternetExplorerCompatibility() + "\"/>";
        outputDocument.replace(idx, idx + 1, str);
    }

    if ((renderContext.isPreviewMode()) && !Boolean.valueOf((String) renderContext.getRequest()
            .getAttribute("org.jahia.StaticAssetFilter.doNotModifyDocumentTitle"))) {
        for (Element title : element.getAllElements(HTMLElementName.TITLE)) {
            int idx = title.getBegin() + title.toString().indexOf(">");
            String str = Messages.getInternal("label.preview", renderContext.getUILocale());
            str = ">" + str + " - ";
            outputDocument.replace(idx, idx + 1, str);
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngine.java

private void registerBindingTypes(final ScriptContext context) {
    if (typeCheckingEnabled) {
        final Map<String, ClassNode> variableTypes = new HashMap<>();
        clearVarTypes();/*  w w w. j a  v a2s.co m*/

        // use null for the classtype if the binding value itself is null - not fully sure if that is
        // a sound way to deal with that.  didn't see a class type for null - maybe it should just be
        // unknown and be "Object".  at least null is properly being accounted for now.
        context.getBindings(ScriptContext.GLOBAL_SCOPE)
                .forEach((k, v) -> variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass())));
        context.getBindings(ScriptContext.ENGINE_SCOPE)
                .forEach((k, v) -> variableTypes.put(k, null == v ? null : ClassHelper.make(v.getClass())));

        COMPILE_OPTIONS.get().put(COMPILE_OPTIONS_VAR_TYPES, variableTypes);
    }
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Load the specified JavaScript library into the global scope of the Nashorn engine
 * @param lib   Path to the JavaScript library.
 *//*w w  w . j  a  va 2s  .c o  m*/
protected boolean loadScriptLibrary(Path lib) {
    try (Reader r = Files.newBufferedReader(lib, Charset.forName("utf-8"))) {
        Nashorn.eval(r, Nashorn.getBindings(ScriptContext.GLOBAL_SCOPE));
    } catch (Exception e) {
        Logger.error("Unable to load JavaScript library " + lib.toAbsolutePath().toString(), e);
        return false;
    }
    return true;
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * This is where Nashorn compiles the script, evals it into global scope to get an endpoint, and invokes the setup method of the endpoint.
 * @param rootPath   The root script directory path to assist in building a relative uri type path to discovered scripts.
 * @param f   The javascript file.//from  ww w  .j a v a 2s. co m
 * @param uriKey   A "pass-back-by-reference" construct to w
 * @return
 */
private static void MakeJavaScriptEndPointDescriptor(Path rootPath, Path f,
        HierarchicalConfiguration scriptConfig, EndpointSetupCompleteCallback cb) {
    CompiledScript compiledScript;
    try (Reader r = Files.newBufferedReader(f, Charset.forName("utf-8"))) {
        compiledScript = ((Compilable) Nashorn).compile(r);
    } catch (Throwable e) {
        cb.setupFailed(f, "Unable to load and compile script at " + f.toAbsolutePath().toString(), e);
        return;
    }
    ScriptObjectMirror obj;
    try {
        obj = (ScriptObjectMirror) compiledScript.eval(Nashorn.getBindings(ScriptContext.GLOBAL_SCOPE));
    } catch (Throwable e) {
        cb.setupFailed(f, "Unable to eval the script at " + f.toAbsolutePath().toString(), e);
        return;
    }
    assert f.startsWith(rootPath);
    String uriKey = FileToUriKey(rootPath, f);
    final JavaScriptEndPoint retVal = new JavaScriptEndPoint(uriKey, obj);

    try {
        if (obj.hasMember("setup")) {
            obj.callMember("setup", uriKey, scriptConfig, ScriptHelper.ScriptLogger,
                    new SetupCompleteCallback() {
                        @Override
                        public void setupComplete() {
                            cb.setupComplete(retVal);
                        }

                        @Override
                        public void setupFailed(String msg) {
                            cb.setupFailed(f, msg, null);
                        }
                    });
        } else {
            cb.setupComplete(retVal);
        }
    } catch (Throwable e) {
        cb.setupFailed(f, "The script at " + f.toAbsolutePath().toString()
                + " did not expose the expected 'setup' method", e);
        return;
    }
}

From source file:org.jahia.ajax.gwt.helper.UIConfigHelper.java

/**
 * Get resources//from  ww w. j  a  v  a  2  s.  c  om
 *
 * @param key
 * @param locale
 * @param site
 * @param jahiaUser
 * @return
 */
private String getResources(String key, Locale locale, JCRSiteNode site, JahiaUser jahiaUser) {
    if (key == null || key.length() == 0) {
        return key;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resources key: " + key);
    }
    String baseName = null;
    String value = null;
    if (key.contains("@")) {
        baseName = StringUtils.substringAfter(key, "@");
        key = StringUtils.substringBefore(key, "@");
    }

    value = Messages.get(baseName, site != null ? site.getTemplatePackage() : null, key, locale, null);
    if (value == null || value.length() == 0) {
        value = Messages.getInternal(key, locale);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Resources value: " + value);
    }
    if (value.contains("${")) {
        try {
            ScriptEngine scriptEngine = scriptEngineUtils.getEngineByName("velocity");
            ScriptContext scriptContext = new SimpleScriptContext();
            final Bindings bindings = new SimpleBindings();
            bindings.put("currentSite", site);
            bindings.put("currentUser", jahiaUser);
            bindings.put("currentLocale", locale);
            bindings.put("PrincipalViewHelper", PrincipalViewHelper.class);
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                    ScriptContext.GLOBAL_SCOPE);
            scriptContext.setWriter(new StringWriter());
            scriptContext.setErrorWriter(new StringWriter());
            scriptEngine.eval(value, scriptContext);
            //String error = scriptContext.getErrorWriter().toString();
            return scriptContext.getWriter().toString().trim();
        } catch (ScriptException e) {
            logger.error("Error while executing script [" + value + "]", e);
        }
    }
    return value;
}