List of usage examples for javax.script ScriptEngineManager ScriptEngineManager
public ScriptEngineManager()
ScriptEngineManager(Thread.currentThread().getContextClassLoader())
. From source file:org.openhab.core.jsr223.internal.engine.scriptmanager.Script.java
public void loadScript(File file) throws FileNotFoundException, ScriptException, NoSuchMethodException { logger.info("Loading Script " + file.getName()); String extension = getFileExtension(file); ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByExtension(extension); if (engine != null) { logger.info("EngineName: " + engine.getFactory().getEngineName()); initializeSciptGlobals();// w ww . j a v a2 s. c o m engine.eval(new FileReader(file)); Invocable inv = (Invocable) engine; RuleSet ruleSet = (RuleSet) inv.invokeFunction("getRules"); rules.addAll(ruleSet.getRules()); } }
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 {/* w ww . jav a 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.mgmtp.jfunk.core.scripting.ScriptExecutor.java
/** * Executes the specified Groovy script. * * @param script/*from w ww . j a v a 2 s . c o m*/ * the script file * @param scriptProperties * properties that are set to the script engine's binding and thus will be available * as variables in the Groovy script * @return the execution result, {@code true} if successful, {@code false} code */ public boolean executeScript(final File script, final Properties scriptProperties) { checkState(script.exists(), "Script file does not exist: %s", script); checkState(script.canRead(), "Script file is not readable: %s", script); Reader reader = null; boolean success = false; Throwable throwable = null; scriptScope.enterScope(); ScriptContext ctx = scriptContextProvider.get(); try { reader = Files.newReader(script, charset); ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByExtension("groovy"); ctx.setScript(script); ctx.load(JFunkConstants.SCRIPT_PROPERTIES, false); ctx.registerReporter(new SimpleReporter()); initGroovyCommands(scriptEngine, ctx); initScriptProperties(scriptEngine, scriptProperties); ScriptMetaData scriptMetaData = scriptMetaDataProvider.get(); scriptMetaData.setScriptName(script.getPath()); Date startDate = new Date(); scriptMetaData.setStartDate(startDate); ctx.set(JFunkConstants.SCRIPT_START_MILLIS, String.valueOf(startDate.getTime())); eventBus.post(scriptEngine); eventBus.post(new BeforeScriptEvent(script.getAbsolutePath())); scriptEngine.eval(reader); success = true; } catch (IOException ex) { throwable = ex; log.error("Error loading script: " + script, ex); } catch (ScriptException ex) { throwable = ex; // Look up the cause hierarchy if we find a ModuleExecutionException. // We only need to log exceptions other than ModuleExecutionException because they // have already been logged and we don't want to pollute the log file any further. // In fact, other exception cannot normally happen. Throwable th = ex; while (!(th instanceof ModuleExecutionException)) { if (th == null) { // log original exception log.error("Error executing script: " + script, ex); success = false; break; } th = th.getCause(); } } finally { try { ScriptMetaData scriptMetaData = scriptMetaDataProvider.get(); Date endDate = new Date(); scriptMetaData.setEndDate(endDate); ctx.set(JFunkConstants.SCRIPT_END_MILLIS, String.valueOf(endDate.getTime())); scriptMetaData.setThrowable(throwable); eventBus.post(new AfterScriptEvent(script.getAbsolutePath(), success)); } finally { scriptScope.exitScope(); closeQuietly(reader); } } return success; }
From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java
@Test public void testNashornWithCompile() throws Exception { ScriptEngineManager engineManager = new ScriptEngineManager(); ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE); assertNotNull(engine);/* www. j a va 2s. c o m*/ Compilable compiler = (Compilable) engine; assertNotNull(compiler); InputStream stream = this.getClass().getResourceAsStream("/testScript" + ".js"); assertNotNull(stream); String js = IOUtils.toString(stream); CompiledScript compiled = compiler.compile(new StringReader(js)); engine.put("mapper", new Mapper()); compiled.eval(engine.getContext()); assertEquals("1" + System.lineSeparator() + "str" + System.lineSeparator() + "[1, 2, {a=1, b=2}]" + System.lineSeparator() + "{a=1, b=2}" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "This is a string" + System.lineSeparator() + "2" + System.lineSeparator() + "[A, B, C]" + System.lineSeparator() + "{a=salut, b=from java}" + System.lineSeparator() + "done" + System.lineSeparator(), outContent.toString()); }
From source file:com.orange.clara.cloud.servicedbdumper.config.CatalogConfig.java
private float getCostFromQuota(String quota, String formula) throws ParseException, ScriptException { long size = ByteFormat.parse(quota); String formulaInjected = formula.replaceAll("quota", String.valueOf(size * this.getDefaultCost())); ScriptEngineManager factory = new ScriptEngineManager(); ScriptEngine engine = factory.getEngineByName("JavaScript"); Object eval = engine.eval(formulaInjected); if (eval instanceof Integer) { return new Float((Integer) eval); }//from ww w.j a va2 s. c om if (eval instanceof Float) { return (Float) eval; } return Math.round((Double) eval); }
From source file:com.heisenberg.api.WorkflowEngineConfiguration.java
protected void initializeScriptEngineManager() { registerService(new ScriptEngineManager()); }
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 ww w .ja v a 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); } } preConfigure(); }
From source file:com.seajas.search.profiler.controller.ModifierController.java
/** * Available script languages.//from w w w.j a v a 2 s . com * * @return Map<String, String> */ @ModelAttribute("scriptLanguages") public Map<String, String> populateScriptLanguages() { Map<String, String> scriptLanguages = new LinkedHashMap<String, String>(); for (ScriptEngineFactory factory : new ScriptEngineManager().getEngineFactories()) if (factory.getLanguageName().equalsIgnoreCase("ECMAScript")) scriptLanguages.put(factory.getLanguageName(), "JavaScript"); else if (factory.getLanguageName().equalsIgnoreCase("Groovy") || factory.getLanguageName().equalsIgnoreCase("Scala") || factory.getLanguageName().equalsIgnoreCase("Ruby")) scriptLanguages.put(factory.getLanguageName(), StringUtils.capitalize(factory.getLanguageName())); scriptLanguages.put("xslt", "XSLT"); return scriptLanguages; }
From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java
@Test public void testGroovyFileAndParam() throws ScriptException, IOException { String engineName = "groovy"; ScriptEngineManager mgr = new ScriptEngineManager(); // create a JavaScript engine ScriptEngine engine = mgr.getEngineByName(engineName); assertNotNull("Can't find engine '" + engineName + "'", engine); File script = new ClassPathResource("test-data/test.groovy").getFile(); assertNotNull("Can't find test script", script); engine.put("gbtest", "testok"); // evaluate code from File engine.eval(new FileReader(script)); }
From source file:org.nyu.edu.dlts.CodeViewerDialog.java
/** * Method to evaluate the syntax of the script. * Basically try running and see if any syntax errors occur *//* ww w . ja v a 2s. com*/ private void evaluateButtonActionPerformed() { try { if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_JAVA)) { Interpreter bsi = new Interpreter(); bsi.set("record", new String("Test")); bsi.set("recordType", "test"); bsi.eval(getCurrentScript()); } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_RUBY)) { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine jri = manager.getEngineByName("jruby"); jri.put("recordType", "test"); jri.eval(getCurrentScript()); } else if (textArea.getSyntaxEditingStyle().equals(RSyntaxTextArea.SYNTAX_STYLE_PYTHON)) { PythonInterpreter pyi = new PythonInterpreter(); pyi.set("record", new String("Test")); pyi.set("recordType", "test"); pyi.exec(getCurrentScript()); } else { // must be java script ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine jsi = manager.getEngineByName("javascript"); jsi.put("record", new String("Test")); jsi.put("recordType", "test"); jsi.eval(getCurrentScript()); } messageTextArea.setText("No Syntax Errors Found ..."); } catch (Exception e) { messageTextArea.setText("Error Occurred:\n" + dbCopyFrame.getStackTrace(e)); } }