javax.script.ScriptContext Java Examples

The following examples show how to use javax.script.ScriptContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiScopes.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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"
}
 
Example #2
Source File: SGraph.java    From constellation with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate a function against a write lock on the graph with commits or
 * rollbacks handled automatically.
 * <p>
 * Note: This method will only work for Python scripts as it makes use of
 * Python specific syntax.
 *
 * @param callback the function to evaluate.
 * @throws ScriptException
 * @throws InterruptedException
 */
public void withWritableGraph(final Object callback) throws ScriptException, InterruptedException {
    final SWritableGraph writableGraph = writableGraph("Scripting View Context Manager");
    LOGGER.log(Level.INFO, "creating context for {0}", writableGraph);
    boolean ok = false;
    try {
        final ScriptContext context = engine.getContext();
        context.setAttribute("__func", callback, ScriptContext.ENGINE_SCOPE);
        context.setAttribute("__p1", writableGraph, ScriptContext.ENGINE_SCOPE);
        engine.eval("__func(__p1)");
        ok = true;
    } catch (ScriptException ex) {
        LOGGER.log(Level.WARNING, "exception in context: {0}", ex.toString());
        writableGraph.rollback();
        throw ex;
    } finally {
        LOGGER.log(Level.WARNING, "context successful = {0}", ok);
        if (ok) {
            writableGraph.commit();
            LOGGER.log(Level.WARNING, "commiting {0}", writableGraph);
        }
    }
}
 
Example #3
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 6 votes vote down vote up
@Test
public void scopeInteractionNewContextSimpleBindingsPropertyAssignment() throws ScriptException {
    ScriptContext context = new SimpleScriptContext();
    context.setBindings(engine.getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE);
    context.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    context.setAttribute("value", "Phecda", ScriptContext.ENGINE_SCOPE);
    context.setAttribute("value", "Scheat", ScriptContext.GLOBAL_SCOPE);

    engine.eval("this.value = 'Aludra'", context);

    assertThat(engine.eval("this.value", context), nullValue());
    assertThat(engine.eval("value", context), instanceOfWith(String.class, is("Phecda")));
    assertThat(context.getAttribute("value", ScriptContext.ENGINE_SCOPE),
            instanceOfWith(String.class, is("Phecda")));
    assertThat(context.getAttribute("value", ScriptContext.GLOBAL_SCOPE),
            instanceOfWith(String.class, is("Scheat")));
}
 
Example #4
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a compiled script and returns the result.
 *
 * @param script Compiled script.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @return The script result.
 * @throws IllegalArgumentException
 */
public static Object executeScript(CompiledScript script, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException {
    Assert.notNull("script", script, "scriptContext", scriptContext);
    Object result = script.eval(scriptContext);
    if (UtilValidate.isNotEmpty(functionName)) {
        if (Debug.verboseOn()) {
            Debug.logVerbose("Invoking function/method " + functionName, module);
        }
        ScriptEngine engine = script.getEngine();
        try {
            Invocable invocableEngine = (Invocable) engine;
            result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
        } catch (ClassCastException e) {
            throw new ScriptException("Script engine " + engine.getClass().getName() + " does not support function/method invocations");
        }
    }
    return result;
}
 
Example #5
Source File: NashornScriptEngine.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final ScriptObject ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final ScriptObject oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        // set ScriptContext variables if ctxt is non-null
        if (ctxt != null) {
            setContextVariables(ctxtGlobal, ctxt);
        }
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #6
Source File: InvocableTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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());
    }
}
 
