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.modules.googleAnalytics.GoogleAnalyticsFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//from  w w  w.j a v a  2  s .c o  m
    String webPropertyID = renderContext.getSite().hasProperty("webPropertyID")
            ? renderContext.getSite().getProperty("webPropertyID").getString()
            : null;
    if (StringUtils.isNotEmpty(webPropertyID)) {
        String script = getResolvedTemplate();
        if (script != null) {
            Source source = new Source(previousOut);
            OutputDocument outputDocument = new OutputDocument(source);
            List<Element> headElementList = source.getAllElements(HTMLElementName.HEAD);
            for (Element element : headElementList) {
                final EndTag headEndTag = element.getEndTag();
                String extension = StringUtils.substringAfterLast(template, ".");
                ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
                ScriptContext scriptContext = new GoogleScriptContext();
                final Bindings bindings = scriptEngine.createBindings();
                bindings.put("webPropertyID", webPropertyID);
                String url = resource.getNode().getUrl();
                if (renderContext.getRequest().getAttribute("analytics-path") != null) {
                    url = (String) renderContext.getRequest().getAttribute("analytics-path");
                }
                bindings.put("resourceUrl", url);
                bindings.put("resource", resource);
                bindings.put("gaMap", renderContext.getRequest().getAttribute("gaMap"));
                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(script, scriptContext);
                StringWriter writer = (StringWriter) scriptContext.getWriter();
                final String googleAnalyticsScript = writer.toString();
                if (StringUtils.isNotBlank(googleAnalyticsScript)) {
                    outputDocument.replace(headEndTag.getBegin(), headEndTag.getBegin() + 1,
                            "\n" + AggregateCacheFilter.removeEsiTags(googleAnalyticsScript) + "\n<");
                }
                break; // avoid to loop if for any reasons multiple body in the page
            }
            out = outputDocument.toString().trim();
        }
    }

    return out;
}

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;/*from  ww  w .  j av a2  s.com*/
    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.jtotus.network.NordnetConnect.java

public String fetchEncryptedPassword(String encryptJS, String pass, String pubKey, String sessionId) {
    String password = null;/* w  ww.  j a va 2 s  .  c  om*/

    StartUpLoader loader = StartUpLoader.getInstance();

    //ScriptEngineManager mgr = loader.getLoadedScriptManager();
    //         Bindings bindings = mgr.getBindings();

    ScriptEngine engine = loader.getLoadedEngine();
    Bindings bindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);

    try {
        StringBuilder strBuild = new StringBuilder();
        strBuild.append(encryptJS);

        strBuild.append(" \n var keyObj = RSA.getPublicKey(\'" + pubKey + "\');\n"
                + "  var encryptedPass = RSA.encrypt(\'" + pass + "\', keyObj, \'" + sessionId + "\');\n");

        engine.eval(strBuild.toString(), bindings);

        password = (String) bindings.get("encryptedPass");

    } catch (ScriptException ex) {
        Logger.getLogger(NordnetConnector.class.getName()).log(Level.SEVERE, null, ex);
    }

    log.info("JavaScript engine loaded:" + engine.NAME);

    return password;
}

From source file:org.jahia.modules.irclogs.filters.IRCLogPageTitleFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/* w  ww.  j av a  2  s .c om*/
    String script = getResolvedTemplate();
    if (script != null) {
        Source source = new Source(previousOut);
        OutputDocument outputDocument = new OutputDocument(source);
        List<Element> headElementList = source.getAllElements(HTMLElementName.TITLE);
        for (Element element : headElementList) {
            final EndTag bodyEndTag = element.getEndTag();
            final StartTag bodyStartTag = element.getStartTag();
            String extension = StringUtils.substringAfterLast(template, ".");
            ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
            ScriptContext scriptContext = new irclogsScriptContext();
            final Bindings bindings = scriptEngine.createBindings();
            bindings.put("resource", resource);
            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()));

            // Parameters needed for title replacing
            bindings.put("orgTitle",
                    outputDocument.toString().substring(bodyStartTag.getEnd(), bodyEndTag.getBegin()));
            bindings.put("dateFormatter", dateFormatter);
            bindings.put("title", getTitle());
            bindings.put("renderContext", renderContext);

            scriptEngine.eval(script, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            final String irclogsScript = writer.toString();
            if (StringUtils.isNotBlank(irclogsScript)) {
                outputDocument.replace(bodyStartTag.getEnd(), bodyEndTag.getBegin() + 1,
                        AggregateCacheFilter.removeEsiTags(irclogsScript) + "<");
            }
            break; // avoid to loop if for any reasons multiple body in the page
        }
        out = outputDocument.toString().trim();
    }

    return out;
}

From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder.java

/**
 * Creates the graph with the given Script and step map.
 *
 * @param script the Dynamic authentication script.
 *///w w  w  .  j  a v  a  2  s.  c om
