Example usage for javax.script ScriptEngineManager getEngineByExtension

List of usage examples for javax.script ScriptEngineManager getEngineByExtension

Introduction

In this page you can find the example usage for javax.script ScriptEngineManager getEngineByExtension.

Prototype

public ScriptEngine getEngineByExtension(String extension) 

Source Link

Document

Look up and create a ScriptEngine for a given extension.

Usage

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

private void execAppBeforeLoadChecks(final String aAppName, String aAppPath) throws Exception {
    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");
    if (!lManifestFile.exists() || !lManifestFile.canRead()) {
        String lMsg = "Unable to load '" + aAppName + "' application. Manifest file no found!";
        mLog.error(lMsg);//from w ww .j av a 2 s .  c  om
        throw new FileNotFoundException(lMsg);
    }
    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // checking jWebSocket version 
    Manifest.checkJwsVersion(lManifestJSON.getString(Manifest.JWEBSOCKET_VERSION, "1.0.0"));

    // checking jWebSocket plug-ins dependencies
    Manifest.checkJwsDependencies(
            lManifestJSON.getList(Manifest.JWEBSOCKET_PLUGINS_DEPENDENCIES, new ArrayList<String>()));

    // checking sandbox permissions dependency
    Manifest.checkPermissions(lManifestJSON.getList(Manifest.PERMISSIONS, new ArrayList()),
            mSettings.getAppPermissions(aAppName, aAppPath), aAppPath);

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);
    if (!lBootstrap.exists() || !lBootstrap.canRead()) {
        String lMsg = "Unable to load '" + aAppName + "' application. Bootstrap file not found!";
        mLog.error(lMsg);
        throw new FileNotFoundException(lMsg);
    }

    LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
    ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

    final ScriptEngine lScriptApp;
    final BaseScriptApp lApp;
    if ("js".equals(lExt)) {
        // making "nashorn" the default engine for JavaScript
        if (null != lManager.getEngineByName("nashorn")) {
            lScriptApp = lManager.getEngineByName("nashorn");
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }
    } else {
        lScriptApp = lManager.getEngineByExtension(lExt);
    }

    // creating the high level script app instance
    if ("js".equals(lExt)) {
        lApp = new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader);
    } else {
        String lMsg = "The extension '" + lExt + "' is not currently supported!";
        mLog.error(lMsg);
        throw new Exception(lMsg);
    }

    // loading application into security sandbox
    Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
        @Override
        public Object run() {
            try {
                // evaluating app content
                lScriptApp.eval(FileUtils.readFileToString(lBootstrap));
                return null;
            } catch (Exception lEx) {
                String lAction = (mApps.containsKey(aAppName)) ? "reloaded" : "loaded";
                String lMsg = "Script applicaton '" + aAppName + "' not " + lAction
                        + " because it failed the 'before-load' checks: " + lEx.getMessage();
                mLog.info(lMsg);
                throw new RuntimeException(lMsg);
            }
        }
    });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application passed the 'before-load' checks successfully!");
    }
}

From source file:org.jwebsocket.plugins.scripting.ScriptingPlugIn.java

/**
 * Loads an script application./*from  w w w.  j  a  va2  s  .c  o m*/
 *
 * @param aAppName The application name
 * @param aAppPath The application home path
 * @param aHotLoad
 * @return
 * @throws Exception
 */
private void loadApp(final String aAppName, String aAppPath, boolean aHotLoad) throws Exception {
    // notifying before app reload event here
    BaseScriptApp lScript = mApps.get(aAppName);
    if (null != lScript) {
        lScript.notifyEvent(BaseScriptApp.EVENT_BEFORE_APP_RELOAD, new Object[] { aHotLoad });
        if (!aHotLoad) {
            destroyAppBeans(lScript);
        }
    }

    // parsing app manifest
    File lManifestFile = new File(aAppPath + "/manifest.json");

    // parsing app manifest file
    ObjectMapper lMapper = new ObjectMapper();
    Map<String, Object> lTree = lMapper.readValue(lManifestFile, Map.class);
    Token lManifestJSON = TokenFactory.createToken();
    lManifestJSON.setMap(lTree);

    // getting script language extension
    String lExt = lManifestJSON.getString(Manifest.LANGUAGE_EXT, "js");

    // validating bootstrap file
    final File lBootstrap = new File(aAppPath + "/App." + lExt);

    // support hot app load
    if (aHotLoad && mApps.containsKey(aAppName)) {
        try {
            // loading app
            mApps.get(aAppName).eval(lBootstrap.getPath());
        } catch (ScriptException lEx) {
            mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
            mApps.remove(aAppName);
            throw new ScriptException(lEx.getMessage());
        }
    } else {
        LocalLoader lClassLoader = new LocalLoader((URLClassLoader) ClassLoader.getSystemClassLoader());
        ScriptEngineManager lManager = new ScriptEngineManager(lClassLoader);

        final ScriptEngine lScriptApp;
        if ("js".equals(lExt)) {
            // making "nashorn" the default engine for JavaScript
            if (null != lManager.getEngineByName("nashorn")) {
                lScriptApp = lManager.getEngineByName("nashorn");
            } else {
                lScriptApp = lManager.getEngineByExtension(lExt);
            }
        } else {
            lScriptApp = lManager.getEngineByExtension(lExt);
        }

        // crating the high level script app instance
        if ("js".equals(lExt)) {
            mApps.put(aAppName, new JavaScriptApp(this, aAppName, aAppPath, lScriptApp, lClassLoader));
        } else {
            String lMsg = "The extension '" + lExt + "' is not currently supported!";
            mLog.error(lMsg);
            throw new Exception(lMsg);
        }

        final BaseScriptApp lApp = mApps.get(aAppName);
        // loading application into security sandbox
        Tools.doPrivileged(mSettings.getAppPermissions(aAppName, aAppPath), new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                try {
                    // loading app
                    lApp.eval(lBootstrap.getPath());
                    return null;
                } catch (Exception lEx) {
                    mLog.error("Script applicaton '" + aAppName + "' failed to start: " + lEx.getMessage());
                    mApps.remove(aAppName);
                    throw new RuntimeException(lEx);
                }
            }
        });
    }

    // notifying app loaded event
    mApps.get(aAppName).notifyEvent(BaseScriptApp.EVENT_APP_LOADED, new Object[] { aHotLoad });

    if (mLog.isDebugEnabled()) {
        mLog.debug(aAppName + "(" + lExt + ") application loaded successfully!");
    }
}

