private synchronized ScriptEngineState getEngineByName(String name, boolean reset) throws SoarException { ScriptEngineState state = engines.get(name); if (state != null && reset) { state.dispose(); engines.remove(name); state = null; } if (state == null) { final ScriptEngine engine = getEngineManager().getEngineByName(name); if (engine == null) { throw new SoarException("Unsupported script engine '" + name + "'"); } final ScriptEngineFactory f = engine.getFactory(); logger.info( String.format( "Loaded '%s' script engine for %s: %s version %s, %s version %s", name, context, f.getEngineName(), f.getEngineVersion(), f.getLanguageName(), f.getLanguageVersion())); engines.put(name, state = new ScriptEngineState(context, name, engine)); } return state; }
/** * Log available script engines at INFO level. * * @param logger the logger instance used to log available script engines. */ public static void logAvailableScriptEngines(Logger logger) { if (!logger.isInfoEnabled()) { return; } ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); List<ScriptEngineFactory> engineFactories = scriptEngineManager.getEngineFactories(); StringBuilder buffer = new StringBuilder(); buffer.append("Available script engines: "); int engineFactoriesCount = engineFactories.size(); for (int i = 0; i < engineFactoriesCount; i++) { ScriptEngineFactory scriptEngineFactory = engineFactories.get(i); buffer.append(scriptEngineFactory.getEngineName()); buffer.append(" ("); buffer.append(scriptEngineFactory.getEngineVersion()); buffer.append(")"); if (i < engineFactoriesCount - 1) { buffer.append(", "); } } logger.info(buffer.toString()); }
// This code worked successfully on command-line but never as JUnit test // <script>:1: undefined method `+' for nil:NilClass (NoMethodError) // raised at "Object obj1 = engine1.eval("$Value + 2010.to_s");" // @Test public void testMultipleEngineStates() throws ScriptException { logger1.info("Multiple Engine States"); ScriptEngine engine1; ScriptEngine engine2; synchronized (this) { System.setProperty("org.jruby.embed.localcontext.scope", "singlethread"); System.setProperty("org.jruby.embed.localvariable.behavior", "global"); ScriptEngineManager manager = new ScriptEngineManager(); List<ScriptEngineFactory> factories = manager.getEngineFactories(); ScriptEngineFactory factory = null; while (factories.iterator().hasNext()) { factory = factories.iterator().next(); if ("ruby".equals(factory.getLanguageName())) { break; } } engine1 = factory.getScriptEngine(); engine2 = factory.getScriptEngine(); } engine1.put("Value", "value of the first engine"); engine2.put("Value", new Double(-0.0149)); Object obj1 = engine1.eval("$Value + 2010.to_s"); Object obj2 = engine2.eval("$Value + 2010"); assertNotSame(obj1, obj2); engine1 = null; engine2 = null; }
@Override protected ScriptEngine makeEngine() { try { Class<?> c; c = this.getClass().getClassLoader().loadClass("com.sun.script.java.JavaScriptEngineFactory"); ScriptEngineFactory fact = (ScriptEngineFactory) c.newInstance(); ScriptEngine engine = fact.getScriptEngine(); engine .getContext() .setAttribute( "com.sun.script.java.parentLoader", Trampoline2.trampoline.getClassLoader(), ScriptContext.ENGINE_SCOPE); engine .getContext() .setAttribute( "parentLoader", Trampoline2.trampoline.getClassLoader(), ScriptContext.ENGINE_SCOPE); return engine; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } return null; }
public static void main(String[] args) { // create ScriptEngineManager ScriptEngineManager manager = new ScriptEngineManager(); List<ScriptEngineFactory> factoryList = manager.getEngineFactories(); for (ScriptEngineFactory factory : factoryList) { System.out.println(factory.getEngineName()); System.out.println(factory.getLanguageName()); } }
private L2ScriptEngineManager() { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); List<ScriptEngineFactory> factories = scriptEngineManager.getEngineFactories(); if (Config.SCRIPT_CACHE) { _cache = 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.warn("Failed initializing factory. "); e.printStackTrace(); } } preConfigure(); }
/** * @return A list containing the short names of all scripting engines supported. An engie can have * multiple names so in general the number of engine names is greather than the number of * actual engines registered into the platform */ public Set<String> getSuportedEngineNames() { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); List<ScriptEngineFactory> scriptEngineFactories = scriptEngineManager.getEngineFactories(); Set<String> engineNames = new HashSet<String>(); for (ScriptEngineFactory scriptEngineFactory : scriptEngineFactories) { engineNames.addAll(scriptEngineFactory.getNames()); } return engineNames; }
/** @return A list containing the names of all scripting languages supported */ public Set<String> getSupportedLanguages() { ScriptEngineManager scriptEngineManager = new ScriptEngineManager(); List<ScriptEngineFactory> scriptEngineFactories = scriptEngineManager.getEngineFactories(); Set<String> languages = new HashSet<String>(); for (ScriptEngineFactory scriptEngineFactory : scriptEngineFactories) { languages.add(scriptEngineFactory.getLanguageName()); } return languages; }
protected Collection<Map<String, String>> getAvailableScriptEngines() { List<Map<String, String>> engines = new LinkedList<Map<String, String>>(); for (ScriptEngineFactory f : FACTORIES) { Map<String, String> engine = new LinkedHashMap<String, String>(); engine.put("engine", f.getNames().get(0)); engine.put("language", f.getLanguageName()); engines.add(engine); } return engines; }
private List<String> getAvailableScriptExtensions() { ArrayList<String> extensions = new ArrayList<String>(); for (ScriptEngineFactory engine : manager.getEngineFactories()) { for (String ext : engine.getExtensions()) { extensions.add(ext); } } return extensions; }
public String getHelpText() { StringBuilder helpText = new StringBuilder( "Custom message content generated from a script using JSR 223. " + "Custom scripts should be placed in " + "$JENKINS_HOME/" + EMAIL_TEMPLATES_DIRECTORY + ". When using custom scripts, " + "the script filename WITH .py/.rb/etc should be used for " + "the \"" + SCRIPT_NAME_ARG + "\" argument.\n" + "templates and other items may be loaded using the\n" + "host.readFile(String fileName) function\n" + "the function will look in the resources for\n" + "the email-ext plugin first, and then in the $JENKINS_HOME/" + EMAIL_TEMPLATES_DIRECTORY + "\n" + "directory. No other directories will be searched.\n" + "<ul>\n" + "<li><i>" + SCRIPT_NAME_ARG + "</i> - the script name.<br>\n" + " Defaults to \"" + DEFAULT_SCRIPT_NAME + "\".</li>\n" + "<li><i>" + SCRIPT_TEMPLATE_ARG + "</i> - the template filename.<br>\n" + " Defaults to \"" + DEFAULT_TEMPLATE_NAME + "\"</li>\n" + "<li><i>" + SCRIPT_INIT_ARG + "</i> - true to run the language's init script.<br>\n" + " Defaults to " + DEFAULT_INIT_VALUE + "</li>\n" + "<li>Available Script Engines\n" + "<ul>\n"); for (ScriptEngineFactory fact : scriptEngineManager.getEngineFactories()) { String extensions = join(fact.getExtensions(), ","); helpText.append( "<li><i>" + fact.getLanguageName() + "</i> - " + fact.getLanguageVersion() + " (" + extensions + ")</li>\n"); } helpText.append("</ul></ul>\n"); return helpText.toString(); }
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; }
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; }
public ObjectPanel(ClientModel model) { super(model); model.addObjectListener(this); // get all installed script engines scriptExtensions = new HashSet<String>(); ScriptEngineManager mgr = new ScriptEngineManager(); for (ScriptEngineFactory sef : mgr.getEngineFactories()) { scriptExtensions.addAll(sef.getExtensions()); } createGUI(); }
/** Test of getFactory method, of class Jsr223JRubyEngine. */ @Test public void testGetFactory() { logger1.info("getFactory"); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine instance = manager.getEngineByName("jruby"); ScriptEngineFactory result = instance.getFactory(); assertTrue(result instanceof JRubyEngineFactory); String expResult = "JSR 223 JRuby Engine"; String ret = result.getEngineName(); assertEquals(expResult, ret); instance.getBindings(ScriptContext.ENGINE_SCOPE).clear(); instance = null; }
@Override public void run() { final String fileExtension = FileUtils.getExtension(file); final ScriptEngineFactory factory = scriptService.getByFileExtension(fileExtension); try { final Object result = factory.getScriptEngine().eval(new FileReader(file)); if (result != null) { System.out.println(result.toString()); } } catch (final ScriptException e) { scriptService.getLogService().error(e.getCause()); } catch (final Throwable e) { scriptService.getLogService().error(e); } }
/** The Script Engine used to evaluate the script. */ protected ScriptEngine createScriptEngine() { for (ScriptEngineFactory factory : new ScriptEngineManager().getEngineFactories()) { for (String name : factory.getNames()) { if (name.equalsIgnoreCase(scriptEngineLookup)) { return factory.getScriptEngine(); } } for (String ext : factory.getExtensions()) { String scriptEngineLookupLowercase = scriptEngineLookup.toLowerCase(); if (scriptEngineLookupLowercase.endsWith(ext.toLowerCase())) { return factory.getScriptEngine(); } } } return null; }
/** * Get a list of available scripting engines for executing scripts. * * @return a list of available scripting engines for executing scripts. */ public List<String> getAvailableScriptEngines() { if (availableScriptEngines == null) { availableScriptEngines = new ArrayList<>(); ScriptEngineManager manager = getScriptEngineManager(); if (manager != null) { List<ScriptEngineFactory> factoryList = manager.getEngineFactories(); for (ScriptEngineFactory factory : factoryList) { availableScriptEngines.addAll(factory.getNames()); } } if (availableScriptEngines.isEmpty()) { useRhino = true; engineName = "Rhino"; availableScriptEngines.add(engineName); } } return availableScriptEngines; }
@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.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; } }
private StringBuilder listScriptEngine() { StringBuilder sb = new StringBuilder(OStrings.getString("SCW_LIST_ENGINES") + "\n"); for (ScriptEngineFactory engine : manager.getEngineFactories()) { sb.append(" - "); sb.append(engine.getEngineName()); sb.append(" "); sb.append(engine.getLanguageName()); sb.append(" v."); sb.append(engine.getLanguageVersion()); sb.append(" (").append(OStrings.getString("SCW_EXTENSIONS")).append(" "); boolean hasMore = false; for (String ext : engine.getExtensions()) { if (hasMore) { sb.append(", "); } sb.append(ext); hasMore = true; } sb.append(")"); sb.append("\n"); } return sb; }
public void printInfo() { ScriptEngineManager mgr = new ScriptEngineManager(); List<ScriptEngineFactory> factories = mgr.getEngineFactories(); for (ScriptEngineFactory factory : factories) { System.out.println("ScriptEngineFactory Info"); String engName = factory.getEngineName(); String engVersion = factory.getEngineVersion(); String langName = factory.getLanguageName(); String langVersion = factory.getLanguageVersion(); System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion); List<String> engNames = factory.getNames(); for (String name : engNames) { System.out.printf("\tEngine Alias: %s\n", name); } System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion); } }
@Override public String getEngineVersion() { return factory.getEngineVersion(); }
@Override public List<String> getMimeTypes() { return factory.getMimeTypes(); }
/** * Unbinds a ScriptEngineFactory. * * @param factory the script engine factory to unbind */ protected void unbindScriptEngineFactory(ScriptEngineFactory factory) { String language = factory.getLanguageName(); String languageVersion = factory.getLanguageVersion(); removeScriptEngineFactory(new ScriptLanguageDescription(language, languageVersion), factory); }
@Override public List<String> getNames() { return factory.getNames(); }
@Override public String getLanguageName() { return factory.getLanguageName(); }
protected void writeHtml(Writer writer) { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if (!baseRef.endsWith("/")) baseRef += "/"; PrintWriter pw = new PrintWriter(writer); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>Script in " + cj.getShortName() + "</title>"); pw.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + getStylesheetRef() + "\">"); pw.println("</head>"); pw.println("<body>"); pw.println( "<h1>Execute script for job <i><a href='/engine/job/" + TextUtils.urlEscape(cj.getShortName()) + "'>" + cj.getShortName() + "</a></i></h1>"); // output of previous script, if any if (linesExecuted > 0) { pw.println("<span class='success'>" + linesExecuted + " lines executed</span>"); } if (ex != null) { pw.println("<pre style='color:red; height:150px; overflow:auto'>"); ex.printStackTrace(pw); pw.println("</pre>"); } if (StringUtils.isNotBlank(htmlOutput)) { pw.println("<fieldset><legend>htmlOut</legend>"); pw.println(htmlOutput); pw.println("</fieldset>"); } if (StringUtils.isNotBlank(rawOutput)) { pw.println("<fieldset><legend>rawOut</legend><pre>"); pw.println(StringEscapeUtils.escapeHtml(rawOutput)); pw.println("</pre></fieldset>"); } pw.println("<form method='POST'>"); pw.println("<input type='submit' value='execute'>"); pw.println("<select name='engine'>"); ; for (ScriptEngineFactory f : FACTORIES) { String opt = f.getNames().get(0); pw.println( "<option " + (opt.equals(chosenEngine) ? " selected='selected' " : "") + "value='" + opt + "'>" + f.getLanguageName() + "</option>"); } pw.println("</select>"); pw.println("<textarea rows='20' style='width:100%' name=\'script\'>" + script + "</textarea>"); pw.println("<input type='submit' value='execute'></input>"); pw.println("</form>"); pw.println( "The script will be executed in an engine preloaded " + "with (global) variables:\n<ul>\n" + "<li><code>rawOut</code>: a PrintWriter for arbitrary text output to this page</li>\n" + "<li><code>htmlOut</code>: a PrintWriter for HTML output to this page</li>\n" + "<li><code>job</code>: the current CrawlJob instance</li>\n" + "<li><code>appCtx</code>: current job ApplicationContext, if any</li>\n" + "<li><code>scriptResource</code>: the ScriptResource implementing this " + "page, which offers utility methods</li>\n" + "</ul>"); pw.println("</body>"); pw.println("</html>"); pw.flush(); }
public ScriptLanguageParameter(ScriptEngineManager engineManager) { for (ScriptEngineFactory factory : engineManager.getEngineFactories()) { languages.add(factory.getLanguageName()); } }
@Override protected PicoContainer createContainerFromScript( final PicoContainer parentContainer, final Object assemblyScope) { Reader reader = null; ScriptEngine engine = null; final ScriptEngineManager mgr = new ScriptEngineManager(); final ClassLoader oldClassLoader = AccessController.doPrivileged( new PrivilegedAction<ClassLoader>() { public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } }); final ClassLoader newClassLoader = this.getClassLoader(); try { if (applyCustomClassLoader()) { AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { Thread.currentThread().setContextClassLoader(newClassLoader); return null; } }); } engine = mgr.getEngineByName(engineName); if (engine == null) { final StringBuilder message = new StringBuilder( "Could not find a script engine named: '" + engineName + "' all script engines in your classpath are:\n"); for (final ScriptEngineFactory eachFactory : mgr.getEngineFactories()) { message.append( "\t Engine named '" + eachFactory.getEngineName() + "' which supports the language '" + eachFactory.getLanguageName() + "' with short names '" + Arrays.toString(eachFactory.getNames().toArray()) + "'\n"); } throw new PicoCompositionException(message.toString()); } final Bindings bindings = engine.createBindings(); bindings.put("parent", parentContainer); bindings.put("assemblyScope", assemblyScope); applyOtherBindings(bindings); reader = this.getScriptReader(); PicoContainer result = (PicoContainer) engine.eval(reader, bindings); if (result == null) { result = (PicoContainer) bindings.get("pico"); if (result == null) { // Todo: remove as a deprecated variable name result = (PicoContainer) bindings.get("nano"); if (result == null) { throw new PicoCompositionException( "Script completed successfully, but did not return any value, nor did it declare a variable named 'pico'"); } } } return result; } catch (final ClassCastException e) { throw new ScriptedPicoContainerMarkupException( "The return type of the script must be of type PicoContainer", e); } catch (final IOException e) { throw new ScriptedPicoContainerMarkupException( "IOException encountered, message -'" + e.getMessage() + "'", e); } catch (final ScriptException e) { throw new ScriptedPicoContainerMarkupException( "Error executing composition script under engine '" + engine.getFactory().getEngineName() + "'", e); } finally { if (applyCustomClassLoader()) { AccessController.doPrivileged( new PrivilegedAction<Void>() { public Void run() { Thread.currentThread().setContextClassLoader(oldClassLoader); return null; } }); } if (reader != null) { try { reader.close(); } catch (final IOException e) { // Ignore } } } }
@Override public List<String> getExtensions() { return factory.getExtensions(); }