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.openmrs.module.appframework.service.AppFrameworkServiceImpl.java

public boolean checkRequireExpression(Extension candidate, AppContextModel contextModel) {
    try {//from   w w  w . ja  v  a2s.co m
        String requireExpression = candidate.getRequire();
        if (StringUtils.isBlank(requireExpression)) {
            return true;
        } else {
            javascriptEngine.setBindings(new SimpleBindings(contextModel), ScriptContext.ENGINE_SCOPE);
            return javascriptEngine.eval("(" + requireExpression + ") == true").equals(Boolean.TRUE);
        }

    } catch (ScriptException e) {
        log.error("Failed to evaluate 'require' check for extension " + candidate.getId(), e);
        return false;
    }
}

From source file:com.galeoconsulting.leonardinius.rest.service.ScriptRunner.java

private ScriptEngine createScriptEngine(String scriptLanguage, Script script) {
    ScriptEngine engine = engineByLanguage(scriptLanguage);
    if (engine == null) {
        throw new IllegalStateException(
                String.format("Language '%s' script engine could not be found", scriptLanguage));
    }//from ww w.j  a  v  a 2 s . c o  m
    updateBindings(engine, ScriptContext.ENGINE_SCOPE, new HashMap<String, Object>() {
        {
            put("log", LOG);
            put("selfScriptRunner", ScriptRunner.this);
        }
    });

    engine.getContext().setAttribute(ScriptEngine.FILENAME, scriptName(script.getFilename()),
            ScriptContext.ENGINE_SCOPE);
    engine.getContext().setAttribute(ScriptEngine.ARGV, getArgvs(script.getArgv()), ScriptContext.ENGINE_SCOPE);

    return engine;
}

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

@Test
public void shouldClearEngineScopeOnReset() throws Exception {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();
    engine.eval("x = { y -> y + 1}");
    Bindings b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    assertTrue(b.containsKey("x"));
    assertEquals(2, ((Closure) b.get("x")).call(1));

    // should clear the bindings
    engine.reset();/*from   ww w .  j  a v a  2s . c  o  m*/
    try {
        engine.eval("x(1)");
        fail("Bindings should have been cleared.");
    } catch (Exception ex) {

    }

    b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    assertFalse(b.containsKey("x"));

    // redefine x
    engine.eval("x = { y -> y + 2}");
    assertEquals(3, engine.eval("x(1)"));
    b = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    assertTrue(b.containsKey("x"));
    assertEquals(3, ((Closure) b.get("x")).call(1));
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException {
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));

    if (VERBOSE_LOADING) {
        _log.info("Loading Script: " + file.getAbsolutePath());
    }/* ww  w  .j a v a  2  s . com*/

    if (PURGE_ERROR_LOG) {
        String name = file.getAbsolutePath() + ".error.log";
        File errorLog = new File(name);
        if (errorLog.isFile()) {
            errorLog.delete();
        }
    }

    if (engine instanceof Compilable && ATTEMPT_COMPILATION) {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);

        setCurrentLoadingScript(file);
        ScriptContext ctx = engine.getContext();
        try {
            engine.setContext(context);
            if (USE_COMPILED_CACHE) {
                CompiledScript cs = _cache.loadCompiledScript(engine, file);
                cs.eval(context);
            } else {
                Compilable eng = (Compilable) engine;
                CompiledScript cs = eng.compile(reader);
                cs.eval(context);
            }
        } finally {
            engine.setContext(ctx);
            setCurrentLoadingScript(null);
            context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }
    } else {
        ScriptContext context = new SimpleScriptContext();
        context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'),
                ScriptContext.ENGINE_SCOPE);
        context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE);
        context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE);
        setCurrentLoadingScript(file);
        try {
            engine.eval(reader, context);
        } finally {
            setCurrentLoadingScript(null);
            engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE);
            engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE);
        }

    }
}

From source file:org.ms123.common.utils.UtilsServiceImpl.java

