Java 类javax.script.ScriptContext 实例源码

项目: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);
    }
}
项目:neoscada    文件:ScriptExecutor.java   
protected Map<String, Object> applyVars ( final ScriptContext context, final Map<String, Object> scriptObjects )
{
    if ( scriptObjects == null || scriptObjects.isEmpty () )
    {
        return null;
    }

    final Map<String, Object> replaced = new HashMap<String, Object> ();
    for ( final Map.Entry<String, Object> entry : scriptObjects.entrySet () )
    {
        final Object original = context.getAttribute ( entry.getKey (), ScriptContext.ENGINE_SCOPE );
        replaced.put ( entry.getKey (), original );
        context.setAttribute ( entry.getKey (), entry.getValue (), ScriptContext.ENGINE_SCOPE );
    }
    return replaced;
}
项目:openjdk-jdk10    文件:Global.java   
private Object printImpl(final boolean newLine, final Object... objects) {
    final ScriptContext sc = currentContext();
    @SuppressWarnings("resource")
    final PrintWriter out = sc != null? new PrintWriter(sc.getWriter()) : getContext().getEnv().getOut();
    final StringBuilder sb = new StringBuilder();

    for (final Object obj : objects) {
        if (sb.length() != 0) {
            sb.append(' ');
        }

        sb.append(JSType.toString(obj));
    }

    // Print all at once to ensure thread friendly result.
    if (newLine) {
        out.println(sb.toString());
    } else {
        out.print(sb.toString());
    }

    out.flush();

    return UNDEFINED;
}
项目:neoscada    文件:ScriptVisibilityProviderImpl.java   
public ScriptVisibilityProviderImpl ( final ScriptEngineManager scriptEngineManager, final ScriptContext scriptContext, String engineName, final String scriptCode )
{
    fireChange ( false );

    if ( engineName == null || engineName.isEmpty () )
    {
        engineName = "JavaScript";
    }

    try
    {
        final ScriptExecutor executor = new ScriptExecutor ( scriptEngineManager, engineName, scriptCode, Activator.class.getClassLoader () );
        fireChange ( makeResult ( executor.execute ( scriptContext ) ) );
    }
    catch ( final Exception e )
    {
        logger.warn ( "Failed to eval visibility", e );
    }
}
项目:openjdk-jdk10    文件:ScriptObjectMirrorTest.java   
@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));
}
项目: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    文件: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;
    }
}
项目: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());
    }
}
项目:neoscada    文件:ScriptDataSource.java   
/**
 * Handle data change
 */
@Override
protected synchronized void handleChange ( final Map<String, DataSourceHandler> sources )
{
    // calculate
    // gather all data
    final Map<String, DataItemValue> values = new HashMap<String, DataItemValue> ();
    for ( final Map.Entry<String, DataSourceHandler> entry : sources.entrySet () )
    {
        values.put ( entry.getKey (), entry.getValue ().getValue () );
    }

    this.scriptContext.setAttribute ( "data", values, ScriptContext.ENGINE_SCOPE );
    this.scriptContext.setAttribute ( "writer", this.writer, ScriptContext.ENGINE_SCOPE );
    this.scriptContext.setAttribute ( "eventProcessor", this.eventProcessor, ScriptContext.ENGINE_SCOPE );

    executeScript ( this.updateCommand );
}
项目:OpenJSharp    文件:NashornScriptEngine.java   
private static 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);
        ctxtGlobal.setScriptContext(ctxt);
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
项目:OpenJSharp    文件:NashornScriptEngine.java   
private static Object evalImpl(final ScriptFunction script, final ScriptContext ctxt, final Global ctxtGlobal) throws ScriptException {
    if (script == null) {
        return null;
    }
    final Global oldGlobal = Context.getGlobal();
    final boolean globalChanged = (oldGlobal != ctxtGlobal);
    try {
        if (globalChanged) {
            Context.setGlobal(ctxtGlobal);
        }

        ctxtGlobal.setScriptContext(ctxt);
        return ScriptObjectMirror.translateUndefined(ScriptObjectMirror.wrap(ScriptRuntime.apply(script, ctxtGlobal), ctxtGlobal));
    } catch (final Exception e) {
        throwAsScriptException(e, ctxtGlobal);
        throw new AssertionError("should not reach here");
    } finally {
        if (globalChanged) {
            Context.setGlobal(oldGlobal);
        }
    }
}
项目: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());
    }
}
项目:jaffa-framework    文件:ScriptEnginePool.java   
/**
 * Clears the script engine of all previous state except, if it is a BeanShell interpreter,
 * the engine is left
 *
 * @param scriptEngine ScriptEngine to clear
 */
