Instantiates the right scripting language interpreter, falling back to Groovy for backward compatibility - Java javax.script

Java examples for javax.script:ScriptEngine

Description

Instantiates the right scripting language interpreter, falling back to Groovy for backward compatibility

Demo Code


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

public class Main{
    private static ScriptEngineManager scriptEngineManager;
    private static final Map<String, List<ScriptEngineFactory>> languageFactoryMap = new HashMap<String, List<ScriptEngineFactory>>();
    private static List<ScriptEngineFactory> engineFactories = null;
    /**/*from   w  w  w .  ja v  a2s .co  m*/
     * Instantiates the right scripting language interpreter, falling back to Groovy for backward compatibility
     *
     * @param engineName
     * @return the desired ScriptEngine, or null if none can be found
     */
    public static ScriptEngine createNewScriptEngine(String engineName) {

        ScriptEngine scriptEngine = getScriptEngineManager()
                .getEngineByName(engineName);
        if (scriptEngine == null) {
            // falls back to Groovy
            scriptEngine = getScriptEngineManager().getEngineByName(
                    "groovy");
        }
        return scriptEngine;
    }
    public static ScriptEngineManager getScriptEngineManager() {
        if (scriptEngineManager == null) {
            System.setProperty("org.jruby.embed.localvariable.behavior",
                    "persistent");// required for JRuby, transparent
            // for others
            scriptEngineManager = new ScriptEngineManager(
                    ScriptUtils.class.getClassLoader());
            populateEngineFactoryMap();
        }
        return scriptEngineManager;
    }
    private static void populateEngineFactoryMap() {
        engineFactories = getScriptEngineManager().getEngineFactories();
        if (engineFactories != null) {
            for (ScriptEngineFactory factory : engineFactories) {
                final String languageName = factory.getLanguageName();
                List<ScriptEngineFactory> languageFactories = languageFactoryMap
                        .get(languageName);
                if (languageFactories == null) {
                    languageFactories = new ArrayList<ScriptEngineFactory>();
                    languageFactoryMap.put(languageName, languageFactories);
                }
                languageFactories.add(factory);
            }
        }
    }
}

Related Tutorials