当前位置: 首页>>代码示例>>Java>>正文


Java ScriptContext类代码示例

本文整理汇总了Java中javax.script.ScriptContext的典型用法代码示例。如果您正苦于以下问题:Java ScriptContext类的具体用法?Java ScriptContext怎么用?Java ScriptContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


ScriptContext类属于javax.script包,在下文中一共展示了ScriptContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: testSlowScope

import javax.script.ScriptContext; //导入依赖的package包/类
/**
 * 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);
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:ScopeTest.java

示例2: applyVars

import javax.script.ScriptContext; //导入依赖的package包/类
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;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:17,代码来源:ScriptExecutor.java

示例3: printImpl

import javax.script.ScriptContext; //导入依赖的package包/类
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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:Global.java

示例4: ScriptVisibilityProviderImpl

import javax.script.ScriptContext; //导入依赖的package包/类
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 );
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:20,代码来源:ScriptVisibilityProviderImpl.java

示例5: mapScriptObjectMirrorCallsiteTest

import javax.script.ScriptContext; //导入依赖的package包/类
@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));
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:ScriptObjectMirrorTest.java

示例6: processInterceptItem

import javax.script.ScriptContext; //导入依赖的package包/类
@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;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:25,代码来源:ExporterInterceptorHandler.java

示例7: customize

import javax.script.ScriptContext; //导入依赖的package包/类
/**
 * <!-- 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 );
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:29,代码来源:ScriptCustomizationPipelineImpl.java

示例8: processInterceptItem

import javax.script.ScriptContext; //导入依赖的package包/类
@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;
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:25,代码来源:ModbusExporterInterceptorHandler.java

示例9: evalName

import javax.script.ScriptContext; //导入依赖的package包/类
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 ();
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:23,代码来源:SetExternalNameWizard.java

示例10: handleEvent

import javax.script.ScriptContext; //导入依赖的package包/类
@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;
    }
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:21,代码来源:ScriptEventHandler.java

示例11: getInterfaceDifferentContext

import javax.script.ScriptContext; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:24,代码来源:InvocableTest.java

示例12: handleChange

import javax.script.ScriptContext; //导入依赖的package包/类
/**
 * 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 );
}
 
开发者ID:eclipse,项目名称:neoscada,代码行数:21,代码来源:ScriptDataSource.java

示例13: evalImpl

import javax.script.ScriptContext; //导入依赖的package包/类
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);
        }
    }
}
 
开发者ID:SunburstApps,项目名称:OpenJSharp,代码行数:21,代码来源:NashornScriptEngine.java

示例14: invokeMethodDifferentContextTest

import javax.script.ScriptContext; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:26,代码来源:InvocableTest.java

示例15: clearEngine

import javax.script.ScriptContext; //导入依赖的package包/类
/**
 * 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();
}
 
开发者ID:jaffa-projects,项目名称:jaffa-framework,代码行数:24,代码来源:ScriptEnginePool.java


注:本文中的javax.script.ScriptContext类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。