private void clearEngine(String language, ScriptEngine scriptEngine) {
    // Clear everything except the BeanShell engine ("bsh" in the binding)
    // This will clear all imported class, methods, and variables
    List<String> itemsToRemove = new ArrayList<String>();
    for (Map.Entry<String, Object> bindingEntry : scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).entrySet()) {
        if (language.equalsIgnoreCase(BEANSHELL) && bindingEntry.getKey().equalsIgnoreCase(BEANSHELL_ENGINE_NAME)) {
            continue;
        }
        itemsToRemove.add(bindingEntry.getKey());
    }
    for (String value : itemsToRemove) {
        scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE).remove(value);
    }

    // Clear entire global scope
    scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE).clear();
}
项目:openjdk-jdk10    文件:Test3.java   
public static void main(String[] args) throws Exception {
    System.out.println("\nTest3\n");
    final Reader reader = new FileReader(
        new File(System.getProperty("test.src", "."), "Test3.js"));
    ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine = Helper.getJsEngine(m);
    if (engine == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    Bindings en = new SimpleBindings();
    engine.setBindings(en, ScriptContext.ENGINE_SCOPE);
    en.put("key", "engine value");
    Bindings gn = new SimpleBindings();
    engine.setBindings(gn, ScriptContext.GLOBAL_SCOPE);
    gn.put("key", "global value");
    engine.eval(reader);
}
项目:L2jBrasil    文件:L2ScriptEngineManager.java   
public ScriptContext getScriptContext(String engineName)
{
    ScriptEngine engine = this.getEngineByName(engineName);
    if (engine == null)
        throw new IllegalStateException("No engine registered with name (" + engineName + ")");
    else
        return this.getScriptContext(engine);
}
项目:L2jBrasil    文件:L2ScriptEngineManager.java   
public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException
{
    if (engine instanceof Compilable && ATTEMPT_COMPILATION)
    {
        Compilable eng = (Compilable) engine;
        CompiledScript cs = eng.compile(script);
        return context != null ? cs.eval(context) : cs.eval();
    } else
        return context != null ? engine.eval(script, context) : engine.eval(script);
}
项目:L2jBrasil    文件:L2ScriptEngineManager.java   
public Object eval(String engineName, String script, ScriptContext context) throws ScriptException
{
    ScriptEngine engine = this.getEngineByName(engineName);
    if (engine == null)
        throw new ScriptException("No engine registered with name (" + engineName + ")");
    else
        return this.eval(engine, script, context);
}
项目:greycat    文件:CoreTask.java   
/**
 * @native ts
 * var print = console.log;
 * var println = console.log;
 * var ctx = context;
 * return eval(script);
 */
private static boolean executeScript(String script, TaskContext context) {
    ScriptContext scriptCtx = new SimpleScriptContext();
    scriptCtx.setAttribute("ctx", context, ScriptContext.ENGINE_SCOPE);
    try {
        return (boolean) TaskHelper.SCRIPT_ENGINE.eval(script, scriptCtx);
    } catch (ScriptException | ClassCastException e) {
        e.printStackTrace();
        return false;
    }
}
项目:greycat    文件:ActionSelect.java   
/**
 * @native ts
 * var print = console.log;
 * return eval(this._script);
 */
private boolean callScript(Node node, TaskContext context) {
    ScriptContext scriptCtx = new SimpleScriptContext();
    scriptCtx.setAttribute("node", node, ScriptContext.ENGINE_SCOPE);
    scriptCtx.setAttribute("context", context, ScriptContext.ENGINE_SCOPE);
    try {
        return (boolean) TaskHelper.SCRIPT_ENGINE.eval(_script, scriptCtx);
    } catch (ScriptException | ClassCastException e) {
        throw new RuntimeException(e);
    }
}
项目:8ComicSDK-JAVA    文件:JSnview.java   
private List<String> invokeJS(String js, int y, int ch) {
    ArrayList<String> pagsList = new ArrayList<String>();
    String str = js.substring(0, js.indexOf("var pt="));
    str = str.replace("ge('TheImg').src", "var src");
    String unuseScript = StringUtility.substring(str, "\'.jpg\';", "break;");
    str = str.replace(unuseScript, "");
    String varSrc = null;

    if(str.indexOf("ci = i;") != -1){
        varSrc = StringUtility.substring(str, "ci = i;", "break;");
    }else if(str.indexOf("ci=i;") != -1){
        varSrc = StringUtility.substring(str, "ci=i;", "break;");
    }

    String getPageJS = String.format(buildGetPagesJS(), varSrc);
    str = str.replace(varSrc, "");
    str = str.replace("break;", getPageJS);
    String script = "function sp2(ch, y){" + str + "} " + buildNviewJS();
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    try {
        Bindings bind = engine.createBindings(); 
        bind.put("pagsList", pagsList); 
        engine.setBindings(bind, ScriptContext.ENGINE_SCOPE); 

        engine.eval(script);
        Invocable inv = (Invocable) engine;
        inv.invokeFunction("sp2", ch, y);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return pagsList;
}
项目:openjdk-jdk10    文件:ScopeTest.java   
/**
 * 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");
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void userEngineScopeBindingsNoLeakTest() 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);

    // in the default context's ENGINE_SCOPE, 'foo' shouldn't exist
    assertTrue(e.eval("typeof foo").equals("undefined"));
}
项目:incubator-netbeans    文件:RsrcLoader.java   
RsrcLoader(FileObject fo, ScriptContext map) {
    this.fo = fo;
    this.map = map;
    this.engineScope = map.getBindings(ScriptContext.ENGINE_SCOPE);
    setTemplateLoader(this);
    setTemplateExceptionHandler(this);
    Logger.getLogger("freemarker.runtime").setLevel(Level.OFF);
}
项目:incubator-netbeans    文件:SpeedTest.java   
@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 = new ScriptEngineManager();
    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");
    }
}
项目:incubator-netbeans    文件:ProcessorTest.java   
static void apply(FileObject template, Writer w, Map<String,? extends Object> values, TemplateExceptionHandler teh) throws Exception {
    ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine eng = mgr.getEngineByName("freemarker");
    assertNotNull("We do have such engine", eng);
    eng.getContext().setWriter(w);
    eng.getContext().setAttribute(FileObject.class.getName(), template, ScriptContext.ENGINE_SCOPE);
    eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE).putAll(values);
    if (teh != null) {
        eng.getContext().setAttribute("org.netbeans.libs.freemarker.exceptionHandler", teh, ScriptContext.ENGINE_SCOPE);
    }
    eng.eval(new InputStreamReader(template.getInputStream()));
}
项目:incubator-netbeans    文件:SpeedTest.java   
@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());

    target = DataFolder.findFolder(lfs.getRoot());
    FileObject fo = lfs.findResource("template.txt");
    obj = DataObject.find(fo);
    obj.setTemplate(true);
    obj.getPrimaryFile().setAttribute("javax.script.ScriptEngine", "freemarker");

    ScriptEngineManager mgr = new ScriptEngineManager();
    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");
    }
}
项目:openjdk-jdk10    文件:ScopeTest.java   
/**
 * Test multi-threaded access to global getters and setters for shared script classes with multiple globals.
 */
@Test
public static void getterSetter2Test() 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 = "accessor2";

    e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), origContext);
    assertEquals(e.eval("accessor2 = 1;"), 1);
    assertEquals(e.eval(sharedScript), 1);

    e.eval(new URLReader(ScopeTest.class.getResource("resources/gettersetter.js")), newCtxt);
    assertEquals(e.eval("accessor2 = 2;", newCtxt), 2);
    assertEquals(e.eval(sharedScript, newCtxt), 2);


    final Thread t1 = new Thread(new ScriptRunner(e, origContext, sharedScript, 1, 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, sharedScript, 2, 1000));

    t1.start();
    t2.start();
    t1.join();
    t2.join();

    assertEquals(e.eval(sharedScript), 1);
    assertEquals(e.eval(sharedScript, newCtxt), 2);
    assertEquals(e.eval("x"), 1);
    assertEquals(e.eval("x", newCtxt), 2);
}
项目:openjdk-jdk10    文件:ScopeTest.java   
@Test
public void invokeFunctionInGlobalScopeTest2() throws Exception {
     final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

     // create a new ScriptContext instance
     final ScriptContext ctxt = new SimpleScriptContext();
     // set it as 'default' ScriptContext
     engine.setContext(ctxt);

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

     // 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
     final Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
项目:helper    文件:HelperScript.java   
@Override
public void run() {
    ScriptEngine engine = loader.getScriptEngine();

    try {
        // create bindings
        Bindings bindings = engine.createBindings();

        // provide an export for this scripts attributes
        bindings.put("loader", loader);
        bindings.put("registry", terminableRegistry);
        bindings.put("logger", logger);

        // the path of the script file (current working directory)
        bindings.put("cwd", path.normalize().toString().replace("\\", "/"));

        // the root scripts directory
        bindings.put("rsd", loader.getDirectory().normalize().toString().replace("\\", "/") + "/");

        // function to depend on another script
        bindings.put("depend", (Consumer<String>) this::depend);

        // append the global helper bindings to this instance
        systemBindings.appendTo(bindings);

        // create a new script context, and attach our bindings
        ScriptContext context = new SimpleScriptContext();
        context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

        // evaluate the header
        engine.eval(systemBindings.getPlugin().getScriptHeader(), context);

        // resolve the load path, relative to the loader directory.
        Path loadPath = loader.getDirectory().normalize().resolve(path);
        engine.eval("__load(\"" + loadPath.toString().replace("\\", "/") + "\");", context);

    } catch (Throwable t) {
        t.printStackTrace();
    }
}
项目:scijava-jupyter-kernel    文件:Worker.java   
private void syncBindings(ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {

    Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
    this.scriptEngines.forEach((String name, ScriptEngine engine) -> {
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        currentBindings.keySet().forEach((String key) -> {
        bindings.put(key, scriptLanguage.decode(currentBindings.get(key)));
        });
    });

    }
项目:scijava-jupyter-kernel    文件:ScijavaEvaluator.java   
private void addLanguage(String langName) {

        if (scriptService.getLanguageByName(langName) == null) {
            log.error("Script Language for '" + langName + "' not found.");
            System.exit(1);
        }

        if (!this.scriptLanguages.keySet().contains(langName)) {

            Bindings bindings = null;
            if (!this.scriptEngines.isEmpty()) {
                String firstLanguage = this.scriptEngines.keySet().iterator().next();
                bindings = this.scriptEngines.get(firstLanguage).getBindings(ScriptContext.ENGINE_SCOPE);
            }

            log.info("Script Language for '" + langName + "' found.");
            ScriptLanguage scriptLanguage = scriptService.getLanguageByName(langName);
            this.scriptLanguages.put(langName, scriptLanguage);

            ScriptEngine engine = this.scriptLanguages.get(langName).getScriptEngine();
            this.scriptEngines.put(langName, engine);

            AutoCompleter completer = scriptLanguage.getAutoCompleter();
            this.completers.put(languageName, completer);

            // Not implemented yet
            //engine.setBindings(this.bindings, ScriptContext.ENGINE_SCOPE);
            if (bindings != null) {
                this.initBindings(bindings, engine, scriptLanguage);
            }

        }

        log.debug("Script Language found for '" + langName + "'");
    }
项目:scijava-jupyter-kernel    文件:ScijavaEvaluator.java   
private void initBindings(Bindings bindings, ScriptEngine scriptEngine, ScriptLanguage scriptLanguage) {

        Bindings currentBindings = scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.keySet().forEach((String key) -> {
            currentBindings.put(key, scriptLanguage.decode(bindings.get(key)));
        });

    }
项目:openjdk-jdk10    文件:ScopeTest.java   
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;
}
项目:openjdk-jdk10    文件:ScopeTest.java   
/**
 * Test multi-threaded scope function invocation for shared script classes with multiple globals.
 */
@Test
public static void multiThreadedFunctionTest() 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);

    e.eval(new URLReader(ScopeTest.class.getResource("resources/func.js")), origContext);
    assertEquals(origContext.getAttribute("scopeVar"), 1);
    assertEquals(e.eval("scopeTest()"), 1);

    e.eval(new URLReader(ScopeTest.class.getResource("resources/func.js")), newCtxt);
    assertEquals(newCtxt.getAttribute("scopeVar"), 1);
    assertEquals(e.eval("scopeTest();", newCtxt), 1);

    assertEquals(e.eval("scopeVar = 3;", newCtxt), 3);
    assertEquals(newCtxt.getAttribute("scopeVar"), 3);


    final Thread t1 = new Thread(new ScriptRunner(e, origContext, "scopeTest()", 1, 1000));
    final Thread t2 = new Thread(new ScriptRunner(e, newCtxt, "scopeTest()", 3, 1000));

    t1.start();
    t2.start();
    t1.join();
    t2.join();

}
项目:neoscada    文件:ScriptExecutor.java   
public Object execute ( final ScriptContext scriptContext, final Map<String, Object> scriptObjects ) throws Exception
{
    return Scripts.executeWithClassLoader ( this.classLoader, new Callable<Object> () {

        @Override
        public Object call () throws Exception
        {
            return executeScript ( scriptContext, scriptObjects );
        }
    } );
}
项目:neoscada    文件:SymbolController.java   
private void assignConsole ( final ScriptContext scriptContext )
{
    this.console = createOrGetConsole ();

    // scriptContext.setReader ( new InputStreamReader ( this.console.getInputStream () ) );

    /* wrapping into a PrintWriter is necessary due to
     * http://bugs.sun.com/view_bug.do?bug_id=6759414
     * */

    this.console.applyTo ( scriptContext );
}
项目:neoscada    文件:FormulaDataSource.java   
/**
 * Handle data change
 */
@Override
protected synchronized void handleChange ( final Map<String, DataSourceHandler> sources )
{
    if ( this.inputFormula == null || this.inputFormula.isEmpty () )
    {
        updateData ( null );
        return;
    }

    try
    {
        final Map<String, Integer> flags = new HashMap<String, Integer> ( 4 );
        final Map<String, Object> values = new HashMap<String, Object> ( sources.size () );

        gatherData ( sources, flags, values );

        for ( final Map.Entry<String, Object> entry : values.entrySet () )
        {
            this.scriptContext.setAttribute ( entry.getKey (), entry.getValue (), ScriptContext.ENGINE_SCOPE );
        }

        // execute inputFormula
        executeScript ( this.inputFormula, this.inputScript, flags );
    }
    catch ( final Throwable e )
    {
        logger.info ( "Failed to evaluate", e );
        logger.debug ( "Failed script: {}", this.inputFormula );
        setError ( e );
    }
}