Search in sources :

Example 1 with Wrapper

use of org.mozilla.javascript.Wrapper in project sling by apache.

the class ScriptableResource method jsFunction_adaptTo.

/**
     * Implements the adaptTo() method for JavaScript scripts. This method takes
     * either a java.lang.Class object or a String containing the fully
     * qualified name of the class to adapt to.
     * <p>
     * Supporting String as an argument to this method allows for much easier
     * use in JavaScript since instead of for example writing
     * <i>"javax.jcr.Node"</i> instead of the much clumsier
     * <i>Packages.javax.jcr.Node</i>.
     *
     * @param cx The current Rhino context
     * @param thisObj The ScriptableResource object in which the method is
     *            called.
     * @param args The argument vector. Only the first argument is used which is
     *            expected to be a Class object or a String. If no argument is
     *            supplied or it has the wrong type, this method just returns
     *            <code>null</code>.
     * @param funObj The object representing the JavaScript adaptTo function.
     * @return The object to which the resource adapts or <code>null</code> if
     *         the resource does not adapt to the required type or if the
     *         argument is of the wrong type or missing.
     */
public static Object jsFunction_adaptTo(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    // get and unwrap the argument
    Object arg = (args.length > 0) ? args[0] : null;
    while (arg instanceof Wrapper) {
        arg = ((Wrapper) arg).unwrap();
    }
    // try to get the Class object for the argument
    Class<?> adapter = null;
    if (arg instanceof Class<?>) {
        adapter = (Class<?>) arg;
    } else if (arg != null && arg != Undefined.instance) {
        // try loading the class from the String
        String className = ScriptRuntime.toString(arg);
        try {
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            if (loader == null) {
                loader = thisObj.getClass().getClassLoader();
            }
            adapter = loader.loadClass(className);
        } catch (Exception e) {
            LOGGER.error("Unable to adapt object.", e);
        }
    }
    if (adapter != null) {
        ScriptableResource sr = (ScriptableResource) thisObj;
        return sr.toJS(sr.resource.adaptTo(adapter));
    }
    return Undefined.instance;
}
Also used : Wrapper(org.mozilla.javascript.Wrapper) SlingWrapper(org.apache.sling.scripting.javascript.SlingWrapper) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 2 with Wrapper

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

the class ListWrapper method coerceComponentType.

private Object coerceComponentType(Object value) {
    Object unwrapped = value;
    if (unwrapped instanceof Wrapper)
        unwrapped = ((Wrapper) unwrapped).unwrap();
    Class type = ((List) javaObject).getComponentType();
    // Use WrapFactory to coerce type if not compatible
    return type.isInstance(unwrapped) ? unwrapped : Context.getCurrentContext().getWrapFactory().coerceType(type, value, unwrapped);
}
Also used : Wrapper(org.mozilla.javascript.Wrapper) ScriptableObject(org.mozilla.javascript.ScriptableObject) List(com.scratchdisk.list.List) ReadOnlyStringIndexList(com.scratchdisk.list.ReadOnlyStringIndexList) StringIndexList(com.scratchdisk.list.StringIndexList) ReadOnlyList(com.scratchdisk.list.ReadOnlyList)

Example 3 with Wrapper

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

the class RhinoCallable method call.

public Object call(Object obj, Object[] args) throws RhinoScriptException {
    // function on it.
    try {
        Scriptable scope = ScriptableObject.getTopLevelScope(function);
        Scriptable wrapper = RhinoEngine.getWrapper(obj, scope);
        for (int i = 0; i < args.length; i++) args[i] = Context.javaToJS(args[i], scope);
        Context cx = Context.getCurrentContext();
        Object ret = function.call(cx, wrapper, wrapper, args);
        if (ret == Undefined.instance) {
            // Do not return undefined, as it cannot be handled by the
            // native side, e.g. ConversionUtils.toBoolean would produce
            // true.
            ret = null;
        } else if (ret instanceof Wrapper) {
            // Unwrap if the return value is a native java object:
            ret = ((Wrapper) ret).unwrap();
        }
        return ret;
    } catch (Throwable t) {
        // Re-throw if it was a RhinoScriptException already
        if (t.getCause() instanceof RhinoScriptException)
            throw (RhinoScriptException) t.getCause();
        throw new RhinoScriptException(engine, t);
    }
}
Also used : Context(org.mozilla.javascript.Context) Wrapper(org.mozilla.javascript.Wrapper) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable)

Example 4 with Wrapper

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

the class TopLevel method toJava.

