Search in sources :

Example 61 with Context

use of org.mozilla.javascript.Context in project Auto.js by hyb1996.

the class AndroidContextFactory method makeContext.

@Override
protected Context makeContext() {
    Context cx = super.makeContext();
    cx.setInstructionObserverThreshold(10000);
    return cx;
}
Also used : Context(org.mozilla.javascript.Context)

Example 62 with Context

use of org.mozilla.javascript.Context in project structr by structr.

the class Scripting method evaluateJavascript.

public static Object evaluateJavascript(final ActionContext actionContext, final GraphObject entity, final Snippet snippet) throws FrameworkException {
    final String entityName = entity != null ? entity.getProperty(AbstractNode.name) : null;
    final String entityDescription = entity != null ? (StringUtils.isNotBlank(entityName) ? "\"" + entityName + "\":" : "") + entity.getUuid() : "anonymous";
    final Context scriptingContext = Scripting.setupJavascriptContext();
    try {
        // enable some optimizations..
        scriptingContext.setLanguageVersion(Context.VERSION_1_2);
        scriptingContext.setOptimizationLevel(9);
        scriptingContext.setInstructionObserverThreshold(0);
        scriptingContext.setGenerateObserverCount(false);
        scriptingContext.setGeneratingDebug(true);
        final Scriptable scope = scriptingContext.initStandardObjects();
        final StructrScriptable scriptable = new StructrScriptable(actionContext, entity, scriptingContext);
        scriptable.setParentScope(scope);
        // register Structr scriptable
        scope.put("Structr", scope, scriptable);
        // clear output buffer
        actionContext.clear();
        // compile or use provided script
        Script compiledScript = snippet.getCompiledScript();
        if (compiledScript == null) {
            final String sourceLocation = snippet.getName() + " [" + entityDescription + "], line ";
            final String embeddedSourceCode = embedInFunction(actionContext, snippet.getSource());
            compiledScript = compileOrGetCached(scriptingContext, embeddedSourceCode, sourceLocation, 1);
        }
        Object extractedValue = compiledScript.exec(scriptingContext, scope);
        if (scriptable.hasException()) {
            throw scriptable.getException();
        }
        // prioritize written output over result returned from method
        final String output = actionContext.getOutput();
        if (output != null && !output.isEmpty()) {
            extractedValue = output;
        }
        if (extractedValue == null || extractedValue == Undefined.instance) {
            extractedValue = scriptable.unwrap(scope.get("_structrMainResult", scope));
        }
        if (extractedValue == null || extractedValue == Undefined.instance) {
            extractedValue = "";
        }
        return extractedValue;
    } catch (final FrameworkException fex) {
        fex.printStackTrace();
        // just throw the FrameworkException so we dont lose the information contained
        throw fex;
    } catch (final Throwable t) {
        t.printStackTrace();
        // if any other kind of Throwable is encountered throw a new FrameworkException and be done with it
        throw new FrameworkException(422, t.getMessage());
    } finally {
        Scripting.destroyJavascriptContext();
    }
}
Also used : SecurityContext(org.structr.common.SecurityContext) Context(org.mozilla.javascript.Context) ScriptContext(javax.script.ScriptContext) ActionContext(org.structr.schema.action.ActionContext) Script(org.mozilla.javascript.Script) FrameworkException(org.structr.common.error.FrameworkException) GraphObject(org.structr.core.GraphObject) Scriptable(org.mozilla.javascript.Scriptable)

Example 63 with Context

use of org.mozilla.javascript.Context in project structr by structr.

the class StructrScriptable method get.

