下面列出了怎么用javax.script.Bindings的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
LOG.debug("Evaluating JavaScript expression: {1}", expression);
try {
final Bindings scope = engine.createBindings();
final StringBuilder localVars = new StringBuilder();
for (final Entry<String, ?> entry : values.entrySet()) {
// workaround for http://ruby.11.x6.nabble.com/undefined-local-variable-in-ScriptEngine-eval-tp3452553p3452557.html
scope.put("$" + entry.getKey(), entry.getValue()); // register as global var
localVars.append(entry.getKey()) // // reference as local var
.append("=$") //
.append(entry.getKey()) //
.append("\n");
}
return engine.eval(localVars.toString() + expression, scope);
} catch (final ScriptException ex) {
throw new ExpressionEvaluationException("Evaluating JRuby expression failed: " + expression, ex);
}
}
public static Object isNum( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
if ( ArgList.length == 1 ) {
try {
if ( isNull( ArgList[0] ) ) {
return null;
} else if ( isUndefined( ArgList[0] ) ) {
return undefinedValue;
}
double sArg1 = (Double) ArgList[0];
if ( Double.isNaN( sArg1 ) ) {
return Boolean.FALSE;
} else {
return Boolean.TRUE;
}
} catch ( Exception e ) {
return Boolean.FALSE;
}
} else {
throw new RuntimeException( "The function call isNum requires 1 argument." );
}
}
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"
}
@Override
public Object eval(ScriptContext context) throws ScriptException {
// Only compile if necessary (should be only the first time!)
if (cachedClazz == null) {
try {
FileWriter out;
IOUtils.write(script, out = new FileWriter(file));
out.flush();
out.close();
cachedClazz = engine.compileScript(file);
} catch (Exception e) {
throw new ScriptException(e);
}
}
// Evaluate it
Bindings bnd = context.getBindings(ScriptContext.ENGINE_SCOPE);
bnd.put(ScriptEngine.FILENAME, file.getAbsolutePath());
return engine.evalClass(cachedClazz, bnd);
}
public static String rpad( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
try {
if ( ArgList.length == 3 ) {
if ( isNull( ArgList, new int[] { 0, 1, 2 } ) ) {
return null;
} else if ( isUndefined( ArgList, new int[] { 0, 1, 2 } ) ) {
return (String) undefinedValue;
}
String valueToPad = (String) ArgList[ 0 ];
String filler = (String) ArgList[ 1 ];
int size = (Integer) ArgList[ 2 ];
while ( valueToPad.length() < size ) {
valueToPad = valueToPad + filler;
}
return valueToPad;
}
} catch ( Exception e ) {
throw new RuntimeException( "The function call rpad requires 3 arguments." );
}
return null;
}
@Override
public boolean nextKeyValue() throws IOException {
while (true) {
if (!this.lineRecordReader.nextKeyValue()) return false;
try {
final Bindings bindings = this.engine.createBindings();
final StarGraph graph = StarGraph.open();
bindings.put(GRAPH, graph);
bindings.put(LINE, this.lineRecordReader.getCurrentValue().toString());
final StarGraph.StarVertex sv = (StarGraph.StarVertex) script.eval(bindings);
if (sv != null) {
final Optional<StarGraph.StarVertex> vertex = sv.applyGraphFilter(this.graphFilter);
if (vertex.isPresent()) {
this.vertexWritable.set(vertex.get());
return true;
}
}
} catch (final ScriptException e) {
throw new IOException(e.getMessage());
}
}
}
@Test
public void shouldProperlyHandleBindings() throws Exception {
final Graph graph = TinkerFactory.createClassic();
final GraphTraversalSource g = graph.traversal();
final ScriptEngine engine = new GremlinGroovyScriptEngine();
engine.put("g", g);
engine.put("marko", convertToVertexId(graph, "marko"));
Assert.assertEquals(g.V(convertToVertexId(graph, "marko")).next(), engine.eval("g.V(marko).next()"));
final Bindings bindings = engine.createBindings();
bindings.put("g", g);
bindings.put("s", "marko");
bindings.put("f", 0.5f);
bindings.put("i", 1);
bindings.put("b", true);
bindings.put("l", 100l);
bindings.put("d", 1.55555d);
assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.E(convertToEdgeId(graph, "marko", "knows", "vadas")).next());
assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
assertEquals(engine.eval("g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
assertEquals(engine.eval("g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
assertEquals(engine.eval("g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
assertEquals(engine.eval("g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.V(convertToVertexId(graph, "marko")).next());
}
private Object executeGremlinScript(String gremlinQuery) throws AtlasBaseException {
GremlinGroovyScriptEngine scriptEngine = getGremlinScriptEngine();
try {
Bindings bindings = scriptEngine.createBindings();
bindings.put("graph", getGraph());
bindings.put("g", getGraph().traversal());
Object result = scriptEngine.eval(gremlinQuery, bindings);
return result;
} catch (ScriptException e) {
throw new AtlasBaseException(AtlasErrorCode.GREMLIN_SCRIPT_EXECUTION_FAILED, gremlinQuery);
} finally {
releaseGremlinScriptEngine(scriptEngine);
}
}
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"
}
@Test
public void testGetServiceProviderFromWrappedContext() throws Exception {
final String SERVICE_PROVIDER_NAME = "service_provider_js_test";
AuthenticationContext authenticationContext = new AuthenticationContext();
authenticationContext.setServiceProviderName(SERVICE_PROVIDER_NAME);
JsAuthenticationContext jsAuthenticationContext = new JsAuthenticationContext(authenticationContext);
Bindings bindings = scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
bindings.put("context", jsAuthenticationContext);
Object result = scriptEngine.eval("context.serviceProviderName");
assertNotNull(result);
assertEquals(result, SERVICE_PROVIDER_NAME, "Service Provider name set in AuthenticationContext is not " +
"accessible from JSAuthenticationContext");
}
public static String expandTemplate(Reader reader, Map<String, Object> values) {
StringWriter writer = new StringWriter();
ScriptEngine eng = getScriptEngine();
Bindings bind = eng.getContext().getBindings(ScriptContext.ENGINE_SCOPE);
if (values != null) {
bind.putAll(values);
}
bind.put(ENCODING_PROPERTY_NAME, Charset.defaultCharset().name());
eng.getContext().setWriter(writer);
try {
eng.eval(reader);
} catch (ScriptException ex) {
Exceptions.printStackTrace(ex);
}
return writer.toString();
}
private Bindings buildBindings(RuleContext ctx, FromDeviceMsg msg) {
Bindings bindings = NashornJsEvaluator.getAttributeBindings(ctx.getDeviceMetaData().getDeviceAttributes());
if (msg != null) {
switch (msg.getMsgType()) {
case POST_ATTRIBUTES_REQUEST:
bindings = NashornJsEvaluator.updateBindings(bindings, (UpdateAttributesRequest) msg);
break;
case POST_TELEMETRY_REQUEST:
TelemetryUploadRequest telemetryMsg = (TelemetryUploadRequest) msg;
for (List<KvEntry> entries : telemetryMsg.getData().values()) {
bindings = NashornJsEvaluator.toBindings(bindings, entries);
}
}
}
return bindings;
}
@Test
public void testUnsupportedWithBindings() throws ScriptException {
// Unsupported Java classes end up as `null` in default bindings
Bindings bindings = engine.createBindings();
Object javaObject = new JavaObject();
bindings.put("javaObject", javaObject);
assertThat(bindings.get("javaObject"), nullValue());
assertThat(engine.eval("javaObject", bindings), nullValue());
assertThat(engine.eval("typeof javaObject", bindings), instanceOfWith(String.class, is("object")));
assertThat(engine.eval("javaObject == null", bindings),
instanceOfWith(Boolean.class, sameInstance(Boolean.TRUE)));
assertThat(engine.eval("javaObject === void 0", bindings),
instanceOfWith(Boolean.class, sameInstance(Boolean.FALSE)));
assertThat(engine.eval("javaObject === null", bindings),
instanceOfWith(Boolean.class, sameInstance(Boolean.TRUE)));
}
@Test
public void createBindingsTest() {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
final Bindings b = e.createBindings();
b.put("foo", 42.0);
Object res = null;
try {
res = e.eval("foo == 42.0", b);
} catch (final ScriptException | NullPointerException se) {
se.printStackTrace();
fail(se.getMessage());
}
assertEquals(res, Boolean.TRUE);
}
public static String resolveIP( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
String sRC = "";
if ( ArgList.length == 2 ) {
try {
InetAddress addr = InetAddress.getByName( (String) ArgList[0] );
if ( ( (String) ArgList[1] ).equals( "IP" ) ) {
sRC = addr.getHostName();
} else {
sRC = addr.getHostAddress();
}
if ( sRC.equals( ArgList[0] ) ) {
sRC = "-";
}
} catch ( Exception e ) {
sRC = "-";
}
} else {
throw new RuntimeException( "The function call resolveIP requires 2 arguments." );
}
return sRC;
}
@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"));
}
public Bindings createBindings(VariableScope variableScope, Bindings engineBindings) {
List<Resolver> scriptResolvers = new ArrayList<Resolver>();
for (ResolverFactory scriptResolverFactory: resolverFactories) {
Resolver resolver = scriptResolverFactory.createResolver(variableScope);
if (resolver!=null) {
scriptResolvers.add(resolver);
}
}
return new ScriptBindings(scriptResolvers, variableScope, engineBindings);
}
@Override
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
try {
List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
Compilable compilable = (Compilable) engine;
Bindings bindings = engine.createBindings();
bindings.put("invokers", invokersCopy);
bindings.put("invocation", invocation);
bindings.put("context", RpcContext.getContext());
CompiledScript function = compilable.compile(rule);
Object obj = function.eval(bindings);
if (obj instanceof Invoker[]) {
invokersCopy = Arrays.asList((Invoker<T>[]) obj);
} else if (obj instanceof Object[]) {
invokersCopy = new ArrayList<Invoker<T>>();
for (Object inv : (Object[]) obj) {
invokersCopy.add((Invoker<T>) inv);
}
} else {
invokersCopy = (List<Invoker<T>>) obj;
}
return invokersCopy;
} catch (ScriptException e) {
//fail then ignore rule .invokers.
logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
return invokers;
}
}
@Test
public void testClaimAssignment() throws ScriptException {
ClaimMapping claimMapping1 = ClaimMapping.build("", "", "", false);
ClaimMapping claimMapping2 = ClaimMapping.build("Test.Remote.Claim.Url.2", "Test.Remote.Claim.Url.2", "",
false);
AuthenticatedUser authenticatedUser = new AuthenticatedUser();
authenticatedUser.getUserAttributes().put(claimMapping1, "TestClaimVal1");
authenticatedUser.getUserAttributes().put(claimMapping2, "TestClaimVal2");
AuthenticationContext authenticationContext = new AuthenticationContext();
setupAuthContextWithStepData(authenticationContext, authenticatedUser);
JsAuthenticationContext jsAuthenticationContext = new JsAuthenticationContext(authenticationContext);
Bindings bindings = scriptEngine.getBindings(ScriptContext.GLOBAL_SCOPE);
bindings.put("context", jsAuthenticationContext);
Object result = scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.1']");
assertNull(result);
result = scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.2']");
assertEquals(result, "TestClaimVal2");
scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.2'] = 'Modified2'");
result = scriptEngine.eval("context.steps[1].subject.remoteClaims['Test.Remote.Claim.Url.2']");
assertEquals(result, "Modified2");
}
public RowTransformer getRowTransformer(String scriptName) {
return (Row input) -> {
if (input == null) {
return null;
}
Reader content = load(ROW_SCRIPT_FOLDER, scriptName);
try {
Bindings bindings = ScriptingEnvironmentProvider.create(manager, this.scriptEngineBindings, input);
return (Row) engine.eval(content, bindings);
} catch (ScriptException ex) {
throw new IllegalStateException("Cannot evaluate script: " + scriptName, ex);
}
};
}
public static void main(String[] args) throws ScriptException {
final ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
final ScriptEngine scriptEngine = scriptEngineManager.getEngineByName( "Nashorn");
final Bindings bindings = scriptEngine.createBindings();
bindings.put( "str", "Let's pass from Java to JavaScript" );
scriptEngine.eval( " print(str)", bindings );
}
@Test
public void shouldEvalScriptWithGlobalAndLocalBindings() throws Exception {
final Bindings g = new SimpleBindings();
g.put("x", 1);
final GremlinExecutor gremlinExecutor = GremlinExecutor.build().globalBindings(g).create();
final Bindings b = new SimpleBindings();
b.put("y", 1);
assertEquals(2, gremlinExecutor.eval("y+x", b).get());
gremlinExecutor.close();
}
void process(Exchange exchange) throws Exception {
Bindings bindings = new SimpleBindings();
bindings.put("env", System.getenv());
bindings.put("sys", System.getProperties());
bindings.put("body", exchange.hasOut() ? exchange.getOut().getBody() : exchange.getIn().getBody());
bindings.put("message", exchange.hasOut() ? exchange.getOut() : exchange.getIn());
bindings.put("exchange", exchange);
bindings.put("lastcommand", this.lastImplementedCommand);
String bot = commandimpl + "\n" + PRE_COMMAND + commandname + POST_COMMAND;
this.engine.eval(bot, bindings);
}
@SuppressWarnings("unchecked")
public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException {
try {
List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers);
Compilable compilable = (Compilable) engine;
Bindings bindings = engine.createBindings();
bindings.put("invokers", invokersCopy);
bindings.put("invocation", invocation);
bindings.put("context", RpcContext.getContext());
CompiledScript function = compilable.compile(rule);
Object obj = function.eval(bindings);
if (obj instanceof Invoker[]) {
invokersCopy = Arrays.asList((Invoker<T>[]) obj);
} else if (obj instanceof Object[]) {
invokersCopy = new ArrayList<Invoker<T>>();
for (Object inv : (Object[]) obj) {
invokersCopy.add((Invoker<T>)inv);
}
} else {
invokersCopy = (List<Invoker<T>>) obj;
}
return invokersCopy;
} catch (ScriptException e) {
//fail then ignore rule .invokers.
logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e);
return invokers;
}
}
@Test
public void globalScopeAccess() throws ScriptException {
Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
globalScope.put("globalVar", "Aldebaran");
assertThat(engine.eval("globalVar"), instanceOfWith(String.class, is("Aldebaran")));
}
@Test
public void testEvalFromFile2() throws FileNotFoundException, ScriptException {
InputStreamReader code = getStream("hello1.kt");
StringWriter out;
Bindings bnd = engine.createBindings();
bnd.put("out", new PrintWriter(out = new StringWriter()));
Object result = engine.eval(code, bnd);
assertNotNull(result);
assertEquals("main", result.getClass().getDeclaredMethods()[0].getName());
assertEquals("Hello, World!", out.toString().trim());
}
public void execute(Diagram d, String code) {
try {
Bindings b = bindings;
b.put("graph", d);
engine.eval(code, b);
} catch (ScriptException ex) {
Exceptions.printStackTrace(ex);
}
}
@Test
public void shouldGetGlobalBindings() throws Exception {
final Bindings b = new SimpleBindings();
final Object bound = new Object();
b.put("x", bound);
final GremlinExecutor gremlinExecutor = GremlinExecutor.build().
addPlugins("gremlin-groovy", triggerPlugin).
globalBindings(b).create();
assertEquals(bound, gremlinExecutor.getScriptEngineManager().getBindings().get("x"));
gremlinExecutor.close();
}
private static GuardedInvocation getMirrorConverter(final Class<?> sourceType, final Class<?> targetType) {
// Could've also used (targetType.isAssignableFrom(ScriptObjectMirror.class) && targetType != Object.class) but
// it's probably better to explicitly spell out the supported target types
if (targetType == Map.class || targetType == Bindings.class || targetType == JSObject.class || targetType == ScriptObjectMirror.class) {
if (ScriptObject.class.isAssignableFrom(sourceType)) {
return new GuardedInvocation(CREATE_MIRROR);
} else if (sourceType.isAssignableFrom(ScriptObject.class) || sourceType.isInterface()) {
return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
}
}
return null;
}
@Test
public void isolatedBindingsAndSimpleBindings() throws ScriptException {
Bindings binding = new SimpleBindings();
engine.eval("var value = 'Alnitak'", binding);
assertThat(engine.eval("value", binding), instanceOfWith(String.class, is("Alnitak")));
assertThat(engine.eval("typeof value"), instanceOfWith(String.class, is("undefined")));
assertThat(engine.eval("typeof value", engine.createBindings()), instanceOfWith(String.class, is("undefined")));
assertThat(engine.eval("typeof value", new SimpleBindings()), instanceOfWith(String.class, is("undefined")));
}