Example usage for javax.script Bindings remove

List of usage examples for javax.script Bindings remove

Introduction

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

Prototype

public Object remove(Object key);

Source Link

Document

Removes the mapping for this key from this map if it is present (optional operation).

Usage

From source file:Main.java

public static void main(String[] args) {
    Bindings params = new SimpleBindings();
    params.put("stringKey", "Hello");
    params.put("valueKey", 2015);

    Object msg = params.get("stringKey");
    Object year = params.get("valueKey");
    System.out.println("stringKey" + msg);
    System.out.println("valueKey = " + year);

    params.remove("valueKey");
    year = params.get("valueKey");

    boolean containsYear = params.containsKey("valueKey");
    System.out.println("valueKey = " + year);
    System.out.println("params contains year = " + containsYear);
}

From source file:Main.java

public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    Bindings params = engine.createBindings();

    params.put("stringKey", "Hello");
    params.put("valueKey", 2015);

    Object msg = params.get("stringKey");
    Object year = params.get("valueKey");
    System.out.println("stringKey" + msg);
    System.out.println("valueKey = " + year);

    params.remove("valueKey");
    year = params.get("valueKey");

    boolean containsYear = params.containsKey("valueKey");
    System.out.println("valueKey = " + year);
    System.out.println("params contains year = " + containsYear);
}

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 a v a  2  s .co m*/

        // 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:com.qspin.qtaste.testsuite.impl.JythonTestScript.java

