Java Code Examples for jdk.nashorn.api.scripting.JSObject

The following examples show how to use jdk.nashorn.api.scripting.JSObject. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: openjdk-8   Source File: NativeFunction.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.3.4.4 Function.prototype.call (thisArg [ , arg1 [ , arg2, ... ] ] )
 *
 * @param self self reference
 * @param args arguments for call
 * @return result of call
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object call(final Object self, final Object... args) {
    if (!(self instanceof ScriptFunction) && !(self instanceof JSObject)) {
        throw typeError("not.a.function", ScriptRuntime.safeToString(self));
    }

    Object thiz = (args.length == 0) ? UNDEFINED : args[0];
    Object[] arguments;

    if (args.length > 1) {
        arguments = new Object[args.length - 1];
        System.arraycopy(args, 1, arguments, 0, arguments.length);
    } else {
        arguments = ScriptRuntime.EMPTY_ARRAY;
    }

    if (self instanceof ScriptFunction) {
        return ScriptRuntime.apply((ScriptFunction)self, thiz, arguments);
    } else if (self instanceof JSObject) {
        return ((JSObject)self).call(thiz, arguments);
    }

    throw new AssertionError("should not reach here");
}
 
Example 2
Source Project: TencentKona-8   Source File: NativeFunction.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 15.3.4.4 Function.prototype.call (thisArg [ , arg1 [ , arg2, ... ] ] )
 *
 * @param self self reference
 * @param args arguments for call
 * @return result of call
 */
@Function(attributes = Attribute.NOT_ENUMERABLE, arity = 1)
public static Object call(final Object self, final Object... args) {
    checkCallable(self);

    final Object thiz = (args.length == 0) ? UNDEFINED : args[0];
    Object[] arguments;

    if (args.length > 1) {
        arguments = new Object[args.length - 1];
        System.arraycopy(args, 1, arguments, 0, arguments.length);
    } else {
        arguments = ScriptRuntime.EMPTY_ARRAY;
    }

    if (self instanceof ScriptFunction) {
        return ScriptRuntime.apply((ScriptFunction)self, thiz, arguments);
    } else if (self instanceof JSObject) {
        return ((JSObject)self).call(thiz, arguments);
    }

    throw new AssertionError("should not reach here");
}
 
Example 3
Source Project: nashorn   Source File: JSObjectLinker.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public GuardedInvocation getGuardedInvocation(final LinkRequest request, final LinkerServices linkerServices) throws Exception {
    final LinkRequest requestWithoutContext = request.withoutRuntimeContext(); // Nashorn has no runtime context
    final Object self = requestWithoutContext.getReceiver();
    final CallSiteDescriptor desc = requestWithoutContext.getCallSiteDescriptor();

    if (desc.getNameTokenCount() < 2 || !"dyn".equals(desc.getNameToken(CallSiteDescriptor.SCHEME))) {
        // We only support standard "dyn:*[:*]" operations
        return null;
    }

    final GuardedInvocation inv;
    if (self instanceof JSObject) {
        inv = lookup(desc);
    } else {
        throw new AssertionError(); // Should never reach here.
    }

    return Bootstrap.asType(inv, linkerServices, desc);
}
 
Example 4
Source Project: openjdk-8   Source File: ScriptRuntime.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The in operator - generic implementation
 *
 * @param property property to check for
 * @param obj object in which to check for property
 *
 * @return true if objects are equal
 */
public static boolean IN(final Object property, final Object obj) {
    final JSType rvalType = JSType.of(obj);

    if (rvalType == JSType.OBJECT || rvalType == JSType.FUNCTION) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)obj).has(property);
        }

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

        return false;
    }

    throw typeError("in.with.non.object", rvalType.toString().toLowerCase(Locale.ENGLISH));
}
 
Example 5
/**
 * ECMA 11.8.6 - The in operator - generic implementation
 *
 * @param property property to check for
 * @param obj object in which to check for property
 *
 * @return true if objects are equal
 */
public static boolean IN(final Object property, final Object obj) {
    final JSType rvalType = JSType.of(obj);

    if (rvalType == JSType.OBJECT || rvalType == JSType.FUNCTION) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)obj).has(property);
        }

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

        return false;
    }

    throw typeError("in.with.non.object", rvalType.toString().toLowerCase(Locale.ENGLISH));
}
 
