Example usage for jdk.nashorn.api.scripting NashornScriptEngineFactory NashornScriptEngineFactory

List of usage examples for jdk.nashorn.api.scripting NashornScriptEngineFactory NashornScriptEngineFactory

Introduction

In this page you can find the example usage for jdk.nashorn.api.scripting NashornScriptEngineFactory NashornScriptEngineFactory.

Prototype

NashornScriptEngineFactory

Source Link

Usage

From source file:io.warp10.script.ext.js.JS.java

License:Apache License

@Override
protected ScriptEngine getEngine() {
    return new NashornScriptEngineFactory().getScriptEngine(new String[] { "--no-java" });
}

From source file:me.finalchild.nashornbukkit.script.Host.java

License:MIT License

public Host() {
    engine = (NashornScriptEngine) new NashornScriptEngineFactory()
            .getScriptEngine(/*new String[] {"-scripting"}, */NashornBukkit.class.getClassLoader());
    importer = new BukkitImporter();
}

From source file:net.codestory.http.compilers.NashornCompiler.java

License:Apache License

private NashornCompiler(String script) {
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();

    String engineVersion = factory.getEngineVersion();
    String cacheLocation = Paths
            .get(System.getProperty("user.home"), ".code-story", "nashorn_code_cache_" + engineVersion).toFile()
            .getAbsolutePath();/*from  w w  w .  j av  a 2s .c  o  m*/
    System.setProperty("nashorn.persistent.code.cache", cacheLocation);

    // --optimistic-types=true in JDK 8u40 slows down everything
    // Don't use varargs because it was introduced only in 8u40
    ScriptEngine nashorn = factory
            .getScriptEngine(new String[] { "--persistent-code-cache=true", "--lazy-compilation=false" });

    try {
        compiledScript = ((Compilable) nashorn).compile(script);
        bindings = nashorn.getBindings(ENGINE_SCOPE);
    } catch (ScriptException e) {
        throw new IllegalStateException("Unable to compile javascript", e);
    }
}

From source file:net.orzo.scripting.JsEngineAdapter.java

License:Apache License

/**
 *//*from  www . j  a  v a2 s  .  com*/
public JsEngineAdapter(EnvParams envParams, SharedServices sharedServices,
        IntermediateResults intermediateResults) {
    this.envParams = envParams;
    this.sharedServices = sharedServices;
    this.intermediateResults = intermediateResults;
    this.modules = new HashMap<>();
    this.engine = new NashornScriptEngineFactory() // TODO configurable timezone
            .getScriptEngine(new String[] { "-timezone=" + getCurrentTimezone().getID() });
}

From source file:org.eclipse.californium.actinium.plugnplay.JavaScriptApp.java

License:Open Source License

/**
 * Executes the given JavaScript code./*  ww  w .  j  av  a  2s  . c  om*/
 * @param code the JavaScript code
 */
public void execute(String code) {

    if (code == null || code.isEmpty())
        return;

    dependencies.clear();
    moduleCache.clear();
    classloader = new DynamicClassloader(Thread.currentThread().getContextClassLoader());
    engine = (NashornScriptEngine) new NashornScriptEngineFactory().getScriptEngine(classloader);
    try {
        // initialize JavaScrip environmetn for the app: scope (variables)

        context = new AppContext();
        context.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);
        Bindings engineScope = context.getBindings(ScriptContext.ENGINE_SCOPE);
        //          scope.setPrototype(s);
        //
        //          // add two global functions dump and addSubResource
        //            String[] names = { "dump", "addSubResource"};
        //            scope.defineFunctionProperties(names, JavaScriptStaticAccess.class,
        //                                           ScriptableObject.DONTENUM);
        //
        //            try {
        //               // Add AJAX' XMLHttpRequest to JavaScript
        //               ScriptableObject.defineClass(scope,   XMLHttpRequest.class);
        //               ScriptableObject.defineClass(scope,   JavaScriptCoapExchange.class);
        //         } catch (IllegalAccessException e) {
        //            e.printStackTrace();
        //         } catch (InstantiationException e) {
        //            e.printStackTrace();
        //         } catch (InvocationTargetException e) {
        //            e.printStackTrace();
        //         }

        // Add object "app" to JavaScript
        jsaccess = new JavaScriptAccess();
        engineScope.put("app", jsaccess);
        engineScope.put("require", (IRequire) moduleName -> jsaccess.require(moduleName));
        engineScope.put("_extend", (IExtend) (a, b) -> jsaccess.extend(a, b));
        engineScope.put("_super", (ISuperCall) (a, b, c) -> jsaccess.superCall(a, b, c));

        String bootstrap = Utils.readFile(JavaScriptApp.class.getResourceAsStream("/bootstrap.js"));
        code = bootstrap.replaceAll("//.*?\n", "\n").replace('\n', ' ') + "(function () {" + code
                + "}).apply({});";

        // Execute code
        engine.eval(code, context);

    } catch (RuntimeException | ScriptException e) {
        Throwable cause = e.getCause();
        if (cause != null && cause instanceof InterruptedException) {
            // this was a controlled shutdown, e.g. with app.stop()
            System.out.println("JavaScript app " + getName() + " has been interrupted");
        } else {
            e.printStackTrace();
            if (e instanceof ScriptException) {
                System.err.println("JavaScript error in [" + ((ScriptException) e).getFileName() + "#"
                        + ((ScriptException) e).getLineNumber() + "]: " + e.getMessage());
            }
        }
    }
}

