Search in sources :

Example 1 with NativeObject

use of org.mozilla.javascript.NativeObject in project hackpad by dropbox.

the class JsonParserTest method shouldParseJsonObject.

@Test
@SuppressWarnings({ "serial", "unchecked" })
public void shouldParseJsonObject() throws Exception {
    String json = "{" + "\"bool\" : false, " + "\"str\"  : \"xyz\", " + "\"obj\"  : {\"a\":1} " + "}";
    NativeObject actual = (NativeObject) parser.parseValue(json);
    assertEquals(false, actual.get("bool", actual));
    assertEquals("xyz", actual.get("str", actual));
    NativeObject innerObj = (NativeObject) actual.get("obj", actual);
    assertEquals(1, innerObj.get("a", innerObj));
}
Also used : NativeObject(org.mozilla.javascript.NativeObject) Test(org.junit.Test)

Example 2 with NativeObject

use of org.mozilla.javascript.NativeObject in project scriptographer by scriptographer.

the class RhinoWrapFactory method coerceType.

public Object coerceType(Class<?> type, Object value, Object unwrapped) {
    // Coerce native objects to maps when needed
    if (value instanceof Function) {
        if (type == Callable.class)
            return new RhinoCallable(engine, (Function) value);
    } else if (value instanceof Scriptable || value instanceof String) {
        // passed value, or can convert to it.
        if (Map.class.isAssignableFrom(type))
            return toMap((Scriptable) value);
        // Try and see if unwrapping NativeObjects through JS unwrap
        // method brings us to the right type.
        boolean isNativeObject = value instanceof NativeObject;
        if (isNativeObject) {
            unwrapped = unwrap(value);
            if (unwrapped != value && type.isInstance(unwrapped))
                return unwrapped;
        }
        ArgumentReader reader = null;
        if (ArgumentReader.canConvert(type) && (reader = getArgumentReader(value)) != null) {
            return ArgumentReader.convert(reader, unwrapped, type, this);
        } else if (isNativeObject) {
            Constructor ctor = getZeroArgumentConstructor(type);
            if (ctor != null) {
                try {
                    Object result = ctor.newInstance();
                    // As a conversion, use setProperties through argument
                    // reader to set all values on the newly
                    // created object.
                    setProperties(result, getArgumentReader(value));
                    return result;
                } catch (Exception e) {
                    throw Context.throwAsScriptRuntimeEx(e);
                }
            }
        }
    } else if (value == Undefined.instance) {
        // Convert undefined to false if destination is boolean
        if (type == Boolean.TYPE)
            return Boolean.FALSE;
    } else if (value instanceof Boolean) {
        // classes.
        if (!((Boolean) value).booleanValue() && !type.isPrimitive())
            return Undefined.instance;
    }
    return null;
}
Also used : NativeObject(org.mozilla.javascript.NativeObject) Function(org.mozilla.javascript.Function) Constructor(java.lang.reflect.Constructor) NativeObject(org.mozilla.javascript.NativeObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) ArgumentReader(com.scratchdisk.script.ArgumentReader) StringArgumentReader(com.scratchdisk.script.StringArgumentReader) Scriptable(org.mozilla.javascript.Scriptable) IdentityHashMap(java.util.IdentityHashMap) WeakIdentityHashMap(com.scratchdisk.util.WeakIdentityHashMap) Map(java.util.Map)

Example 3 with NativeObject

use of org.mozilla.javascript.NativeObject in project scriptographer by scriptographer.

the class ExtendedJavaClass method construct.

