/** * @see de.matrixweb.smaller.javascript.JavaScriptExecutor#addGlobalFunction(java.lang.String, * java.lang.Object) */ @Override public final void addGlobalFunction(final String name, final Object object) { addGlobalFunction(name, object, name); }
/** * This creates a new script environment. * * @param name * The path of the script to add * @param optimizationLevel * The optimization level to use (-1 lowest, 9 highest) * @param clazz * The class used for resource resolving */ public JavaScriptExecutorRhino(final String name, final int optimizationLevel, final Class<?> clazz) { this.name = name; this.optimizationLevel = optimizationLevel; init(clazz); }
private void init(final Class<?> clazz) { final Context context = Context.enter(); context.setOptimizationLevel(this.optimizationLevel); context.setLanguageVersion(Context.VERSION_1_7); final ScriptableObject scope = context.initStandardObjects(); final Require require = new Require(Context.getCurrentContext(), scope, getModuleScriptProvider(clazz), null, null, false); require.install(scope); try { this.moduleScope = new ModuleScope(scope, new URI("./" + this.name), null); } catch (final URISyntaxException e) { throw new SmallerException("Failed to create moduleScope", e); } addGlobalFunction("print", LOGGER, "info"); }
/** * @param name * @param optimizationLevel * @param clazz */ public JavaScriptExecutorFast(final String name, final int optimizationLevel, final Class<?> clazz) { try { LOGGER.info("Try v8 executor"); this.executor = new JavaScriptExecutorV8(name, clazz); } catch (final NoClassDefFoundError e) { LOGGER.info("Fallback to rhino executor"); this.executor = new JavaScriptExecutorRhino(name, optimizationLevel, clazz); } catch (final UnsatisfiedLinkError e) { LOGGER.info("Fallback to rhino executor"); this.executor = new JavaScriptExecutorRhino(name, optimizationLevel, clazz); } }
/** * @see de.matrixweb.smaller.javascript.JavaScriptExecutor#addGlobalFunction(java.lang.String, * java.lang.Object, java.lang.String) */ @Override public final void addGlobalFunction(final String name, final Object object, final String method) { // @formatter:off final String script = "this['" + name + "'] = (function() {\n" + " var fn = __" + name + "__['" + method + "'];\n" + " return function() { return fn.apply(__" + name + "__, arguments); }\n" + "})();\n"; // @formatter:on ScriptableObject.putProperty(this.moduleScope, "__" + name + "__", Context.javaToJS(object, this.moduleScope)); addScriptSource(script, name + "_function_publisher"); }