public JsGraphBuilder createWith(String script) {

    try {
        currentBuilder.set(this);
        Bindings globalBindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
        Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_EXECUTE_STEP,
                (StepExecutor) this::executeStep);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SEND_ERROR,
                (BiConsumer<String, Map>) this::sendError);
        globalBindings.put(FrameworkConstants.JSAttributes.JS_FUNC_SHOW_PROMPT,
                (PromptExecutor) this::addShowPrompt);
        engineBindings.put("exit", (RestrictedFunction) this::exitFunction);
        engineBindings.put("quit", (RestrictedFunction) this::quitFunction);
        JsFunctionRegistry jsFunctionRegistrar = FrameworkServiceDataHolder.getInstance()
                .getJsFunctionRegistry();
        if (jsFunctionRegistrar != null) {
            Map<String, Object> functionMap = jsFunctionRegistrar
                    .getSubsystemFunctionsMap(JsFunctionRegistry.Subsystem.SEQUENCE_HANDLER);
            functionMap.forEach(globalBindings::put);
        }
        Invocable invocable = (Invocable) engine;
        engine.eval(script);
        invocable.invokeFunction(FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST,
                new JsAuthenticationContext(authenticationContext));
        JsGraphBuilderFactory.persistCurrentContext(authenticationContext, engine);
    } catch (ScriptException e) {
        result.setBuildSuccessful(false);
        result.setErrorReason("Error in executing the Javascript. Nested exception is: " + e.getMessage());
        if (log.isDebugEnabled()) {
            log.debug("Error in executing the Javascript.", e);
        }
    } catch (NoSuchMethodException e) {
        result.setBuildSuccessful(false);
        result.setErrorReason("Error in executing the Javascript. "
                + FrameworkConstants.JSAttributes.JS_FUNC_ON_LOGIN_REQUEST + " function is not defined.");
        if (log.isDebugEnabled()) {
            log.debug("Error in executing the Javascript.", e);
        }
    } finally {
        clearCurrentBuilder();
    }
    return this;
}

From source file:org.jahia.modules.portal.filter.PortalLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;//  w  w w .  j  a  v  a 2 s . com

    // add portal API lib
    String path = "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JS_API_FILE;
    path = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath() + path
            : path;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JS_API_FILE + "'/>");

    // add portal instance
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(template, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new PortalScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("portalContext", serializePortal(renderContext));
        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(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String portalScript = writer.toString();
        if (StringUtils.isNotBlank(portalScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(portalScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}

From source file:org.jahia.services.render.scripting.bundle.BundleScriptEngineManager.java

private ScriptEngine getEngine(String key, Map<String, ScriptEngineFactory> factoriesForKeyType,
        KeyType keyType) {/*from  w w  w.j  a v  a  2  s .c o m*/
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    Map<String, ScriptEngine> stringScriptEngineMap = engineCache.get(contextClassLoader);

    if (stringScriptEngineMap == null) {
        stringScriptEngineMap = new ConcurrentHashMap<>();
        engineCache.put(contextClassLoader, stringScriptEngineMap);
    }

    ScriptEngine scriptEngine = stringScriptEngineMap.get(key);
    if (scriptEngine == null) {

        final ScriptEngineFactory scriptEngineFactory = factoriesForKeyType.get(key);
        if (scriptEngineFactory != null) {
            // perform configuration of the factory if needed
            if (scriptEngineFactory instanceof BundleScriptEngineFactory) {
                BundleScriptEngineFactory factory = (BundleScriptEngineFactory) scriptEngineFactory;
                factory.configurePreScriptEngineCreation();
            }

            scriptEngine = scriptEngineFactory.getScriptEngine();
            scriptEngine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
        } else {
            switch (keyType) {
            case EXTENSION:
                scriptEngine = super.getEngineByExtension(key);
                break;
            case MIME_TYPE:
                scriptEngine = super.getEngineByMimeType(key);
                break;
            case NAME:
                scriptEngine = super.getEngineByName(key);
                break;
            default:
                scriptEngine = null;
            }
        }

        if (scriptEngine != null) {
            stringScriptEngineMap.put(key, scriptEngine);
        }
    }
    return scriptEngine;
}

From source file:org.jahia.modules.portal.filter.JCRRestJavaScriptLibFilter.java

@Override
public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain)
        throws Exception {
    String out = previousOut;/*  w  ww.ja v a  2 s  .c  o  m*/
    String context = StringUtils.isNotEmpty(renderContext.getRequest().getContextPath())
            ? renderContext.getRequest().getContextPath()
            : "";

    // add lib
    String path = context + "/modules/" + renderContext.getMainResource().getNode().getPrimaryNodeType()
            .getTemplatePackage().getBundle().getSymbolicName() + "/javascript/" + JCR_REST_JS_FILE;
    String encodedPath = URLEncoder.encode(path, "UTF-8");
    out += ("<jahia:resource type='javascript' path='" + encodedPath + "' insert='true' resource='"
            + JCR_REST_JS_FILE + "'/>");

    // instance JavaScript object
    String script = getResolvedTemplate();
    if (script != null) {
        String extension = StringUtils.substringAfterLast(JCR_REST_SCRIPT_TEMPLATE, ".");
        ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
        ScriptContext scriptContext = new JCRRestUtilsScriptContext();
        final Bindings bindings = scriptEngine.createBindings();

        // bindings
        bindings.put("options", getBindingMap(renderContext, resource, context));
        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(script, scriptContext);
        StringWriter writer = (StringWriter) scriptContext.getWriter();
        final String resultScript = writer.toString();
        if (StringUtils.isNotBlank(resultScript)) {
            out += ("<jahia:resource type='inlinejavascript' path='" + URLEncoder.encode(resultScript, "UTF-8")
                    + "' insert='false' resource='' title='' key=''/>");
        }
    }

    return out;
}