Example #7
Source File: NashornScriptEngine.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private Object evalImpl(final Context.MultiGlobalCompiledScript mgcs, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        final ScriptFunction script = mgcs.getFunction(ctxtGlobal);
        final ScriptContext oldCtxt = ctxtGlobal.getScriptContext();
        ctxtGlobal.setScriptContext(ctxt);
        try {
            return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
        } finally {
            ctxtGlobal.setScriptContext(oldCtxt);
        }
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
 
Example #8
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 6 votes vote down vote up
@Test
public void isolatedBindingsWithContextAndSimpleBindings() throws ScriptException {
    ScriptContext context = new SimpleScriptContext();
    Bindings binding = new SimpleBindings();
    context.setBindings(binding, ScriptContext.ENGINE_SCOPE);
    engine.eval("var value = 'Zeta Scorpii'", context);

    assertThat(engine.eval("value", context), instanceOfWith(String.class, is("Zeta Scorpii")));

    context.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
    assertThat(engine.eval("typeof value", context), instanceOfWith(String.class, is("undefined")));

    context.setBindings(new SimpleBindings(), ScriptContext.ENGINE_SCOPE);
    assertThat(engine.eval("typeof value", context), instanceOfWith(String.class, is("undefined")));

    context.setBindings(binding, ScriptContext.ENGINE_SCOPE);
    assertThat(engine.eval("value", context), instanceOfWith(String.class, is("Zeta Scorpii")));
}
 
Example #9
Source File: ScriptMixin.java    From attic-polygene-java with Apache License 2.0 6 votes vote down vote up
public ScriptMixin( @Structure PolygeneSPI spi,
                    @This Object thisComposite,
                    @State StateHolder state,
                    @Structure Layer layer,
                    @Structure Module module,
                    @Structure Application application )
{
    descriptor = spi.compositeDescriptorFor( thisComposite );
    engine = createNewEngine();
    Bindings mixinBindings = engine.getBindings( ScriptContext.ENGINE_SCOPE );
    mixinBindings.put( "Polygene", spi );
    mixinBindings.put( "application", application );
    mixinBindings.put( "layer", layer );
    mixinBindings.put( "module", module );
    mixinBindings.put( "This", thisComposite );
    mixinBindings.put( "state", state );
    mixinBindings.put( "objectFactory", module.objectFactory() );
    mixinBindings.put( "unitOfWorkFactory", module.unitOfWorkFactory() );
    mixinBindings.put( "valueBuilderFactory", module.valueBuilderFactory() );
    mixinBindings.put( "transientBuilderFactory", module.transientBuilderFactory() );
    mixinBindings.put( "serviceFinder", module.serviceFinder() );
    mixinBindings.put( "typeLookup", module.typeLookup() );
}
 
Example #10
Source File: JavaScriptOperator.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public void setup(OperatorContext context)
{
  for (Map.Entry<String, Object> entry : serializableBindings.entrySet()) {
    scriptBindings.put(entry.getKey(), entry.getValue());
  }
  this.scriptContext.setBindings(scriptBindings, ScriptContext.ENGINE_SCOPE);
  engine.setContext(this.scriptContext);
  try {
    for (String s : setupScripts) {
      engine.eval(s, this.scriptContext);
    }
  } catch (ScriptException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #11
Source File: TrustedScriptEngineTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@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"));
}
 
Example #12
Source File: TrustedScriptEngineTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@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"));
}
 
Example #13
Source File: ScopeTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@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"));
}
 
Example #15
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void mapScriptObjectMirrorCallsiteTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = m.getEngineByName("nashorn");
    final String TEST_SCRIPT = "typeof obj.foo";

    final Bindings global = engine.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
    engine.eval("var obj = java.util.Collections.emptyMap()");
    // this will drive callsite "obj.foo" of TEST_SCRIPT
    // to use "obj instanceof Map" as it's guard
    engine.eval(TEST_SCRIPT, global);
    // redefine 'obj' to be a script object
    engine.eval("obj = {}");

    final Bindings newGlobal = engine.createBindings();
    // transfer 'obj' from default global to new global
    // new global will get a ScriptObjectMirror wrapping 'obj'
    newGlobal.put("obj", global.get("obj"));

    // Every ScriptObjectMirror is a Map! If callsite "obj.foo"
    // does not see the new 'obj' is a ScriptObjectMirror, it'll
    // continue to use Map's get("obj.foo") instead of ScriptObjectMirror's
    // getMember("obj.foo") - thereby getting null instead of undefined
    assertEquals("undefined", engine.eval(TEST_SCRIPT, newGlobal));
}
 
Example #16
Source File: ScriptEngineTest.java    From es6draft with MIT License 6 votes vote down vote up
@Test
public void contextAndBindings() {
    ScriptContext context = engine.getContext();
    assertThat(context, notNullValue());
    assertThat(context, sameInstance(engine.getContext()));

    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    assertThat(globalScope, notNullValue());
    assertThat(globalScope, sameInstance(engine.getBindings(ScriptContext.GLOBAL_SCOPE)));
    assertThat(globalScope, sameInstance(context.getBindings(ScriptContext.GLOBAL_SCOPE)));
    assertThat(globalScope, sameInstance(manager.getBindings()));

    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    assertThat(engineScope, notNullValue());
    assertThat(engineScope, sameInstance(engine.getBindings(ScriptContext.ENGINE_SCOPE)));
    assertThat(engineScope, sameInstance(context.getBindings(ScriptContext.ENGINE_SCOPE)));
    assertThat(engineScope, not(sameInstance(manager.getBindings())));
}
 
