public void testSandboxed() throws Exception { final Context cx = createContext(); final Require require = getSandboxedRequire(cx); require.requireMain(cx, "testSandboxed"); // Also, test idempotent double-require of same main: require.requireMain(cx, "testSandboxed"); // Also, test failed require of different main: try { require.requireMain(cx, "blah"); fail(); } catch(IllegalStateException e) { // Expected, success } }
public boolean executeNextStatement(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (hasStatements()) { if (currentChildStatement < numberOfStatements()) { Statement st = (Statement) getStatements().get(currentChildStatement); executeNextStatement(st, javascriptContext, scope); if (bContinue) return executeNextStatement(javascriptContext, scope); } else { if (isLoop) { currentChildStatement = 0; if (bContinue) return doLoop(javascriptContext, scope); } } } return true; } return false; }
public void setFilter(String filter) throws ServiceException { if (filter == null) { filter = ""; } if (!this.filter.equals(filter)) { this.filter = filter; if (filter.length() != 0) { Context js_context = Context.enter(); try { js_and.reset(filter); js_or.reset(js_and.replaceAll(" && ")); filter = js_or.replaceAll(" || "); js_filter = js_context.compileString(filter, "filter", 0, null); } catch (EvaluatorException e) { throw new ServiceException("Failed to compile JS filter : " + e.getMessage(), e); } finally { Context.exit(); } } else { js_filter = null; } bContinue = false; } }
Scriptable compile(Context cx, Scriptable scope, Object[] args) { if (args.length > 0 && args[0] instanceof NativeRegExp) { if (args.length > 1 && args[1] != Undefined.instance) { // report error throw ScriptRuntime.typeError0("msg.bad.regexp.compile"); } NativeRegExp thatObj = (NativeRegExp) args[0]; this.re = thatObj.re; this.lastIndex = thatObj.lastIndex; return this; } String s = args.length == 0 ? "" : ScriptRuntime.toString(args[0]); String global = args.length > 1 && args[1] != Undefined.instance ? ScriptRuntime.toString(args[1]) : null; this.re = (RECompiled)compileRE(cx, s, global, false); this.lastIndex = 0; return this; }
private void testWithTwoScopes(final String scriptScope1, final String scriptScope2) { final ContextAction action = new ContextAction() { public Object run(final Context cx) { final Scriptable scope1 = cx.initStandardObjects( new MySimpleScriptableObject("scope1")); final Scriptable scope2 = cx.initStandardObjects( new MySimpleScriptableObject("scope2")); cx.evaluateString(scope2, scriptScope2, "source2", 1, null); scope1.put("scope2", scope1, scope2); return cx.evaluateString(scope1, scriptScope1, "source1", 1, null); } }; Utils.runWithAllOptimizationLevels(action); }
private void ensureScopePresent() { if (scope == null) { // Create a scope for the value conversion. This scope will be an empty scope exposing basic Object and Function, sufficient for value-conversion. // In case no context is active for the current thread, we can safely enter end exit one to get hold of a scope Context ctx = Context.getCurrentContext(); boolean closeContext = false; if (ctx == null) { ctx = Context.enter(); closeContext = true; } scope = ctx.initStandardObjects(); scope.setParentScope(null); if (closeContext) { // Only an exit call should be done when context didn't exist before Context.exit(); } } }
/** * @return The array of aspects applied to this node as short prefix qname strings */ public Scriptable getAspectsShort() { final NamespaceService ns = this.services.getNamespaceService(); final Map<String, String> cache = new HashMap<String, String>(); final Set<QName> aspects = getAspectsSet(); final Object[] result = new Object[aspects.size()]; int count = 0; for (final QName qname : aspects) { String prefix = cache.get(qname.getNamespaceURI()); if (prefix == null) { // first request for this namespace prefix, get and cache result Collection<String> prefixes = ns.getPrefixes(qname.getNamespaceURI()); prefix = prefixes.size() != 0 ? prefixes.iterator().next() : ""; cache.put(qname.getNamespaceURI(), prefix); } result[count++] = prefix + QName.NAMESPACE_PREFIX + qname.getLocalName(); } return Context.getCurrentContext().newArray(this.scope, result); }
/** * Get active workflow instances this node belongs to * * @return the active workflow instances this node belongs to */ public Scriptable getActiveWorkflows() { if (this.activeWorkflows == null) { WorkflowService workflowService = this.services.getWorkflowService(); List<WorkflowInstance> workflowInstances = workflowService.getWorkflowsForContent(this.nodeRef, true); Object[] jsWorkflowInstances = new Object[workflowInstances.size()]; int index = 0; for (WorkflowInstance workflowInstance : workflowInstances) { jsWorkflowInstances[index++] = new JscriptWorkflowInstance(workflowInstance, this.services, this.scope); } this.activeWorkflows = Context.getCurrentContext().newArray(this.scope, jsWorkflowInstances); } return this.activeWorkflows; }
@JSStaticFunction public static Object getContext() { Context jsContext = KakaoTalkListener.getJsEngines()[0].getContext(); ScriptableObject scope = KakaoTalkListener.getJsEngines()[0].getScope(); return jsContext.javaToJS(MainActivity.getContext(), scope); }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { Logger log = engine ? Engine.logEngine : Engine.logContext; if(level.equals(Level.WARN.toString()) && log.isEnabledFor(Level.WARN)) log.warn(getEvalString(javascriptContext, scope)); else if(level.equals(Level.INFO.toString()) && log.isInfoEnabled()) log.info(getEvalString(javascriptContext, scope)); else if(level.equals(Level.DEBUG.toString()) && log.isDebugEnabled()) log.debug(getEvalString(javascriptContext, scope)); else if(level.equals(Level.TRACE.toString()) && log.isTraceEnabled()) log.trace(getEvalString(javascriptContext, scope)); else if(level.equals(Level.ERROR.toString()) && log.isEnabledFor(Level.ERROR)) log.error(getEvalString(javascriptContext, scope)); return true; } } return false; }
@Override public void put(String name, Scriptable start, Object value) { if (name.equals("__proxy__")) { NativeObject proxy = (NativeObject) value; Object getter = proxy.get("get", start); if (getter instanceof NativeFunction) { mGetter = (NativeFunction) getter; } Object setter = proxy.get("set", start); if (setter instanceof NativeFunction) { mSetter = (NativeFunction) setter; } } else if (mSetter != null) { mSetter.call(Context.getCurrentContext(), start, start, new Object[]{name, value}); } else { super.put(name, start, value); } }
public void init() { //this can be initiated only once if (mScriptContextFactory == null) { mScriptContextFactory = new ScriptContextFactory(); ContextFactory.initGlobal(mScriptContextFactory); } mScriptContextFactory.setInterpreter(this); rhino = Context.enter(); // observingDebugger = new ObservingDebugger(); // rhino.setDebugger(observingDebugger, new Integer(0)); // rhino.setGeneratingDebug(true); // give some android love rhino.setOptimizationLevel(-1); scope = rhino.initStandardObjects(); //let rhino do some java <-> js transformations for us rhino.getWrapFactory().setJavaPrimitiveWrap(false); }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { String referer = null; try { HtmlConnector connector = (HtmlConnector)getConnector(); com.twinsoft.convertigo.engine.Context ctx = getParentTransaction().context; referer = connector.getHtmlParser().getReferer(ctx); } catch (ClassCastException e) { return false; } addToScope(scope, referer); return true; } } return false; }
@Override protected boolean stepExecute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.stepExecute(javascriptContext, scope)) { List<StepWithExpressions> parents = new ArrayList<StepWithExpressions>(); DatabaseObject parentStep = this.parent; while (parentStep != null) { try { parents.add((StepWithExpressions) parentStep); } catch (Exception e) {}; if (parentStep instanceof LoopStep) { for (StepWithExpressions swe : parents) swe.bContinue = false; break; } parentStep = parentStep.getParent(); } return true; } } return false; }
CompilerState(Context cx, char[] source, int length, int flags) { this.cx = cx; this.cpbegin = source; this.cp = 0; this.cpend = length; this.flags = flags; this.parenCount = 0; this.classCount = 0; this.progLength = 0; }
public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { if (evaluated != null) { String message = "A statement exception has been raised: "; Throwable t = new Throwable(evaluated.toString()); EngineException ee = new EngineException(message,t); throw ee; } return true; } } return false; }
static void processFiles(Context cx, String[] args) { // define "arguments" array in the top-level object: // need to allocate new array since newArray requires instances // of exactly Object[], not ObjectSubclass[] Object[] array = new Object[args.length]; System.arraycopy(args, 0, array, 0, args.length); Scriptable argsObj = cx.newArray(global, array); global.defineProperty("arguments", argsObj, ScriptableObject.DONTENUM); for (String file : fileList) { try { processSource(cx, file); } catch (IOException ioex) { Context.reportError(ToolErrorReporter.getMessage( "msg.couldnt.read.source", file, ioex.getMessage())); exitCode = EXITCODE_FILE_NOT_FOUND; } catch (RhinoException rex) { ToolErrorReporter.reportException( cx.getErrorReporter(), rex); exitCode = EXITCODE_RUNTIME_ERROR; } catch (VirtualMachineError ex) { // Treat StackOverflow and OutOfMemory as runtime errors ex.printStackTrace(); String msg = ToolErrorReporter.getMessage( "msg.uncaughtJSException", ex.toString()); Context.reportError(msg); exitCode = EXITCODE_RUNTIME_ERROR; } } }
@Override public DebugFrame getFrame(Context cx, DebuggableScript fnOrScript) { if (debugFrame == null) { debugFrame = new ObservingDebugFrame(isDisconnected); } return debugFrame; }
public static void processFile(Context cx, Scriptable scope, String filename) throws IOException { if (securityImpl == null) { processFileSecure(cx, scope, filename, null); } else { //securityImpl.callProcessFileSecure(cx, scope, filename); } }
private static Script loadCompiledScript(Context cx, String path, byte[] data, Object securityDomain) throws FileNotFoundException { if (data == null) { throw new FileNotFoundException(path); } // XXX: For now extract class name of compiled Script from path // instead of parsing class bytes int nameStart = path.lastIndexOf('/'); if (nameStart < 0) { nameStart = 0; } else { ++nameStart; } int nameEnd = path.lastIndexOf('.'); if (nameEnd < nameStart) { // '.' does not exist in path (nameEnd < 0) // or it comes before nameStart nameEnd = path.length(); } String name = path.substring(nameStart, nameEnd); try { GeneratedClassLoader loader = SecurityController.createLoader(cx.getApplicationClassLoader(), securityDomain); Class<?> clazz = loader.defineClass(name, data); loader.linkClass(clazz); if (!Script.class.isAssignableFrom(clazz)) { throw Context.reportRuntimeError("msg.must.implement.Script"); } return (Script) clazz.newInstance(); } catch (IllegalAccessException iaex) { Context.reportError(iaex.toString()); throw new RuntimeException(iaex); } catch (InstantiationException inex) { Context.reportError(inex.toString()); throw new RuntimeException(inex); } }
public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { evaluate(javascriptContext, scope, expression, "ContextSet", true); scope.put("__tmp__ContextSetStatement", scope, evaluated); evaluate(javascriptContext, scope, "context.set('"+key+"',__tmp__ContextSetStatement)", "ContextSet", true); scope.delete("__tmp__ContextSetStatement"); return true; } } return false; }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { returnLoop(this.parent, this.evaluated); return true; } } return false; }
void initRequireBuilder(Context context, Scriptable scope) { List<URI> list = new ArrayList<>(); for (String path : mRequirePath) { list.add(new File(path).toURI()); } AssetAndUrlModuleSourceProvider provider = new AssetAndUrlModuleSourceProvider(mAndroidContext, list); new RequireBuilder() .setModuleScriptProvider(new SoftCachingModuleScriptProvider(provider)) .setSandboxed(true) .createRequire(context, scope) .install(scope); }
void initRequireBuilder(Context context, Scriptable scope) { List<URI> list = new ArrayList<>(); for (String path : mRequirePath) { list.add(new File(path).toURI()); } AssetAndUrlModuleSourceProvider provider = new AssetAndUrlModuleSourceProvider(mAndroidContext, list); new RequireBuilder() .setModuleScriptProvider(new SoftCachingModuleScriptProvider(provider)) .setSandboxed(false) .createRequire(context, scope) .install(scope); }
public void testScriptWithMultipleContinuations() { Context cx = Context.enter(); try { cx.setOptimizationLevel(-1); // must use interpreter mode Script script = cx.compileString( "myObject.f(3) + myObject.g(3) + 2;", "test source", 1, null); cx.executeScriptWithContinuations(script, globalScope); fail("Should throw ContinuationPending"); } catch (ContinuationPending pending) { try { Object applicationState = pending.getApplicationState(); assertEquals(new Integer(3), applicationState); int saved = (Integer) applicationState; cx.resumeContinuation(pending.getContinuation(), globalScope, saved + 1); fail("Should throw another ContinuationPending"); } catch (ContinuationPending pending2) { Object applicationState2 = pending2.getApplicationState(); assertEquals(new Integer(6), applicationState2); int saved2 = (Integer) applicationState2; Object result2 = cx.resumeContinuation(pending2.getContinuation(), globalScope, saved2 + 1); assertEquals(13, ((Number)result2).intValue()); } } finally { Context.exit(); } }
private KeyboardEntry parseResult(NativeObject nativeObject) { List<List<KeyEntry>> keyboard = new ArrayList<>(5); int index = 0; String presetNumber = null; KeyboardType keyboardType = null; NumberType presetNumberType = NumberType.AUTO_DETECT; int numberLength = 0; int numberLimitLength = 0; NumberType detectedNumberType = NumberType.AUTO_DETECT; Set<Map.Entry<Object, Object>> entrySet = nativeObject.entrySet(); for (Map.Entry<Object, Object> entry : entrySet) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); if ("index".equals(key)) { index = (int) Context.toNumber(value); } else if ("presetNumber".equals(key)) { presetNumber = Context.toString(value); } else if ("keyboardType".equals(key)) { keyboardType = KeyboardType.values()[(int) Context.toNumber(value)]; } else if ("numberType".equals(key)) { presetNumberType = NumberType.values()[(int) Context.toNumber(value)]; } else if ("numberLength".equals(key)) { numberLength = (int) Context.toNumber(value); } else if ("numberLimitLength".equals(key)) { numberLimitLength = (int) Context.toNumber(value); } else if (key.startsWith("row")) { List<KeyEntry> keyList = getKeyEntries(entry); if (keyList == null) { continue; } keyboard.add(keyList); } else if ("detectedNumberType".equals(key)) { detectedNumberType = NumberType.values()[(int) Context.toNumber(value)]; } } return new KeyboardEntry(index, presetNumber, keyboardType, presetNumberType, numberLength, numberLimitLength, keyboard, detectedNumberType); }
/** * get the (cached) handler Function for this event Handler * on first access compile the function * @return */ Function getHandler() { if (_handler == null) { String attribute = _baseElement.getAttributeWithNoDefault( _handlerName ); if (attribute != null && Context.getCurrentContext() != null) { _handler = Context.getCurrentContext().compileFunction( _baseElement, "function " + AbstractDomComponent.createAnonymousFunctionName() + "() { " + attribute + "}", "httpunit", 0, null ); } } return _handler; }
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(); } }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { com.twinsoft.convertigo.engine.Context context = getParentTransaction().context; context.newXulRecorder(urlRegex, entryLifetime); Engine.logBeans.debug("(RecordForSiteClipperStatement) Recording start for URL like '" + urlRegex + "'"); } return isEnabled(); }
private Map<String, Object> jsHint(Scriptable jsHintScope, final String source, final String sourceName) { return childScope(jsHintScope, new DefaultScopeOperation<Map<String, Object>>() { public Map<String, Object> action(Scriptable scope, Context context) { scope.put("jsHintSource", scope, source); Object data = context.evaluateString(scope, "JSHINT(jsHintSource); JSHINT.data();", sourceName, 0, null); return toMap((Scriptable) data); } }); }
public int f(int a) { Context cx = Context.enter(); try { ContinuationPending pending = cx.captureContinuation(); pending.setApplicationState(a); throw pending; } finally { Context.exit(); } }
private String compile(Scriptable rootScope, final String source, final String sourceName) { return childScope(rootScope, new DefaultScopeOperation<String>() { public String action(Scriptable compileScope, Context context) { compileScope.put("coffeeScriptSource", compileScope, source); try { return (String) context.evaluateString(compileScope, "CoffeeScript.compile(coffeeScriptSource, {});", sourceName, 0, null); } catch (JavaScriptException jse) { throw new SourceTransformationException(String.format("Failed to compile coffeescript file: %s", sourceName), jse); } } }); }
public Object run(Context cx) { if (useRequire) { require = global.installRequire(cx, modulePath, sandboxed); } if (type == PROCESS_FILES) { processFiles(cx, args); } else if (type == EVAL_INLINE_SCRIPT) { evalInlineScript(cx, scriptText); } else { throw Kit.codeBug(); } return null; }
@Override public Object get(String name, Scriptable start) { Object value = super.get(name, start); if (value != null && value != UniqueTag.NOT_FOUND) { return value; } if (mGetter != null) { value = mGetter.call(Context.getCurrentContext(), start, start, new Object[]{name}); } return value; }
private Require getSandboxedRequire(Context cx, Scriptable scope, boolean sandboxed) throws URISyntaxException { return new Require(cx, cx.initStandardObjects(), new StrongCachingModuleScriptProvider( new UrlModuleSourceProvider(Collections.singleton( getDirectory()), null)), null, null, true); }
@Override protected boolean hasFeature(Context cx, int featureIndex) { switch (featureIndex) { case Context.FEATURE_STRICT_MODE: case Context.FEATURE_STRICT_VARS: case Context.FEATURE_STRICT_EVAL: case Context.FEATURE_WARNING_AS_ERROR: return true; } return super.hasFeature(cx, featureIndex); }
public void jsFunction_include(final Scriptable scope, String scriptName) throws Exception { final Context cx = Context.getCurrentContext(); if (scriptName.charAt(0) != '/') { // relative script name -- resolve it against currently executing // script's directory String pathPrefix = currentScriptDirectory; while (scriptName.startsWith("../")) { final int lastSlash = pathPrefix.lastIndexOf('/'); if (lastSlash == -1) { throw new FileNotFoundException("script:" + currentScriptDirectory + '/' + scriptName); } scriptName = scriptName.substring(3); pathPrefix = pathPrefix.substring(0, lastSlash); } scriptName = pathPrefix + '/' + scriptName; } else { // strip off leading slash scriptName = scriptName.substring(1); } final Script script = scriptStorage.getScript(scriptName); if (script == null) { throw new FileNotFoundException("script:" + scriptName); } try { final String oldScriptDirectory = currentScriptDirectory; currentScriptDirectory = getDirectoryForScript(scriptName); try { script.exec(cx, scope); } finally { currentScriptDirectory = oldScriptDirectory; } } finally { } }
@Override protected boolean executeNextStep(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (inError()) { Engine.logBeans.info("Skipping step "+ this +" ("+ hashCode()+") because its source is in error"); return true; } return super.executeNextStep(javascriptContext, scope); } return false; }
protected boolean executeTest(Context javascriptContext, Scriptable scope) throws EngineException { NodeList list = getSource().getContextValues(); if (list != null) { return list.getLength() > 0; } return false; }
/** * For current user, get feed controls * * @return JavaScript array of user feed controls */ public Scriptable getFeedControls() { List<FeedControl> feedControls = activityService.getFeedControls(); Object[] results = new Object[feedControls.size()]; int i = 0; for(FeedControl fc : feedControls) { results[i] = new FeedControl(this.tenantService.getBaseName(fc.getSiteId()), fc.getAppToolId()); i++; } return Context.getCurrentContext().newArray(getScope(), results); }