private static Function compile(String function) { final ContextFactory contextFactory = ContextFactory.getGlobal(); final Context context = contextFactory.enterContext(); context.setOptimizationLevel(JavaScriptConfig.DEFAULT_OPTIMIZATION_LEVEL); final ScriptableObject scope = context.initStandardObjects(); final org.mozilla.javascript.Function fn = context.compileFunction(scope, function, "fn", 1, null); Context.exit(); return new Function() { @Override public double apply(Object[] args) { // ideally we need a close() function to discard the context once it is not used anymore Context cx = Context.getCurrentContext(); if (cx == null) { cx = contextFactory.enterContext(); } return Context.toNumber(fn.call(cx, scope, scope, args)); } }; }
public JavaScriptPredicateFactory(final String script, final ExtractionFn extractionFn) { Preconditions.checkNotNull(script, "script must not be null"); this.script = script; this.extractionFn = extractionFn; final Context cx = Context.enter(); try { cx.setOptimizationLevel(9); scope = cx.initStandardObjects(); fnApply = cx.compileFunction(scope, script, "script", 1, null); } finally { Context.exit(); } }
@Override public @Nullable Object evaluate(@NonNull String expression) throws Throwable { Object result; final Context jsContext = enterJsContext(); try { result = jsContext.evaluateString(mJsScope, expression, "chrome", 1, null); // Google chrome automatically saves the last expression to `$_`, we do the same Object jsValue = Context.javaToJS(result, mJsScope); ScriptableObject.putProperty(mJsScope, "$_", jsValue); } finally { Context.exit(); } return Context.jsToJava(result, Object.class); }
@Override public String apply(Object input) { // ideally we need a close() function to discard the context once it is not used anymore Context cx = Context.getCurrentContext(); if (cx == null) { cx = contextFactory.enterContext(); } final Object res = fn.call(cx, scope, scope, new Object[]{input}); return res != null ? Context.toString(res) : null; } };
@Override public Object apply(Object input) { // ideally we need a close() function to discard the context once it is not used anymore Context cx = Context.getCurrentContext(); if (cx == null) { cx = contextFactory.enterContext(); } final Object res = fn.call(cx, scope, scope, new Object[]{input}); return res != null ? Context.toObject(res, scope) : null; } };
jscx = ContextFactory.getGlobal().enterContext(); jsscope = jscx.initStandardObjects( null, false ); try { jscx.setOptimizationLevel( Integer.valueOf( transMeta.environmentSubstitute( optimizationLevel ) ) ); } catch ( NumberFormatException nfe ) { error_message = Scriptable jsR = Context.toObject( jsScripts[i].getScript(), jsscope ); jsscope.put( jsScripts[i].getScriptName(), jsscope, jsR ); if ( getAddClasses() != null ) { for ( int i = 0; i < getAddClasses().length; i++ ) { Object jsOut = Context.javaToJS( getAddClasses()[i].getAddObject(), jsscope ); ScriptableObject.putProperty( jsscope, getAddClasses()[i].getJSName(), jsOut ); Context.javaToJS( ScriptValuesAddedFunctions.class, jsscope ); ( (ScriptableObject) jsscope ) .defineFunctionProperties( ScriptValuesAddedFunctions.jsFunctionList, ScriptValuesAddedFunctions.class, ScriptableObject.DONTENUM ); Scriptable jsvalue = Context.toObject( dummyStep, jsscope ); Scriptable jsRowMeta = Context.toObject( prev, jsscope ); Scriptable jsarg = Context.toObject( value, jsscope ); Scriptable jsarg = Context.toObject( valueData, jsscope );
private String decryptSignature(String encryptedSig, String decryptionCode) throws DecryptException { Context context = Context.enter(); context.setOptimizationLevel(-1); Object result; try { ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, decryptionCode, "decryptionCode", 1, null); Function decryptionFunc = (Function) scope.get("decrypt", scope); result = decryptionFunc.call(context, scope, scope, new Object[]{encryptedSig}); } catch (Exception e) { throw new DecryptException("could not get decrypt signature", e); } finally { Context.exit(); } return result == null ? "" : result.toString(); }
Scriptable scope; cx = ContextFactory.getGlobal().enterContext(); scope = cx.initStandardObjects( null ); Long nr = new Long( result.getEntryNr() ); scope.put( "errors", scope, errors ); scope.put( "lines_input", scope, lines_input ); scope.put( "lines_output", scope, lines_output ); scope.put( "lines_updated", scope, lines_updated ); scope.put( "lines_rejected", scope, lines_rejected ); Object res = cx.evaluateString( scope, this.script, "<cmd>", 1, null ); boolean retval = Context.toBoolean( res ); return false; } finally { Context.exit();
Context cx = factory.enterContext(); ScriptableObject scriptable = new ImporterTopLevel(cx); Scriptable scope = cx.initStandardObjects(scriptable); ScriptableObject.putProperty(scope, entry.getKey(), Context.javaToJS(entry.getValue(), scope)); return cx.evaluateString(scope, script, filename, 1, null); } catch (Error e) { throw new ScriptException(e.getMessage()); Context.exit();
/** * Setups a proper javascript context so that it can run javascript code properly under android. * For android we need to disable bytecode generation since the android vms don't understand JVM bytecode. * @return a proper javascript context */ static @NonNull Context enterJsContext() { final Context jsContext = Context.enter(); // If we cause the context to throw a runtime exception from this point // we need to make sure that exit the context. try { jsContext.setLanguageVersion(Context.VERSION_1_8); // We can't let Rhino to optimize the JS and to use a JIT because it would generate JVM bytecode // and android runs on DEX bytecode. Instead we need to go in interpreted mode. jsContext.setOptimizationLevel(-1); } catch (RuntimeException e) { // Something bad happened to the javascript context but it might still be usable. // The first thing to do is to exit the context and then propagate the error. Context.exit(); throw e; } return jsContext; } }
String script = "function abc(x,y) {return x+y;}" + "function def(u,v) {return u-v;}"; Context context = Context.enter(); try { ScriptableObject scope = context.initStandardObjects(); context.evaluateString(scope, script, "script", 1, null); Function fct = (Function)scope.get("abc", scope); Object result = fct.call( context, scope, scope, new Object[] {2, 3}); System.out.println(Context.jsToJava(result, int.class)); } finally { Context.exit(); }
public static String getVariable( Context actualContext, Scriptable actualObject, Object[] ArgList, Function FunctionContext ) { String sRC = ""; String sArg1 = ""; String sArg2 = ""; if ( ArgList.length == 2 ) { try { Object scmo = actualObject.get( "_step_", actualObject ); Object scmO = Context.jsToJava( scmo, StepInterface.class ); if ( scmO instanceof StepInterface ) { StepInterface scm = (StepInterface) Context.jsToJava( scmO, StepInterface.class ); sArg1 = Context.toString( ArgList[0] ); sArg2 = Context.toString( ArgList[1] ); return scm.getVariable( sArg1, sArg2 ); } else { // running via the Test button in a dialog sArg2 = Context.toString( ArgList[1] ); return sArg2; } } catch ( Exception e ) { sRC = ""; } } else { throw Context.reportRuntimeError( "The function call getVariable requires 2 arguments." ); } return sRC; }
private Scriptable executeModuleScript(Context cx, String id, Scriptable exports, ModuleScript moduleScript, boolean isMain) { final ScriptableObject moduleObject = (ScriptableObject)cx.newObject( nativeScope); URI uri = moduleScript.getUri(); URI base = moduleScript.getBase(); defineReadOnlyProperty(moduleObject, "id", id); if(!sandboxed) { defineReadOnlyProperty(moduleObject, "uri", uri.toString()); } final Scriptable executionScope = new ModuleScope(nativeScope, uri, base); // Set this so it can access the global JS environment objects. // This means we're currently using the "MGN" approach (ModuleScript // with Global Natives) as specified here: // <http://wiki.commonjs.org/wiki/Modules/ProposalForNativeExtension> executionScope.put("exports", executionScope, exports); executionScope.put("module", executionScope, moduleObject); moduleObject.put("exports", moduleObject, exports); install(executionScope); if(isMain) { defineReadOnlyProperty(this, "main", moduleObject); } executeOptionalScript(preExec, cx, executionScope); moduleScript.getScript().exec(cx, executionScope); executeOptionalScript(postExec, cx, executionScope); return ScriptRuntime.toObject(cx, nativeScope, ScriptableObject.getProperty(moduleObject, "exports")); }
String script = "function abc(x,y) {return x+y;}"; Context context = Context.enter(); try { ScriptableObject scope = context.initStandardObjects(); Scriptable that = context.newObject(scope); Function fct = context.compileFunction(scope, script, "script", 1, null); Object result = fct.call( context, scope, that, new Object[] {2, 3}); System.out.println(Context.jsToJava(result, int.class)); } finally { Context.exit(); }
@Override @SuppressWarnings({ "unchecked" }) public void render(HttpRequest request, HttpResponse response, BeanMap beanMap, SpiderBean bean) { Context cx = Context.enter(); ScriptableObject scope = cx.initSafeStandardObjects(); String windowScript = "var window = {};var document = {};"; cx.evaluateString(scope, windowScript, "window", 1, null); HtmlParser parser = new HtmlParser(request.getUrl(), response.getContent()); for (Element ele : parser.$("script")) { String sc = ele.html(); if (StringUtils.isNotEmpty(sc)) { try { cx.evaluateString(scope, sc, "", 1, null); } catch (Exception ex) { // ex.printStackTrace(); } } } Map<String, Object> fieldMap = new HashMap<String, Object>(); Set<Field> jsVarFields = ReflectionUtils.getAllFields(bean.getClass(), ReflectionUtils.withAnnotation(JSVar.class)); for (Field jsVarField : jsVarFields) { Object value = injectJsVarField(request, beanMap, jsVarField, cx, scope); if(value != null) { fieldMap.put(jsVarField.getName(), value); } } beanMap.putAll(fieldMap); Context.exit(); }
public Object getObject() { Scriptable newPackages; Context.enter(); try { final String JAVA_PACKAGE = "JavaPackage"; ClassLoader cl = Thread.currentThread().getContextClassLoader(); // FIXME - NativeJavaPackage is an internal class which we should not use newPackages = new NativeJavaPackage( "", cl ); newPackages.setParentScope( getScope() ); newPackages.setPrototype( ScriptableObject.getClassPrototype( getScope(), JAVA_PACKAGE ) ); //objectModel.put( "Packages", newPackages ); //objectModel.put( "java", ScriptableObject.getProperty( getScope(), "java" ) ); } finally { Context.exit(); } return newPackages; }
@BeforeClass public static void setUp() throws Exception { ctx = Context.enter(); scope = ctx.initStandardObjects(); }
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)); } }
public String[] getPropertyNames(Object obj) { Context.enter(); try { Object[] ids; if (obj instanceof ScriptableObject) { ids = ((ScriptableObject)obj).getAllIds(); } else { ids = ((Scriptable)obj).getIds(); } String[] result = new String[ids.length]; for (int i = 0; i < result.length; i++) { result[i] = (String)ids[i]; } return result; } finally { Context.exit(); } }