Search in sources :

Example 96 with Scriptable

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

the class SlingGlobal method load.

private void load(Context cx, Scriptable thisObj, Object[] args) {
    SlingScriptHelper sling = getProperty(cx, thisObj, SlingBindings.SLING, SlingScriptHelper.class);
    if (sling == null) {
        throw new NullPointerException(SlingBindings.SLING);
    }
    Scriptable globalScope = ScriptableObject.getTopLevelScope(thisObj);
    Resource scriptResource = sling.getScript().getScriptResource();
    ResourceResolver resolver = scriptResource.getResourceResolver();
    // the path of the current script to resolve realtive paths
    String currentScript = sling.getScript().getScriptResource().getPath();
    String scriptParent = ResourceUtil.getParent(currentScript);
    for (Object arg : args) {
        String scriptName = ScriptRuntime.toString(arg);
        Resource loadScript = null;
        if (!scriptName.startsWith("/")) {
            String absScriptName = scriptParent + "/" + scriptName;
            loadScript = resolver.resolve(absScriptName);
        }
        // not resolved relative to the current script
        if (loadScript == null) {
            loadScript = resolver.resolve(scriptName);
        }
        if (loadScript == null) {
            throw Context.reportRuntimeError("Script file " + scriptName + " not found");
        }
        InputStream scriptStream = loadScript.adaptTo(InputStream.class);
        if (scriptStream == null) {
            throw Context.reportRuntimeError("Script file " + scriptName + " cannot be read from");
        }
        try {
            // reader for the stream
            Reader scriptReader = new InputStreamReader(scriptStream, Charset.forName("UTF-8"));
            // check whether we have to wrap the basic reader
            if (scriptName.endsWith(RhinoJavaScriptEngineFactory.ESP_SCRIPT_EXTENSION)) {
                scriptReader = new EspReader(scriptReader);
            }
            // read the suff buffered for better performance
            scriptReader = new BufferedReader(scriptReader);
            // now, let's go
            cx.evaluateReader(globalScope, scriptReader, scriptName, 1, null);
        } catch (IOException ioe) {
            throw Context.reportRuntimeError("Failure reading file " + scriptName + ": " + ioe);
        } finally {
            // ensure the script input stream is closed
            try {
                scriptStream.close();
            } catch (IOException ignore) {
            }
        }
    }
}
Also used : InputStreamReader(java.io.InputStreamReader) SlingScriptHelper(org.apache.sling.api.scripting.SlingScriptHelper) InputStream(java.io.InputStream) NonExistingResource(org.apache.sling.api.resource.NonExistingResource) Resource(org.apache.sling.api.resource.Resource) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) EspReader(org.apache.sling.scripting.javascript.io.EspReader) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Scriptable(org.mozilla.javascript.Scriptable) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) EspReader(org.apache.sling.scripting.javascript.io.EspReader) BufferedReader(java.io.BufferedReader) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) ScriptableObject(org.mozilla.javascript.ScriptableObject)

Example 97 with Scriptable

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

the class ScriptableNode method get.

/**
     * Gets the value of a (Javascript) property or child node. If there is a single single-value
     * JCR property of this node, return its string value. If there are multiple properties
     * of the same name or child nodes of the same name, return an array.
     */
@Override
public Object get(String name, Scriptable start) {
    // builtin javascript properties (jsFunction_ etc.) have priority
    final Object fromSuperclass = super.get(name, start);
    if (fromSuperclass != Scriptable.NOT_FOUND) {
        return fromSuperclass;
    }
    if (node == null) {
        return Undefined.instance;
    }
    final List<Scriptable> items = new ArrayList<Scriptable>();
    // Add all matching nodes to result
    try {
        NodeIterator it = node.getNodes(name);
        while (it.hasNext()) {
            items.add(ScriptRuntime.toObject(this, it.nextNode()));
        }
    } catch (RepositoryException e) {
        log.debug("RepositoryException while collecting Node children", e);
    }
    // Add all matching properties to result
    boolean isMulti = false;
    try {
        PropertyIterator it = node.getProperties(name);
        while (it.hasNext()) {
            Property prop = it.nextProperty();
            if (prop.getDefinition().isMultiple()) {
                isMulti = true;
                Value[] values = prop.getValues();
                for (int i = 0; i < values.length; i++) {
                    items.add(wrap(values[i]));
                }
            } else {
                items.add(wrap(prop.getValue()));
            }
        }
    } catch (RepositoryException e) {
        log.debug("RepositoryException while collecting Node properties", e);
    }
    if (items.size() == 0) {
        return getNative(name, start);
    } else if (items.size() == 1 && !isMulti) {
        return items.iterator().next();
    } else {
        NativeArray result = new NativeArray(items.toArray());
        ScriptRuntime.setObjectProtoAndParent(result, this);
        return result;
    }
}
Also used : NodeIterator(javax.jcr.NodeIterator) NativeArray(org.mozilla.javascript.NativeArray) ArrayList(java.util.ArrayList) PropertyIterator(javax.jcr.PropertyIterator) RepositoryException(javax.jcr.RepositoryException) Scriptable(org.mozilla.javascript.Scriptable) Value(javax.jcr.Value) Property(javax.jcr.Property)

