jdk.nashorn.api.scripting.ScriptObjectMirror Java Examples

The following examples show how to use jdk.nashorn.api.scripting.ScriptObjectMirror. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Script.java    From karate with MIT License 6 votes vote down vote up
public static ScriptValue evalJsFunctionCall(ScriptObjectMirror som, Object callArg, ScenarioContext context) {
    Object result;
    try {
        if (callArg != null) {
            result = som.call(som, callArg);
        } else {
            result = som.call(som);
        }
        return new ScriptValue(result);
    } catch (Exception e) {
        String message = "javascript function call failed: " + e.getMessage();
        context.logger.error(message);
        context.logger.error("failed function body: " + som);
        throw new KarateException(message);
    }
}
 
Example #2
Source File: EventManager.java    From HeavenMS with GNU Affero General Public License v3.0 6 votes vote down vote up
private List<Integer> getLobbyRange() {
    try {
        if (!ServerConstants.JAVA_8) {
            return convertToIntegerArray((List<Object>)iv.invokeFunction("setLobbyRange", (Object) null));
        } else {  // java 8 support here thanks to MedicOP
            ScriptObjectMirror object = (ScriptObjectMirror) iv.invokeFunction("setLobbyRange", (Object) null);
            int[] to = object.to(int[].class);
            List<Integer> list = new ArrayList<>();
            for (int i : to) {
                list.add(i);
            }
            return list;

        }
    } catch (ScriptException | NoSuchMethodException ex) { // they didn't define a lobby range
        List<Integer> defaultRange = new ArrayList<>();
        defaultRange.add(0);
        defaultRange.add(maxLobbys);
        
        return defaultRange;
    }
}
 
Example #3
Source File: ScriptEngineTest.java    From jdk8u_nashorn with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void functionalInterfaceObjectTest() throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine e = manager.getEngineByName("nashorn");
    final AtomicBoolean invoked = new AtomicBoolean(false);
    e.put("c", new Consumer<Object>() {
        @Override
        public void accept(Object t) {
            assertTrue(t instanceof ScriptObjectMirror);
            assertEquals(((ScriptObjectMirror)t).get("a"), "xyz");
            invoked.set(true);
        }
    });
    e.eval("var x = 'xy'; x += 'z';c({a:x})");
    assertTrue(invoked.get());
}
 
Example #4
Source File: WithObject.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object bindToExpression(final Object fn, final Object receiver) {
    if (fn instanceof ScriptFunction) {
        return bindToExpression((ScriptFunction) fn, receiver);
    } else if (fn instanceof ScriptObjectMirror) {
        final ScriptObjectMirror mirror = (ScriptObjectMirror)fn;
        if (mirror.isFunction()) {
            // We need to make sure correct 'this' is used for calls with Ident call
            // expressions. We do so here using an AbstractJSObject instance.
            return new AbstractJSObject() {
                @Override
                public Object call(final Object thiz, final Object... args) {
                    return mirror.call(withFilterExpression(receiver), args);
                }
            };
        }
    }

    return fn;
}
 
Example #5
Source File: ScriptEngineTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void functionalInterfaceObjectTest() throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine e = manager.getEngineByName("nashorn");
    final AtomicBoolean invoked = new AtomicBoolean(false);
    e.put("c", new Consumer<Object>() {
        @Override
        public void accept(Object t) {
            assertTrue(t instanceof ScriptObjectMirror);
            assertEquals(((ScriptObjectMirror)t).get("a"), "xyz");
            invoked.set(true);
        }
    });
    e.eval("var x = 'xy'; x += 'z';c({a:x})");
    assertTrue(invoked.get());
}
 
Example #6
Source File: NativeObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.2.3.2 Object.getPrototypeOf ( O )
 *
 * @param  self self reference
 * @param  obj object to get prototype from
 * @return the prototype of an object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object getPrototypeOf(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).getProto();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).getProto();
    } else {
        final JSType type = JSType.of(obj);
        if (type == JSType.OBJECT) {
            // host (Java) objects have null __proto__
            return null;
        }

        // must be some JS primitive
        throw notAnObject(obj);
    }
}
 
Example #7
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void indexPropertiesExternalBufferTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptObjectMirror obj = (ScriptObjectMirror)e.eval("var obj = {}; obj");
    final ByteBuffer buf = ByteBuffer.allocate(5);
    int i;
    for (i = 0; i < 5; i++) {
        buf.put(i, (byte)(i+10));
    }
    obj.setIndexedPropertiesToExternalArrayData(buf);

    for (i = 0; i < 5; i++) {
        assertEquals((byte)(i+10), ((Number)e.eval("obj[" + i + "]")).byteValue());
    }

    e.eval("for (i = 0; i < 5; i++) obj[i] = 0");
    for (i = 0; i < 5; i++) {
        assertEquals((byte)0, ((Number)e.eval("obj[" + i + "]")).byteValue());
        assertEquals((byte)0, buf.get(i));
    }
}
 