Example 6
Source Project: openjdk-jdk9   Source File: NativeArray.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static void concatToList(final ArrayList<Object> list, final Object obj) {
    final boolean isScriptArray  = isArray(obj);
    final boolean isScriptObject = isScriptArray || obj instanceof ScriptObject;
    if (isScriptArray || obj instanceof Iterable || obj instanceof JSObject || (obj != null && obj.getClass().isArray())) {
        final Iterator<Object> iter = arrayLikeIterator(obj, true);
        if (iter.hasNext()) {
            for (int i = 0; iter.hasNext(); ++i) {
                final Object value = iter.next();
                if (value == ScriptRuntime.UNDEFINED && isScriptObject && !((ScriptObject)obj).has(i)) {
                    // TODO: eventually rewrite arrayLikeIterator to use a three-state enum for handling
                    // UNDEFINED instead of an "includeUndefined" boolean with states SKIP, INCLUDE,
                    // RETURN_EMPTY. Until then, this is how we'll make sure that empty elements don't make it
                    // into the concatenated array.
                    list.add(ScriptRuntime.EMPTY);
                } else {
                    list.add(value);
                }
            }
        } else if (!isScriptArray) {
            list.add(obj); // add empty object, but not an empty array
        }
    } else {
        // single element, add it
        list.add(obj);
    }
}
 
Example 7
Source Project: openjdk-jdk9   Source File: JSObjectLinker.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        } else {
            return ((JSObject)jsobj).getMember(JSType.toString(key));
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 8
Source Project: jdk8u60   Source File: JSObjectLinker.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 9
Source Project: jdk8u60   Source File: ScriptRuntime.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 10
/**
 * ECMA 11.8.6 - The strict instanceof operator - generic implementation
 *
 * @param obj first object to compare
 * @param clazz type to check against
 *
 * @return true if {@code obj} is an instanceof {@code clazz}
 */
public static boolean INSTANCEOF(final Object obj, final Object clazz) {
    if (clazz instanceof ScriptFunction) {
        if (obj instanceof ScriptObject) {
            return ((ScriptObject)clazz).isInstance((ScriptObject)obj);
        }
        return false;
    }

    if (clazz instanceof StaticClass) {
        return ((StaticClass)clazz).getRepresentedClass().isInstance(obj);
    }

    if (clazz instanceof JSObject) {
        return ((JSObject)clazz).isInstance(obj);
    }

    // provide for reverse hook
    if (obj instanceof JSObject) {
        return ((JSObject)obj).isInstanceOf(clazz);
    }

    throw typeError("instanceof.on.non.object");
}
 
Example 11
Source Project: jdk8u_nashorn   Source File: JSObjectLinker.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unused")
private static Object get(final MethodHandle fallback, final Object jsobj, final Object key)
    throws Throwable {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        } else {
            return ((JSObject)jsobj).getMember(JSType.toString(key));
        }
    } else if (isString(key)) {
        final String name = key.toString();
        // get with method name and signature. delegate it to beans linker!
        if (name.indexOf('(') != -1) {
            return fallback.invokeExact(jsobj, (Object) name);
        }
        return ((JSObject)jsobj).getMember(name);
    }
    return null;
}
 
Example 12
Source Project: openjdk-jdk8u   Source File: JSObjectLinker.java    License: 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 13
Source Project: TencentKona-8   Source File: NativeJSON.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static String[] getOwnKeys(final Object obj) {
    if (obj instanceof ScriptObject) {
        return ((ScriptObject)obj).getOwnKeys(false);
    } else if (obj instanceof ScriptObjectMirror) {
        return ((ScriptObjectMirror)obj).getOwnKeys(false);
    } else if (obj instanceof JSObject) {
        // No notion of "own keys" or "proto" for general JSObject! We just
        // return all keys of the object. This will be useful for POJOs
        // implementing JSObject interface.
        return ((JSObject)obj).keySet().toArray(new String[0]);
    } else {
        throw new AssertionError("should not reach here");
    }
}
 
Example 14
Source Project: openjdk-jdk8u   Source File: ScriptRuntime.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 11.4.3 The typeof Operator - generic implementation
 *
 * @param object   the object from which to retrieve property to type check
 * @param property property in object to check
 *
 * @return type name
 */