Example 98 with Scriptable

use of org.mozilla.javascript.Scriptable in project jslint4java by happygiraffe.

the class JSLint method optionsAsJavaScriptObject.

/**
 * Turn the set of options into a JavaScript object, where the key is the
 * name of the option and the value is true.
 */
@NeedsContext
private Scriptable optionsAsJavaScriptObject() {
    return (Scriptable) contextFactory.call(new ContextAction() {

        public Object run(Context cx) {
            applyDefaultOptions();
            Scriptable opts = cx.newObject(lintFunc);
            for (Entry<Option, Object> entry : options.entrySet()) {
                String key = entry.getKey().getLowerName();
                // Use our "custom" version in order to get native arrays.
                Object value = Util.javaToJS(entry.getValue(), opts);
                opts.put(key, opts, value);
            }
            return opts;
        }
    });
}
Also used : Context(org.mozilla.javascript.Context) ContextAction(org.mozilla.javascript.ContextAction) ScriptableObject(org.mozilla.javascript.ScriptableObject) Scriptable(org.mozilla.javascript.Scriptable)

Example 99 with Scriptable

use of org.mozilla.javascript.Scriptable in project jslint4java by happygiraffe.

the class Util method listValue.

/**
 * Convert a JavaScript array into a Java {@link List}. You must provide a
 * converter which will be called on each value in order to convert it to a
 * Java object.
 *
 * @param <T>
 *            The type of every array member.
 * @param name
 *            The name of the array.
 * @param scope
 *            The scope which contains the array.
 * @param c
 *            A {@link Converter} instance to change the JavaScript object
 *            into a Java one.
 * @return A {@link List} of Java objects.
 */
static <T> List<T> listValue(String name, Scriptable scope, Converter<T> c) {
    Object val = scope.get(name, scope);
    if (val == UniqueTag.NOT_FOUND || val instanceof Undefined) {
        return new ArrayList<T>();
    }
    Scriptable ary = (Scriptable) val;
    int count = intValue("length", ary);
    List<T> list = new ArrayList<T>(count);
    for (int i = 0; i < count; i++) {
        list.add(c.convert(ary.get(i, ary)));
    }
    return list;
}
Also used : Undefined(org.mozilla.javascript.Undefined) ArrayList(java.util.ArrayList) Scriptable(org.mozilla.javascript.Scriptable)

Example 100 with Scriptable

use of org.mozilla.javascript.Scriptable in project gradle by gradle.

the class RhinoWorkerUtils method parseRhino.

public static <T> T parseRhino(File rhinoScript, ScopeOperation<T> operation) {
    Context context = Context.enter();
    try {
        operation.initContext(context);
        Scriptable scope = context.initStandardObjects();
        String printFunction = "function print(message) {}";
        context.evaluateString(scope, printFunction, "print", 1, null);
        context.evaluateString(scope, readFile(rhinoScript, "UTF-8"), rhinoScript.getName(), 1, null);
        return operation.action(scope, context);
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) Scriptable(org.mozilla.javascript.Scriptable)

Aggregations

Scriptable (org.mozilla.javascript.Scriptable)106 Context (org.mozilla.javascript.Context)49 ScriptableObject (org.mozilla.javascript.ScriptableObject)30 ContextAction (org.mozilla.javascript.ContextAction)12 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)7 NativeObject (org.mozilla.javascript.NativeObject)7 Function (org.mozilla.javascript.Function)6 Map (java.util.Map)5 Notifier (org.apache.cxf.javascript.JavascriptTestUtilities.Notifier)5 Test (org.junit.Test)5 InputStreamReader (java.io.InputStreamReader)4 RhinoException (org.mozilla.javascript.RhinoException)4 Wrapper (org.mozilla.javascript.Wrapper)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 IdentityHashMap (java.util.IdentityHashMap)3 ScriptContext (javax.script.ScriptContext)3 Callable (org.mozilla.javascript.Callable)3 ContextFactory (org.mozilla.javascript.ContextFactory)3 NativeJavaClass (org.mozilla.javascript.NativeJavaClass)3