Example usage for javax.script Bindings put

List of usage examples for javax.script Bindings put

Introduction

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

Prototype

public Object put(String name, Object value);

Source Link

Document

Set a named value.

Usage

From source file:org.apache.tinkerpop.gremlin.groovy.engine.GremlinExecutorTest.java

@Test
public void shouldAllowConcurrentModificationOfGlobals() throws Exception {
    // this test simulates a scenario that likely shouldn't happen - where globals are modified by multiple
    // threads.  globals are created in a synchronized fashion typically but it's possible that someone
    // could do something like this and this test validate that concurrency exceptions don't occur as a
    // result/*from ww  w .  j  ava 2 s . c o m*/
    final ExecutorService service = Executors.newFixedThreadPool(8, testingThreadFactory);
    final Bindings globals = new SimpleBindings();
    globals.put("g", -1);
    final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(globals).create();

    final AtomicBoolean failed = new AtomicBoolean(false);
    final int max = 512;
    final List<Pair<Integer, List<Integer>>> futures = Collections.synchronizedList(new ArrayList<>(max));
    IntStream.range(0, max).forEach(i -> {
        final int yValue = i * 2;
        final Bindings b = new SimpleBindings();
        b.put("x", i);
        b.put("y", yValue);
        final int zValue = i * -1;

        final String script = "z=" + zValue + ";[x,y,z,g]";
        try {
            service.submit(() -> {
                try {
                    // modify the global in a separate thread
                    gremlinExecutor.getGlobalBindings().put("g", i);
                    gremlinExecutor.getGlobalBindings().put(Integer.toString(i), i);
                    gremlinExecutor.getGlobalBindings().keySet().stream()
                            .filter(s -> i % 2 == 0 && !s.equals("g")).findFirst().ifPresent(globals::remove);
                    final List<Integer> result = (List<Integer>) gremlinExecutor.eval(script, b).get();
                    futures.add(Pair.with(i, result));
                } catch (Exception ex) {
                    failed.set(true);
                }
            });
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    });

    service.shutdown();
    assertThat(service.awaitTermination(60000, TimeUnit.MILLISECONDS), is(true));

    // likely a concurrency exception if it occurs - and if it does then we've messed up because that's what this
    // test is partially designed to protected against.
    assertThat(failed.get(), is(false));

    assertEquals(max, futures.size());
    futures.forEach(t -> {
        assertEquals(t.getValue0(), t.getValue1().get(0));
        assertEquals(t.getValue0() * 2, t.getValue1().get(1).intValue());
        assertEquals(t.getValue0() * -1, t.getValue1().get(2).intValue());
        assertThat(t.getValue1().get(3).intValue(), greaterThan(-1));
    });
}

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 w w  . j  av  a2  s .  com*/

        // 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.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java

private Bindings createBindings(final Map<String, Object> bindingMap, final Map<String, String> rebindingMap) {
    final Bindings bindings = new SimpleBindings();

    // rebind any global bindings to a different variable.
    if (!rebindingMap.isEmpty()) {
        for (Map.Entry<String, String> kv : rebindingMap.entrySet()) {
            boolean found = false;
            final Map<String, Graph> graphs = this.graphManager.getGraphs();
            if (graphs.containsKey(kv.getValue())) {
                bindings.put(kv.getKey(), graphs.get(kv.getValue()));
                found = true;/*from www . ja va2  s  . c o  m*/
            }

            if (!found) {
                final Map<String, TraversalSource> traversalSources = this.graphManager.getTraversalSources();
                if (traversalSources.containsKey(kv.getValue())) {
                    bindings.put(kv.getKey(), traversalSources.get(kv.getValue()));
                    found = true;
                }
            }

            if (!found) {
                final String error = String.format(
                        "Could not rebind [%s] to [%s] as [%s] not in the Graph or TraversalSource global bindings",
                        kv.getKey(), kv.getValue(), kv.getValue());
                throw new IllegalStateException(error);
            }
        }
    }

    bindings.putAll(bindingMap);

    return bindings;
}

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

protected Bindings getBindings(WorkItem workItem, JCRSessionWrapper session) throws RepositoryException {
    final Map<String, Object> vars = workItem.getParameters();
    Locale locale = (Locale) vars.get("locale");
    final Bindings bindings = new MyBindings(workItem);
    WorkflowDefinition workflowDefinition = (WorkflowDefinition) vars.get("workflow");
    ResourceBundle resourceBundle = ResourceBundles
            .get(workflowDefinition.getPackageName() + "." + workflowDefinition.getName(), locale);
    bindings.put("bundle", resourceBundle);
    // user is the one that initiate the Execution  (WorkflowService.startProcess)
    // currentUser is the one that "moves" the Execution  (JBPMProvider.assignTask)
    JCRUserNode jahiaUser = userManagerService.lookupUserByPath((String) vars.get("user"));
    if (vars.containsKey("currentUser")) {
        JCRUserNode currentUser = userManagerService.lookupUserByPath((String) vars.get("currentUser"));
        bindings.put("currentUser", currentUser);
    } else {/*from  ww  w .  j a  va 2 s .  c o  m*/
        bindings.put("currentUser", jahiaUser);
    }
    bindings.put("user", jahiaUser);
    if (jahiaUser != null && !UserPreferencesHelper.areEmailNotificationsDisabled(jahiaUser)) {
        bindings.put("userNotificationEmail", UserPreferencesHelper.getPersonalizedEmailAddress(jahiaUser));
    }
    if (vars.containsKey("comments")) {
        bindings.put("comments", vars.get("comments"));
    }
    bindings.put("date", new DateTool());
    bindings.put("submissionDate", Calendar.getInstance());
    bindings.put("locale", locale);
    bindings.put("workspace", vars.get("workspace"));

    List<JCRNodeWrapper> nodes = new LinkedList<JCRNodeWrapper>();
    @SuppressWarnings("unchecked")
    List<String> stringList = (List<String>) vars.get("nodeIds");
    for (String s : stringList) {
        JCRNodeWrapper nodeByUUID = session.getNodeByUUID(s);
        if (!nodeByUUID.isNodeType("jnt:translation")) {
            nodes.add(nodeByUUID);
        }
    }
    bindings.put("nodes", nodes);
    return bindings;
}

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

@Override
public Traversal.Admin eval(final Bytecode bytecode, final Bindings bindings, final String traversalSource)
        throws ScriptException {
    // these validations occur before merging in bytecode bindings which will override existing ones. need to
    // extract the named traversalsource prior to that happening so that bytecode bindings can share the same
    // namespace as global bindings (e.g. traversalsources and graphs).
    if (traversalSource.equals(HIDDEN_G))
        throw new IllegalArgumentException(
                "The traversalSource cannot have the name " + HIDDEN_G + " - it is reserved");

    if (bindings.containsKey(HIDDEN_G))
        throw new IllegalArgumentException("Bindings cannot include " + HIDDEN_G + " - it is reserved");

    if (!bindings.containsKey(traversalSource))
        throw new IllegalArgumentException(
                "The bindings available to the ScriptEngine do not contain a traversalSource named: "
                        + traversalSource);

    final Object b = bindings.get(traversalSource);
    if (!(b instanceof TraversalSource))
        throw new IllegalArgumentException(traversalSource + " is of type " + b.getClass().getSimpleName()
                + " and is not an instance of TraversalSource");

    final Bindings inner = new SimpleBindings();
    inner.putAll(bindings);// ww w  .  j a  va2 s.c  o  m
    inner.putAll(bytecode.getBindings());
    inner.put(HIDDEN_G, b);

    return (Traversal.Admin) this.eval(GroovyTranslator.of(HIDDEN_G).translate(bytecode), inner);
}

From source file:org.lsc.utils.GroovyEvaluator.java

/**
 * Local instance evaluation.//from w  w w .  j  ava  2  s . com
 *
 * @param expression
 *                the expression to eval
 * @param params
 *                the keys are the name used in the
 * @return the evaluation result
 */
private Object instanceEval(final Task task, final String expression, final Map<String, Object> params) {
    Bindings bindings = engine.createBindings();

    /* Allow to have shorter names for function in the package org.lsc.utils.directory */
    String expressionImport =
            //                  "import static org.lsc.utils.directory.*\n" +
            //                  "import static org.lsc.utils.*\n" + 
            expression;

    // add LDAP interface for destination
    if (!bindings.containsKey("ldap") && task.getDestinationService() instanceof AbstractSimpleJndiService) {
        ScriptableJndiServices dstSjs = new ScriptableJndiServices();
        dstSjs.setJndiServices(((AbstractSimpleJndiService) task.getDestinationService()).getJndiServices());
        bindings.put("ldap", dstSjs);
    }

    // add LDAP interface for source
    if (!bindings.containsKey("srcLdap") && task.getSourceService() instanceof AbstractSimpleJndiService) {
        ScriptableJndiServices srcSjs = new ScriptableJndiServices();
        srcSjs.setJndiServices(((AbstractSimpleJndiService) task.getSourceService()).getJndiServices());
        bindings.put("srcLdap", srcSjs);
    }

    if (params != null) {
        for (String paramName : params.keySet()) {
            bindings.put(paramName, params.get(paramName));
        }
    }

    Object ret = null;
    try {
        if (task.getScriptIncludes() != null) {
            for (File scriptInclude : task.getScriptIncludes()) {
                String extension = FilenameUtils.getExtension(scriptInclude.getAbsolutePath());
                if ("groovy".equals(extension) || "gvy".equals(extension) || "gy".equals(extension)
                        || "gsh".equals(extension)) {
                    FileReader reader = new FileReader(scriptInclude);
                    try {
                        engine.eval(reader, bindings);
                    } finally {
                        reader.close();
                    }
                }
            }
        }
        ret = engine.eval(expressionImport, bindings);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.error(e.toString());
        LOGGER.debug(e.toString(), e);
        return null;
    }

    return ret;
}

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;/*w w  w .  j a  v  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.jahia.ajax.gwt.helper.UIConfigHelper.java

/**
 * Get resources/*from w  ww.jav  a  2s . 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;
}

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.
 */// ww w  . j ava2  s  .co  m
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;
}