Search in sources :

Example 6 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project hackpad by dropbox.

the class JsTestsBase method runJsTests.

public void runJsTests(File[] tests) throws IOException {
    ContextFactory factory = ContextFactory.getGlobal();
    Context cx = factory.enterContext();
    try {
        cx.setOptimizationLevel(this.optimizationLevel);
        Scriptable shared = cx.initStandardObjects();
        for (File f : tests) {
            // don't worry about very long
            int length = (int) f.length();
            // files
            char[] buf = new char[length];
            new FileReader(f).read(buf, 0, length);
            String session = new String(buf);
            runJsTest(cx, shared, f.getName(), session);
        }
    } finally {
        Context.exit();
    }
}
Also used : ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) FileReader(java.io.FileReader) Scriptable(org.mozilla.javascript.Scriptable) File(java.io.File)

Example 7 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project hackpad by dropbox.

the class ContextFactoryTest method testCustomContextFactory.

public void testCustomContextFactory() {
    ContextFactory factory = new MyFactory();
    Context cx = factory.enterContext();
    try {
        Scriptable globalScope = cx.initStandardObjects();
    // Test that FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME is enabled
    /* TODO(stevey): fix this functionality in parser
            Object result = cx.evaluateString(globalScope,
                    "var obj = {};" +
                    "function obj.foo() { return 'bar'; }" +
                    "obj.foo();",
                    "test source", 1, null);
            assertEquals("bar", result);
            */
    } catch (RhinoException e) {
        fail(e.toString());
    } finally {
        Context.exit();
    }
}
Also used : ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) RhinoException(org.mozilla.javascript.RhinoException) Scriptable(org.mozilla.javascript.Scriptable)

Example 8 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project sling by apache.

the class RhinoJavaScriptEngineFactory method activate.

// ---------- SCR integration
@Activate
protected void activate(final ComponentContext context, final RhinoJavaScriptEngineFactoryConfiguration configuration) {
    Dictionary<?, ?> props = context.getProperties();
    boolean debugging = getProperty("org.apache.sling.scripting.javascript.debug", props, context.getBundleContext(), false);
    optimizationLevel = readOptimizationLevel(configuration);
    // setup the wrap factory
    wrapFactory = new SlingWrapFactory();
    // initialize the Rhino Context Factory
    SlingContextFactory.setup(this);
    Context cx = Context.enter();
    setEngineName(getEngineName() + " (" + cx.getImplementationVersion() + ")");
    languageVersion = String.valueOf(cx.getLanguageVersion());
    Context.exit();
    setExtensions(ECMA_SCRIPT_EXTENSION, ESP_SCRIPT_EXTENSION);
    setMimeTypes("text/javascript", "application/ecmascript", "application/javascript");
    setNames("javascript", ECMA_SCRIPT_EXTENSION, ESP_SCRIPT_EXTENSION);
    final ContextFactory contextFactory = ContextFactory.getGlobal();
    if (contextFactory instanceof SlingContextFactory) {
        ((SlingContextFactory) contextFactory).setDebugging(debugging);
    }
    // set the dynamic class loader as the application class loader
    final DynamicClassLoaderManager dclm = this.dynamicClassLoaderManager;
    if (dclm != null) {
        contextFactory.initApplicationClassLoader(dynamicClassLoaderManager.getDynamicClassLoader());
    }
    log.info("Activated with optimization level {}", optimizationLevel);
}
Also used : ComponentContext(org.osgi.service.component.ComponentContext) Context(org.mozilla.javascript.Context) BundleContext(org.osgi.framework.BundleContext) SlingContextFactory(org.apache.sling.scripting.javascript.helper.SlingContextFactory) ContextFactory(org.mozilla.javascript.ContextFactory) SlingContextFactory(org.apache.sling.scripting.javascript.helper.SlingContextFactory) SlingWrapFactory(org.apache.sling.scripting.javascript.helper.SlingWrapFactory) DynamicClassLoaderManager(org.apache.sling.commons.classloader.DynamicClassLoaderManager) Activate(org.osgi.service.component.annotations.Activate)

Example 9 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project closure-templates by google.

the class EscapingConventionsTest method applyDirectiveInRhino.