@Override
public boolean execute(TestData data, TestResult result, final boolean debug) {
    // Interpret the file
    testData = data;//from   ww w  . j  ava2  s  .  co  m
    testResult = result;

    if (debug) {
        testScriptBreakPointEventHandler.addTestScriptBreakpointListener(scriptBreakpoint);
    }

    try {
        Bindings bindings = engine.createBindings();
        engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

        engine.eval("import sys as __sys");
        engine.eval("if not globals().has_key('__initModules'):\n" + "  __initModules = __sys.modules.keys()\n"
                + "else:\n" + "  for m in __sys.modules.keys():\n" + "    if m not in __initModules:\n"
                + "      del __sys.modules[m]", globalBindings);

        // add all global bindinds
        bindings.putAll(globalBindings);

        if (testSuite != null) {
            // add pythonlib subdirectories of test script directory up to test suites directory, to python path
            List<String> additionalPythonPath = getAdditionalPythonPath();
            String pythonPathScript = "";
            for (String pythonlib : additionalPythonPath) {
                pythonPathScript += "__sys.path.append(r'" + pythonlib + "')\n";
            }
            engine.eval(pythonPathScript);
        }

        // reset doStep count / step id / step name stacks
        engine.eval("doStep.countStack = [0]\n" + "doStep.stepIdStack = []\n" + "doStep.stepNameStack = []\n");

        // add testAPI, testData and scriptBreakpoint to bindings
        bindings.put("this", this);
        engine.eval("testAPI = __TestAPIWrapper(this)");
        bindings.remove("__TestAPIWrapper");
        bindings.remove("this");
        bindings.put("testData", scriptTestData);
        bindings.put("DoubleWithPrecision", DoubleWithPrecision.class);
        bindings.put("QTasteException", QTasteException.class);
        bindings.put("QTasteDataException", QTasteDataException.class);
        bindings.put("QTasteTestFailException", QTasteTestFailException.class);
        bindings.put("__scriptBreakpoint", scriptBreakpoint);
        globalBindings.put("testScript", this);

        // create QTaste module with testAPI, testData, DoubleWithPrecision, doStep, doSteps, doSubStep, logger and Status
        engine.eval("class __QTaste_Module:\n" + "    def __init__(self):\n"
                + "        self.importTestScript= importTestScript\n"
                + "        self.isInTestScriptImport= isInTestScriptImport\n"
                + "        self.testAPI= testAPI\n" + "        self.testData = testData\n"
                + "        self.DoubleWithPrecision = DoubleWithPrecision\n" + "        self.doStep = doStep\n"
                + "        self.doSteps = doSteps\n" + "        self.doSubStep = doStep\n"
                + "        self.doSubSteps = doSteps\n" + "        self.logger = logger\n"
                + "        self.Status = Status\n" + "        self.QTasteException = QTasteException\n"
                + "        self.QTasteDataException = QTasteDataException\n"
                + "        self.QTasteTestFailException = QTasteTestFailException\n"
                + "__sys.modules['qtaste'] = __QTaste_Module()");

        // remove testAPI, testData, DoubleWithPrecision, doStep, doSteps, logger and Status from bindinds
        bindings.remove("__QTaste_Module");
        bindings.remove("importTestScript");
        bindings.remove("isCalledFromMainTestScript");
        bindings.remove("testAPI");
        bindings.remove("testData");
        bindings.remove("DoubleWithPrecision");
        bindings.remove("doStep");
        bindings.remove("doSteps");
        bindings.remove("logger");
        bindings.remove("Status");
        bindings.remove("QTasteException");
        bindings.remove("QTasteDataException");
        bindings.remove("QTasteTestFailException");

        // Check if test was aborted by user before execute testscript.py
        if (TestEngine.isAbortedByUser()) {
            return false;
        }

        if (!debug) {
            engine.eval("execfile(r'" + fileName + "', globals())");
        } else {
            // execute in debugger
            engine.eval(scriptDebuggerClassCode);
            engine.eval("__debugger = __ScriptDebugger()");
            bindings.remove("__bdb");
            bindings.remove("__ScriptDebugger");
            for (Breakpoint b : breakPointEventHandler.getBreakpoints()) {
                engine.eval("__debugger.set_break(r'" + b.getFileName() + "', " + b.getLineIndex() + ")");
            }
            engine.eval("__debugger.runcall(execfile, r'" + fileName + "', globals())");
        }
    } catch (ScriptException e) {
        handleScriptException(e, result);
    } finally {
        if (debug) {
            testScriptBreakPointEventHandler.removeTestScriptBreakpointListener(scriptBreakpoint);
        }
    }
    return true;
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldEvalGlobalClosuresEvenAfterEvictionOfClass() throws ScriptException {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("marko", convertToVertexId("marko"));
    bindings.put("vadas", convertToVertexId("vadas"));

    // strong referenced global closure
    engine.eval("def isVadas(v){v.value('name')=='vadas'}", bindings);
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));

    // phantom referenced global closure
    bindings.put(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE,
            GremlinGroovyScriptEngine.REFERENCE_TYPE_PHANTOM);
    engine.eval("def isMarko(v){v.value('name')=='marko'}", bindings);

    try {/*from  w  w w .  j  a v a  2 s.com*/
        engine.eval("isMarko(g.V(marko).next())", bindings);
        fail("the isMarko function should not be present");
    } catch (Exception ex) {

    }

    assertEquals(true,
            engine.eval("def isMarko(v){v.value('name')=='marko'}; isMarko(g.V(marko).next())", bindings));

    try {
        engine.eval("isMarko(g.V(marko" + ").next())", bindings);
        fail("the isMarko function should not be present");
    } catch (Exception ex) {

    }

    bindings.remove(GremlinGroovyScriptEngine.KEY_REFERENCE_TYPE);

    // isVadas class was a hard reference so it should still be hanging about
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));
}

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

