Java 类javax.script.SimpleScriptContext 实例源码

项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:neoscada    文件:ExporterInterceptorHandler.java   
@Override
protected boolean processInterceptItem ( final Item item, final ItemInterceptor interceptorElement, final MasterContext masterContext, final Properties properties )
{
    final ExporterItemInterceptor interceptor = (ExporterItemInterceptor)interceptorElement;

    final Script script = interceptor.getScript ();

    final ScriptEngineManager manager = new ScriptEngineManager ();
    try
    {
        final ScriptExecutor executor = new ScriptExecutor ( manager, script.getLanguage (), script.getSource (), null );
        final ScriptContext context = new SimpleScriptContext ();
        final IEC60870Processor modbus = new IEC60870Processor ( this, interceptor, masterContext, item );
        context.setAttribute ( "IEC60870", modbus, ScriptContext.ENGINE_SCOPE );
        context.setAttribute ( "item", item, ScriptContext.ENGINE_SCOPE );
        context.setAttribute ( "properties", properties, ScriptContext.ENGINE_SCOPE );
        executor.execute ( context );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( "Failed to process script", e );
    }
    return true;
}
项目:neoscada    文件:ScriptCustomizationPipelineImpl.java   
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 *
 * @generated NOT
 */
@Override
public void customize ( final CustomizationRequest request )
{
    // FIXME: we should somehow take this out of here
    try
    {
        if ( this.executor == null )
        {
            final String resource = eResource ().getURI ().toString ();
            this.executor = new ScriptExecutor ( getScriptEngine (), this.code, ScriptCustomizationPipelineImpl.class.getClassLoader (), resource );
        }

        final SimpleScriptContext ctx = new SimpleScriptContext ();
        ctx.setAttribute ( "request", request, ScriptContext.ENGINE_SCOPE );

        this.executor.execute ( ctx );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( e );
    }
}
项目:neoscada    文件:ScriptSelectorImpl.java   
/**
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 *
 * @generated NOT
 */
