Example usage for javax.script ScriptEngineManager ScriptEngineManager

List of usage examples for javax.script ScriptEngineManager ScriptEngineManager

Introduction

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

Prototype

public ScriptEngineManager(ClassLoader loader) 

Source Link

Document

This constructor loads the implementations of ScriptEngineFactory visible to the given ClassLoader using the service provider mechanism.

If loader is null, the script engine factories that are bundled with the platform are loaded.

Usage

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;//from  w ww.  j  av a  2  s.c o  m
    // 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:ca.hedlund.jiss.preprocessor.LangPreprocessor.java

@Override
public boolean preprocessCommand(JissModel jissModel, String orig, StringBuffer cmd) {
    final String c = cmd.toString();
    if (c.equals("::langs")) {
        cmd.setLength(0);/*  ww  w .  j a v a  2  s.c  om*/
        printLangs(jissModel, cmd);
    } else if (c.equals("::lang")) {
        cmd.setLength(0);
        printCurrentLang(jissModel, cmd);
    } else if (c.startsWith("::lang")) {
        cmd.setLength(0);

        final String parts[] = c.split("\\p{Space}");
        if (parts.length == 2) {
            final String lang = parts[1];

            final ScriptEngineManager manager = new ScriptEngineManager(JissModel.class.getClassLoader());
            ScriptEngine newEngine = null;
            for (ScriptEngineFactory factory : manager.getEngineFactories()) {
                if (factory.getLanguageName().equals(lang) || factory.getExtensions().contains(lang)
                        || factory.getMimeTypes().contains(lang)) {
                    newEngine = factory.getScriptEngine();
                    break;
                }
            }

            if (newEngine != null) {
                jissModel.setScriptEngine(newEngine);
                printCurrentLang(jissModel, cmd);
            }
        }
    }
    return false;
}

From source file:me.tfeng.toolbox.dust.NashornEngine.java

@Override
public void initialize() throws Exception {
    scriptEngine = new ScriptEngineManager(null).getEngineByName("nashorn");
    InputStream dustJsStream = getAssetLocator().getResource(DUST_JS_NAME);
    String dustJs = readAndClose(dustJsStream);
    scriptEngine.eval(dustJs);//from w w w .ja v  a  2  s  .c om
}

From source file:com.adaptris.core.services.ScriptingServiceImp.java

@Override
protected void initService() throws CoreException {
    try {/*from  w ww .  j ava2 s .co m*/
        Args.notBlank(language, "language");
        String error = String.format("getEngineByName('%s')", getLanguage());
        fatController = new ScriptEngineManager(this.getClass().getClassLoader());
        engine = Args.notNull(fatController.getEngineByName(getLanguage()), error);
    } catch (Exception e) {
        throw ExceptionHelper.wrapCoreException(e);
    }
}

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 w  w  .  ja  va2s . com

    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;
}

From source file:ca.hedlund.jiss.preprocessor.LangPreprocessor.java

private void printLangs(JissModel model, StringBuffer cmd) {
    final ScriptEngineManager manager = new ScriptEngineManager(JissModel.class.getClassLoader());
    final List<String> cmds = new ArrayList<String>();

    for (ScriptEngineFactory factory : manager.getEngineFactories()) {
        final String engineInfo = factory.getLanguageName() + " " + factory.getLanguageVersion() + ":"
                + factory.getEngineName() + " " + factory.getEngineVersion();
        cmds.add(createPrintCmd(model, engineInfo));
    }// w w w  .  jav  a  2  s.c o  m
    final ScriptEngineFactory factory = model.getScriptEngine().getFactory();
    final String prog = StringEscapeUtils.unescapeJava(factory.getProgram(cmds.toArray(new String[0])));
    cmd.append(prog);
}

From source file:com.linkedin.drelephant.util.Utils.java

/**
 * Returns the configured thresholds after evaluating and verifying the levels.
 *
 * @param rawLimits A comma separated string of threshold limits
 * @param thresholdLevels The number of threshold levels
 * @return The evaluated threshold limits
 */// w  w w .  j  av  a 2s  .c om
