下面列出了javax.script.Bindings#get ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* SelectionScript must give its result in the 'result_script' variable.
*
* @see org.ow2.proactive.scripting.Script#getResult(Object, Bindings)
*/
@Override
protected ScriptResult<Boolean> getResult(Object evalResult, Bindings bindings) {
if (bindings.containsKey(RESULT_VARIABLE)) {
Object result = bindings.get(RESULT_VARIABLE);
if (result instanceof Boolean) {
return new ScriptResult<>((Boolean) result);
} else if (result instanceof Integer) {
return new ScriptResult<>((Integer) result != 0);
} else if (result instanceof CharSequence) {
return new ScriptResult<>(!(result.equals("false") || result.equals("False")));
} else {
return new ScriptResult<>(new Exception("Bad result format : awaited Boolean (or Integer when not existing), found " +
result.getClass().getName()));
}
} else {
String msg = "No binding for key : " + RESULT_VARIABLE +
"\na Selection script must define a variable named '" + RESULT_VARIABLE +
"' set to true or false";
logger.error(msg);
return new ScriptResult<>(new Exception(msg));
}
}
@Override
protected ScriptResult<Serializable> getResult(Object evalResult, Bindings bindings) {
if (bindings.containsKey(RESULT_VARIABLE)) {
Object result = bindings.get(RESULT_VARIABLE);
if (result == null) {
return new ScriptResult<>(null);
} else {
if (result instanceof Serializable) {
return new ScriptResult<>((Serializable) result);
} else {
return new ScriptResult<>(new Exception("Bad result format : awaited Serializable, found " +
result.getClass().getName()));
}
}
} else {
if (evalResult != null && evalResult instanceof Serializable) {
return new ScriptResult<>((Serializable) evalResult);
} else {
// assuming script ran fine
return new ScriptResult<Serializable>(true);
}
}
}
public Object evalClass(Class<?> clazz, Bindings ctx) throws ScriptException {
try {
String[] args = (String[]) ctx.get(ScriptEngine.ARGV);
// Fix arguments if null
if (args == null)
args = new String[0];
// Get constructor and invoke that
Constructor<?> constr = clazz.getConstructor(String[].class, Map.class);
// Create new instance
Object[] invArgs = new Object[] { args, ctx };
Object obj = constr.newInstance(invArgs);
// Invoke main method if given (non-script)
Method mainMth;
if ((mainMth = ReflUtils.findMethod(clazz, "main", String[].class)) != null)
mainMth.invoke(obj, new Object[] { args });
// Return it!
return obj;
} catch (Exception e) {
throw new ScriptException(e);
}
}
public static Object[] createRowCopy( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
if ( ArgList.length == 1 ) {
try {
int newSize = (int) Math.round( (Double) ArgList[0] );
Object scmO = actualObject.get( "row" );
Object[] row = (Object[]) scmO; // TODO AKRETION ensure
return RowDataUtil.createResizedCopy( row, newSize );
} catch ( Exception e ) {
throw new RuntimeException( "Unable to create a row copy: " + Const.CR + e.toString() );
}
} else {
throw new RuntimeException(
"The function call createRowCopy requires a single arguments : the new size of the row" );
}
}
public static double getProcessCount( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
if ( ArgList.length == 1 ) {
try {
Object scmO = actualObject.get( "_transform_" );
ScriptInterface scm = (ScriptInterface) scmO;
String strType = ( (String) ArgList[ 0 ] ).toLowerCase();
if ( strType.equals( "i" ) ) {
return scm.getLinesInput();
} else if ( strType.equals( "o" ) ) {
return scm.getLinesOutput();
} else if ( strType.equals( "r" ) ) {
return scm.getLinesRead();
} else if ( strType.equals( "u" ) ) {
return scm.getLinesUpdated();
} else if ( strType.equals( "w" ) ) {
return scm.getLinesWritten();
} else if ( strType.equals( "e" ) ) {
return scm.getLinesRejected();
} else {
return 0;
}
} catch ( Exception e ) {
// throw new RuntimeException(e.toString());
return 0;
}
} else {
throw new RuntimeException( "The function call getProcessCount requires 1 argument." );
}
}
public static double getProcessCount( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
if ( ArgList.length == 1 ) {
try {
Object scmO = actualObject.get( "_step_" );
ScriptInterface scm = (ScriptInterface) scmO;
String strType = ( (String) ArgList[0] ).toLowerCase();
if ( strType.equals( "i" ) ) {
return scm.getLinesInput();
} else if ( strType.equals( "o" ) ) {
return scm.getLinesOutput();
} else if ( strType.equals( "r" ) ) {
return scm.getLinesRead();
} else if ( strType.equals( "u" ) ) {
return scm.getLinesUpdated();
} else if ( strType.equals( "w" ) ) {
return scm.getLinesWritten();
} else if ( strType.equals( "e" ) ) {
return scm.getLinesRejected();
} else {
return 0;
}
} catch ( Exception e ) {
// throw new RuntimeException(e.toString());
return 0;
}
} else {
throw new RuntimeException( "The function call getProcessCount requires 1 argument." );
}
}
@Test
public void emptyRowHasMemory() {
Row row = new Row();
Memory expected = new Memory();
row.useMemory(expected);
Bindings bindings = ScriptingEnvironmentProvider.create(new ScriptEngineManager(), null, row);
Object actual = bindings.get("$MEMORY");
assertNotNull(actual);
assertThat(actual, is(expected));
}
public static void testBindings(ScriptEngine e, Bindings b) throws ScriptException {
CompiledScript cs = ((Compilable)e).compile(
"print( 'somejavaint', type(somejavaint), somejavaint )\n" +
"print( 'somejavadouble', type(somejavadouble), somejavadouble )\n" +
"print( 'somejavastring', type(somejavastring), somejavastring )\n" +
"print( 'somejavaobject', type(somejavaobject), somejavaobject )\n" +
"print( 'somejavaarray', type(somejavaarray), somejavaarray, somejavaarray[1] )\n" +
"someluaint = 444\n" +
"someluadouble = 555.666\n" +
"someluastring = 'def'\n" +
"someluauserdata = somejavaobject\n" +
"someluatable = { 999, 111 }\n" +
"someluafunction = function(x) print( 'hello, world', x ) return 678 end\n" +
"" );
b.put("somejavaint", 111);
b.put("somejavadouble", 222.333);
b.put("somejavastring", "abc");
b.put("somejavaobject", new SomeUserClass());
b.put("somejavaarray", new int[] { 777, 888 } );
System.out.println( "eval: "+cs.eval(b) );
Object someluaint = b.get("someluaint");
Object someluadouble = b.get("someluaint");
Object someluastring = b.get("someluastring");
Object someluauserdata = b.get("someluauserdata");
Object someluatable = b.get("someluatable");
Object someluafunction = b.get("someluafunction");
System.out.println( "someluaint: "+someluaint.getClass()+" "+someluaint );
System.out.println( "someluadouble: "+someluadouble.getClass()+" "+someluadouble );
System.out.println( "someluastring: "+someluastring.getClass()+" "+someluastring );
System.out.println( "someluauserdata: "+someluauserdata.getClass()+" "+someluauserdata );
System.out.println( "someluatable: "+someluatable.getClass()+" "+someluatable );
System.out.println( "someluafunction: "+someluafunction.getClass()+" "+someluafunction );
System.out.println( "someluafunction(345): "+((LuaValue) someluafunction).call(LuaValue.valueOf(345)) );
}
/**
* Execute a script and return a result of this form : 'selected={true|false}'
* Return null if problem occurs
*
* @param the path of your script
* @param the language of your script
* @param propertyFile the file where to find the properties to test
* behavior just used for the test. The filePath (relative issue) is passed to the script as argument
* @return the result string or null if problem occurs
*/
public static String EvalScript(String pathFile, Language language, String propertyFile) {
// ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine moteur;
// Engine selection
switch (language) {
case javascript:
case python:
case ruby:
moteur = manager.getEngineByExtension(language.getExtension());
break;
default:
System.out.println("Invalid language");
return null;
}
try {
Bindings bindings = moteur.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.clear();
bindings.put(propertiesFile, propertyFile);
moteur.eval(readFile(new File(pathFile)), bindings);
return "selected=" + bindings.get("selected");
} catch (ScriptException e) {
e.printStackTrace();
return null;
}
}
@Override
public void onStart(Object param) {
Map<String, Object> mapParam = (Map<String, Object>) param;
ScriptEngine engine = (ScriptEngine) mapParam.get("engine");
String entryActor = (String) mapParam.get("entryActor");
String entryActorName = (String) mapParam.get("entryActorName");
Bindings bind = engine.getBindings(ScriptContext.ENGINE_SCOPE);
//
ScriptObjectMirror mirFunc = (ScriptObjectMirror) bind.get(entryActor);
//
DFActorManagerJs.get().createActor(mirFunc, entryActorName, null, null);
mapParam.clear(); mapParam = null;
}
private boolean _initCustomScript(File dir){
boolean bRet = false;
do {
LinkedList<File> lsFile = new LinkedList<>();
_iteratorCustomScript(dir, lsFile);
Iterator<File> it = lsFile.iterator();
while(it.hasNext()){
File f = it.next();
if(!_checkScriptFileValid(f)){
return false;
}
try {
_jsEngine.eval(new FileReader(f));
} catch (FileNotFoundException | ScriptException e) {
e.printStackTrace();
return false;
}
}
Bindings bind = _jsEngine.getBindings(ScriptContext.ENGINE_SCOPE);
Object objEntry = bind.get(_entryActor);
if(objEntry == null){
printError("EntryActor not found: "+_entryActor);
break;
}
if(!(objEntry instanceof ScriptObjectMirror)){
printError("invalid EntryActor class: "+objEntry.getClass());
break;
}
ScriptObjectMirror mir = (ScriptObjectMirror) objEntry;
if(!mir.isFunction()){
printError("invalid EntryActor type: not function");
break;
}
bRet = true;
} while (false);
return bRet;
}
private Matcher<Bindings> bindingsHasResource(final Resource resource) {
return new TypeSafeMatcher<Bindings>() {
@Override
protected boolean matchesSafely(Bindings bindings) {
return bindings.get(SlingBindings.RESOURCE) == resource;
}
@Override
public void describeTo(Description description) {
description.appendText("a bindings object with the resource " + resource);
}
};
}
public static Bindings updateBindings(Bindings bindings, UpdateAttributesRequest msg) {
Map<String, Object> attrMap = (Map<String, Object>) bindings.get(CLIENT_SIDE);
for (AttributeKvEntry attr : msg.getAttributes()) {
if (!CLIENT_SIDE.equalsIgnoreCase(attr.getKey()) && !SERVER_SIDE.equalsIgnoreCase(attr.getKey())
&& !SHARED.equalsIgnoreCase(attr.getKey())) {
bindings.put(attr.getKey(), getValue(attr));
}
attrMap.put(attr.getKey(), getValue(attr));
}
bindings.put(CLIENT_SIDE, attrMap);
return bindings;
}
public static String getVariable( ScriptEngine actualContext, Bindings actualObject, Object[] ArgList,
Object FunctionContext ) {
String sRC = "";
String sArg1 = "";
String sArg2 = "";
if ( ArgList.length == 2 ) {
try {
Object scmo = actualObject.get( "_step_" );
Object scmO = scmo;
if ( scmO instanceof Script ) {
Script scm = (Script) scmO;
sArg1 = (String) ArgList[0];
sArg2 = (String) ArgList[1];
return scm.getVariable( sArg1, sArg2 );
} else {
// running via the Test button in a dialog
sArg2 = (String) ArgList[1];
return sArg2;
}
} catch ( Exception e ) {
sRC = "";
}
} else {
throw new RuntimeException( "The function call getVariable requires 2 arguments." );
}
return sRC;
}
@Test
// check that engine.js definitions are visible in all new global instances
public void checkBuiltinsInNewBindingsTest() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
// check default global instance has engine.js definitions
final Bindings g = (Bindings) e.eval("this");
Object value = g.get("__noSuchProperty__");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
value = g.get("print");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
// check new global instance created has engine.js definitions
final Bindings b = e.createBindings();
value = b.get("__noSuchProperty__");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
value = b.get("print");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
// put a mapping into GLOBAL_SCOPE
final Bindings globalScope = e.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
globalScope.put("x", "hello");
// GLOBAL_SCOPE mapping should be visible from default ScriptContext eval
assertTrue(e.eval("x").equals("hello"));
final ScriptContext ctx = new SimpleScriptContext();
ctx.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);
ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
// GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
assertTrue(e.eval("x", ctx).equals("hello"));
// try some arbitray Bindings for ENGINE_SCOPE
final Bindings sb = new SimpleBindings();
ctx.setBindings(sb, ScriptContext.ENGINE_SCOPE);
// GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
assertTrue(e.eval("x", ctx).equals("hello"));
// engine.js builtins are still defined even with arbitrary Bindings
assertTrue(e.eval("typeof print", ctx).equals("function"));
assertTrue(e.eval("typeof __noSuchProperty__", ctx).equals("function"));
// ENGINE_SCOPE definition should 'hide' GLOBAL_SCOPE definition
sb.put("x", "newX");
assertTrue(e.eval("x", ctx).equals("newX"));
}
@Test
// check that engine.js definitions are visible in all new global instances
public void checkBuiltinsInNewBindingsTest() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
// check default global instance has engine.js definitions
final Bindings g = (Bindings) e.eval("this");
Object value = g.get("__noSuchProperty__");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
value = g.get("print");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
// check new global instance created has engine.js definitions
final Bindings b = e.createBindings();
value = b.get("__noSuchProperty__");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
value = b.get("print");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
// put a mapping into GLOBAL_SCOPE
final Bindings globalScope = e.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
globalScope.put("x", "hello");
// GLOBAL_SCOPE mapping should be visible from default ScriptContext eval
assertTrue(e.eval("x").equals("hello"));
final ScriptContext ctx = new SimpleScriptContext();
ctx.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);
ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
// GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
assertTrue(e.eval("x", ctx).equals("hello"));
// try some arbitray Bindings for ENGINE_SCOPE
final Bindings sb = new SimpleBindings();
ctx.setBindings(sb, ScriptContext.ENGINE_SCOPE);
// GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
assertTrue(e.eval("x", ctx).equals("hello"));
// engine.js builtins are still defined even with arbitrary Bindings
assertTrue(e.eval("typeof print", ctx).equals("function"));
assertTrue(e.eval("typeof __noSuchProperty__", ctx).equals("function"));
// ENGINE_SCOPE definition should 'hide' GLOBAL_SCOPE definition
sb.put("x", "newX");
assertTrue(e.eval("x", ctx).equals("newX"));
}
public static Object funcBindings(final Bindings bindings) {
return bindings.get("foo");
}
public static Object funcBindings(final Bindings bindings) {
return bindings.get("foo");
}
@Test
// check that engine.js definitions are visible in all new global instances
public void checkBuiltinsInNewBindingsTest() throws ScriptException {
final ScriptEngineManager m = new ScriptEngineManager();
final ScriptEngine e = m.getEngineByName("nashorn");
// check default global instance has engine.js definitions
final Bindings g = (Bindings) e.eval("this");
Object value = g.get("__noSuchProperty__");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
value = g.get("print");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
// check new global instance created has engine.js definitions
final Bindings b = e.createBindings();
value = b.get("__noSuchProperty__");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
value = b.get("print");
assertTrue(value instanceof ScriptObjectMirror && ((ScriptObjectMirror)value).isFunction());
// put a mapping into GLOBAL_SCOPE
final Bindings globalScope = e.getContext().getBindings(ScriptContext.GLOBAL_SCOPE);
globalScope.put("x", "hello");
// GLOBAL_SCOPE mapping should be visible from default ScriptContext eval
assertTrue(e.eval("x").equals("hello"));
final ScriptContext ctx = new SimpleScriptContext();
ctx.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);
ctx.setBindings(b, ScriptContext.ENGINE_SCOPE);
// GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
assertTrue(e.eval("x", ctx).equals("hello"));
// try some arbitray Bindings for ENGINE_SCOPE
final Bindings sb = new SimpleBindings();
ctx.setBindings(sb, ScriptContext.ENGINE_SCOPE);
// GLOBAL_SCOPE mapping should be visible from non-default ScriptContext eval
assertTrue(e.eval("x", ctx).equals("hello"));
// engine.js builtins are still defined even with arbitrary Bindings
assertTrue(e.eval("typeof print", ctx).equals("function"));
assertTrue(e.eval("typeof __noSuchProperty__", ctx).equals("function"));
// ENGINE_SCOPE definition should 'hide' GLOBAL_SCOPE definition
sb.put("x", "newX");
assertTrue(e.eval("x", ctx).equals("newX"));
}
public static Object funcBindings(final Bindings bindings) {
return bindings.get("foo");
}