From source file:org.openhab.core.jsr223.internal.engine.scriptmanager.Script.java

public void loadScript(File file) throws FileNotFoundException, ScriptException, NoSuchMethodException {
    logger.info("Loading Script " + file.getName());
    String extension = getFileExtension(file);
    ScriptEngineManager factory = new ScriptEngineManager();
    engine = factory.getEngineByExtension(extension);
    if (engine != null) {
        logger.info("EngineName: " + engine.getFactory().getEngineName());
        initializeSciptGlobals();//from   w  ww .  j a  v a 2s . c  o m
        engine.eval(new FileReader(file));
        Invocable inv = (Invocable) engine;
        RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules");
        rules.addAll(ruleSet.getRules());
    }
}

From source file:org.opennms.opennms.pris.plugins.script.util.ScriptManager.java

public static Object execute(final InstanceConfiguration config, final Map<String, Object> bindings)
        throws IOException, ScriptException {

    Requisition requisition = null;/*w w  w .j  av a2s  .  com*/
    // Get the path to the script
    final List<Path> scripts = config.getPaths("file");

    // Get the script engine by language defined in config or by extension if it
    // is not defined in the config
    final ScriptEngineManager SCRIPT_ENGINE_MANAGER = new ScriptEngineManager(
            ScriptManager.class.getClassLoader());

    for (Path script : scripts) {

        final ScriptEngine scriptEngine = config.containsKey("lang")
                ? SCRIPT_ENGINE_MANAGER.getEngineByName(config.getString("lang"))
                : SCRIPT_ENGINE_MANAGER.getEngineByExtension(FilenameUtils.getExtension(script.toString()));

        if (scriptEngine == null) {
            throw new RuntimeException("Script engine implementation not found");
        }

        // Create some bindings for values available in the script
        final Bindings scriptBindings = scriptEngine.createBindings();
        scriptBindings.put("script", script);
        scriptBindings.put("logger", LoggerFactory.getLogger(script.toString()));
        scriptBindings.put("config", config);
        scriptBindings.put("instance", config.getInstanceIdentifier());
        scriptBindings.put("interfaceUtils", new InterfaceUtils(config));
        scriptBindings.putAll(bindings);

        // Overwrite initial requisition with the requisition from the previous script, if there was any.
        if (requisition != null) {
            scriptBindings.put("requisition", requisition);
        }

        // Evaluate the script and return the requisition created in the script
        try (final Reader scriptReader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) {
            LOGGER.debug("Start Script {}", script);
            requisition = (Requisition) scriptEngine.eval(scriptReader, scriptBindings);
            LOGGER.debug("Done  Script {}", script);
        }
    }
    return requisition;
}

From source file:org.springframework.data.hadoop.scripting.Jsr223ScriptEvaluator.java

protected ScriptEngine discoverEngine(ScriptSource script, Map<String, Object> arguments) {
    ScriptEngineManager engineManager = new ScriptEngineManager(classLoader);
    ScriptEngine engine = null;//w ww.  j a va 2 s  . c om

    if (StringUtils.hasText(language)) {
        engine = engineManager.getEngineByName(language);
    } else {
        // make use the extension (enhanced ScriptSource interface)
        Assert.hasText(extension, "no language or extension specified");
        engine = engineManager.getEngineByExtension(extension);
    }

    Assert.notNull(engine, "No suitable engine found for "
            + (StringUtils.hasText(language) ? "language " + language : "extension " + extension));

    if (log.isDebugEnabled()) {
        ScriptEngineFactory factory = engine.getFactory();
        log.debug(String.format("Using ScriptEngine %s (%s), language %s (%s)", factory.getEngineName(),
                factory.getEngineVersion(), factory.getLanguageName(), factory.getLanguageVersion()));
    }

    return engine;
}