@Override
public Boolean selected ( final CustomizationRequest request )
{
    try
    {
        if ( this.executor == null )
        {
            this.executor = new ScriptExecutor ( getScriptEngine (), this.code, ScriptCustomizationPipelineImpl.class.getClassLoader () );
        }

        final SimpleScriptContext ctx = new SimpleScriptContext ();
        ctx.setAttribute ( "request", request, ScriptContext.ENGINE_SCOPE );

        return (Boolean)this.executor.execute ( ctx );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( e );
    }
}
项目:neoscada    文件:ModbusExporterInterceptorHandler.java   
@Override
protected boolean processInterceptItem ( final Item item, final ItemInterceptor interceptorElement, final MasterContext masterContext, final Properties properties )
{
    final ModbusExporterInterceptor interceptor = (ModbusExporterInterceptor)interceptorElement;

    final Script script = interceptor.getScript ();

    final ScriptEngineManager manager = new ScriptEngineManager ();
    try
    {
        final ScriptExecutor executor = new ScriptExecutor ( manager, script.getLanguage (), script.getSource (), null );
        final ScriptContext context = new SimpleScriptContext ();
        final ModbusProcessor modbus = new ModbusProcessor ( this, interceptor, masterContext, item );
        context.setAttribute ( "MODBUS", modbus, ScriptContext.ENGINE_SCOPE );
        context.setAttribute ( "item", item, ScriptContext.ENGINE_SCOPE );
        context.setAttribute ( "properties", properties, ScriptContext.ENGINE_SCOPE );
        executor.execute ( context );
    }
    catch ( final Exception e )
    {
        throw new RuntimeException ( "Failed to process script", e );
    }
    return true;
}
项目:neoscada    文件:SetExternalNameWizard.java   
public static String evalName ( final CompiledScript script, final ExternalValue v ) throws Exception
{
    final SimpleScriptContext ctx = new SimpleScriptContext ();

    ctx.setAttribute ( "item", v, ScriptContext.ENGINE_SCOPE ); //$NON-NLS-1$

    final Object result = Scripts.executeWithClassLoader ( Activator.class.getClassLoader (), new Callable<Object> () {

        @Override
        public Object call () throws Exception
        {
            return script.eval ( ctx );
        }
    } );

    if ( result == null )
    {
        return null;
    }

    return result.toString ();
}
项目:neoscada    文件:ScriptEventHandler.java   
@Override
public Event handleEvent ( final Event event, final InjectionContext context )
{
    final ScriptContext scriptContext = new SimpleScriptContext ();
    try
    {
        scriptContext.setAttribute ( "event", event, ScriptContext.GLOBAL_SCOPE );
        scriptContext.setAttribute ( "logger", logger, ScriptContext.GLOBAL_SCOPE );
        scriptContext.setAttribute ( "injector", this.injector, ScriptContext.GLOBAL_SCOPE );

        final Object result = this.script.execute ( scriptContext );
        final Event resultEvent = convert ( result, event );
        logger.debug ( "Result: {}", resultEvent );
        return resultEvent;
    }
    catch ( final Exception e )
    {
        return event;
    }
}
项目:neoscada    文件:ScriptMonitor.java   
private synchronized void setScript ( final ConfigurationDataHelper cfg ) throws Exception
{
    String engineName = cfg.getString ( "scriptEngine", DEFAULT_ENGINE_NAME ); //$NON-NLS-1$
    if ( "".equals ( engineName ) ) // catches null
    {
        engineName = DEFAULT_ENGINE_NAME;
    }

    final ScriptEngine engine = Scripts.createEngine ( engineName, this.classLoader );
    this.scriptContext = new SimpleScriptContext ();

    // trigger init script
    final String initScript = cfg.getString ( "init" ); //$NON-NLS-1$
    if ( initScript != null )
    {
        new ScriptExecutor ( engine, initScript, this.classLoader ).execute ( this.scriptContext );
    }

    this.updateCommand = makeScript ( engine, cfg.getString ( "updateCommand" ) ); //$NON-NLS-1$
}
项目:neoscada    文件:RequestSignatureRuleImpl.java   
private void postProcess ( final AuthorizationContext context, final Result result ) throws Exception
{
    if ( this.postProcessor == null )
    {
        return;
    }

    logger.debug ( "Running post processor" );

    final ScriptContext scriptContext = new SimpleScriptContext ();

    final Map<String, Object> scriptObjects = new HashMap<String, Object> ();
    scriptObjects.put ( "authorizationContext", context );
    scriptObjects.put ( "authenticator", this.authenticator );

    this.postProcessor.execute ( scriptContext, scriptObjects );
}
项目:openjdk-jdk10    文件:MultiScopes.java   
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
项目:openjdk-jdk10    文件:ScopeTest.java   
/**
 * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
 * @throws ScriptException
 * @throws InterruptedException
 */
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (int i = 0; i < 100; i++) {
        final Bindings b = e.createBindings();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

        e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
        assertEquals(e.eval("a", ctxt), 1);
        assertEquals(b.get("a"), 1);
        assertEquals(e.eval("b", ctxt), 3);
        assertEquals(b.get("b"), 3);
        assertEquals(e.eval("c", ctxt), 10);
        assertEquals(b.get("c"), 10);
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that we can get interface out of a script object even after
 * switching to use different ScriptContext.
 */
public void getInterfaceDifferentContext() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final Object obj = e.eval("({ run: function() { } })");

        // change script context
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
        r.run();
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:openjdk-jdk10    文件:InvocableTest.java   
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:openjdk-jdk10    文件:TrustedScriptEngineTest.java   
@Test
public void globalPerEngineTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final String[] options = new String[] { "--global-per-engine" };
    final ScriptEngine e = fac.getScriptEngine(options);

    e.eval("function foo() {}");

    final ScriptContext newCtx = new SimpleScriptContext();
    newCtx.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);

    // all global definitions shared and so 'foo' should be
    // visible in new Bindings as well.
    assertTrue(e.eval("typeof foo", newCtx).equals("function"));

    e.eval("function bar() {}", newCtx);

    // bar should be visible in default context
    assertTrue(e.eval("typeof bar").equals("function"));
}
项目:openjdk-jdk10    文件:TrustedScriptEngineTest.java   
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}
项目:openjdk9    文件:MultiScopes.java   
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
项目:openjdk9    文件:InvocableTest.java   
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:openjdk9    文件:InvocableTest.java   
@Test
/**
 * Check that we can get interface out of a script object even after
 * switching to use different ScriptContext.
 */