@Test
@LoadGraphWith(LoadGraphWith.GraphData.MODERN)
public void shouldAllowFunctionsUsedInClosure() throws ScriptException {
    final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine();

    final Bindings bindings = engine.createBindings();
    bindings.put("g", g);
    bindings.put("#jsr223.groovy.engine.keep.globals", "phantom");
    bindings.put("vadas", convertToVertexId("vadas"));

    // this works on its own when the function and the line that uses it is in one "script".  this is the
    // current workaround
    assertEquals(g.V(convertToVertexId("vadas")).next(), engine
            .eval("def isVadas(v){v.value('name')=='vadas'};g.V().filter{isVadas(it.get())}.next()", bindings));

    // let's reset this piece and make sure isVadas is not hanging around.
    engine.reset();/*from  w  ww  .j a  v a  2 s.com*/

    // validate that isVadas throws an exception since it is not defined
    try {
        engine.eval("isVadas(g.V(vadas).next())", bindings);

        // fail the test if the above doesn't throw an exception
        fail();
    } catch (Exception ex) {
        // this is good...we want this. it means isVadas isn't hanging about
    }

    // now...define the function separately on its own in one script
    bindings.remove("#jsr223.groovy.engine.keep.globals");
    engine.eval("def isVadas(v){v.value('name')=='vadas'}", bindings);

    // make sure the function works on its own...no problem
    assertEquals(true, engine.eval("isVadas(g.V(vadas).next())", bindings));

    // make sure the function works in a closure...this generates a StackOverflowError
    assertEquals(g.V(convertToVertexId("vadas")).next(),
            engine.eval("g.V().filter{isVadas(it.get())}.next()", bindings));
}

From source file:org.onesec.raven.ivr.actions.StartRecordingActionTest.java

@Test
public void test() throws Exception {
    MocksControl control = new MocksControl(MocksControl.MockType.NICE);
    IvrEndpointConversation conv = control.createMock(IvrEndpointConversation.class);
    ConversationScenarioState state = control.createMock(ConversationScenarioState.class);
    Bindings bindings = control.createMock(Bindings.class);
    IncomingRtpStream inRtp = control.createMock(IncomingRtpStream.class);

    expect(conv.getConversationScenarioState()).andReturn(state).atLeastOnce();
    expect(state.getBindings()).andReturn(bindings).atLeastOnce();
    expect(bindings.get(BindingNames.DATA_CONTEXT_BINDING)).andReturn(null);
    expect(bindings.get(StartRecordingAction.RECORDER_BINDING)).andReturn(null);
    expect(conv.getOwner()).andReturn(actionNode);
    expect(conv.getExecutorService()).andReturn(executor).atLeastOnce();
    expect(conv.getIncomingRtpStream()).andReturn(inRtp);
    expect(inRtp.addDataSourceListener(checkRtpListener(codecManager, executor, actionNode, bufferCache),
            isNull(AudioFormat.class))).andReturn(true);
    state.setBinding(eq(StartRecordingAction.RECORDER_BINDING), isA(Recorder.class),
            eq(BindingScope.CONVERSATION));
    expect(bindings.remove(StartRecordingAction.RECORDER_BINDING)).andReturn(null);

    control.replay();/*w  w w  .  j  a v a2s  .  c  om*/

    StartRecordingAction action = (StartRecordingAction) actionNode.createAction();
    assertNotNull(action);
    action.doExecute(conv);
    Thread.sleep(1000);
    assertNotNull(recorder);
    recorder.stopRecording(false);

    assertEquals(1, collector.getDataListSize());
    assertTrue(collector.getDataList().get(0) instanceof DataSource);
    DataSource ds = (DataSource) collector.getDataList().get(0);
    FileOutputStream out = new FileOutputStream("target/test.wav");
    IOUtils.copy(ds.getInputStream(), out);
    out.close();
    //        while (action.)
    control.verify();
}

From source file:org.rhq.bindings.ScriptEngineFactory.java

/**
 * Remove the specified bindings from the engine.
 * //w  w  w.  j a  v a2 s  . co  m
 * @param engine the engine
 * @param keySet the binding keys to be removed
 */
public static void removeBindings(ScriptEngine engine, Set<String> keySet) {

    Bindings engineBindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);

    for (String key : keySet) {
        engineBindings.remove(key);
    }

    engine.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
}