Example usage for javax.script ScriptEngineFactory getScriptEngine

List of usage examples for javax.script ScriptEngineFactory getScriptEngine

Introduction

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

Prototype

public ScriptEngine getScriptEngine();

Source Link

Document

Returns an instance of the ScriptEngine associated with this ScriptEngineFactory.

Usage

From source file:sample.fa.ScriptRunnerApplication.java

void createGUI() {
    Box buttonBox = Box.createHorizontalBox();

    JButton loadButton = new JButton("Load");
    loadButton.addActionListener(this::loadScript);
    buttonBox.add(loadButton);/* w  w w . j  ava2s  .  c o m*/

    JButton saveButton = new JButton("Save");
    saveButton.addActionListener(this::saveScript);
    buttonBox.add(saveButton);

    JButton executeButton = new JButton("Execute");
    executeButton.addActionListener(this::executeScript);
    buttonBox.add(executeButton);

    languagesModel = new DefaultComboBoxModel();

    ScriptEngineManager sem = new ScriptEngineManager();
    for (ScriptEngineFactory sef : sem.getEngineFactories()) {
        languagesModel.addElement(sef.getScriptEngine());
    }

    JComboBox<ScriptEngine> languagesCombo = new JComboBox<>(languagesModel);
    JLabel languageLabel = new JLabel();
    languagesCombo.setRenderer((JList<? extends ScriptEngine> list, ScriptEngine se, int index,
            boolean isSelected, boolean cellHasFocus) -> {
        ScriptEngineFactory sef = se.getFactory();
        languageLabel.setText(sef.getEngineName() + " - " + sef.getLanguageName() + " (*."
                + String.join(", *.", sef.getExtensions()) + ")");
        return languageLabel;
    });
    buttonBox.add(Box.createHorizontalGlue());
    buttonBox.add(languagesCombo);

    scriptContents = new JTextArea();
    scriptContents.setRows(8);
    scriptContents.setColumns(40);

    scriptResults = new JTextArea();
    scriptResults.setEditable(false);
    scriptResults.setRows(8);
    scriptResults.setColumns(40);

    JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scriptContents, scriptResults);

    JFrame frame = new JFrame("Script Runner");
    frame.add(buttonBox, BorderLayout.NORTH);
    frame.add(jsp, BorderLayout.CENTER);

    frame.pack();
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    frame.setVisible(true);
}

From source file:com.lucidtechnics.blackboard.util.Jsr223ScriptingUtil.java