public void getInterfaceDifferentContext() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final Object obj = e.eval("({ run: function() { } })");

        // change script context
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
        r.run();
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:openjdk9    文件:InvocableTest.java   
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:openjdk9    文件:TrustedScriptEngineTest.java   
@Test
public void globalPerEngineTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final String[] options = new String[] { "--global-per-engine" };
    final ScriptEngine e = fac.getScriptEngine(options);

    e.eval("function foo() {}");

    final ScriptContext newCtx = new SimpleScriptContext();
    newCtx.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);

    // all global definitions shared and so 'foo' should be
    // visible in new Bindings as well.
    assertTrue(e.eval("typeof foo", newCtx).equals("function"));

    e.eval("function bar() {}", newCtx);

    // bar should be visible in default context
    assertTrue(e.eval("typeof bar").equals("function"));
}
项目:openjdk9    文件:TrustedScriptEngineTest.java   
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}
项目:kaziranga    文件:MultiScopes.java   
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
项目:kaziranga    文件:ScopeTest.java   
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
项目:kaziranga    文件:ScopeTest.java   
/**
 * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
 * @throws ScriptException
 * @throws InterruptedException
 */
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (int i = 0; i < 100; i++) {
        final Bindings b = e.createBindings();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

        e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
        assertEquals(e.eval("a", ctxt), 1);
        assertEquals(b.get("a"), 1);
        assertEquals(e.eval("b", ctxt), 3);
        assertEquals(b.get("b"), 3);
        assertEquals(e.eval("c", ctxt), 10);
        assertEquals(b.get("c"), 10);
    }
}
项目:kaziranga    文件:InvocableTest.java   
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:jdk8u_nashorn    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:kaziranga    文件:InvocableTest.java   
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:kaziranga    文件:TrustedScriptEngineTest.java   
@Test
public void globalPerEngineTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final String[] options = new String[] { "--global-per-engine" };
    final ScriptEngine e = fac.getScriptEngine(options);

    e.eval("function foo() {}");

    final ScriptContext newCtx = new SimpleScriptContext();
    newCtx.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);

    // all global definitions shared and so 'foo' should be
    // visible in new Bindings as well.
    assertTrue(e.eval("typeof foo", newCtx).equals("function"));

    e.eval("function bar() {}", newCtx);

    // bar should be visible in default context
    assertTrue(e.eval("typeof bar").equals("function"));
}
项目:kaziranga    文件:TrustedScriptEngineTest.java   
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}
项目:qupath    文件:DefaultScriptEditor.java   
/**
 * Execute the script currently shown in the specified ScriptTab.
 * 
 * Output will be shown in the console of the ScriptTab.
 * 
 * @param tab
 * @param script
 * @param imageData
 */
