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

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

Introduction

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

Prototype

public ScriptEngine getScriptEngine(final String... args) 

Source Link

Document

Create a new Script engine initialized with the given arguments.

Usage

From source file:com.mckoi.webplatform.nashorn.NashornInstanceGlobalFactory.java

License:Open Source License

/**
 * Initializes the NashornInternal object.
 * //from   w w w  .j ava 2 s .co m
 * @param cl the ClassLoader to use, or null for default.
 */
public void init(final ClassLoader cl) {

    // Incase we call 'init' more than once,
    if (PRIV_nashorn_ctx != null) {
        return;
    }

    // Hacky way to return properties from the Nashorn engine,
    final Object[] inner_data = new Object[5];

    // Run initialization in a privileged security context,
    AccessController.doPrivileged(new PrivilegedAction<Object>() {
        @Override
        public Object run() {

            // We make a VM static NashornScriptEngine that we use to compile
            // scripts and fork new JavaScript instances.

            NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
            NashornScriptEngine engine;
            if (cl == null) {
                engine = (NashornScriptEngine) factory.getScriptEngine(engine_args);
            } else {
                engine = (NashornScriptEngine) factory.getScriptEngine(engine_args, cl);
            }

            // We add some functions to the global object,
            ScriptObjectMirror global_object = (ScriptObjectMirror) engine
                    .getBindings(ScriptContext.ENGINE_SCOPE);

            // A function that performs startup. We execute this to obtain
            // information about the engine such as the Global and Context object.
            // It seems the only way to get at this information is from code
            // running within the engine.
            global_object.put("engineStartup", new EngineStartupFunction(inner_data));

            // Invoke the 'engineStartup' function to get at the priviledged
            // information.
            try {
                engine.invokeFunction("engineStartup", new Object[0]);
            } catch (ScriptException | NoSuchMethodException ex) {
                // Oops,
                throw new RuntimeException(ex);
            } finally {
                // Don't leave this function around, just incase,
                global_object.delete("engineStartup");
            }

            return null;
        }
    });

    PRIV_nashorn_ctx = (Context) inner_data[0];
    //    base_nashorn_global = (Global) inner_data[1];

}

From source file:com.wx3.galacdecks.game.GameRules.java

License:Open Source License

private static ScriptEngine getScriptEngine() {
    if (scriptEngine == null) {
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        scriptEngine = factory.getScriptEngine(new RestrictiveFilter());
        if (scriptEngine == null) {
            throw new RuntimeException("Unable to get script engine");
        }/*from w  ww.j  av a2s .  co m*/
    }
    return scriptEngine;
}

From source file:de.hasait.genesis.scriptgen.ScriptGenProcessor.java

License:Apache License

private ScriptEngine determineScriptEngine(final String pScriptFileExtension, final ClassLoader pClassLoader) {
    final ScriptEngine engine;
    final NashornScriptEngineFactory nashornScriptEngineFactory = new NashornScriptEngineFactory();
    if (nashornScriptEngineFactory.getExtensions().contains(pScriptFileExtension)) {
        engine = nashornScriptEngineFactory.getScriptEngine(pClassLoader);
    } else {/*from   w  w  w . j  a  v a  2  s .  c om*/
        final ScriptEngineManager factory = new ScriptEngineManager();
        engine = factory.getEngineByExtension(pScriptFileExtension);
    }
    return engine;
}

From source file:io.devcon5.misc.scripting.js.ClassFilterSandboxScripting.java

License:Apache License

public static void main(String... args) throws IOException, ScriptException {

    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine(s -> {
        if (!s.startsWith("java.util.ArrayList")) {
            return true;
        }//  ww  w .  j  a  v  a  2s  . c om
        return false;
    });

    //this will work, as it will create the ArrayList using a factory
    try (InputStreamReader reader = getScriptReader("/java.js")) {
        engine.eval(reader);
    }
    //this will not work, as it will create the ArrayList directly
    try (InputStreamReader reader = getScriptReader("/java_fail.js")) {
        engine.eval(reader);
    }
}

From source file:io.devcon5.misc.scripting.js.HelloWorldScripting.java

License:Apache License

public static void main(String... args) throws IOException, ScriptException {

    final NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    final ScriptEngine engine = factory.getScriptEngine(new String[] { "-scripting" });

    try (InputStreamReader reader = getScriptReader("/helloworld-scripting.js")) {
        engine.put("name", "Bob");
        engine.eval(reader);//from ww w  .ja v a2 s .c  o  m
    }
}

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();//w  w w.  j av  a 2 s  . 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.vpc.app.vainruling.core.service.util.JavascriptEvaluator.java

License:Open Source License

private ScriptEngine createScriptEngine() {
    jdk.nashorn.api.scripting.NashornScriptEngineFactory f = new jdk.nashorn.api.scripting.NashornScriptEngineFactory();
    return f.getScriptEngine(new jdk.nashorn.api.scripting.ClassFilter() {
        @Override//from  ww  w  .  ja va 2s  . co  m
        public boolean exposeToScripts(String s) {
            if (blacklistClassNames.contains(s)) {
                return false;
            }
            for (Pattern pattern : blacklistClassNamePatterns) {
                if (pattern.matcher(s).matches()) {
                    return false;
                }
            }
            return true;
        }
    });
}

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  ww.  j a v  a 2s.com*/
    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 w w  w  .  j  a  va2 s  . 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.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 ww. jav a  2  s.co m*/
        sandbox.allowLoadFunctions(true);
        sandbox.setMaxPreparedStatements(30);
    } else {
        NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
        engine = factory.getScriptEngine(new String[] { "--no-java" });
    }
}