Java Code Examples for javax.script.ScriptEngineFactory#getScriptEngine()

The following examples show how to use javax.script.ScriptEngineFactory#getScriptEngine() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ScriptingTutorial.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public ScriptEngine listAll() {
    // BEGIN: org.netbeans.libs.graalsdk.ScriptingTutorial#listAll
    ScriptEngine found = null;
    final ScriptEngineManager manager = Scripting.createManager();
    for (ScriptEngineFactory factory : manager.getEngineFactories()) {
        final String name = factory.getEngineName();
        System.err.println("Found " + name);
        if (factory.getMimeTypes().contains("text/javascript")) {
            if (name.equals("GraalVM:js")) {
                found = factory.getScriptEngine();
            }
        }
    }
    // END: org.netbeans.libs.graalsdk.ScriptingTutorial#listAll
    return found;
}
 
Example 2
Source File: StandardScriptUtils.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Retrieve a {@link ScriptEngine} from the given {@link ScriptEngineManager}
 * by name, delegating to {@link ScriptEngineManager#getEngineByName} but
 * throwing a descriptive exception if not found or if initialization failed.
 * @param scriptEngineManager the ScriptEngineManager to use
 * @param engineName the name of the engine
 * @return a corresponding ScriptEngine (never {@code null})
 * @throws IllegalArgumentException if no matching engine has been found
 * @throws IllegalStateException if the desired engine failed to initialize
 */
public static ScriptEngine retrieveEngineByName(ScriptEngineManager scriptEngineManager, String engineName) {
	ScriptEngine engine = scriptEngineManager.getEngineByName(engineName);
	if (engine == null) {
		Set<String> engineNames = new LinkedHashSet<>();
		for (ScriptEngineFactory engineFactory : scriptEngineManager.getEngineFactories()) {
			List<String> factoryNames = engineFactory.getNames();
			if (factoryNames.contains(engineName)) {
				// Special case: getEngineByName returned null but engine is present...
				// Let's assume it failed to initialize (which ScriptEngineManager silently swallows).
				// If it happens to initialize fine now, alright, but we really expect an exception.
				try {
					engine = engineFactory.getScriptEngine();
					engine.setBindings(scriptEngineManager.getBindings(), ScriptContext.GLOBAL_SCOPE);
				}
				catch (Throwable ex) {
					throw new IllegalStateException("Script engine with name '" + engineName +
							"' failed to initialize", ex);
				}
			}
			engineNames.addAll(factoryNames);
		}
		throw new IllegalArgumentException("Script engine with name '" + engineName +
				"' not found; registered engine names: " + engineNames);
	}
	return engine;
}
 
Example 3
Source File: PrismJsHighlighter.java    From asciidoctorj with Apache License 2.0 5 votes vote down vote up
public PrismJsHighlighter() {
    ScriptEngineFactory engine = new NashornScriptEngineFactory(); // <2>
    this.scriptEngine = engine.getScriptEngine();
    try {
        this.scriptEngine.eval(new InputStreamReader(getClass().getResourceAsStream("/prismjs/prism.js")));
    } catch (ScriptException e) {
        throw new RuntimeException(e);
    }
}
 
Example 4
Source File: ScriptingComponentHelper.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a ScriptEngine corresponding to the currently selected script engine name.
 * ScriptEngineManager.getEngineByName() doesn't use find ScriptEngineFactory.getName(), which
 * is what we used to populate the list. So just search the list of factories until a match is
 * found, then create and return a script engine.
 *
 * @return a Script Engine corresponding to the currently specified name, or null if none is found.
 */
protected ScriptEngine createScriptEngine() {
    //
    ScriptEngineFactory factory = scriptEngineFactoryMap.get(scriptEngineName);
    if (factory == null) {
        return null;
    }
    return factory.getScriptEngine();
}
 
Example 5
Source File: ScriptManager.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
public ScriptEngine getScriptEngine(String engineInfo){
    ScriptEngineFactory factory=engines.get(engineInfo);
    if(factory==null){
        javax.script.ScriptEngineManager manager=new javax.script.ScriptEngineManager();
        List<ScriptEngineFactory> fs=manager.getEngineFactories();
        int bestScore=0;
        for(ScriptEngineFactory f : fs){
            int s=matchEngine(engineInfo,f);
            if(s==10) {
                factory=f;
                break;
            }
            else if(s>bestScore){
                bestScore=s;
                factory=f;
            }
        }
        engines.put(engineInfo,factory);
    }
    if(factory==null) return null;
    
    ScriptEngine engine = factory.getScriptEngine();
    
    if(engine != null) {
        try {
            String engineName = factory.getEngineName();
            if(engineName != null && engineName.toLowerCase().contains("nashorn")) {
                // https://bugs.openjdk.java.net/browse/JDK-8025132
                engine.eval("load('nashorn:mozilla_compat.js');");
            }
        }
        catch(Exception e) {}
    }
    return engine;
}
 
Example 6
Source File: ScriptingComponentHelper.java    From nifi-script-tester with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a ScriptEngine corresponding to the currently selected script engine name.
 * ScriptEngineManager.getEngineByName() doesn't use find ScriptEngineFactory.getName(), which
 * is what we used to populate the list. So just search the list of factories until a match is
 * found, then create and return a script engine.
 *
 * @return a Script Engine corresponding to the currently specified name, or null if none is found.
 */
protected ScriptEngine createScriptEngine() {
    //
    ScriptEngineFactory factory = scriptEngineFactoryMap.get(scriptEngineName);
    if (factory == null) {
        return null;
    }
    return factory.getScriptEngine();
}
 
Example 7
Source File: Extender.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({"rawtypes"})
@Override
public ScriptEngine resolveScriptEngine(String name) {
    try {
        BufferedReader in = new BufferedReader(new InputStreamReader(configFile.openStream()));
        String className = in.readLine();
        in.close();
        Class cls = bundle.loadClass(className);
        if (!ScriptEngineFactory.class.isAssignableFrom(cls)) {
            throw new IllegalStateException("Invalid ScriptEngineFactory: " + cls.getName());
        }
        ScriptEngineFactory factory = (ScriptEngineFactory) cls.newInstance();
        List<String> names = factory.getNames();
        for (String test : names) {
            if (test.equals(name)) {
                ClassLoader old = Thread.currentThread().getContextClassLoader();
                ScriptEngine engine;
                try {
                    // JRuby seems to require the correct TCCL to call
                    // getScriptEngine
                    Thread.currentThread().setContextClassLoader(factory.getClass().getClassLoader());
                    engine = factory.getScriptEngine();
                } finally {
                    Thread.currentThread().setContextClassLoader(old);
                }
                LOGGER.trace("Resolved ScriptEngineFactory: {} for expected name: {}", engine, name);
                return engine;
            }
        }
        LOGGER.debug("ScriptEngineFactory: {} does not match expected name: {}", factory.getEngineName(), name);
        return null;
    } catch (Exception e) {
        LOGGER.warn("Cannot create ScriptEngineFactory: {}", e.getClass().getName(), e);
        return null;
    }
}
 
Example 8
Source File: StandardScriptUtils.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve a {@link ScriptEngine} from the given {@link ScriptEngineManager}
 * by name, delegating to {@link ScriptEngineManager#getEngineByName} but
 * throwing a descriptive exception if not found or if initialization failed.
 * @param scriptEngineManager the ScriptEngineManager to use
 * @param engineName the name of the engine
 * @return a corresponding ScriptEngine (never {@code null})
 * @throws IllegalArgumentException if no matching engine has been found
 * @throws IllegalStateException if the desired engine failed to initialize
 */
public static ScriptEngine retrieveEngineByName(ScriptEngineManager scriptEngineManager, String engineName) {
	ScriptEngine engine = scriptEngineManager.getEngineByName(engineName);
	if (engine == null) {
		Set<String> engineNames = new LinkedHashSet<String>();
		for (ScriptEngineFactory engineFactory : scriptEngineManager.getEngineFactories()) {
			List<String> factoryNames = engineFactory.getNames();
			if (factoryNames.contains(engineName)) {
				// Special case: getEngineByName returned null but engine is present...
				// Let's assume it failed to initialize (which ScriptEngineManager silently swallows).
				// If it happens to initialize fine now, alright, but we really expect an exception.
				try {
					engine = engineFactory.getScriptEngine();
					engine.setBindings(scriptEngineManager.getBindings(), ScriptContext.GLOBAL_SCOPE);
				}
				catch (Throwable ex) {
					throw new IllegalStateException("Script engine with name '" + engineName +
							"' failed to initialize", ex);
				}
			}
			engineNames.addAll(factoryNames);
		}
		throw new IllegalArgumentException("Script engine with name '" + engineName +
				"' not found; registered engine names: " + engineNames);
	}
	return engine;
}
 
Example 9
Source File: SpagoBIScriptManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private ScriptEngine getScriptEngineByName(String name) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
	List<ScriptEngineFactory> scriptEngineFactories = scriptEngineManager.getEngineFactories();

	for (ScriptEngineFactory scriptEngineFactory : scriptEngineFactories) {
		if (scriptEngineFactory.getNames().contains(name)) {
			return scriptEngineFactory.getScriptEngine();
		}
	}
	return null;
}
 
Example 10
Source File: SpagoBIScriptManager.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private ScriptEngine getScriptEngineByLanguage(String language) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
	List<ScriptEngineFactory> scriptEngineFactories = scriptEngineManager.getEngineFactories();

	for (ScriptEngineFactory scriptEngineFactory : scriptEngineFactories) {
		if (scriptEngineFactory.getLanguageName().equals(language)) {
			return scriptEngineFactory.getScriptEngine();
		}
	}
	return null;
}
 