@Override
public Object get(final String name, Scriptable start) {
    if ("get".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length == 1 && parameters[0] != null) {
                    try {
                        return wrap(context, thisObject, null, actionContext.evaluate(entity, parameters[0].toString(), null, null, 0));
                    } catch (FrameworkException ex) {
                        exception = ex;
                    }
                } else if (parameters.length > 1) {
                    // execute builtin get function
                    final Function<Object, Object> function = Functions.get("get");
                    try {
                        final Object[] unwrappedParameters = new Object[parameters.length];
                        int i = 0;
                        // unwrap JS objects
                        for (final Object param : parameters) {
                            unwrappedParameters[i++] = unwrap(param);
                        }
                        return wrap(context, scope, null, function.apply(actionContext, entity, unwrappedParameters));
                    } catch (FrameworkException fex) {
                        exception = fex;
                    }
                    return null;
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("clear".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                actionContext.clear();
                return null;
            }
        }, null, 0, 0);
    }
    if ("this".equals(name)) {
        return wrap(this.scriptingContext, start, null, entity);
    }
    if ("me".equals(name)) {
        return wrap(this.scriptingContext, start, null, actionContext.getSecurityContext().getUser(false));
    }
    if ("vars".equals(name)) {
        NativeObject nobj = new NativeObject();
        for (Map.Entry<String, Object> entry : actionContext.getAllVariables().entrySet()) {
            nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
        }
        return nobj;
    }
    if ("include".equals(name) || "render".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length > 0 && parameters[0] != null) {
                    try {
                        final Function func = Functions.get(name);
                        if (func != null) {
                            actionContext.print(func.apply(actionContext, entity, parameters));
                        }
                        return null;
                    } catch (FrameworkException ex) {
                        exception = ex;
                    }
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("includeJs".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                if (parameters.length == 1) {
                    final String fileName = parameters[0].toString();
                    final String source = actionContext.getJavascriptLibraryCode(fileName);
                    // use cached / compiled source code for JS libs
                    Scripting.compileOrGetCached(context, source, fileName, 1).exec(context, scope);
                } else {
                    logger.warn("Incorrect usage of includeJs function. Takes exactly one parameter: The filename of the javascript file!");
                }
                return null;
            }
        }, null, 0, 0);
    }
    if ("batch".equals(name)) {
        return new IdFunctionObject(new BatchFunctionCall(actionContext, this), null, 0, 0);
    }
    if ("cache".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                final CacheExpression cacheExpr = new CacheExpression();
                Object retVal = null;
                try {
                    for (int i = 0; i < parameters.length; i++) {
                        cacheExpr.add(new ConstantExpression(parameters[i]));
                    }
                    retVal = cacheExpr.evaluate(actionContext, entity);
                } catch (FrameworkException ex) {
                    exception = ex;
                }
                return retVal;
            }
        }, null, 0, 0);
    }
    if ("slice".equals(name)) {
        return new IdFunctionObject(new SliceFunctionCall(actionContext, entity, scriptingContext), null, 0, 0);
    }
    if ("doPrivileged".equals(name) || "do_privileged".equals(name)) {
        return new IdFunctionObject(new IdFunctionCall() {

            @Override
            public Object execIdCall(final IdFunctionObject info, final Context context, final Scriptable scope, final Scriptable thisObject, final Object[] parameters) {
                // backup security context
                final SecurityContext securityContext = StructrScriptable.this.actionContext.getSecurityContext();
                try {
                    // replace security context with super user context
                    actionContext.setSecurityContext(SecurityContext.getSuperUserInstance());
                    if (parameters != null && parameters.length == 1) {
                        final Object param = parameters[0];
                        if (param instanceof Script) {
                            final Script script = (Script) param;
                            return script.exec(context, scope);
                        } else {
                        // ...
                        }
                    } else {
                    // ...
                    }
                    return null;
                } finally {
                    // restore saved security context
                    StructrScriptable.this.actionContext.setSecurityContext(securityContext);
                }
            }
        }, null, 0, 0);
    }
    // execute builtin function?
    final Function<Object, Object> function = Functions.get(CaseHelper.toUnderscore(name, false));
    if (function != null) {
        return new IdFunctionObject(new FunctionWrapper(function), null, 0, 0);
    }
    return null;
}
Also used : SecurityContext(org.structr.common.SecurityContext) Context(org.mozilla.javascript.Context) ActionContext(org.structr.schema.action.ActionContext) Script(org.mozilla.javascript.Script) FrameworkException(org.structr.common.error.FrameworkException) ConstantExpression(org.structr.core.parser.ConstantExpression) IdFunctionCall(org.mozilla.javascript.IdFunctionCall) Scriptable(org.mozilla.javascript.Scriptable) CacheExpression(org.structr.core.parser.CacheExpression) NativeObject(org.mozilla.javascript.NativeObject) Function(org.structr.schema.action.Function) GrantFunction(org.structr.core.function.GrantFunction) SecurityContext(org.structr.common.SecurityContext) NativeObject(org.mozilla.javascript.NativeObject) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) GraphObject(org.structr.core.GraphObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) IdFunctionObject(org.mozilla.javascript.IdFunctionObject) PropertyMap(org.structr.core.property.PropertyMap) Map(java.util.Map) GraphObjectMap(org.structr.core.GraphObjectMap)

Example 64 with Context

use of org.mozilla.javascript.Context in project BPjs by bThink-BGU.

the class BProgramSyncSnapshot method triggerEvent.

/**
 * Runs the program from the snapshot, triggering the passed event.
 * @param exSvc the executor service that will advance the threads.
 * @param anEvent the event selected.
 * @param listeners
 * @return A set of b-thread snapshots that should participate in the next cycle.
 * @throws InterruptedException
 */
