Search in sources :

Example 86 with Scriptable

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

the class SecureJavascriptUtil method evaluateScript.

// exposes beans
public static Object evaluateScript(VariableScope variableScope, String script, Map<Object, Object> beans) {
    Context context = Context.enter();
    try {
        Scriptable scope = context.initStandardObjects();
        SecureScriptScope secureScriptScope = new SecureScriptScope(variableScope, beans);
        scope.setPrototype(secureScriptScope);
        return context.evaluateString(scope, script, "<script>", 0, null);
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) Scriptable(org.mozilla.javascript.Scriptable)

Example 87 with Scriptable

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

the class JavaScript method executeWithRhino.

/**
     * @param previousResult {@link SampleResult}
     * @param currentSampler {@link Sampler}
     * @param jmctx {@link JMeterContext}
     * @param vars {@link JMeterVariables}
     * @param script Javascript code
     * @param varName variable name
     * @return result as String
     * @throws InvalidVariableException
     */
private String executeWithRhino(SampleResult previousResult, Sampler currentSampler, JMeterContext jmctx, JMeterVariables vars, String script, String varName) throws InvalidVariableException {
    Context cx = Context.enter();
    String resultStr = null;
    try {
        Scriptable scope = cx.initStandardObjects(null);
        // Set up some objects for the script to play with
        //$NON-NLS-1$
        scope.put("log", scope, log);
        //$NON-NLS-1$
        scope.put("ctx", scope, jmctx);
        //$NON-NLS-1$
        scope.put("vars", scope, vars);
        //$NON-NLS-1$
        scope.put("props", scope, JMeterUtils.getJMeterProperties());
        // Previously mis-spelt as theadName
        //$NON-NLS-1$
        scope.put("threadName", scope, Thread.currentThread().getName());
        //$NON-NLS-1$
        scope.put("sampler", scope, currentSampler);
        //$NON-NLS-1$
        scope.put("sampleResult", scope, previousResult);
        //$NON-NLS-1$
        Object result = cx.evaluateString(scope, script, "<cmd>", 1, null);
        resultStr = Context.toString(result);
        if (varName != null && vars != null) {
            // vars can be null if run from TestPlan
            vars.put(varName, resultStr);
        }
    } catch (RhinoException e) {
        log.error("Error processing Javascript: [" + script + "]\n", e);
        throw new InvalidVariableException("Error processing Javascript: [" + script + "]", e);
    } finally {
        Context.exit();
    }
    return resultStr;
}
Also used : Context(org.mozilla.javascript.Context) SimpleScriptContext(javax.script.SimpleScriptContext) ScriptContext(javax.script.ScriptContext) JMeterContext(org.apache.jmeter.threads.JMeterContext) RhinoException(org.mozilla.javascript.RhinoException) Scriptable(org.mozilla.javascript.Scriptable)

Example 88 with Scriptable

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

the class BSFJavaScriptEngine method initialize.

/**
     * Initialize the engine.
     * Put the manager into the context-manager
     * map hashtable too.
     */
@Override
public void initialize(BSFManager mgr, String lang, // superclass does not support types
@SuppressWarnings("rawtypes") Vector declaredBeans) throws BSFException {
    super.initialize(mgr, lang, declaredBeans);
    // Initialize context and global scope object
    try {
        Context cx = Context.enter();
        global = new ImporterTopLevel(cx);
        Scriptable bsf = Context.toObject(new BSFFunctions(mgr, this), global);
        global.put("bsf", global, bsf);
        // superclass does not support types
        @SuppressWarnings("unchecked") final Vector<BSFDeclaredBean> beans = declaredBeans;
        for (BSFDeclaredBean declaredBean : beans) {
            declareBean(declaredBean);
        }
    } catch (Throwable t) {
        // NOSONAR We handle correctly Error case in function
        handleError(t);
    } finally {
        Context.exit();
    }
}
Also used : Context(org.mozilla.javascript.Context) ImporterTopLevel(org.mozilla.javascript.ImporterTopLevel) Scriptable(org.mozilla.javascript.Scriptable) BSFFunctions(org.apache.bsf.util.BSFFunctions) BSFDeclaredBean(org.apache.bsf.BSFDeclaredBean)

Example 89 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 90 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)

Aggregations

Scriptable (org.mozilla.javascript.Scriptable)90 Context (org.mozilla.javascript.Context)44 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 Test (org.junit.Test)5 RhinoException (org.mozilla.javascript.RhinoException)4 InputStreamReader (java.io.InputStreamReader)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 ReadOnlyList (com.scratchdisk.list.ReadOnlyList)2 ArgumentReader (com.scratchdisk.script.ArgumentReader)2 WeakIdentityHashMap (com.scratchdisk.util.WeakIdentityHashMap)2