本文整理汇总了Java中javax.script.SimpleBindings类的典型用法代码示例。如果您正苦于以下问题:Java SimpleBindings类的具体用法?Java SimpleBindings怎么用?Java SimpleBindings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
SimpleBindings类属于javax.script包,在下文中一共展示了SimpleBindings类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: getAttributesFromInlineGroovyScript
import javax.script.SimpleBindings; //导入依赖的package包/类
private static Map<String, Object> getAttributesFromInlineGroovyScript(final Map<String, Object> attributes,
final Matcher matcherInline) throws ScriptException {
final String script = matcherInline.group(1).trim();
final ScriptEngine engine = new ScriptEngineManager().getEngineByName("groovy");
if (engine == null) {
LOGGER.warn("Script engine is not available for Groovy");
return new HashMap<>();
}
final Object[] args = {attributes, LOGGER};
LOGGER.debug("Executing script, with parameters [{}]", args);
final Bindings binding = new SimpleBindings();
binding.put("attributes", attributes);
binding.put("logger", LOGGER);
return (Map<String, Object>) engine.eval(script, binding);
}
示例2: executeScriptWithConsole
import javax.script.SimpleBindings; //导入依赖的package包/类
public Object executeScriptWithConsole(ScriptType type, String script, Map<String, Object> params, StringWriter console) {
ScriptEngine scriptEngine = produceScriptEngine(type);
if (console != null) {
scriptEngine.getContext().setWriter(console);
}
SimpleBindings bindings = new SimpleBindings();
bindings.putAll(params);
bindings.put("spring", context);
try {
return scriptEngine.eval(script, bindings);
} catch (ScriptException ex) {
throw new GeneralException(ex);
}
}
示例3: main
import javax.script.SimpleBindings; //导入依赖的package包/类
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);
}
示例4: userEngineScopeBindingsRetentionTest
import javax.script.SimpleBindings; //导入依赖的package包/类
@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"));
}
示例5: parseObject
import javax.script.SimpleBindings; //导入依赖的package包/类
private Object parseObject()
{
Bindings map = new SimpleBindings();
advance();
if( _token.getType() == TokenType.STRING )
{
parseMember( map );
while( _token.getType() == TokenType.COMMA )
{
advance();
parseMember( map );
}
}
checkAndSkip( TokenType.RCURLY, "}" );
return map;
}
示例6: genClass
import javax.script.SimpleBindings; //导入依赖的package包/类
private SrcClass genClass( String fqnImpl, JsonStructureType model )
{
SrcClass srcClass = new SrcClass( fqnImpl, SrcClass.Kind.Class )
.modifiers( !fqnImpl.equals( _fqn ) ? Modifier.STATIC : 0 )
.imports( Bindings.class )
.imports( SimpleBindings.class )
.imports( IJsonIO.class )
.imports( List.class )
.imports( SourcePosition.class )
//.iface( fqnIface )
.superClass( JsonImplBase.class );
addConstructors( srcClass );
addProperties( srcClass, model );
addInnerTypes( srcClass, model.getInnerTypes() );
return srcClass;
}
示例7: Session
import javax.script.SimpleBindings; //导入依赖的package包/类
public Session(final String session, final Context context, final ConcurrentHashMap<String, Session> sessions) {
logger.info("New session established for {}", session);
this.session = session;
this.bindings = new SimpleBindings();
this.settings = context.getSettings();
this.graphManager = context.getGraphManager();
this.scheduledExecutorService = context.getScheduledExecutorService();
this.sessions = sessions;
final Settings.ProcessorSettings processorSettings = this.settings.processors.stream()
.filter(p -> p.className.equals(SessionOpProcessor.class.getCanonicalName()))
.findAny().orElse(SessionOpProcessor.DEFAULT_SETTINGS);
this.configuredSessionTimeout = Long.parseLong(processorSettings.config.get(SessionOpProcessor.CONFIG_SESSION_TIMEOUT).toString());
this.gremlinExecutor = initializeGremlinExecutor().create();
}
示例8: shouldNotPreserveInstantiatedVariablesBetweenEvals
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void shouldNotPreserveInstantiatedVariablesBetweenEvals() throws Exception {
final ScriptEngines engines = new ScriptEngines(se -> {});
engines.reload("gremlin-groovy", Collections.<String>emptySet(),
Collections.<String>emptySet(), Collections.emptyMap());
final Bindings localBindingsFirstRequest = new SimpleBindings();
localBindingsFirstRequest.put("x", "there");
assertEquals("herethere", engines.eval("z = 'here' + x", localBindingsFirstRequest, "gremlin-groovy"));
try {
final Bindings localBindingsSecondRequest = new SimpleBindings();
engines.eval("z", localBindingsSecondRequest, "gremlin-groovy");
fail("Should not have knowledge of z");
} catch (Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
assertThat(root, instanceOf(MissingPropertyException.class));
}
}
示例9: shouldMergeBindingsFromLocalAndGlobal
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void shouldMergeBindingsFromLocalAndGlobal() throws Exception {
final ScriptEngines engines = new ScriptEngines(se -> {});
engines.reload("gremlin-groovy", Collections.<String>emptySet(),
Collections.<String>emptySet(), Collections.emptyMap());
engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
@Override
public String getName() {
return "mock";
}
@Override
public void pluginTo(final PluginAcceptor pluginAcceptor) throws IllegalEnvironmentException, PluginInitializationException {
pluginAcceptor.addBinding("y", "here");
}
}));
final Bindings localBindings = new SimpleBindings();
localBindings.put("x", "there");
assertEquals("herethere", engines.eval("y+x", localBindings, "gremlin-groovy"));
}
示例10: shouldMergeBindingsWhereLocalOverridesGlobal
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void shouldMergeBindingsWhereLocalOverridesGlobal() throws Exception {
final ScriptEngines engines = new ScriptEngines(se -> {});
engines.reload("gremlin-groovy", Collections.<String>emptySet(),
Collections.<String>emptySet(), Collections.emptyMap());
engines.loadPlugins(Arrays.asList(new GremlinPlugin() {
@Override
public String getName() {
return "mock";
}
@Override
public void pluginTo(final PluginAcceptor pluginAcceptor) throws IllegalEnvironmentException, PluginInitializationException {
pluginAcceptor.addBinding("y", "here");
}
}));
// the "y" below should override the global variable setting.
final Bindings localBindings = new SimpleBindings();
localBindings.put("y", "there");
localBindings.put("z", "where");
assertEquals("therewhere", engines.eval("y+z", localBindings, "gremlin-groovy"));
}
示例11: shouldRaiseExceptionInWithResultOfLifeCycle
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void shouldRaiseExceptionInWithResultOfLifeCycle() throws Exception {
final GremlinExecutor gremlinExecutor = GremlinExecutor.build().create();
final GremlinExecutor.LifeCycle lc = GremlinExecutor.LifeCycle.build()
.withResult(r -> {
throw new RuntimeException("no worky");
}).create();
final AtomicBoolean exceptionRaised = new AtomicBoolean(false);
final CompletableFuture<Object> future = gremlinExecutor.eval("1+1", "gremlin-groovy", new SimpleBindings(), lc);
future.handle((r, t) -> {
exceptionRaised.set(t != null && t instanceof RuntimeException && t.getMessage().equals("no worky"));
return null;
}).get();
assertThat(exceptionRaised.get(), is(true));
gremlinExecutor.close();
}
示例12: shouldOverrideAfterFailure
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void shouldOverrideAfterFailure() throws Exception {
final AtomicInteger called = new AtomicInteger(0);
final GremlinExecutor gremlinExecutor = GremlinExecutor.build().afterFailure((b,t) -> called.set(1)).create();
try {
gremlinExecutor.eval("10/0", null, new SimpleBindings(),
GremlinExecutor.LifeCycle.build().afterFailure((b,t) -> called.set(200)).create()).get();
fail("Should have failed with division by zero");
} catch (Exception ignored) {
}
// need to wait long enough for the callback to register
Thread.sleep(500);
assertEquals(200, called.get());
}
示例13: shouldPromoteDefinedVarsInInterpreterModeWithBindings
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void shouldPromoteDefinedVarsInInterpreterModeWithBindings() throws Exception {
final GremlinGroovyScriptEngine engine = new GremlinGroovyScriptEngine(new InterpreterModeCustomizerProvider());
final Bindings b = new SimpleBindings();
b.put("x", 2);
engine.eval("def addItUp = { x, y -> x + y }", b);
assertEquals(3, engine.eval("int xxx = 1 + x", b));
assertEquals(4, engine.eval("yyy = xxx + 1", b));
assertEquals(7, engine.eval("def zzz = yyy + xxx", b));
assertEquals(4, engine.eval("zzz - xxx", b));
assertEquals("accessible-globally", engine.eval("if (yyy > 0) { def inner = 'should-stay-local'; outer = 'accessible-globally' }\n outer", b));
assertEquals("accessible-globally", engine.eval("outer", b));
try {
engine.eval("inner", b);
fail("Should not have been able to access 'inner'");
} catch (Exception ex) {
final Throwable root = ExceptionUtils.getRootCause(ex);
assertThat(root, instanceOf(MissingPropertyException.class));
}
assertEquals(10, engine.eval("addItUp(zzz,xxx)", b));
}
示例14: getJSAppName
import javax.script.SimpleBindings; //导入依赖的package包/类
/**
* Attempts to determine the app name by looking up the value of the
* system property {@link #JS_APP_NAME}, and compiling its value
* as a JS script, then returning the value of the evaluation of the script.
* The following binds are passed to the script: <ul>
* <li><b>sysprops</b>: The system properties</li>
* <li><b>agprops</b>: The agent properties which will be an empty properties instance if {@link JMXHelper#getAgentProperties()} failed.</li>
* <li><b>envs</b>: A map of environment variables</li>
* <li><b>mbs</b>: The platform MBeanServer</li>
* <li><b>cla</b>: The command line arguments as an array of strings</li>
* </ul>
* @return The app name or null if {@link #JS_APP_NAME} was not defined
* or did not compile, or did not return a valid app name
*/
public static String getJSAppName() {
String js = System.getProperty(JS_APP_NAME, "").trim();
if(js==null || js.isEmpty()) return null;
try {
ScriptEngine se = new ScriptEngineManager().getEngineByExtension("js");
Bindings b = new SimpleBindings();
b.put("sysprops", System.getProperties());
b.put("envs", System.getenv());
b.put("mbs", JMXHelper.getHeliosMBeanServer());
b.put("cla", ManagementFactory.getRuntimeMXBean().getInputArguments().toArray(new String[0]));
Properties p = JMXHelper.getAgentProperties();
b.put("agprops", p);
Object value = se.eval(js, b);
if(value!=null && !value.toString().trim().isEmpty()) return value.toString().trim();
return null;
} catch (Exception ex) {
return null;
}
}
示例15: itCanEnableRequireInDifferentBindingsOnTheSameEngine
import javax.script.SimpleBindings; //导入依赖的package包/类
@Test
public void itCanEnableRequireInDifferentBindingsOnTheSameEngine() throws Throwable {
NashornScriptEngine engine =
(NashornScriptEngine) new ScriptEngineManager().getEngineByName("nashorn");
Bindings bindings1 = new SimpleBindings();
Bindings bindings2 = new SimpleBindings();
Require.enable(engine, root, bindings1);
assertNull(engine.getBindings(ScriptContext.ENGINE_SCOPE).get("require"));
assertNotNull(bindings1.get("require"));
assertNull(bindings2.get("require"));
assertEquals("file1", ((Bindings) engine.eval("require('./file1')", bindings1)).get("file1"));
try {
engine.eval("require('./file1')", bindings2);
fail();
} catch (ScriptException ignored) {
}
Require.enable(engine, root, bindings2);
assertNull(engine.getBindings(ScriptContext.ENGINE_SCOPE).get("require"));
assertNotNull(bindings2.get("require"));
assertEquals("file1", ((Bindings) engine.eval("require('./file1')", bindings2)).get("file1"));
}