public Object executeScript(String scriptName, String namespace, String user, Map params) throws Exception {
    System.out.println("UtilsServiceImpl.executeScript:" + params);
    String storeId = (String) params.get("storeId");
    StoreDesc sdesc = StoreDesc.get(storeId);
    namespace = sdesc.getNamespace();//  ww w  .java 2s  . co m
    System.out.println("UtilsServiceImpl.namespace:" + sdesc + "/" + namespace);
    ScriptEngine se = m_scriptEngineService.getEngineByName("groovy");
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    se.getContext().setWriter(pw);
    Bindings b = se.createBindings();
    b.putAll(params);
    b.put("jdo", m_dataLayer);
    b.put("ws", lookupServiceByName("org.ms123.common.workflow.api.WorkflowService"));
    b.put("ss", lookupServiceByName("org.ms123.common.setting.api.SettingService"));
    b.put("et", lookupServiceByName("org.ms123.common.entity.api.EntityService"));
    b.put("storeDesc", sdesc);
    b.put("home", System.getProperty("simpl4.dir"));
    b.put("log", m_logger);
    b.put("user", user);
    b.put("namespace", namespace);
    se.setBindings(b, ScriptContext.ENGINE_SCOPE);
    b.put("se", se);
    Object r = "";
    FileReader fr = getScriptFile(namespace, scriptName);
    r = se.eval(fr);
    System.out.println("r:" + r);
    pw.close();
    m_logger.info("executeScript:" + sw);
    System.out.println("executeScript:" + sw);
    return null;
}

From source file:de.axelfaust.alfresco.nashorn.repo.processor.NashornScriptProcessor.java

protected void initScriptContext() throws ScriptException {
    final Bindings oldEngineBindings = this.engine.getBindings(ScriptContext.ENGINE_SCOPE);
    final AMDModulePreloader oldPreloader = this.amdPreloader;
    final AMDScriptRunner oldAMDRunner = this.amdRunner;

    LOGGER.debug("Initializing new script context");

    inEngineContextInitialization.set(Boolean.TRUE);
    try (NashornScriptModel model = NashornScriptModel.openModel()) {
        // create new (unpolluted) engine bindings
        final Bindings engineBindings = this.engine.createBindings();
        this.engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);

        final Bindings globalBindings = new SimpleBindings();
        this.engine.setBindings(globalBindings, ScriptContext.GLOBAL_SCOPE);

        // only available during initialisation
        globalBindings.put("applicationContext", this.applicationContext);

        LOGGER.debug("Executing bootstrap scripts");
        URL resource;/*w ww  . ja v a 2  s  . c  om*/

        // 1) simple logger facade for SLF4J
        LOGGER.debug("Bootstrapping simple logger");
        resource = NashornScriptProcessor.class.getResource(SCRIPT_SIMPLE_LOGGER);
        this.executeScriptFromResource(resource);

        // 2) AMD loader and noSuchProperty to be used for all scripts apart from bootstrap
        LOGGER.debug("Setting up AMD");
        resource = NashornScriptProcessor.class.getResource(SCRIPT_AMD);
        this.executeScriptFromResource(resource);

        resource = NashornScriptProcessor.class.getResource(SCRIPT_NO_SUCH_PROPERTY);
        this.executeScriptFromResource(resource);

        final Object define = this.engine.get("define");
        this.amdPreloader = ((Invocable) this.engine).getInterface(define, AMDModulePreloader.class);

        // 3) the nashorn loader plugin so we can control access to globals
        LOGGER.debug("Setting up nashorn AMD loader");
        this.preloadAMDModule("loaderMetaLoader", "nashorn", "nashorn");

        // 4) remove Nashorn globals
        LOGGER.debug("Removing disallowed Nashorn globals \"{}\" and \"{}\"",
                NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE, this.nashornGlobalPropertiesToRemove);
        for (final String property : NASHORN_GLOBAL_PROPERTIES_TO_ALWAYS_REMOVE) {
            engineBindings.remove(property);
        }

        if (this.nashornGlobalPropertiesToRemove != null) {
            for (final String property : this.nashornGlobalPropertiesToRemove.split(",")) {
                engineBindings.remove(property.trim());
            }
        }

        // 5) Java extensions (must be picked up by modules before #9)
        globalBindings.put("processorExtensions", this.processorExtensions);

        // 6) AMD config
        LOGGER.debug("Applying AMD config \"{}\"", this.amdConfig);
        resource = this.amdConfig.getURL();
        this.executeScriptFromResource(resource);

        // 7) configured JavaScript base modules
        LOGGER.debug("Bootstrapping base modules");
        this.initScriptContextBaseModules(this.amdPreloader);

        // 8) configured JavaScript extension modules
        LOGGER.debug("Bootstrapping extension modules");
        this.initScriptContextExtensions(this.amdPreloader);

        // 9) remove any init data that shouldn't be publicly available
        globalBindings.clear();

        // 10) obtain the runner interface
        LOGGER.debug("Preparing AMD script runner");
        resource = NashornScriptProcessor.class.getResource(SCRIPE_AMD_SCRIPT_RUNNER);
        final Object scriptRunnerObj = this.executeScriptFromResource(resource);
        this.amdRunner = ((Invocable) this.engine).getInterface(scriptRunnerObj, AMDScriptRunner.class);

        LOGGER.info("New script context initialized");
    } catch (final Throwable t) {
        LOGGER.warn("Initialization of script context failed", t);

        // reset
        this.engine.setBindings(oldEngineBindings, ScriptContext.ENGINE_SCOPE);
        this.engine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
        this.amdPreloader = oldPreloader;
        this.amdRunner = oldAMDRunner;

        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        } else if (t instanceof ScriptException) {
            throw (ScriptException) t;
        } else {
            throw new org.alfresco.scripts.ScriptException(
                    "Unknown error initializing script context - reset to previous state", t);
        }
    } finally {
        inEngineContextInitialization.remove();
    }
}