public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
    // If the normal constructor failed, try to see if the last
    // argument is a Callable or a NativeObject object. 
    // If it is a NativeObject, use it as a hashtable containing
    // fields to be added to the object. If it is a Callable,
    // call it on the object and again use its return value
    // as a hashtable if it is a NativeObject.
    Class classObject = getClassObject();
    int modifiers = classObject.getModifiers();
    NativeObject properties = null;
    Callable initialize = null;
    if (args.length > 0 && !Modifier.isInterface(modifiers) && !Modifier.isAbstract(modifiers)) {
        // Look at the last argument to find out if we need to do something
        // special. Possibilities: a object literal that defines fields to
        // be set, or a function that is executed on the object and of which
        // the result can be fields to be set.
        Object last = args[args.length - 1];
        // which might be arguments to methods...
        if (last instanceof Callable && !(last instanceof NativeJavaClass))
            initialize = (Callable) last;
        else if (last instanceof NativeObject) {
            // Now see if the constructor takes a Map as the last argument.
            // If so, the NativeObject will be converted to it thought
            // RhinoWrapFactory. Otherwise, the NativeObject is used
            // as the properties to be set on the instance after creation.
            MemberBox ctor = findConstructor(cx, args);
            if (ctor != null) {
                Class[] types = ctor.ctor().getParameterTypes();
                Class lastType = types[types.length - 1];
                // of which NativeObject's can be converted to.
                if (!ArgumentReader.class.isAssignableFrom(lastType) && !Map.class.isAssignableFrom(lastType)) {
                    properties = (NativeObject) last;
                    if (ScriptableObject.hasProperty(properties, "unwrap"))
                        properties = null;
                }
            } else {
                // There is no constructor that has to be checked, so it
                // can only be a properties list.
                properties = (NativeObject) last;
            }
            if (properties != null) {
                // Support initialize in the passed object literal too.
                Object obj = ScriptableObject.getProperty(properties, "initialize");
                if (obj instanceof Callable)
                    initialize = (Callable) obj;
            }
        }
        // will be found:
        if (initialize != null || properties != null) {
            Object[] newArgs = new Object[args.length - 1];
            for (int i = 0; i < newArgs.length; i++) newArgs[i] = args[i];
            args = newArgs;
        }
    }
    Scriptable obj = super.construct(cx, scope, args);
    // properties returned by initialize.
    if (properties != null)
        setProperties(obj, properties);
    // into the object after, if it is a NativeObject.
    if (initialize != null) {
        Object res = initialize.call(cx, scope, obj, args);
        if (res instanceof NativeObject)
            setProperties(obj, (NativeObject) res);
    }
    return obj;
}
Also used : NativeObject(org.mozilla.javascript.NativeObject) MemberBox(org.mozilla.javascript.MemberBox) NativeJavaClass(org.mozilla.javascript.NativeJavaClass) NativeObject(org.mozilla.javascript.NativeObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) NativeJavaClass(org.mozilla.javascript.NativeJavaClass) ArgumentReader(com.scratchdisk.script.ArgumentReader) Scriptable(org.mozilla.javascript.Scriptable) IdentityHashMap(java.util.IdentityHashMap) Map(java.util.Map) HashMap(java.util.HashMap) Callable(org.mozilla.javascript.Callable)

Example 4 with NativeObject

use of org.mozilla.javascript.NativeObject in project scriptographer by scriptographer.

the class ExtendedJavaClass method getInstancePrototype.

public Scriptable getInstancePrototype() {
    if (instanceProto == null) {
        instanceProto = new NativeObject();
        // Set the prototype chain correctly for this prototype object, 
        // so properties in the prototype of parent classes are found too:
        Class sup = getClassObject().getSuperclass();
        Scriptable parent;
        if (sup != null) {
            ExtendedJavaClass classWrapper = getClassWrapper(ScriptableObject.getTopLevelScope(this), sup);
            parent = classWrapper.getInstancePrototype();
        } else {
            // At the end of the chain, there is always the Object prototype.
            parent = ScriptableObject.getObjectPrototype(this);
        }
        instanceProto.setPrototype(parent);
    }
    return instanceProto;
}
Also used : NativeObject(org.mozilla.javascript.NativeObject) NativeJavaClass(org.mozilla.javascript.NativeJavaClass) Scriptable(org.mozilla.javascript.Scriptable)

Example 5 with NativeObject

use of org.mozilla.javascript.NativeObject in project jaggery by wso2.

the class ResponseHostObject method jsFunction_addCookie.

public static void jsFunction_addCookie(Context cx, Scriptable thisObj, Object[] args, Function funObj) throws ScriptException {
    String functionName = "addCookie";
    int argsCount = args.length;
    if (argsCount != 1) {
        HostObjectUtil.invalidNumberOfArgs(hostObjectName, functionName, argsCount, false);
    }
    if (!(args[0] instanceof NativeObject)) {
        HostObjectUtil.invalidArgsError(hostObjectName, functionName, "1", "string", args[0], false);
    }
    NativeObject jcookie = (NativeObject) args[0];
    Gson gson = new Gson();
    Cookie cookie = gson.fromJson(HostObjectUtil.serializeJSON(jcookie), Cookie.class);
    ResponseHostObject rho = (ResponseHostObject) thisObj;
    rho.response.addCookie(cookie);
}
Also used : NativeObject(org.mozilla.javascript.NativeObject) Cookie(javax.servlet.http.Cookie) Gson(com.google.gson.Gson)

Aggregations

NativeObject (org.mozilla.javascript.NativeObject)10 Scriptable (org.mozilla.javascript.Scriptable)5 ScriptableObject (org.mozilla.javascript.ScriptableObject)3 Gson (com.google.gson.Gson)2 ArgumentReader (com.scratchdisk.script.ArgumentReader)2 IdentityHashMap (java.util.IdentityHashMap)2 Map (java.util.Map)2 Function (org.mozilla.javascript.Function)2 NativeJavaClass (org.mozilla.javascript.NativeJavaClass)2 StringArgumentReader (com.scratchdisk.script.StringArgumentReader)1 WeakIdentityHashMap (com.scratchdisk.util.WeakIdentityHashMap)1 Constructor (java.lang.reflect.Constructor)1 HashMap (java.util.HashMap)1 Cookie (javax.servlet.http.Cookie)1 DataSource (javax.sql.DataSource)1 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)1 Test (org.junit.Test)1 Callable (org.mozilla.javascript.Callable)1 Context (org.mozilla.javascript.Context)1 MemberBox (org.mozilla.javascript.MemberBox)1