Example #17
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void invokeFunctionInGlobalScopeTest() throws Exception {
     final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
     final ScriptContext ctxt = engine.getContext();

     // define a function called "func"
     engine.eval("func = function() { return 42 }");

     // move ENGINE_SCOPE Bindings to GLOBAL_SCOPE
     ctxt.setBindings(ctxt.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.GLOBAL_SCOPE);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define new function that calls "func" now in GLOBAL_SCOPE
     engine.eval("newfunc = function() { return func() }");

     // call "newfunc" and check the return value
     Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
 
Example #18
Source File: GremlinGroovyScriptEngine.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
private Object callGlobal(final String name, final Object args[], final ScriptContext ctx) {
    final Closure closure = globalClosures.get(name);
    if (closure != null) {
        return closure.call(args);
    }

    final Object value = ctx.getAttribute(name);
    if (value instanceof Closure) {
        return ((Closure) value).call(args);
    } else {
        throw new MissingMethodException(name, getClass(), args);
    }
}
 
Example #19
Source File: BindingsScriptEngineTest.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddLazyGlobalBindingsViaPlugin() throws Exception {
    final Bindings bindings = new SimpleBindings();
    bindings.put("x", 100);
    final BindingsGremlinPlugin plugin = new BindingsGremlinPlugin(() -> bindings);

    final DefaultGremlinScriptEngineManager manager = new DefaultGremlinScriptEngineManager();
    manager.addPlugin(plugin);
    final GremlinScriptEngine engine = manager.getEngineByName(ENGINE_TO_TEST);
    assertThat(engine.getBindings(ScriptContext.GLOBAL_SCOPE).size(), is(1));
    assertEquals(101, (int) engine.eval("x+1"));
}
 
Example #20
Source File: NashornScriptEngine.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static Source makeSource(final Reader reader, final ScriptContext ctxt) throws ScriptException {
    try {
        if (reader instanceof URLReader) {
            final URL url = ((URLReader)reader).getURL();
            final Charset cs = ((URLReader)reader).getCharset();
            return new Source(url.toString(), url, cs);
        }
        return new Source(getScriptName(ctxt), Source.readFully(reader));
    } catch (final IOException e) {
        throw new ScriptException(e);
    }
}
 
Example #21
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
ScriptRunner(final ScriptEngine engine, final ScriptContext context, final String source, final Object expected, final int iterations) {
    this.engine = engine;
    this.context = context;
    this.source = source;
    this.expected = expected;
    this.iterations = iterations;
}
 
Example #22
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void method() throws ScriptException {
    // a context with a new global bindings, same engine bindings
    final ScriptContext sc = new SimpleScriptContext();
    final Bindings global = new SimpleBindings();
    sc.setBindings(global, ScriptContext.GLOBAL_SCOPE);
    sc.setBindings(engineBindings, ScriptContext.ENGINE_SCOPE);
    global.put("text", "methodText");
    String value = engine.eval("text", sc).toString();
    Assert.assertEquals(value, "methodText");
}
 
Example #23
Source File: JavascriptEngine.java    From proxyee-down with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ScriptException, NoSuchMethodException, JsonProcessingException, InterruptedException {
  ScriptEngine engine = buildEngine();
  Invocable invocable = (Invocable) engine;
  engine.eval("load('E:/study/extensions/bilibili-helper/dist/hook.js')");
  HttpRequestForm requestForm = new HttpRequestForm();
  requestForm.setUrl("https://www.bilibili.com/video/av34765642");
  Object result = invocable.invokeFunction("error");
  ScriptContext ctx = new SimpleScriptContext();
  ctx.setAttribute("result", result, ScriptContext.ENGINE_SCOPE);
  System.out.println(engine.eval("!!result&&typeof result=='object'&&typeof result.then=='function'", ctx));
}
 
Example #24
Source File: JuelScriptEngine.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
private ValueExpression parse(String script, ScriptContext scriptContext) throws ScriptException {
  try {
    return expressionFactory.createValueExpression(createElContext(scriptContext), script, Object.class);
  } catch (ELException ele) {
    throw new ScriptException(ele);
  }
}
 
Example #25
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Test multi-threaded access to defined global variables for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedVarTest() throws ScriptException, InterruptedException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final Bindings b = e.createBindings();
    final ScriptContext origContext = e.getContext();
    final ScriptContext newCtxt = new SimpleScriptContext();
    newCtxt.setBindings(b, ScriptContext.ENGINE_SCOPE);
    final String sharedScript = "foo";

    assertEquals(e.eval("var foo = 'original context';", origContext), null);
    assertEquals(e.eval("var foo = 'new context';", newCtxt), null);

    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "new context", 1000));
    t1.start();
    t2.start();
    t1.join();
    t2.join();

    assertEquals(e.eval("var foo = 'newer context';", newCtxt), null);
    final Thread t3 = new Thread(new ScriptRunner(e, origContext, sharedScript, "original context", 1000));
    final Thread t4 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, "newer context", 1000));

    t3.start();
    t4.start();
    t3.join();
    t4.join();

    assertEquals(e.eval(sharedScript), "original context");
    assertEquals(e.eval(sharedScript, newCtxt), "newer context");
}
 