public BProgramSyncSnapshot triggerEvent(BEvent anEvent, ExecutorService exSvc, Iterable<BProgramRunnerListener> listeners) throws InterruptedException {
    if (anEvent == null)
        throw new IllegalArgumentException("Cannot trigger a null event.");
    if (triggered) {
        throw new IllegalStateException("A BProgramSyncSnapshot is not allowed to be triggered twice.");
    }
    triggered = true;
    Set<BThreadSyncSnapshot> resumingThisRound = new HashSet<>(threadSnapshots.size());
    Set<BThreadSyncSnapshot> sleepingThisRound = new HashSet<>(threadSnapshots.size());
    Set<BThreadSyncSnapshot> nextRound = new HashSet<>(threadSnapshots.size());
    List<BEvent> nextExternalEvents = new ArrayList<>(getExternalEvents());
    try {
        Context ctxt = Context.enter();
        handleInterrupts(anEvent, listeners, bprog, ctxt);
        nextExternalEvents.addAll(bprog.drainEnqueuedExternalEvents());
        // Split threads to those that advance this round and those that sleep.
        threadSnapshots.forEach(snapshot -> {
            (snapshot.getBSyncStatement().shouldWakeFor(anEvent) ? resumingThisRound : sleepingThisRound).add(snapshot);
        });
    } finally {
        Context.exit();
    }
    BPEngineTask.Listener halter = new HaltOnAssertion(exSvc);
    try {
        // add the run results of all those who advance this stage
        nextRound.addAll(exSvc.invokeAll(resumingThisRound.stream().map(bt -> new ResumeBThread(bt, anEvent, halter)).collect(toList())).stream().map(f -> safeGet(f)).filter(Objects::nonNull).collect(toList()));
        // inform listeners which b-threads completed
        Set<String> nextRoundIds = nextRound.stream().map(t -> t.getName()).collect(toSet());
        resumingThisRound.stream().filter(t -> !nextRoundIds.contains(t.getName())).forEach(t -> listeners.forEach(l -> l.bthreadDone(bprog, t)));
        executeAllAddedBThreads(nextRound, exSvc, halter);
        nextExternalEvents.addAll(bprog.drainEnqueuedExternalEvents());
        // carry over BThreads that did not advance this round to next round.
        nextRound.addAll(sleepingThisRound);
        return new BProgramSyncSnapshot(bprog, nextRound, nextExternalEvents, violationRecord.get());
    } catch (RejectedExecutionException ree) {
        // The executor thread pool must have been shut down, e.g. due to program violation.
        return new BProgramSyncSnapshot(bprog, Collections.emptySet(), nextExternalEvents, violationRecord.get());
    }
}
Also used : Context(org.mozilla.javascript.Context) ResumeBThread(il.ac.bgu.cs.bp.bpjs.execution.tasks.ResumeBThread) Context(org.mozilla.javascript.Context) BProgramException(il.ac.bgu.cs.bp.bpjs.exceptions.BProgramException) ContinuationPending(org.mozilla.javascript.ContinuationPending) Set(java.util.Set) Logger(java.util.logging.Logger) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Level(java.util.logging.Level) HashSet(java.util.HashSet) Objects(java.util.Objects) ExecutionException(java.util.concurrent.ExecutionException) List(java.util.List) Future(java.util.concurrent.Future) Collectors.toList(java.util.stream.Collectors.toList) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) StartBThread(il.ac.bgu.cs.bp.bpjs.execution.tasks.StartBThread) Scriptable(org.mozilla.javascript.Scriptable) BProgramRunnerListener(il.ac.bgu.cs.bp.bpjs.execution.listeners.BProgramRunnerListener) Collections(java.util.Collections) Collectors.toSet(java.util.stream.Collectors.toSet) BPEngineTask(il.ac.bgu.cs.bp.bpjs.execution.tasks.BPEngineTask) ExecutorService(java.util.concurrent.ExecutorService) ArrayList(java.util.ArrayList) ResumeBThread(il.ac.bgu.cs.bp.bpjs.execution.tasks.ResumeBThread) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Objects(java.util.Objects) BPEngineTask(il.ac.bgu.cs.bp.bpjs.execution.tasks.BPEngineTask) HashSet(java.util.HashSet)

Example 65 with Context

use of org.mozilla.javascript.Context in project freemarker by apache.

the class RhinoFunctionModel method exec.

public Object exec(List arguments) throws TemplateModelException {
    Context cx = Context.getCurrentContext();
    Object[] args = arguments.toArray();
    BeansWrapper wrapper = getWrapper();
    for (int i = 0; i < args.length; i++) {
        args[i] = wrapper.unwrap((TemplateModel) args[i]);
    }
    return wrapper.wrap(((Function) getScriptable()).call(cx, ScriptableObject.getTopLevelScope(fnThis), fnThis, args));
}
Also used : Context(org.mozilla.javascript.Context) ScriptableObject(org.mozilla.javascript.ScriptableObject) BeansWrapper(freemarker.ext.beans.BeansWrapper) TemplateModel(freemarker.template.TemplateModel)

Aggregations

Context (org.mozilla.javascript.Context)152 Scriptable (org.mozilla.javascript.Scriptable)68 ScriptableObject (org.mozilla.javascript.ScriptableObject)62 ContextAction (org.mozilla.javascript.ContextAction)23 ContextFactory (org.mozilla.javascript.ContextFactory)22 Script (org.mozilla.javascript.Script)17 IOException (java.io.IOException)14 Function (org.mozilla.javascript.Function)13 ScriptContext (javax.script.ScriptContext)10 Test (org.junit.Test)8 RhinoException (org.mozilla.javascript.RhinoException)8 ArrayList (java.util.ArrayList)7 ContinuationPending (org.mozilla.javascript.ContinuationPending)7 NativeJavaObject (org.mozilla.javascript.NativeJavaObject)7 InputStreamReader (java.io.InputStreamReader)6 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)6 JavaScriptException (org.mozilla.javascript.JavaScriptException)6 Date (java.util.Date)5 HashSet (java.util.HashSet)5 List (java.util.List)5