Example #8
Source File: WithObject.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object bindToExpression(final Object fn, final Object receiver) {
    if (fn instanceof ScriptFunction) {
        return bindToExpression((ScriptFunction) fn, receiver);
    } else if (fn instanceof ScriptObjectMirror) {
        final ScriptObjectMirror mirror = (ScriptObjectMirror)fn;
        if (mirror.isFunction()) {
            // We need to make sure correct 'this' is used for calls with Ident call
            // expressions. We do so here using an AbstractJSObject instance.
            return new AbstractJSObject() {
                @Override
                public Object call(final Object thiz, final Object... args) {
                    return mirror.call(withFilterExpression(receiver), args);
                }
            };
        }
    }

    return fn;
}
 
Example #9
Source File: NativeObject.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.4 Object.getOwnPropertyNames ( O )
 *
 * @param self self reference
 * @param obj  object to query for property names
 * @return array of property names
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object getOwnPropertyNames(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return new NativeArray(((ScriptObject)obj).getOwnKeys(true));
    } else if (obj instanceof ScriptObjectMirror) {
        return new NativeArray(((ScriptObjectMirror)obj).getOwnKeys(true));
    } else {
        throw notAnObject(obj);
    }
}
 
Example #10
Source File: NativeObject.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.10 Object.preventExtensions ( O )
 *
 * @param self self reference
 * @param obj  object, for which to set the internal extensible property to false
 * @return object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object preventExtensions(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).preventExtensions();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).preventExtensions();
    } else {
        throw notAnObject(obj);
    }
}
 
Example #11
Source File: ListAdapter.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Factory to create a ListAdapter for a given script object.
 *
 * @param obj script object to wrap as a ListAdapter
 * @return A ListAdapter wrapper object
 */
public static ListAdapter create(final Object obj) {
    if (obj instanceof ScriptObject) {
        final Object mirror = ScriptObjectMirror.wrap(obj, Context.getGlobal());
        return new JSObjectListAdapter((JSObject)mirror);
    } else if (obj instanceof JSObject) {
        return new JSObjectListAdapter((JSObject)obj);
    } else {
        throw new IllegalArgumentException("ScriptObject or JSObject expected");
    }
}
 
Example #12
Source File: ScriptRuntime.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 11.4.1 - delete operation, generic implementation
 *
 * @param obj       object with property to delete
 * @param property  property to delete
 * @param strict    are we in strict mode
 *
 * @return true if property was successfully found and deleted
 */
public static boolean DELETE(final Object obj, final Object property, final Object strict) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).delete(property, Boolean.TRUE.equals(strict));
    }

    if (obj instanceof Undefined) {
        return ((Undefined)obj).delete(property, false);
    }

    if (obj == null) {
        throw typeError("cant.delete.property", safeToString(property), "null");
    }

    if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).delete(property);
    }

    if (JSType.isPrimitive(obj)) {
        return ((ScriptObject) JSType.toScriptObject(obj)).delete(property, Boolean.TRUE.equals(strict));
    }

    if (obj instanceof JSObject) {
        ((JSObject)obj).removeMember(Objects.toString(property));
        return true;
    }

    // if object is not reference type, vacuously delete is successful.
    return true;
}
 
Example #13
Source File: NativeObject.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.13 Object.isExtensible ( O )
 *
 * @param self self reference
 * @param obj check whether an object is extensible
 * @return true if object is extensible, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isExtensible(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).isExtensible();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).isExtensible();
    } else {
        throw notAnObject(obj);
    }
}
 
Example #14
Source File: NativeObject.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.10 Object.preventExtensions ( O )
 *
 * @param self self reference
 * @param obj  object, for which to set the internal extensible property to false
 * @return object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object preventExtensions(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).preventExtensions();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).preventExtensions();
    } else {
        throw notAnObject(obj);
    }
}
 
