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;
}
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();
}
}
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;
}
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());
}
}
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));
}
Aggregations