private boolean isJavaScriptAvailable() { if(isJSAvailableChecked) { return isJSAvailable; } ScriptEngineManager mgr = new ScriptEngineManager(); List<ScriptEngineFactory> factories = mgr.getEngineFactories(); for (ScriptEngineFactory factory: factories) { List<String> engNames = factory.getNames(); for(String name: engNames) { if(name.equalsIgnoreCase("js") || name.equalsIgnoreCase("javascript")) { //NOI18N isJSAvailableChecked = true; isJSAvailable = true; return isJSAvailable; } } } isJSAvailableChecked = true; isJSAvailable = false; return isJSAvailable; }
private String getEngineInfo(ScriptEngine engine) { StringBuilder sb = new StringBuilder(); ScriptEngineFactory f = engine.getFactory(); sb.append("LanguageName="); sb.append("\"").append(f.getLanguageName()).append("\""); sb.append(" "); sb.append("LanguageVersion="); sb.append("\"").append(f.getLanguageVersion()).append("\""); sb.append(" "); sb.append("EngineName="); sb.append("\"").append(f.getEngineName()).append("\""); sb.append(" "); sb.append("EngineNameAliases="); sb.append(Arrays.toString(f.getNames().toArray(new String[f.getNames().size()]))); sb.append(" "); sb.append("EngineVersion="); sb.append("\"").append(f.getEngineVersion()).append("\""); return sb.toString(); }
@Override @PreAuthorize("checkPermission('Scripts')") public ScriptOptionsInterface execute(GetScriptOptionsRpcRequest request, SessionContext context) { ScriptOptionsInterface options = new ScriptOptionsInterface(); for (ScriptEngineFactory factory: new ScriptEngineManager().getEngineFactories()) options.addEngine(factory.getLanguageName()); for (Right right: Right.values()) { if (!right.hasType() || right.type().equals(Session.class) || right.type().equals(Department.class) || right.type().equals(SubjectArea.class)) options.addPermission(right.toString()); } options.setCanAdd(context.hasPermission(Right.ScriptEdit)); return options; }
/** * Basic test of iterator() to test iteration order. Providers deployed * as named modules should be found before providers deployed on the class * path. */ @Test public void testIteratorOrder() { ServiceLoader<ScriptEngineFactory> loader = ServiceLoader.load(ScriptEngineFactory.class); boolean foundUnnamed = false; for (ScriptEngineFactory factory : collectAll(loader)) { if (factory.getClass().getModule().isNamed()) { if (foundUnnamed) { assertTrue(false, "Named module element after unnamed"); } } else { foundUnnamed = true; } } }
/** * Basic test of the public static provider method. BananaScriptEngine * defines a provider method that returns the same instance. */ @Test public void testSingleton() { Optional<Provider<ScriptEngineFactory>> oprovider = ServiceLoader.load(ScriptEngineFactory.class) .stream() .filter(p -> p.type().getName().equals("org.banana.BananaScriptEngineFactory")) .findFirst(); assertTrue(oprovider.isPresent()); Provider<ScriptEngineFactory> provider = oprovider.get(); // invoke Provider::get twice ScriptEngineFactory factory1 = provider.get(); ScriptEngineFactory factory2 = provider.get(); assertTrue(factory1 == factory2); }
/** * Basic test of stream() to ensure that elements for providers in named * modules come before elements for providers in unnamed modules. */ @Test public void testStreamOrder() { List<Class<?>> types = ServiceLoader.load(ScriptEngineFactory.class) .stream() .map(Provider::type) .collect(Collectors.toList()); boolean foundUnnamed = false; for (Class<?> factoryClass : types) { if (factoryClass.getModule().isNamed()) { if (foundUnnamed) { assertTrue(false, "Named module element after unnamed"); } } else { foundUnnamed = true; } } }
/** * Basic test ServiceLoader.load specifying the platform class loader. * The providers on the module path and class path should not be located. */ @Test public void testWithPlatformClassLoader() { ClassLoader pcl = ClassLoader.getPlatformClassLoader(); // iterator ServiceLoader<ScriptEngineFactory> loader = ServiceLoader.load(ScriptEngineFactory.class, pcl); Set<String> names = collectAll(loader) .stream() .map(ScriptEngineFactory::getEngineName) .collect(Collectors.toSet()); assertFalse(names.contains("BananaScriptEngine")); assertFalse(names.contains("PearScriptEngine")); // stream names = ServiceLoader.load(ScriptEngineFactory.class, pcl) .stream() .map(Provider::get) .map(ScriptEngineFactory::getEngineName) .collect(Collectors.toSet()); assertFalse(names.contains("BananaScriptEngine")); assertFalse(names.contains("PearScriptEngine")); }
/** * Basic test of ServiceLoader.load, using the class loader for * a module in a custom layer as the context. */ @Test public void testWithCustomLayer1() { ModuleLayer layer = createCustomLayer("bananascript"); ClassLoader loader = layer.findLoader("bananascript"); List<ScriptEngineFactory> providers = collectAll(ServiceLoader.load(ScriptEngineFactory.class, loader)); // should have at least 2 x bananascript + pearscript assertTrue(providers.size() >= 3); // first element should be the provider in the custom layer ScriptEngineFactory factory = providers.get(0); assertTrue(factory.getClass().getClassLoader() == loader); assertTrue(factory.getClass().getModule().getLayer() == layer); assertTrue(factory.getEngineName().equals("BananaScriptEngine")); // remainder should be the boot layer providers.remove(0); Set<String> names = providers.stream() .map(ScriptEngineFactory::getEngineName) .collect(Collectors.toSet()); assertTrue(names.contains("BananaScriptEngine")); assertTrue(names.contains("PearScriptEngine")); }
/** * Basic test of ServiceLoader.load using a custom Layer as the context. */ @Test public void testWithCustomLayer2() { ModuleLayer layer = createCustomLayer("bananascript"); List<ScriptEngineFactory> factories = collectAll(ServiceLoader.load(layer, ScriptEngineFactory.class)); // should have at least 2 x bananascript assertTrue(factories.size() >= 2); // first element should be the provider in the custom layer ScriptEngineFactory factory = factories.get(0); assertTrue(factory.getClass().getModule().getLayer() == layer); assertTrue(factory.getEngineName().equals("BananaScriptEngine")); // remainder should be the boot layer factories.remove(0); Set<String> names = factories.stream() .map(ScriptEngineFactory::getEngineName) .collect(Collectors.toSet()); assertTrue(names.contains("BananaScriptEngine")); assertFalse(names.contains("PearScriptEngine")); }
@Test public void factoryClassLoaderTest() { final ScriptEngineManager sm = new ScriptEngineManager(); for (final ScriptEngineFactory fac : sm.getEngineFactories()) { if (fac instanceof NashornScriptEngineFactory) { final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; final MyClassLoader loader = new MyClassLoader(); // set the classloader as app class loader final ScriptEngine e = nfac.getScriptEngine(loader); try { e.eval("Packages.foo"); // check that the class loader was attempted assertTrue(loader.reached(), "did not reach class loader!"); } catch (final ScriptException se) { se.printStackTrace(); fail(se.getMessage()); } return; } } fail("Cannot find nashorn factory!"); }
@Test public void factoryOptionsTest() { final ScriptEngineManager sm = new ScriptEngineManager(); for (final ScriptEngineFactory fac : sm.getEngineFactories()) { if (fac instanceof NashornScriptEngineFactory) { final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; // specify --no-syntax-extensions flag final String[] options = new String[] { "--no-syntax-extensions" }; final ScriptEngine e = nfac.getScriptEngine(options); try { // try nashorn specific extension e.eval("var f = funtion(x) 2*x;"); fail("should have thrown exception!"); } catch (final Exception ex) { //empty } return; } } fail("Cannot find nashorn factory!"); }
@Test /** * Test repeated evals with --loader-per-compile=false * We used to get "class redefinition error". */ public void noLoaderPerCompilerTest() { final ScriptEngineManager sm = new ScriptEngineManager(); for (final ScriptEngineFactory fac : sm.getEngineFactories()) { if (fac instanceof NashornScriptEngineFactory) { final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; final String[] options = new String[] { "--loader-per-compile=false" }; final ScriptEngine e = nfac.getScriptEngine(options); try { e.eval("2 + 3"); e.eval("4 + 4"); } catch (final ScriptException se) { se.printStackTrace(); fail(se.getMessage()); } return; } } fail("Cannot find nashorn factory!"); }
@Test /** * Test that we can use same script name in repeated evals with --loader-per-compile=false * We used to get "class redefinition error" as name was derived from script name. */ public void noLoaderPerCompilerWithSameNameTest() { final ScriptEngineManager sm = new ScriptEngineManager(); for (final ScriptEngineFactory fac : sm.getEngineFactories()) { if (fac instanceof NashornScriptEngineFactory) { final NashornScriptEngineFactory nfac = (NashornScriptEngineFactory)fac; final String[] options = new String[] { "--loader-per-compile=false" }; final ScriptEngine e = nfac.getScriptEngine(options); e.put(ScriptEngine.FILENAME, "test.js"); try { e.eval("2 + 3"); e.eval("4 + 4"); } catch (final ScriptException se) { se.printStackTrace(); fail(se.getMessage()); } return; } } fail("Cannot find nashorn factory!"); }
/** * Tests the evaluation of a simple java script expression executed on a set of objects. */ @Test public void testEvaluation() { setSystemAdministratorContext(); // as a test print scripting language names final ScriptEngineManager manager = new ScriptEngineManager(); for (final ScriptEngineFactory sef : manager.getEngineFactories()) { log.debug(sef.getEngineName()); } final List<Table> tables = OBDal.getInstance().createCriteria(Table.class).list(); boolean found = false; for (final Table t : tables) { final String script = Table.PROPERTY_CLIENT + "." + Client.PROPERTY_ID + " == '0' && " + Table.PROPERTY_DBTABLENAME + "== 'AD_Client' && " + Table.PROPERTY_DATAACCESSLEVEL + " > 5"; final Boolean result = Evaluator.getInstance().evaluateBoolean(t, script); log.debug(t.getName() + " : " + result); found = found || result; if (found) { break; } } assertTrue(found); }
protected static ScriptEngineFactory lookupScriptEngineFactory(String language) { ScriptEngineManager manager = new ScriptEngineManager(); for (ScriptEngineFactory factory : manager.getEngineFactories()) { // some script names has alias String[] names = getScriptNames(language); for (String name : names) { if (factory.getLanguageName().equals(name)) { return factory; } } } // fallback to get engine by name ScriptEngine engine = createScriptEngine(language, true); if (engine != null) { return engine.getFactory(); } return null; }
private void fillLanguageBox(final ScriptEngineManager manager) { final List<ScriptEngineFactory> factories = manager.getEngineFactories(); final List<ScriptingLanguage> languages = new ArrayList<ScriptingLanguage>(); for (final ScriptEngineFactory factory : factories) { // Disable Rhino scripting engine for JavaScript / ECMAScript. if (factory.getLanguageName().equals("python")) { languages .add(new ScriptingLanguage(factory.getLanguageName(), factory.getLanguageVersion())); } } Collections.sort(languages); for (final ScriptingLanguage language : languages) { addItem(language); } }
/** * Display all script engines. */ public static void listEngines() { final ScriptEngineManager mgr = new ScriptEngineManager(); final List<ScriptEngineFactory> factories = mgr.getEngineFactories(); for (final ScriptEngineFactory factory: factories) { System.out.println("ScriptEngineFactory Info"); final String engName = factory.getEngineName(); final String engVersion = factory.getEngineVersion(); final String langName = factory.getLanguageName(); final String langVersion = factory.getLanguageVersion(); System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion); final List<String> engNames = factory.getNames(); for (final String name: engNames) { System.out.printf("\tEngine Alias: %s\n", name); } System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion); } }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ScriptEngineManager m = new ScriptEngineManager(); ScriptEngine engine = m.getEngineByMimeType("application/javascript"); if (engine != null) { // workaround until we find a way to get a headless WebView object WebView wv = new WebView(getBaseContext()); ((JJSBridge4AndroidEngine) engine).setView(wv); Log.d(TAG, ScriptEngine.NAME + " " + engine.get(ScriptEngine.NAME)); Log.d(TAG, ScriptEngine.ENGINE + " " + engine.get(ScriptEngine.ENGINE)); ScriptEngineFactory f = engine.getFactory(); String program = f.getOutputStatement("\"Hello world\""); try { engine.eval(program); } catch (ScriptException ex) { Log.e(TAG, "eval()", ex); } } }
/** * Constructor. Uses the JSR-223 script engine factory to gather the * language adapter attributes. Sub-classes must be annotated with * {@link ScriptEngines}. * * @throws LanguageAdapterException */ public Jsr223LanguageAdapter() throws LanguageAdapterException { ScriptEngines scriptEngineNames = getClass().getAnnotation( ScriptEngines.class ); if( scriptEngineNames == null ) throw new LanguageAdapterException( getClass(), getClass().getCanonicalName() + " does not have a ScriptEngines annotation" ); String scriptEngineName = scriptEngineNames.value()[0]; ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); scriptEngine = scriptEngineManager.getEngineByName( scriptEngineName ); if( scriptEngine == null ) throw new LanguageAdapterException( getClass(), getClass().getCanonicalName() + " could not load ScriptEngine " + scriptEngineName ); ScriptEngineFactory factory = scriptEngine.getFactory(); attributes.put( NAME, "JSR-223/" + factory.getEngineName() ); attributes.put( VERSION, factory.getEngineVersion() ); attributes.put( LANGUAGE_NAME, factory.getLanguageName() ); attributes.put( LANGUAGE_VERSION, factory.getLanguageVersion() ); attributes.put( EXTENSIONS, new ArrayList<String>( factory.getExtensions() ) ); attributes.put( DEFAULT_EXTENSION, factory.getExtensions().get( 0 ) ); attributes.put( TAGS, Arrays.asList( scriptEngineNames.value() ) ); attributes.put( DEFAULT_TAG, factory.getNames().get( 0 ) ); attributes.put( JSR223_SCRIPT_ENGINE_NAME, scriptEngineName ); }
private Map<ScriptEngine, Integer> findScriptEngineCandidates(boolean findByName) { Map<ScriptEngine, Integer> matchPositionPerScriptEngineCandidate = new HashMap<>(); int matchPosition; List<String> lookupCriteria; for (ScriptEngineFactory factory : new ScriptEngineManager().getEngineFactories()) { matchPosition = 0; if (findByName) { lookupCriteria = factory.getNames(); } else { lookupCriteria = factory.getExtensions(); } for (String criteria : lookupCriteria) { if (criteria.equalsIgnoreCase(scriptEngineLookupName)) { matchPositionPerScriptEngineCandidate.put(factory.getScriptEngine(), matchPosition); } matchPosition++; } } return matchPositionPerScriptEngineCandidate; }
public ScriptManager(RuleTriggerManager triggerManager, ItemRegistry itemRegistry) { this.triggerManager = triggerManager; instance = this; logger.info("Available engines:"); for (ScriptEngineFactory f : new ScriptEngineManager().getEngineFactories()) { logger.info(f.getEngineName()); } this.setItemRegistry(itemRegistry); File folder = getFolder("scripts"); if (folder.exists() && folder.isDirectory()) { loadScripts(folder); scriptUpdateWatcher = new Thread(new ScriptUpdateWatcher(this, folder)); scriptUpdateWatcher.start(); } else { logger.warn("Script directory: jsr_scripts missing, no scripts will be added!"); } }
/** * For error messages - returns null if there are any exceptions of any * kind building the string (or of the list is empty for some unknown reason). * @param ext - if true, list of extensions, otherwise a list of engine names */ private static String getSupportedEngines(ScriptEngineManager mgr, boolean ext) { String result = null; try { List<ScriptEngineFactory> factories = mgr.getEngineFactories(); if (null == factories) return result; Set<String> engines = new LinkedHashSet<>(factories.size()); for (ScriptEngineFactory f : factories) { if (ext) { engines.addAll(f.getExtensions()); } else { engines.addAll(f.getNames()); } } result = StringUtils.join(engines, ", "); } catch (RuntimeException e) { /* :NOOP: */ } return result; }