From source file:org.fseek.simon.gameone.blog.video.NashornScriptParser.java

License:Open Source License

protected ScriptEngine getScriptEngine() {
    if (NashornScriptParser.scriptEngine == null) {
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        // ensure only the SWFObject class can be used in the passed
        // JavaScript to prevent malicious js code.
        NashornScriptParser.scriptEngine = factory
                .getScriptEngine((String string) -> string.equals(SWFObject.class.getName()));
    }/*w  w  w  . ja v a2  s .c o  m*/
    return scriptEngine;
}

From source file:org.labkey.nashorn.NashornController.java

License:Apache License

private Pair<ScriptEngine, ScriptContext> getNashorn(boolean useSession) throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine;//from   ww  w. ja  v  a  2s  . c o  m
    ScriptContext context;

    Callable<ScriptEngine> createContext = new Callable<ScriptEngine>() {
        @Override
        @NotNull
        public ScriptEngine call() throws Exception {
            NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
            ScriptEngine engine = factory.getScriptEngine(new String[] { "--global-per-engine" });
            return engine;
        }
    };

    if (useSession) {
        HttpServletRequest req = getViewContext().getRequest();
        engine = SessionHelper.getAttribute(req, this.getClass().getName() + "#scriptEngine", createContext);
    } else {
        engine = createContext.call();
    }

    Bindings engineScope = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    engineScope.put("LABKEY", new org.labkey.nashorn.env.LABKEY(getViewContext()));

    Bindings globalScope = engine.getBindings(ScriptContext.GLOBAL_SCOPE);
    // null==engine.getBindings(ScriptContext.GLOBAL_SCOPE), because of --global-per-engine
    // some docs mention enginScope.get("nashorn.global"), but that is also null
    if (null == globalScope)
        globalScope = (Bindings) engineScope.get("nashorn.global");
    if (null == globalScope)
        globalScope = engineScope;
    globalScope.put("console", new Console());

    return new Pair<>(engine, engine.getContext());
}

From source file:org.nuxeo.automation.scripting.internals.ScriptingCache.java

License:Apache License

public ScriptingCache(boolean enabled) {
    this.nashornScriptEngineFactory = new NashornScriptEngineFactory();
    this.enabled = enabled;
}

From source file:org.nuxeo.automation.scripting.internals.ScriptingCacheClassFilter.java

License:Apache License

public ScriptingCacheClassFilter(boolean cacheEnable) {
    this.nashornScriptEngineFactory = new NashornScriptEngineFactory();
    this.cacheEnable = cacheEnable;
}

From source file:org.thingsboard.server.service.script.AbstractNashornJsInvokeService.java

License:Apache License

@PostConstruct
public void init() {
    if (useJsSandbox()) {
        sandbox = NashornSandboxes.create();
        monitorExecutorService = Executors.newFixedThreadPool(getMonitorThreadPoolSize());
        sandbox.setExecutor(monitorExecutorService);
        sandbox.setMaxCPUTime(getMaxCpuTime());
        sandbox.allowNoBraces(false);/*from  w w w . ja  v  a  2s  .c om*/
        sandbox.allowLoadFunctions(true);
        sandbox.setMaxPreparedStatements(30);
    } else {
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        engine = factory.getScriptEngine(new String[] { "--no-java" });
    }
}