/**
 * Convert an object into a wrapper that exposes the java methods of the
 * object to JavaScript. This is useful for treating native numbers,
 * strings, etc as their java counterpart such as java.lang.Double,
 * java.lang.String etc.
 *
 * @param thisObj a java object that is wrapped in a special way Rhino
 * @return the object wrapped as NativeJavaObject, exposing the public
 *         methods of the underlying class.
 */
public static Object toJava(Context cx, Scriptable thisObj, Object[] args, Function funObj) {
    if (thisObj == null || thisObj instanceof NativeJavaObject || thisObj == Undefined.instance) {
        return thisObj;
    }
    Scriptable topLevel = ScriptRuntime.getTopCallScope(cx);
    Object obj = thisObj;
    if (thisObj instanceof Wrapper) {
        obj = ((Wrapper) thisObj).unwrap();
    } else {
        if ("Date".equals(thisObj.getClassName())) {
            return new NativeJavaObject(topLevel, new Date((long) ScriptRuntime.toNumber(thisObj)), null);
        }
    }
    return new NativeJavaObject(topLevel, obj, null);
}
Also used : Wrapper(org.mozilla.javascript.Wrapper) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) NativeJavaObject(org.mozilla.javascript.NativeJavaObject) Scriptable(org.mozilla.javascript.Scriptable) Date(java.util.Date)

Example 5 with Wrapper

use of org.mozilla.javascript.Wrapper in project wso2-synapse by wso2.

the class CommonScriptMessageContext method serializeJSON.

/**
 * Serialize json payload.
 *
 * @param obj Json object which required to be serialized
 */
private String serializeJSON(Object obj) {
    StringWriter json = new StringWriter();
    if (obj instanceof Wrapper) {
        obj = ((Wrapper) obj).unwrap();
    }
    if (obj instanceof NativeObject) {
        json.append("{");
        NativeObject o = (NativeObject) obj;
        Object[] ids = o.getIds();
        boolean first = true;
        for (Object id : ids) {
            String key = (String) id;
            Object value = o.get((String) id, o);
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append("\"").append(key).append("\" : ").append(serializeJSON(value));
        }
        json.append("}");
    } else if (obj instanceof NativeArray) {
        json.append("[");
        NativeArray o = (NativeArray) obj;
        Object[] ids = o.getIds();
        boolean first = true;
        for (Object id : ids) {
            Object value = o.get((Integer) id, o);
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append(serializeJSON(value));
        }
        json.append("]");
    } else if (obj instanceof Object[]) {
        json.append("[");
        boolean first = true;
        for (Object value : (Object[]) obj) {
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append(serializeJSON(value));
        }
        json.append("]");
    } else if (obj instanceof String) {
        json.append("\"").append(obj.toString()).append("\"");
    } else if (obj instanceof Integer || obj instanceof Long || obj instanceof Float || obj instanceof Double || obj instanceof Short || obj instanceof BigInteger || obj instanceof BigDecimal || obj instanceof Boolean) {
        json.append(obj.toString());
    } else {
        json.append("{}");
    }
    return json.toString();
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) Wrapper(org.mozilla.javascript.Wrapper) ConsString(org.mozilla.javascript.ConsString) BigDecimal(java.math.BigDecimal) NativeObject(org.mozilla.javascript.NativeObject) BigInteger(java.math.BigInteger) StringWriter(java.io.StringWriter) BigInteger(java.math.BigInteger) XMLObject(org.mozilla.javascript.xml.XMLObject) NativeObject(org.mozilla.javascript.NativeObject)

Aggregations

Wrapper (org.mozilla.javascript.Wrapper)14 ScriptableObject (org.mozilla.javascript.ScriptableObject)7 Scriptable (org.mozilla.javascript.Scriptable)5 Context (org.mozilla.javascript.Context)4 NativeArray (org.mozilla.javascript.NativeArray)4 XMLObject (org.mozilla.javascript.xml.XMLObject)3 BigDecimal (java.math.BigDecimal)2 BigInteger (java.math.BigInteger)2 HashMap (java.util.HashMap)2 Map (java.util.Map)2 ConsString (org.mozilla.javascript.ConsString)2 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)2 NativeObject (org.mozilla.javascript.NativeObject)2 List (com.scratchdisk.list.List)1 ReadOnlyList (com.scratchdisk.list.ReadOnlyList)1 ReadOnlyStringIndexList (com.scratchdisk.list.ReadOnlyStringIndexList)1 StringIndexList (com.scratchdisk.list.StringIndexList)1 OutputStreamWriter (java.io.OutputStreamWriter)1 PrintWriter (java.io.PrintWriter)1 StringWriter (java.io.StringWriter)1