private List<String> applyDirectiveInRhino(String directiveName, Iterable<String> toEscape, String soyUtilsPath) throws Exception {
    List<String> output = Lists.newArrayList();
    Context context = new ContextFactory().enterContext();
    // Only running once.
    context.setOptimizationLevel(-1);
    ScriptableObject globalScope = context.initStandardObjects();
    globalScope.defineProperty("navigator", Context.javaToJS(new Navigator(), globalScope), ScriptableObject.DONTENUM);
    Reader soyutils = new InputStreamReader(new FileInputStream(soyUtilsPath), UTF_8);
    try {
        String basename = soyUtilsPath.substring(soyUtilsPath.lastIndexOf('/') + 1);
        context.evaluateReader(globalScope, soyutils, basename, 1, null);
    } finally {
        soyutils.close();
    }
    globalScope.defineProperty("test_toEscape", ImmutableList.copyOf(toEscape), ScriptableObject.DONTENUM);
    globalScope.defineProperty("test_output", output, ScriptableObject.DONTENUM);
    context.evaluateString(globalScope, Joiner.on('\n').join("(function () {", "  if (typeof goog !== 'undefined') {", // Make sure we get the innocuous value from filters and not an exception.
    "    goog.asserts.ENABLE_ASSERTS = goog.DEBUG = false;", "  }", "  for (var i = 0, n = test_toEscape.size(); i < n; ++i) {", "    var raw = String(test_toEscape.get(i));", "    var escaped = String(soy.$$" + directiveName + "(raw));", "    test_output.add(raw);", "    test_output.add(escaped);", "  }", "})()"), // File name for JS traces.
    getClass() + ":" + testName.getMethodName(), 1, null);
    return output;
}
Also used : Context(org.mozilla.javascript.Context) ContextFactory(org.mozilla.javascript.ContextFactory) ScriptableObject(org.mozilla.javascript.ScriptableObject) InputStreamReader(java.io.InputStreamReader) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) FileInputStream(java.io.FileInputStream)

Example 10 with ContextFactory

use of org.mozilla.javascript.ContextFactory in project jaggery by wso2.

the class DatabaseHostObject method executeBatch.

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings("SQL_INJECTION_JDBC")
private static Object executeBatch(Context cx, final DatabaseHostObject db, NativeArray queries, NativeArray params, final Function callback) throws ScriptException, SQLException {
    if (params != null && (queries.getLength() != params.getLength())) {
        String msg = "Query array and values array should be in the same size. HostObject : " + hostObjectName + ", Method : query";
        log.warn(msg);
        throw new ScriptException(msg);
    }
    final Statement stmt = db.conn.createStatement();
    for (int index : (Integer[]) queries.getIds()) {
        Object obj = queries.get(index, db);
        if (!(obj instanceof String)) {
            String msg = "Invalid query type : " + obj.toString() + ". Query should be a string";
            log.warn(msg);
            throw new ScriptException(msg);
        }
        String query = (String) obj;
        if (params != null) {
            Object valObj = params.get(index, db);
            if (!(valObj instanceof NativeArray)) {
                String msg = "Invalid value type : " + obj.toString() + " for the query " + query;
                log.warn(msg);
                throw new ScriptException(msg);
            }
            query = replaceWildcards(db, query, (NativeArray) valObj);
        }
        stmt.addBatch(query);
    }
    if (callback != null) {
        final ContextFactory factory = cx.getFactory();
        final ExecutorService es = Executors.newSingleThreadExecutor();
        es.submit(new Callable() {

            public Object call() throws Exception {
                Context ctx = RhinoEngine.enterContext(factory);
                try {
                    int[] result = stmt.executeBatch();
                    callback.call(ctx, db, db, new Object[] { result });
                } catch (SQLException e) {
                    log.warn(e);
                } finally {
                    es.shutdown();
                    RhinoEngine.exitContext();
                }
                return null;
            }
        });
        return null;
    } else {
        return stmt.executeBatch();
    }
}
Also used : NativeArray(org.mozilla.javascript.NativeArray) ContextFactory(org.mozilla.javascript.ContextFactory) Context(org.mozilla.javascript.Context) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException) ExecutorService(java.util.concurrent.ExecutorService) StreamHostObject(org.jaggeryjs.hostobjects.stream.StreamHostObject) NativeObject(org.mozilla.javascript.NativeObject) ScriptableObject(org.mozilla.javascript.ScriptableObject) Callable(java.util.concurrent.Callable) DataSourceException(org.wso2.carbon.ndatasource.common.DataSourceException) ScriptException(org.jaggeryjs.scriptengine.exceptions.ScriptException)

Aggregations

ContextFactory (org.mozilla.javascript.ContextFactory)25 Context (org.mozilla.javascript.Context)22 ScriptableObject (org.mozilla.javascript.ScriptableObject)15 Function (com.google.common.base.Function)4 ContextAction (org.mozilla.javascript.ContextAction)4 IOException (java.io.IOException)3 Method (java.lang.reflect.Method)3 Callable (java.util.concurrent.Callable)3 ExecutorService (java.util.concurrent.ExecutorService)3 ScriptException (org.jaggeryjs.scriptengine.exceptions.ScriptException)3 Scriptable (org.mozilla.javascript.Scriptable)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 SlingContextFactory (org.apache.sling.scripting.javascript.helper.SlingContextFactory)2 StreamHostObject (org.jaggeryjs.hostobjects.stream.StreamHostObject)2 Function (org.mozilla.javascript.Function)2 NativeObject (org.mozilla.javascript.NativeObject)2 RhinoException (org.mozilla.javascript.RhinoException)2 ImmutableList (com.google.common.collect.ImmutableList)1 ObjectColumnSelector (io.druid.segment.ObjectColumnSelector)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1