private void executeScript(final ScriptTab tab, final String script, final ImageData<BufferedImage> imageData) {
    ScriptEditorControl console = tab.getConsoleComponent();

    ScriptContext context = new SimpleScriptContext();
    context.setWriter(new ScriptConsoleWriter(console, false));
    context.setErrorWriter(new ScriptConsoleWriter(console, true));

    LoggingAppender.getInstance().addTextComponent(console);
    if (outputScriptStartTime.get())
        logger.info("Starting script at {}", new Date());
    Object result = executeScript(tab.getLanguage(), script, imageData, useDefaultBindings.get(), context);
    if (result != null)
        logger.info("Result: {}", result);
    LoggingAppender.getInstance().removeTextComponent(console);
}
项目:lookaside_java-1.8.0-openjdk    文件:MultiScopes.java   
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    engine.put("x", "hello");
    // print global variable "x"
    engine.eval("print(x);");
    // the above line prints "hello"

    // Now, pass a different script context
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    final Bindings engineScope = newContext.getBindings(ScriptContext.ENGINE_SCOPE);

    // add new variable "x" to the new engineScope
    engineScope.put("x", "world");

    // execute the same script - but this time pass a different script context
    engine.eval("print(x);", newContext);
    // the above line prints "world"
}
项目:lookaside_java-1.8.0-openjdk    文件:ScopeTest.java   
@Test
public void userEngineScopeBindingsRetentionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptContext newContext = new SimpleScriptContext();
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    e.eval("function foo() {}", newContext);

    // definition retained with user's ENGINE_SCOPE Binding
    assertTrue(e.eval("typeof foo", newContext).equals("function"));

    final Bindings oldBindings = newContext.getBindings(ScriptContext.ENGINE_SCOPE);
    // but not in another ENGINE_SCOPE binding
    newContext.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("undefined"));

    // restore ENGINE_SCOPE and check again
    newContext.setBindings(oldBindings, ScriptContext.ENGINE_SCOPE);
    assertTrue(e.eval("typeof foo", newContext).equals("function"));
}
项目:jdk8u_nashorn    文件:ScopeTest.java   
/**
 * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
 * @throws ScriptException
 * @throws InterruptedException
 */
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (int i = 0; i < 100; i++) {
        final Bindings b = e.createBindings();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

        e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
        assertEquals(e.eval("a", ctxt), 1);
        assertEquals(b.get("a"), 1);
        assertEquals(e.eval("b", ctxt), 3);
        assertEquals(b.get("b"), 3);
        assertEquals(e.eval("c", ctxt), 10);
        assertEquals(b.get("c"), 10);
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:ScopeTest.java   
/**
 * Test "slow" scopes involving {@code with} and {@code eval} statements for shared script classes with multiple globals.
 * @throws ScriptException
 * @throws InterruptedException
 */
@Test
public static void testSlowScope() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    for (int i = 0; i < 100; i++) {
        final Bindings b = e.createBindings();
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(b, ScriptContext.ENGINE_SCOPE);

        e.eval(new URLReader(ScopeTest.class.getResource("resources/witheval.js")), ctxt);
        assertEquals(e.eval("a", ctxt), 1);
        assertEquals(b.get("a"), 1);
        assertEquals(e.eval("b", ctxt), 3);
        assertEquals(b.get("b"), 3);
        assertEquals(e.eval("c", ctxt), 10);
        assertEquals(b.get("c"), 10);
    }
}
项目:jdk8u_nashorn    文件:InvocableTest.java   
@Test
/**
 * Check that invokeFunction calls functions only from current context's
 * Bindings.
 */
public void invokeFunctionDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        e.eval("function hello() { return 'Hello World!'; }");
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        // change engine's current context
        e.setContext(ctxt);

        ((Invocable) e).invokeFunction("hello"); // no 'hello' in new context!
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
项目:lookaside_java-1.8.0-openjdk    文件:ScopeTest.java   
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    CompiledScript compiledScript = ((Compilable)engine).compile(script);
    Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
项目:lookaside_java-1.8.0-openjdk    文件:InvocableTest.java   
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
项目:jdk8u_nashorn    文件:TrustedScriptEngineTest.java   
@Test
public void evalFileNameWithSpecialCharsTest() throws ScriptException {
    final NashornScriptEngineFactory fac = new NashornScriptEngineFactory();
    final ScriptEngine engine = fac.getScriptEngine(new String[] { "--verify-code=true" });
    final ScriptContext ctxt = new SimpleScriptContext();
    // use file name with "dangerous" chars.
    ctxt.setAttribute(ScriptEngine.FILENAME, "<myscript>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var a = 3;");
    ctxt.setAttribute(ScriptEngine.FILENAME, "[myscript]", ScriptContext.ENGINE_SCOPE);
    engine.eval("var h = 'hello';");
    ctxt.setAttribute(ScriptEngine.FILENAME, ";/\\$.", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
    // name used by jjs shell tool for the interactive mode
    ctxt.setAttribute(ScriptEngine.FILENAME, "<shell>", ScriptContext.ENGINE_SCOPE);
    engine.eval("var foo = 'world';");
}