From source file:org.jahia.services.content.rules.RulesNotificationService.java

private void sendMail(String template, Object user, String toMail, String fromMail, String ccList,
        String bcclist, Locale locale, KnowledgeHelper drools)
        throws RepositoryException, ScriptException, IOException {
    if (!notificationService.isEnabled()) {
        return;/* ww  w .j  ava 2  s . co  m*/
    }
    if (StringUtils.isEmpty(toMail)) {
        logger.warn("A mail couldn't be sent because to: has no recipient");
        return;
    }

    // Resolve template :
    String extension = StringUtils.substringAfterLast(template, ".");
    ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(extension);
    ScriptContext scriptContext = new SimpleScriptContext();
    final Bindings bindings = new SimpleBindings();
    bindings.put("currentUser", user);
    bindings.put("contextPath", Jahia.getContextPath());
    bindings.put("currentLocale", locale);
    final Object object = drools.getMatch().getTuple().getHandle().getObject();
    JCRNodeWrapper node = null;
    if (object instanceof AbstractNodeFact) {
        node = ((AbstractNodeFact) object).getNode();
        bindings.put("currentNode", node);
        final int siteURLPortOverride = SettingsBean.getInstance().getSiteURLPortOverride();
        bindings.put("servername",
                "http" + (siteURLPortOverride == 443 ? "s" : "") + "://" + node.getResolveSite().getServerName()
                        + ((siteURLPortOverride != 0 && siteURLPortOverride != 80 && siteURLPortOverride != 443)
                                ? ":" + siteURLPortOverride
                                : ""));
    }
    InputStream scriptInputStream = JahiaContextLoaderListener.getServletContext()
            .getResourceAsStream(template);
    if (scriptInputStream == null && node != null) {
        RulesListener rulesListener = RulesListener.getInstance(node.getSession().getWorkspace().getName());
        String packageName = drools.getRule().getPackageName();
        JahiaTemplateManagerService jahiaTemplateManagerService = ServicesRegistry.getInstance()
                .getJahiaTemplateManagerService();
        for (Map.Entry<String, String> entry : rulesListener.getModulePackageNameMap().entrySet()) {
            if (packageName.equals(entry.getValue())) {
                JahiaTemplatesPackage templatePackage = jahiaTemplateManagerService
                        .getTemplatePackage(entry.getKey());
                Resource resource = templatePackage.getResource(template);
                if (resource != null) {
                    scriptInputStream = resource.getInputStream();
                    break;
                }
            }
        }
    }
    if (scriptInputStream != null) {
        String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH
                .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/"))
                .replaceAll("."), ".");
        String subject = "";
        try {
            ResourceBundle resourceBundle = ResourceBundles.get(resourceBundleName, locale);
            bindings.put("bundle", resourceBundle);
            subject = resourceBundle.getString("subject");
        } catch (MissingResourceException e) {
            if (node != null) {
                final Value[] values = node.getResolveSite().getProperty("j:installedModules").getValues();
                for (Value value : values) {
                    try {
                        ResourceBundle resourceBundle = ResourceBundles
                                .get(ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                                        .getTemplatePackageById(value.getString()).getName(), locale);
                        subject = resourceBundle.getString(
                                drools.getRule().getName().toLowerCase().replaceAll(" ", ".") + ".subject");
                        bindings.put("bundle", resourceBundle);
                    } catch (MissingResourceException ee) {
                        // Do nothing
                    }
                }
            }
        }
        Reader scriptContent = null;
        try {
            scriptContent = new InputStreamReader(scriptInputStream);
            scriptContext.setWriter(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();
            String body = writer.toString();
            notificationService.sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body);
        } finally {
            if (scriptContent != null) {
                IOUtils.closeQuietly(scriptContent);
            }
        }
    }
}

From source file:org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngine.java