Example #15
Source File: DFActorManagerJs.java    From dfactor with MIT License 5 votes vote down vote up
protected int createActor(Object template, Object name, Object param, Object initCfg) {
	
	HashMap<String,Object> mapParam = new HashMap<>();
	mapParam.put("template", template);
	mapParam.put("fnApi", _jsFnApi);
	if(param != null && !ScriptObjectMirror.isUndefined(param)){
		mapParam.put("param", param);
	}
	ActorProp prop = ActorProp.newProp()
			.classz(DFJsActor.class)
			.param(mapParam);
	if(name != null && name instanceof String){
		prop.name((String) name);
	}
	if(initCfg == null){ //check default cfg
		ScriptObjectMirror mirFunc = (ScriptObjectMirror) template;
		ScriptObjectMirror tmpInstance = (ScriptObjectMirror) mirFunc.newObject();
		initCfg = tmpInstance.getMember("initCfg");
		tmpInstance = null;
	}
	if(initCfg != null){ //has cfg
		try{
			if(!ScriptObjectMirror.isUndefined(initCfg)){
				ScriptObjectMirror mirCfg = (ScriptObjectMirror) initCfg;
				Object objTmp = mirCfg.get("block");
				if(objTmp != null) prop.blockActor((Boolean)objTmp);
				objTmp = mirCfg.get("schedule");
				if(objTmp != null) prop.scheduleMilli((Integer)objTmp);
			}
		}catch(Throwable e){e.printStackTrace();}
	}
	return _mgrActor.createActor(prop.getName(), prop.getClassz(), prop.getParam(),
			(int) (prop.getScheduleMilli()/DFActor.TIMER_UNIT_MILLI), prop.getConsumeType(), prop.isBlock());
}
 
Example #16
Source File: ScriptObjectMirrorTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void checkMirrorToObject() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine engine = engineManager.getEngineByName("nashorn");
    final Invocable invocable = (Invocable)engine;

    engine.eval("function test1(arg) { return { arg: arg }; }");
    engine.eval("function test2(arg) { return arg; }");
    engine.eval("function compare(arg1, arg2) { return arg1 == arg2; }");

    final Map<String, Object> map = new HashMap<>();
    map.put("option", true);

    final MirrorCheckExample example = invocable.getInterface(MirrorCheckExample.class);

    final Object value1 = invocable.invokeFunction("test1", map);
    final Object value2 = example.test1(map);
    final Object value3 = invocable.invokeFunction("test2", value2);
    final Object value4 = example.test2(value2);

    // check that Object type argument receives a ScriptObjectMirror
    // when ScriptObject is passed
    assertEquals(ScriptObjectMirror.class, value1.getClass());
    assertEquals(ScriptObjectMirror.class, value2.getClass());
    assertEquals(ScriptObjectMirror.class, value3.getClass());
    assertEquals(ScriptObjectMirror.class, value4.getClass());
    assertTrue((boolean)invocable.invokeFunction("compare", value1, value1));
    assertTrue(example.compare(value1, value1));
    assertTrue((boolean)invocable.invokeFunction("compare", value3, value4));
    assertTrue(example.compare(value3, value4));
}
 
Example #17
Source File: Tags.java    From karate with MIT License 5 votes vote down vote up
public boolean isEach(ScriptObjectMirror som) {
    if (!som.isFunction()) {
        return false;
    }            
    for (String s : values) {
        Object o = som.call(som, s);
        ScriptValue sv = new ScriptValue(o);
        if (!sv.isBooleanTrue()) {
            return false;
        }
    }
    return true;
}
 
Example #18
Source File: NashornAutoBridge.java    From proxy2 with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws ScriptException, IOException {
  ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
  try(Reader reader = Files.newBufferedReader(Paths.get("demo8/funlist.js"))) {
    engine.eval(reader);
  }
  ScriptObjectMirror global = (ScriptObjectMirror)engine.eval("this");
  
  FunListFactory f = bridge(FunListFactory.class, global);
  FunList list = f.cons(1, f.cons(2, f.cons(3, f.nil())));
  
  System.out.println(list.size());
  list.forEach(System.out::println);
}
 
Example #19
Source File: ListAdapter.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static JSObject getJSObject(final Object obj, final Global global) {
    if (obj instanceof ScriptObject) {
        return (JSObject)ScriptObjectMirror.wrap(obj, global);
    } else if (obj instanceof JSObject) {
        return (JSObject)obj;
    }
    throw new IllegalArgumentException("ScriptObject or JSObject expected");
}
 
Example #20
Source File: JDK_8078414_Test.java    From jdk8u_nashorn with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testCanNotConvertArbitraryClassToMirror() {
    assertCanNotConvert(Double.class, Map.class);
    assertCanNotConvert(Double.class, Bindings.class);
    assertCanNotConvert(Double.class, JSObject.class);
    assertCanNotConvert(Double.class, ScriptObjectMirror.class);
}
 
Example #21
Source File: NativeObject.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.12 Object.isFrozen ( O )
 *
 * @param self self reference
 * @param obj check whether an object
 * @return true if object is frozen, false otherwise
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static boolean isFrozen(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).isFrozen();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).isFrozen();
    } else {
        throw notAnObject(obj);
    }
}
 
Example #22
Source File: DFJsUtil.java    From dfactor with MIT License 5 votes vote down vote up
public static boolean isJsArray(Object arr){
	if(arr != null && arr instanceof ScriptObjectMirror){
		ScriptObjectMirror mir = (ScriptObjectMirror) arr;
		boolean b = mir.isArray();
		b = mir.isExtensible();
		
		return mir.isArray();
	}
	return false;
}
 