Example #26
Source File: FastJavaScriptEngine.java    From kite with Apache License 2.0 5 votes vote down vote up
private static String getSourcePath(ScriptContext ctx) {
	int scope = ctx.getAttributesScope(SOURCEPATH);
	if (scope != -1) {
		return ctx.getAttribute(SOURCEPATH).toString();
	} else {
		// look for "com.sun.script.java.sourcepath"
		return System.getProperty(SYSPROP_PREFIX + SOURCEPATH);
	}		
}
 
Example #27
Source File: ScriptEngineScopeTest.java    From es6draft with MIT License 5 votes vote down vote up
@Test
public void isolatedContextsEvalContextWithDefaults() throws ScriptException {
    ScriptContext context = new SimpleScriptContext();
    engine.eval("var value = 'Arcturus'", context);

    assertThat(engine.eval("value", context), instanceOfWith(String.class, is("Arcturus")));
    assertThat(engine.eval("typeof value"), instanceOfWith(String.class, is("undefined")));
    assertThat(engine.eval("typeof value", new SimpleScriptContext()),
            instanceOfWith(String.class, is("undefined")));
}
 
Example #28
Source File: ArrayConversionTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public static void assertLargeObjectObjectArray(Object[][] array) throws ScriptException {
    assertEquals(4, array.length);
    assertTrue(Arrays.equals(new Object[] { Boolean.FALSE }, array[0]));
    assertTrue(Arrays.equals(new Object[] { 1 }, array[1]));
    assertTrue(Arrays.equals(new Object[] { "foo", 42.3d }, array[2]));
    assertEquals(1, array[3].length);
    e.getBindings(ScriptContext.ENGINE_SCOPE).put("obj", array[3][0]);
    assertEquals(17, e.eval("obj.x"));
}
 
Example #29
Source File: SpeedTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {
    clearWorkDir();
    
    FileWriter w = new FileWriter(new File(getWorkDir(), "template.txt"));
    w.write("<html><h1>${title}</h1></html>");
    w.close();
    
    
    parameters = new HashMap<String,String>();
    parameters.put("title", "SOME_TITLE");

    LocalFileSystem lfs = new LocalFileSystem();
    lfs.setRootDirectory(getWorkDir());
    fo = lfs.findResource("template.txt");
    

    ScriptEngineManager mgr = Scripting.createManager();
    eng = mgr.getEngineByName("freemarker");
    assertNotNull("We do have such engine", eng);
    eng.getContext().setAttribute(FileObject.class.getName(), fo, ScriptContext.ENGINE_SCOPE);
    eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(parameters);
        
    whereTo = new File[10000];
    for (int i = 0; i < whereTo.length; i++) {
        whereTo[i] = new File(getWorkDir(), "outFile"+i+".txt");
    }
}
 
Example #30
Source File: Nashorn11.java    From java8-tutorial with MIT License 5 votes vote down vote up
private static void test4() throws ScriptException {
    NashornScriptEngine engine = createEngine();

    engine.eval("function foo() { print('bar') };");

    ScriptContext defaultContext = engine.getContext();
    Bindings defaultBindings = defaultContext.getBindings(ScriptContext.ENGINE_SCOPE);

    SimpleScriptContext context = new SimpleScriptContext();
    context.setBindings(defaultBindings, ScriptContext.ENGINE_SCOPE);

    engine.eval("foo();", context);
    System.out.println(context.getAttribute("foo"));
}