public Jsr223ScriptingUtil(String _extension) {
    String factoryName = null;/*from   w w w  .j a v a 2s.c  om*/

    try {
        factoryName = extensionToEngineMap.get(_extension);
        if (factoryName == null) {
            throw new RuntimeException("Scripting not supported for files ending in: " + _extension);
        }

        ScriptEngineFactory factory = (ScriptEngineFactory) Class.forName(factoryName).newInstance();
        ScriptEngine scriptEngine = factory.getScriptEngine();

        setScriptEngine(scriptEngine);
        setBindingsMap(new HashMap<String, Object>());
    } catch (ClassNotFoundException t) {
        throw new RuntimeException("Please make sure the appropriate jar files for factory: " + factoryName
                + " are place in the lib/engines directory in order to run scripts of extension: "
                + _extension);
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

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);/*from   w ww.  j a  va 2 s  . c o  m*/
        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:it.geosolutions.geobatch.action.scripting.ScriptingTest.java

@Test
public void testLoop() throws ScriptException {

    String engineName = "groovy";

    ScriptEngine foundEngine = null;
    // create a script engine manager
    ScriptEngineManager mgr = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = mgr.getEngineFactories();
    System.out.println("FOUND " + factories.size() + " factories");
    for (ScriptEngineFactory sef : factories) {
        System.out.println("FACTORY: " + "'" + sef.getEngineName() + "' " + "'" + sef.getLanguageName() + "' "
                + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' ");
        if (sef.getEngineName().contains(engineName)) {
            foundEngine = sef.getScriptEngine();
        }// ww w. jav  a2 s .c  om

    }

    assertNotNull("Can't find engine '" + engineName + "'", foundEngine);
    foundEngine.eval("print('Hello, World')");
}

From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java

private AionScriptEngineManager() {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
    if (USE_COMPILED_CACHE) {
        _cache = loadCompiledScriptCache();
    } else {//from  w ww  .ja  va  2s .c  o  m
        _cache = null;
    }
    log.info("Initializing Script Engine Manager");

    for (ScriptEngineFactory factory : factories) {
        try {
            log.info("Script Engine: " + factory.getEngineName() + " " + factory.getEngineVersion()
                    + " - Language: " + factory.getLanguageName() + " " + factory.getLanguageVersion());

            ScriptEngine engine = factory.getScriptEngine();

            for (String name : factory.getNames()) {
                if (_nameEngines.containsKey(name))
                    throw new IllegalStateException("Multiple script engines for the same name!");

                _nameEngines.put(name, engine);
            }

            for (String ext : factory.getExtensions()) {
                if (_extEngines.containsKey(ext))
                    throw new IllegalStateException("Multiple script engines for the same extension!");

                _extEngines.put(ext, engine);
            }
        } catch (Exception e) {
            log.warn("Failed initializing factory.", e);
        }
    }
}

From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java

private L2ScriptEngineManager() {
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
    if (USE_COMPILED_CACHE) {
        _cache = loadCompiledScriptCache();
    } else {/*from  w ww .  j  a va 2s. co  m*/
        _cache = null;
    }
    _log.info("Initializing Script Engine Manager");

    for (ScriptEngineFactory factory : factories) {
        try {
            _log.info("Script Engine: " + factory.getEngineName() + " " + factory.getEngineVersion()
                    + " - Language: " + factory.getLanguageName() + " " + factory.getLanguageVersion());

            ScriptEngine engine = factory.getScriptEngine();

            for (String name : factory.getNames()) {
                if (_nameEngines.containsKey(name))
                    throw new IllegalStateException("Multiple script engines for the same name!");

                _nameEngines.put(name, engine);
            }

            for (String ext : factory.getExtensions()) {
                if (_extEngines.containsKey(ext))
                    throw new IllegalStateException("Multiple script engines for the same extension!");

                _extEngines.put(ext, engine);
            }
        } catch (Exception e) {
            _log.warn("Failed initializing factory.", e);
        }
    }

    preConfigure();
}

From source file:org.apache.felix.webconsole.plugins.scriptconsole.internal.ScriptEngineManager.java

public ScriptEngine getEngineByExtension(String extension) {
    ScriptEngineFactory factory = state.extensionAssociations.get(extension);
    if (factory == null)
        return null;

    ScriptEngine engine = factory.getScriptEngine();

    //We do not support global scope for now
    //engine.setBindings(globalScope, ScriptContext.GLOBAL_SCOPE);

    return engine;
}

From source file:org.jahia.services.render.scripting.bundle.BundleScriptEngineManager.java

private ScriptEngine getEngine(String key, Map<String, ScriptEngineFactory> factoriesForKeyType,
        KeyType keyType) {/* w  w  w  .ja va2s  .c o  m*/
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

    Map<String, ScriptEngine> stringScriptEngineMap = engineCache.get(contextClassLoader);

    if (stringScriptEngineMap == null) {
        stringScriptEngineMap = new ConcurrentHashMap<>();
        engineCache.put(contextClassLoader, stringScriptEngineMap);
    }

    ScriptEngine scriptEngine = stringScriptEngineMap.get(key);
    if (scriptEngine == null) {

        final ScriptEngineFactory scriptEngineFactory = factoriesForKeyType.get(key);
        if (scriptEngineFactory != null) {
            // perform configuration of the factory if needed
            if (scriptEngineFactory instanceof BundleScriptEngineFactory) {
                BundleScriptEngineFactory factory = (BundleScriptEngineFactory) scriptEngineFactory;
                factory.configurePreScriptEngineCreation();
            }

            scriptEngine = scriptEngineFactory.getScriptEngine();
            scriptEngine.setBindings(getBindings(), ScriptContext.GLOBAL_SCOPE);
        } else {
            switch (keyType) {
            case EXTENSION:
                scriptEngine = super.getEngineByExtension(key);
                break;
            case MIME_TYPE:
                scriptEngine = super.getEngineByMimeType(key);
                break;
            case NAME:
                scriptEngine = super.getEngineByName(key);
                break;
            default:
                scriptEngine = null;
            }
        }

        if (scriptEngine != null) {
            stringScriptEngineMap.put(key, scriptEngine);
        }
    }
    return scriptEngine;
}

From source file:org.openadaptor.auxil.processor.script.ScriptProcessor.java

/**
 * Locates a ScriptEngine for the current language.
 * <br>//ww  w  .j  a v  a  2 s  .  c  om
 * Complicated slightly by differences between implementations 
 * in java 1.5 and earlier versus 1.6 and later.
 * See Issue [SC52]
 * <br>
 * 
 * @return ScriptEngine instance for the current language
 */
protected ScriptEngine createScriptEngine() {
    ScriptEngine engine = null;
    ScriptEngineManager mgr = new ScriptEngineManager();
    List factories = getEngineFactories(mgr);
    Iterator it = factories.iterator();
    while (it.hasNext() && (engine == null)) { //More factories to try, and no match yet.
        ScriptEngineFactory factory = (ScriptEngineFactory) it.next();
        if (log.isDebugEnabled()) { //Debug code to identify origins of factories etc.
            Object origin = ClasspathUtils.getClassOrigin(mgr);
            if (origin == null) {
                origin = "<JRE>";
            }
            log.debug("ScriptEngineManager loaded from: " + origin);
            origin = ClasspathUtils.getClassOrigin(factory);
            if (origin == null) {
                origin = "<JRE>";
            }
            String name = factory.getEngineName();
            String version = factory.getEngineVersion();
            log.debug("ScriptEngineFactory " + name + " (" + version + "): " + origin);
        }
        try {
            List aliases = getFactoryNames(factory);
            if (aliases != null) { //If null couldn't get any for factory.
                Iterator aliasIterator = aliases.iterator();
                while (aliasIterator.hasNext()) {
                    if (language.equals(aliasIterator.next())) {
                        log.debug("Found matching script engine for " + language);
                        engine = factory.getScriptEngine();
                        break;
                    }
                }
            } else {
                log.debug("Failed to get names for factory " + factory.getEngineName());
            }
        } catch (AbstractMethodError ame) {
            log.debug("Failed to interrogate Factory - " + factory.getEngineName());
        }
    }
    if (engine == null) {
        log.error("Failed to find engine for language " + language);
        throw new RuntimeException("Failed to find engine for language " + language);
    }
    return engine;
}