Example 11
Source File: StandardScriptUtils.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Retrieve a {@link ScriptEngine} from the given {@link ScriptEngineManager}
 * by name, delegating to {@link ScriptEngineManager#getEngineByName} but
 * throwing a descriptive exception if not found or if initialization failed.
 * @param scriptEngineManager the ScriptEngineManager to use
 * @param engineName the name of the engine
 * @return a corresponding ScriptEngine (never {@code null})
 * @throws IllegalArgumentException if no matching engine has been found
 * @throws IllegalStateException if the desired engine failed to initialize
 */
public static ScriptEngine retrieveEngineByName(ScriptEngineManager scriptEngineManager, String engineName) {
	ScriptEngine engine = scriptEngineManager.getEngineByName(engineName);
	if (engine == null) {
		Set<String> engineNames = new LinkedHashSet<String>();
		for (ScriptEngineFactory engineFactory : scriptEngineManager.getEngineFactories()) {
			List<String> factoryNames = engineFactory.getNames();
			if (factoryNames.contains(engineName)) {
				// Special case: getEngineByName returned null but engine is present...
				// Let's assume it failed to initialize (which ScriptEngineManager silently swallows).
				// If it happens to initialize fine now, alright, but we really expect an exception.
				try {
					engine = engineFactory.getScriptEngine();
					engine.setBindings(scriptEngineManager.getBindings(), ScriptContext.GLOBAL_SCOPE);
				}
				catch (Throwable ex) {
					throw new IllegalStateException("Script engine with name '" + engineName +
							"' failed to initialize", ex);
				}
			}
			engineNames.addAll(factoryNames);
		}
		throw new IllegalArgumentException("Script engine with name '" + engineName +
				"' not found; registered engine names: " + engineNames);
	}
	return engine;
}
 
Example 12
Source File: JavaScriptEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static void fillArray(final ScriptEngineManager man, boolean allowAllAccess, List<Object[]> arr) {
    for (ScriptEngineFactory f : man.getEngineFactories()) {
        final String name = f.getEngineName();
        if (
                f.getMimeTypes().contains("text/javascript") ||
                name.contains("Nashorn")
                ) {
            final ScriptEngine eng = f.getScriptEngine();
            arr.add(new Object[] { name, "engineFactories", implName(eng), eng, allowAllAccess });
            for (String n : eng.getFactory().getNames()) {
                ScriptEngine byName = n == null ? null : man.getEngineByName(n);
                if (byName != null && eng.getClass() == byName.getClass()) {
                    arr.add(new Object[] { n, "name", implName(byName), byName, allowAllAccess });
                }
            }
            for (String t : eng.getFactory().getMimeTypes()) {
                ScriptEngine byType = t == null ? null : man.getEngineByMimeType(t);
                if (byType != null && eng.getClass() == byType.getClass()) {
                    arr.add(new Object[] { t, "type", implName(byType), byType, allowAllAccess });
                }
            }
            for (String e : eng.getFactory().getExtensions()) {
                ScriptEngine byExt = e == null ? null : man.getEngineByExtension(e);
                if (byExt != null && eng.getClass() == byExt.getClass()) {
                    arr.add(new Object[] { e, "ext", implName(byExt), byExt, allowAllAccess });
                }
            }
        }
    }
}
 
Example 13
Source File: L2ScriptEngineManager.java    From L2jBrasil with GNU General Public License v3.0 5 votes vote down vote up
private L2ScriptEngineManager()
{
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
	List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories();
	if (USE_COMPILED_CACHE)
		_cache = this.loadCompiledScriptCache();
	else
		_cache = null;
	_log.info("Initializing Script Engine Manager");
	for (ScriptEngineFactory factory : factories)
		try
		{
			ScriptEngine engine = factory.getScriptEngine();
			boolean reg = false;
			for (String name : factory.getNames())
			{
				ScriptEngine existentEngine = _nameEngines.get(name);
				if (existentEngine != null)
				{
					double engineVer = Double.parseDouble(factory.getEngineVersion());
					double existentEngVer = Double.parseDouble(existentEngine.getFactory().getEngineVersion());
					if (engineVer <= existentEngVer)
						continue;
				}
				reg = true;
				_nameEngines.put(name, engine);
			}
			if (reg)
				_log.info("Script Engine: " + factory.getEngineName() + " " + factory.getEngineVersion() + " - Language: " + factory.getLanguageName() + " - Language Version: " + factory.getLanguageVersion());
			for (String ext : factory.getExtensions())
				if (!ext.equals("java") || factory.getLanguageName().equals("java"))
					_extEngines.put(ext, engine);
		}
		catch (Exception e)
		{
			_log.warning("Failed initializing factory. ");
			e.printStackTrace();
		}
	this.preConfigure();
}
 
Example 14
Source File: Extender.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes" })
public ScriptEngine resolveScriptEngine(String name) {
  try {
    BufferedReader in = new BufferedReader(new InputStreamReader(configFile.openStream()));
    String className = in.readLine();
    in.close();
    Class cls = bundle.loadClass(className);
    if (!ScriptEngineFactory.class.isAssignableFrom(cls)) {
      throw new IllegalStateException("Invalid ScriptEngineFactory: " + cls.getName());
    }
    ScriptEngineFactory factory = (ScriptEngineFactory) cls.newInstance();
    List<String> names = factory.getNames();
    for (String test : names) {
      if (test.equals(name)) {
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        ScriptEngine engine;
        try {
          // JRuby seems to require the correct TCCL to call
          // getScriptEngine
          Thread.currentThread().setContextClassLoader(factory.getClass().getClassLoader());
          engine = factory.getScriptEngine();
        } finally {
          Thread.currentThread().setContextClassLoader(old);
        }
        LOGGER.trace("Resolved ScriptEngineFactory: {} for expected name: {}", engine, name);
        return engine;
      }
    }
    LOGGER.debug("ScriptEngineFactory: {} does not match expected name: {}", factory.getEngineName(), name);
    return null;
  } catch (Exception e) {
    LOGGER.warn("Cannot create ScriptEngineFactory: {}", e.getClass().getName(), e);
    return null;
  }
}
 
Example 15
Source File: ScriptingComponentHelper.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Provides a ScriptEngine corresponding to the currently selected script engine name.
 * ScriptEngineManager.getEngineByName() doesn't use find ScriptEngineFactory.getName(), which
 * is what we used to populate the list. So just search the list of factories until a match is
 * found, then create and return a script engine.
 *
 * @return a Script Engine corresponding to the currently specified name, or null if none is found.
 */
protected ScriptEngine createScriptEngine() {
    //
    ScriptEngineFactory factory = scriptEngineFactoryMap.get(scriptEngineName);
    if (factory == null) {
        return null;
    }
    return factory.getScriptEngine();
}
 
Example 16
Source File: StandardScriptUtils.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Retrieve a {@link ScriptEngine} from the given {@link ScriptEngineManager}
 * by name, delegating to {@link ScriptEngineManager#getEngineByName} but
 * throwing a descriptive exception if not found or if initialization failed.
 * @param scriptEngineManager the ScriptEngineManager to use
 * @param engineName the name of the engine
 * @return a corresponding ScriptEngine (never {@code null})
 * @throws IllegalArgumentException if no matching engine has been found
 * @throws IllegalStateException if the desired engine failed to initialize
 */
public static ScriptEngine retrieveEngineByName(ScriptEngineManager scriptEngineManager, String engineName) {
	ScriptEngine engine = scriptEngineManager.getEngineByName(engineName);
	if (engine == null) {
		Set<String> engineNames = new LinkedHashSet<>();
		for (ScriptEngineFactory engineFactory : scriptEngineManager.getEngineFactories()) {
			List<String> factoryNames = engineFactory.getNames();
			if (factoryNames.contains(engineName)) {
				// Special case: getEngineByName returned null but engine is present...
				// Let's assume it failed to initialize (which ScriptEngineManager silently swallows).
				// If it happens to initialize fine now, alright, but we really expect an exception.
				try {
					engine = engineFactory.getScriptEngine();
					engine.setBindings(scriptEngineManager.getBindings(), ScriptContext.GLOBAL_SCOPE);
				}
				catch (Throwable ex) {
					throw new IllegalStateException("Script engine with name '" + engineName +
							"' failed to initialize", ex);
				}
			}
			engineNames.addAll(factoryNames);
		}
		throw new IllegalArgumentException("Script engine with name '" + engineName +
				"' not found; registered engine names: " + engineNames);
	}
	return engine;
}
 
Example 17
Source File: BundleScriptEngineResolver.java    From camunda-bpm-platform-osgi with Apache License 2.0 4 votes vote down vote up
@Override
 public ScriptEngine resolveScriptEngine(String name) {
	try {
		BufferedReader in = new BufferedReader(new InputStreamReader(
				configFile.openStream()));
		String className = removeCommentsFromInput(in);
		in.close();
		Class<?> cls = bundle.loadClass(className);
		if (!ScriptEngineFactory.class.isAssignableFrom(cls)) {
			throw new IllegalStateException("Invalid ScriptEngineFactory: "
					+ cls.getName());
		}
		ScriptEngineFactory factory = (ScriptEngineFactory) cls
				.newInstance();
		List<String> names = factory.getNames();
		for (String n : names) {
			if (n.equals(name)) {
				ClassLoader old = Thread.currentThread()
						.getContextClassLoader();
				ScriptEngine engine;
				try {
					// JRuby seems to require the correct TCCL to call
					// getScriptEngine
					Thread.currentThread().setContextClassLoader(
							factory.getClass().getClassLoader());
					engine = factory.getScriptEngine();
				} finally {
					Thread.currentThread().setContextClassLoader(old);
				}
				LOGGER.finest("Resolved ScriptEngineFactory: " + engine
						+ " for expected name: " + name);
				return engine;
			}
		}
		LOGGER.fine("ScriptEngineFactory: " + factory.getEngineName()
				+ " does not match expected name: " + name);
		return null;
	} catch (Exception e) {
		LOGGER.log(Level.WARNING, "Cannot create ScriptEngineFactory: "
				+ e.getClass().getName(), e);
		return null;
	}
}