Example #23
Source File: JSObjectLinker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static Object jsObjectScopeCall(final JSObject jsObj, final Object thiz, final Object[] args) {
    final Object modifiedThiz;
    if (thiz == ScriptRuntime.UNDEFINED && !jsObj.isStrictFunction()) {
        final Global global = Context.getGlobal();
        modifiedThiz = ScriptObjectMirror.wrap(global, global);
    } else {
        modifiedThiz = thiz;
    }
    return jsObj.call(modifiedThiz, args);
}
 
Example #24
Source File: NativeObject.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.4 Object.getOwnPropertyNames ( O )
 *
 * @param self self reference
 * @param obj  object to query for property names
 * @return array of property names
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static ScriptObject getOwnPropertyNames(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return new NativeArray(((ScriptObject)obj).getOwnKeys(true));
    } else if (obj instanceof ScriptObjectMirror) {
        return new NativeArray(((ScriptObjectMirror)obj).getOwnKeys(true));
    } else {
        throw notAnObject(obj);
    }
}
 
Example #25
Source File: Do.java    From SikuliNG with MIT License 5 votes vote down vote up
public static void showcase(Object... args) {
  Element eShowcase = new Element();
  eShowcase.setName("SHOWCASE");
  for (Object arg : args) {
    log.trace("arg: %s", arg);
    if (((ScriptObjectMirror) arg).isFunction()) {
      ((ScriptObjectMirror) arg).call(arg, eShowcase);
    }
  }
}
 
Example #26
Source File: Jdk8072596TestSubject.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void test2(String x, final Object y, final ScriptObject w, final Object... z) {
    test1(x, y, w);

    Assert.assertEquals(z.length, 2);

    Assert.assertTrue(z[0] instanceof ScriptObjectMirror);
    Assert.assertEquals(((ScriptObjectMirror)z[0]).get("baz"), 3);

    Assert.assertTrue(z[1] instanceof ScriptObjectMirror);
    Assert.assertEquals(((ScriptObjectMirror)z[1]).get("bing"), 4);
}
 
Example #27
Source File: NativeObject.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.8 Object.seal ( O )
 *
 * @param self self reference
 * @param obj  object to seal
 * @return sealed object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object seal(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).seal();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).seal();
    } else {
        throw notAnObject(obj);
    }
}
 
Example #28
Source File: ScriptObjectMirrorTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void mirrorNewObjectInstanceFunctionTest() throws ScriptException {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    final ScriptEngine e2 = m.getEngineByName("nashorn");

    e.eval("function func() {}");
    e2.put("func", e.get("func"));
    final ScriptObjectMirror e2obj = (ScriptObjectMirror)e2.eval("({ foo: func })");
    final Object newObj = ((ScriptObjectMirror)e2obj.getMember("foo")).newObject();
    assertTrue(newObj instanceof ScriptObjectMirror);
}
 
Example #29
Source File: NativeObject.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.2.3.9 Object.freeze ( O )
 *
 * @param self self reference
 * @param obj object to freeze
 * @return frozen object
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, where = Where.CONSTRUCTOR)
public static Object freeze(final Object self, final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).freeze();
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).freeze();
    } else {
        throw notAnObject(obj);
    }
}
 
Example #30
Source File: ScriptRuntime.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Entering a {@code with} node requires new scope. This is the implementation. When exiting the with statement,
 * use {@link ScriptObject#getProto()} on the scope.
 *
 * @param scope      existing scope
 * @param expression expression in with
 *
 * @return {@link WithObject} that is the new scope
 */
public static ScriptObject openWith(final ScriptObject scope, final Object expression) {
    final Global global = Context.getGlobal();
    if (expression == UNDEFINED) {
        throw typeError(global, "cant.apply.with.to.undefined");
    } else if (expression == null) {
        throw typeError(global, "cant.apply.with.to.null");
    }

    if (expression instanceof ScriptObjectMirror) {
        final Object unwrapped = ScriptObjectMirror.unwrap(expression, global);
        if (unwrapped instanceof ScriptObject) {
            return new WithObject(scope, (ScriptObject)unwrapped);
        }
        // foreign ScriptObjectMirror
        final ScriptObject exprObj = global.newObject();
        NativeObject.bindAllProperties(exprObj, (ScriptObjectMirror)expression);
        return new WithObject(scope, exprObj);
    }

    final Object wrappedExpr = JSType.toScriptObject(global, expression);
    if (wrappedExpr instanceof ScriptObject) {
        return new WithObject(scope, (ScriptObject)wrappedExpr);
    }

    throw typeError(global, "cant.apply.with.to.non.scriptobject");
}