public static Object TYPEOF(final Object object, final Object property) {
    Object obj = object;

    if (property != null) {
        if (obj instanceof ScriptObject) {
            obj = ((ScriptObject)obj).get(property);
            if(Global.isLocationPropertyPlaceholder(obj)) {
                if(CompilerConstants.__LINE__.name().equals(property)) {
                    obj = Integer.valueOf(0);
                } else {
                    obj = "";
                }
            }
        } else if (object instanceof Undefined) {
            obj = ((Undefined)obj).get(property);
        } else if (object == null) {
            throw typeError("cant.get.property", safeToString(property), "null");
        } else if (JSType.isPrimitive(obj)) {
            obj = ((ScriptObject)JSType.toScriptObject(obj)).get(property);
        } else if (obj instanceof JSObject) {
            obj = ((JSObject)obj).getMember(property.toString());
        } else {
            obj = UNDEFINED;
        }
    }

    return JSType.of(obj).typeName();
}
 
Example 15
Source Project: jdk8u_nashorn   Source File: NativeFunction.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ECMA 15.3.4.3 Function.prototype.apply (thisArg, argArray)
 *
 * @param self   self reference
 * @param thiz   {@code this} arg for apply
 * @param array  array of argument for apply
 * @return result of apply
 */
@Function(attributes = Attribute.NOT_ENUMERABLE)
public static Object apply(final Object self, final Object thiz, final Object array) {
    checkCallable(self);

    final Object[] args = toApplyArgs(array);

    if (self instanceof ScriptFunction) {
        return ScriptRuntime.apply((ScriptFunction)self, thiz, args);
    } else if (self instanceof JSObject) {
        return ((JSObject)self).call(thiz, args);
    }
    throw new AssertionError("Should not reach here");
}
 
Example 16
Source Project: jdk8u_nashorn   Source File: ListAdapter.java    License: GNU General Public License v2.0 5 votes vote down vote up
ListAdapter(final JSObject obj, final Global global) {
    if (global == null) {
        throw new IllegalStateException(ECMAErrors.getMessage("list.adapter.null.global"));
    }

    this.obj = obj;
    this.global = global;
}
 
Example 17
@SuppressWarnings("unused")
private static Object get(final Object jsobj, final Object key) {
    if (key instanceof Integer) {
        return ((JSObject)jsobj).getSlot((Integer)key);
    } else if (key instanceof Number) {
        final int index = getIndex((Number)key);
        if (index > -1) {
            return ((JSObject)jsobj).getSlot(index);
        }
    } else if (key instanceof String) {
        return ((JSObject)jsobj).getMember((String)key);
    }
    return null;
}
 
Example 18
Source Project: hottub   Source File: Bootstrap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the given object is a strict callable
 * @param callable the callable object to be checked for strictness
 * @return true if the obj is a strict callable, false if it is a non-strict callable.
 * @throws ECMAException with {@code TypeError} if the object is not a callable.
 */
public static boolean isStrictCallable(final Object callable) {
    if (callable instanceof ScriptFunction) {
        return ((ScriptFunction)callable).isStrict();
    } else if (isJSObjectFunction(callable)) {
        return ((JSObject)callable).isStrictFunction();
    } else if (callable instanceof BoundCallable) {
        return isStrictCallable(((BoundCallable)callable).getCallable());
    } else if (BeansLinker.isDynamicMethod(callable) || callable instanceof StaticClass) {
        return false;
    }
    throw notFunction(callable);
}
 
Example 19
Source Project: TencentKona-8   Source File: JSObjectLinker.java    License: 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 20
private static GuardedInvocation getMirrorConverter(Class<?> sourceType, 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, null);
        }
        return new GuardedInvocation(CREATE_MIRROR, IS_SCRIPT_OBJECT);
    }
    return null;
}
 
Example 21
Source Project: openjdk-8   Source File: ConsStringTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsStringFromMirror() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    final Map<Object, Object> m = new HashMap<>();
    e.eval("var x = 'f'; x += 'oo'; var obj = {x: x};");
    assertEquals("foo", ((JSObject)b.get("obj")).getMember("x"));
}
 
Example 22
Source Project: jdk8u_nashorn   Source File: JSObjectLinker.java    License: 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 23
@Test
public void topLevelAnonFuncStatement() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine e = engineManager.getEngineByName("nashorn");
    final JSObject func = (JSObject)e.eval("function(x) { return x + ' world' }");
    assertTrue(func.isFunction());
    assertEquals(func.call(e.eval("this"), "hello"), "hello world");
}
 