private String getScriptName(ScriptContext scriptContext) {
    Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
    String scriptName = (String) bindings.get(ScriptEngine.FILENAME);
    if (scriptName != null && !"".equals(scriptName)) {
        return scriptName;
    }/*from ww w . j av a  2s. c  om*/
    SlingScriptHelper sling = (SlingScriptHelper) bindings.get(SlingBindings.SLING);
    if (sling != null) {
        return sling.getScript().getScriptResource().getPath();
    }
    return NO_SCRIPT_NAME;
}

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

/**
 * Resets the entire {@code GremlinGroovyScriptEngine} by clearing script caches, recreating the classloader,
 * clearing bindings.//w w  w.j a  v a2  s  .c  o  m
 */
public void reset() {
    internalReset();
    getContext().getBindings(ScriptContext.ENGINE_SCOPE).clear();
}

From source file:org.jahia.services.mail.MailServiceImpl.java

@Override
public void sendMessageWithTemplate(String template, Map<String, Object> boundObjects, String toMail,
        String fromMail, String ccList, String bcclist, Locale locale, String templatePackageName)
        throws RepositoryException, ScriptException {
    // Resolve template :
    ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(StringUtils.substringAfterLast(template, "."));
    ScriptContext scriptContext = new SimpleScriptContext();

    //try if it is multilingual 
    String suffix = StringUtils.substringAfterLast(template, ".");
    String languageMailConfTemplate = template.substring(0, template.length() - (suffix.length() + 1)) + "_"
            + locale.toString() + "." + suffix;
    JahiaTemplatesPackage templatePackage = templateManagerService.getTemplatePackage(templatePackageName);
    Resource templateRealPath = templatePackage.getResource(languageMailConfTemplate);
    if (templateRealPath == null) {
        templateRealPath = templatePackage.getResource(template);
    }/*from   ww w.  java  2s. c om*/
    InputStream scriptInputStream = null;
    try {
        scriptInputStream = templateRealPath.getInputStream();
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    if (scriptInputStream != null) {
        ResourceBundle resourceBundle;
        if (templatePackageName == null) {
            String resourceBundleName = StringUtils.substringBeforeLast(Patterns.SLASH
                    .matcher(StringUtils.substringAfter(Patterns.WEB_INF.matcher(template).replaceAll(""), "/"))
                    .replaceAll("."), ".");
            resourceBundle = ResourceBundles.get(resourceBundleName, locale);
        } else {
            resourceBundle = ResourceBundles.get(ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                    .getTemplatePackage(templatePackageName), locale);
        }
        final Bindings bindings = new SimpleBindings();
        bindings.put("bundle", resourceBundle);
        bindings.putAll(boundObjects);
        Reader scriptContent = null;
        // Subject
        String subject;
        try {
            String subjectTemplatePath = StringUtils.substringBeforeLast(template, ".") + ".subject."
                    + StringUtils.substringAfterLast(template, ".");
            InputStream stream = templatePackage.getResource(subjectTemplatePath).getInputStream();
            scriptContent = templateCharset != null ? new InputStreamReader(stream, templateCharset)
                    : new InputStreamReader(stream);
            scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
            scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                    ScriptContext.GLOBAL_SCOPE);
            scriptContext.setWriter(new StringWriter());
            scriptEngine.eval(scriptContent, scriptContext);
            subject = scriptContext.getWriter().toString().trim();
        } catch (Exception e) {
            logger.warn("Not able to render mail subject using "
                    + StringUtils.substringBeforeLast(template, ".") + ".subject."
                    + StringUtils.substringAfterLast(template, ".")
                    + " template file - set org.jahia.services.mail.MailService in debug for more information");
            if (logger.isDebugEnabled()) {
                logger.debug("generating the mail subject throw an exception : ", e);
            }
            subject = resourceBundle.getString(
                    StringUtils.substringBeforeLast(StringUtils.substringAfterLast(template, "/"), ".")
                            + ".subject");
        } finally {
            IOUtils.closeQuietly(scriptContent);
        }
        try {
            try {
                scriptContent = templateCharset != null
                        ? new InputStreamReader(scriptInputStream, templateCharset)
                        : new InputStreamReader(scriptInputStream);
            } catch (UnsupportedEncodingException e) {
                throw new IllegalArgumentException(e);
            }
            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);
            scriptEngine.eval(scriptContent, scriptContext);
            StringWriter writer = (StringWriter) scriptContext.getWriter();
            String body = writer.toString();

            sendMessage(fromMail, toMail, ccList, bcclist, subject, null, body);
        } finally {
            IOUtils.closeQuietly(scriptContent);
        }
    } else {
        logger.warn("Cannot send mail, template [" + template + "] from module [" + templatePackageName
                + "] not found");
    }
}