public static double[] getParam(String rawLimits, int thresholdLevels) {
    double[] parsedLimits = null;

    if (rawLimits != null && !rawLimits.isEmpty()) {
        String[] thresholds = rawLimits.split(",");
        if (thresholds.length != thresholdLevels) {
            logger.error("Could not find " + thresholdLevels + " threshold levels in " + rawLimits);
            parsedLimits = null;
        } else {
            // Evaluate the limits
            parsedLimits = new double[thresholdLevels];
            ScriptEngineManager mgr = new ScriptEngineManager(null);
            ScriptEngine engine = mgr.getEngineByName("JavaScript");
            for (int i = 0; i < thresholdLevels; i++) {
                try {
                    parsedLimits[i] = Double.parseDouble(engine.eval(thresholds[i]).toString());
                } catch (ScriptException e) {
                    logger.error("Could not evaluate " + thresholds[i] + " in " + rawLimits);
                    parsedLimits = null;
                }
            }
        }
    }

    return parsedLimits;
}

From source file:org.freeplane.plugin.script.GenericScript.java

static ScriptEngineManager getScriptEngineManager() {
    synchronized (scriptEngineManagerMutex) {
        if (scriptEngineManager == null) {
            final ClassLoader classLoader = createClassLoader();
            scriptEngineManager = new ScriptEngineManager(classLoader);
        }/*from  w w  w. j av a2  s .  co  m*/
        return scriptEngineManager;
    }
}

From source file:org.netbeans.jcode.core.util.FileUtil.java

/**
 * Used core method for getting {@code ScriptEngine} from {@code
 * org.netbeans.modules.templates.ScriptingCreateFromTemplateHandler}.
 *///from  w  ww  . j a  v a  2s.c  o  m
private static ScriptEngine getScriptEngine() {
    if (manager == null) {
        synchronized (FileUtil.class) {
            if (manager == null) {
                ClassLoader loader = Lookup.getDefault().lookup(ClassLoader.class);
                try {
                    loader.loadClass(PrefixResolver.class.getName());
                } catch (ClassNotFoundException ex) {
                    Exceptions.printStackTrace(ex);
                }
                manager = new ScriptEngineManager(
                        loader != null ? loader : Thread.currentThread().getContextClassLoader());
            }
        }
    }
    return manager.getEngineByName((String) "freemarker");
}

From source file:org.apache.solr.update.processor.StatelessScriptUpdateProcessorFactory.java

/**
 * Initializes a list of script engines - an engine per script file.
 *
 * @param req The solr request./*from   w ww  . ja v a  2s . com*/
 * @param rsp The solr response
 * @return The list of initialized script engines.
 */
private List<EngineInfo> initEngines(SolrQueryRequest req, SolrQueryResponse rsp) throws SolrException {

    List<EngineInfo> scriptEngines = new ArrayList<>();

    ScriptEngineManager scriptEngineManager = new ScriptEngineManager(resourceLoader.getClassLoader());

    scriptEngineManager.put("logger", log);
    scriptEngineManager.put("req", req);
    scriptEngineManager.put("rsp", rsp);
    if (params != null) {
        scriptEngineManager.put("params", params);
    }

    for (ScriptFile scriptFile : scriptFiles) {
        ScriptEngine engine = null;
        if (null != engineName) {
            engine = scriptEngineManager.getEngineByName(engineName);
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, false);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "No ScriptEngine found by name: "
                        + engineName + (null != details ? " -- supported names: " + details : ""));
            }
        } else {
            engine = scriptEngineManager.getEngineByExtension(scriptFile.getExtension());
            if (engine == null) {
                String details = getSupportedEngines(scriptEngineManager, true);
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                        "No ScriptEngine found by file extension: " + scriptFile.getFileName()
                                + (null != details ? " -- supported extensions: " + details : ""));

            }
        }

        if (!(engine instanceof Invocable)) {
            String msg = "Engine "
                    + ((null != engineName) ? engineName : ("for script " + scriptFile.getFileName()))
                    + " does not support function invocation (via Invocable): " + engine.getClass().toString()
                    + " (" + engine.getFactory().getEngineName() + ")";
            log.error(msg);
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, msg);
        }

        if (scriptEngineCustomizer != null) {
            scriptEngineCustomizer.customize(engine);
        }

        scriptEngines.add(new EngineInfo((Invocable) engine, scriptFile));
        try {
            Reader scriptSrc = scriptFile.openReader(resourceLoader);

            try {
                engine.eval(scriptSrc);
            } catch (ScriptException e) {
                throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                        "Unable to evaluate script: " + scriptFile.getFileName(), e);
            } finally {
                IOUtils.closeQuietly(scriptSrc);
            }
        } catch (IOException ioe) {
            throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,
                    "Unable to evaluate script: " + scriptFile.getFileName(), ioe);
        }
    }
    return scriptEngines;
}