Example 24
Source Project: hottub   Source File: ArrayLikeIterator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ArrayLikeIterator factory (reverse order)
 * @param object object over which to do reverse element iteration
 * @param includeUndefined should undefined elements be included in the iteration
 * @return iterator
 */
public static ArrayLikeIterator<Object> reverseArrayLikeIterator(final Object object, final boolean includeUndefined) {
    Object obj = object;

    if (ScriptObject.isArray(obj)) {
        return new ReverseScriptArrayIterator((ScriptObject) obj, includeUndefined);
    }

    obj = JSType.toScriptObject(obj);
    if (obj instanceof ScriptObject) {
        return new ReverseScriptObjectIterator((ScriptObject)obj, includeUndefined);
    }

    if (obj instanceof JSObject) {
        return new ReverseJSObjectIterator((JSObject)obj, includeUndefined);
    }

    if (obj instanceof List) {
        return new ReverseJavaListIterator((List<?>)obj, includeUndefined);
    }

    if (obj != null && obj.getClass().isArray()) {
        return new ReverseJavaArrayIterator(obj, includeUndefined);
    }

    return new EmptyArrayLikeIterator();
}
 
Example 25
Source Project: openjdk-8   Source File: Bootstrap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns if the given object is a "callable"
 * @param obj object to be checked for callability
 * @return true if the obj is callable
 */
public static boolean isCallable(final Object obj) {
    if (obj == ScriptRuntime.UNDEFINED || obj == null) {
        return false;
    }

    return obj instanceof ScriptFunction ||
        ((obj instanceof JSObject) && ((JSObject)obj).isFunction()) ||
        isDynamicMethod(obj) ||
        isFunctionalInterfaceObject(obj) ||
        obj instanceof StaticClass;
}
 
Example 26
@Test
public void checkThisForJSObjectEval() throws Exception {
    final ScriptEngineManager engineManager = new ScriptEngineManager();
    final ScriptEngine e = engineManager.getEngineByName("nashorn");
    final JSObject jsobj = (JSObject)e.eval("({foo: 23, bar: 'hello' })");
    assertEquals(((Number)jsobj.eval("this.foo")).intValue(), 23);
    assertEquals(jsobj.eval("this.bar"), "hello");
    assertEquals(jsobj.eval("String(this)"), "[object Object]");
    final Object global = e.eval("this");
    assertFalse(global.equals(jsobj.eval("this")));
}
 
Example 27
Source Project: jdk8u_nashorn   Source File: Bootstrap.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns true if the given object is a strict callable
 * @param callable the callable object to be checked for strictness
 * @return true if the obj is a strict callable, false if it is a non-strict callable.
 * @throws ECMAException with {@code TypeError} if the object is not a callable.
 */
public static boolean isStrictCallable(final Object callable) {
    if (callable instanceof ScriptFunction) {
        return ((ScriptFunction)callable).isStrict();
    } else if (isJSObjectFunction(callable)) {
        return ((JSObject)callable).isStrictFunction();
    } else if (callable instanceof BoundCallable) {
        return isStrictCallable(((BoundCallable)callable).getCallable());
    } else if (BeansLinker.isDynamicMethod(callable) ||
            callable instanceof StaticClass ||
            isFunctionalInterfaceObject(callable)) {
        return false;
    }
    throw notFunction(callable);
}
 
Example 28
/**
 * 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 29
Source Project: jdk8u_nashorn   Source File: ConsStringTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testConsStringFromMirror() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    //final Map<Object, Object> m = new HashMap<>();
    e.eval("var x = 'f'; x += 'oo'; var obj = {x: x};");
    assertEquals("foo", ((JSObject)b.get("obj")).getMember("x"));
}
 
Example 30
@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 31
Source Project: openjdk-jdk9   Source File: NativeJSON.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static Object getProperty(final Object holder, final Object key) {
    if (holder instanceof ScriptObject) {
        return ((ScriptObject)holder).get(key);
    } else if (holder instanceof JSObject) {
        final JSObject jsObj = (JSObject)holder;
        if (key instanceof Integer) {
            return jsObj.getSlot((Integer)key);
        } else {
            return jsObj.getMember(Objects.toString(key));
        }
    } else {
        return new AssertionError("should not reach here");
    }
}
 
Example 32
@Test
public void testConsStringFromMirror() throws ScriptException {
    final Bindings b = e.getBindings(ScriptContext.ENGINE_SCOPE);
    final Map<Object, Object> m = new HashMap<>();
    e.eval("var x = 'f'; x += 'oo'; var obj = {x: x};");
    assertEquals("foo", ((JSObject)b.get("obj")).getMember("x"));
}
 
Example 33
/**
 * ArrayLikeIterator factory (reverse order)
 * @param object object over which to do reverse element iteration
 * @param includeUndefined should undefined elements be included in the iteration
 * @return iterator
 */
public static ArrayLikeIterator<Object> reverseArrayLikeIterator(final Object object, final boolean includeUndefined) {
    Object obj = object;

    if (ScriptObject.isArray(obj)) {
        return new ReverseScriptArrayIterator((ScriptObject) obj, includeUndefined);
    }

    obj = JSType.toScriptObject(obj);
    if (obj instanceof ScriptObject) {
        return new ReverseScriptObjectIterator((ScriptObject)obj, includeUndefined);
    }

    if (obj instanceof JSObject) {
        return new ReverseJSObjectIterator((JSObject)obj, includeUndefined);
    }

    if (obj instanceof List) {
        return new ReverseJavaListIterator((List<?>)obj, includeUndefined);
    }

    if (obj != null && obj.getClass().isArray()) {
        return new ReverseJavaArrayIterator(obj, includeUndefined);
    }

    return new EmptyArrayLikeIterator();
}
 
Example 34
Source Project: openjdk-jdk8u   Source File: JSObjectLinker.java    License: GNU General Public License v2.0 5 votes vote down vote up
static boolean canLinkTypeStatic(final Class<?> type) {
    // can link JSObject also handles Map, Bindings to make
    // sure those are not JSObjects.
    return Map.class.isAssignableFrom(type) ||
           Bindings.class.isAssignableFrom(type) ||
           JSObject.class.isAssignableFrom(type);
}
 
Example 35
Source Project: jdk8u60   Source File: JSObjectLinker.java    License: GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unused")
private static Object callToApply(final MethodHandle mh, final JSObject obj, final Object thiz, final Object... args) {
    assert args.length >= 2;
    final Object   receiver  = args[0];
    final Object[] arguments = new Object[args.length - 1];
    System.arraycopy(args, 1, arguments, 0, arguments.length);
    try {
        return mh.invokeExact(obj, thiz, new Object[] { receiver, arguments });
    } catch (final RuntimeException | Error e) {
        throw e;
    } catch (final Throwable e) {
        throw new RuntimeException(e);
    }
}
 
Example 36
Source Project: jdk8u_nashorn   Source File: ScriptRuntime.java    License: 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 37
Source Project: jdk8u_nashorn   Source File: NashornLinker.java    License: GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 38
Source Project: jdk8u60   Source File: ArrayLikeIterator.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * ArrayLikeIterator factory
 * @param object object over which to do reverse element iteration
 * @param includeUndefined should undefined elements be included in the iteration
 * @return iterator
 */
public static ArrayLikeIterator<Object> arrayLikeIterator(final Object object, final boolean includeUndefined) {
    Object obj = object;

    if (ScriptObject.isArray(obj)) {
        return new ScriptArrayIterator((ScriptObject) obj, includeUndefined);
    }

    obj = JSType.toScriptObject(obj);
    if (obj instanceof ScriptObject) {
        return new ScriptObjectIterator((ScriptObject)obj, includeUndefined);
    }

    if (obj instanceof JSObject) {
        return new JSObjectIterator((JSObject)obj, includeUndefined);
    }

    if (obj instanceof List) {
        return new JavaListIterator((List<?>)obj, includeUndefined);
    }

    if (obj != null && obj.getClass().isArray()) {
        return new JavaArrayIterator(obj, includeUndefined);
    }

    return new EmptyArrayLikeIterator();
}
 
Example 39
@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 40
private ArrayList<ValidationError> invoke(String function) throws ScriptException, NoSuchMethodException {
	JSObject msgs = (JSObject) invocable.invokeFunction(function, new JSObjectMap(args));
	ArrayList<ValidationError> result = new ArrayList<ValidationError>();
	if (msgs != null) {
		Iterator<String> it = msgs.keySet().iterator();
		while (it.hasNext()) {
			int index = Integer.parseInt(it.next());
			result.add(new ValidationError((JSObject) msgs.getSlot(index)));
		}
	}
	return result;
}