List of usage examples for javax.script Compilable compile
public CompiledScript compile(Reader script) throws ScriptException;
Reader
) for later execution. From source file:org.apache.accumulo.core.util.shell.commands.ScriptCommand.java
public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }//from ww w.jav a 2s . c o m ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:org.apache.accumulo.shell.commands.ScriptCommand.java
@Override public int execute(String fullCommand, CommandLine cl, Shell shellState) throws Exception { boolean invoke = false; ScriptEngineManager mgr = new ScriptEngineManager(); if (cl.hasOption(list.getOpt())) { listJSREngineInfo(mgr, shellState); } else if (cl.hasOption(file.getOpt()) || cl.hasOption(script.getOpt())) { String engineName = DEFAULT_ENGINE; if (cl.hasOption(engine.getOpt())) { engineName = cl.getOptionValue(engine.getOpt()); }/* w w w . j a v a 2 s .co m*/ ScriptEngine engine = mgr.getEngineByName(engineName); if (null == engine) { shellState.printException(new Exception(engineName + " not found")); return 1; } if (cl.hasOption(object.getOpt()) || cl.hasOption(function.getOpt())) { if (!(engine instanceof Invocable)) { shellState.printException( new Exception(engineName + " does not support invoking functions or methods")); return 1; } invoke = true; } ScriptContext ctx = new SimpleScriptContext(); // Put the following objects into the context so that they // are available to the scripts // TODO: What else should go in here? Bindings b = engine.getBindings(ScriptContext.ENGINE_SCOPE); b.put("connection", shellState.getConnector()); List<Object> argValues = new ArrayList<Object>(); if (cl.hasOption(args.getOpt())) { String[] argList = cl.getOptionValue(args.getOpt()).split(","); for (String arg : argList) { String[] parts = arg.split("="); if (parts.length == 0) { continue; } else if (parts.length == 1) { b.put(parts[0], null); argValues.add(null); } else if (parts.length == 2) { b.put(parts[0], parts[1]); argValues.add(parts[1]); } } } ctx.setBindings(b, ScriptContext.ENGINE_SCOPE); Object[] argArray = argValues.toArray(new Object[argValues.size()]); Writer writer = null; if (cl.hasOption(out.getOpt())) { File f = new File(cl.getOptionValue(out.getOpt())); writer = new FileWriter(f); ctx.setWriter(writer); } if (cl.hasOption(file.getOpt())) { File f = new File(cl.getOptionValue(file.getOpt())); if (!f.exists()) { if (null != writer) { writer.close(); } shellState.printException(new Exception(f.getAbsolutePath() + " not found")); return 1; } Reader reader = new FileReader(f); try { engine.eval(reader, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { reader.close(); if (null != writer) { writer.close(); } } } else if (cl.hasOption(script.getOpt())) { String inlineScript = cl.getOptionValue(script.getOpt()); try { if (engine instanceof Compilable) { Compilable compiledEng = (Compilable) engine; CompiledScript script = compiledEng.compile(inlineScript); script.eval(ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } else { engine.eval(inlineScript, ctx); if (invoke) { this.invokeFunctionOrMethod(shellState, engine, cl, argArray); } } } catch (ScriptException ex) { shellState.printException(ex); return 1; } finally { if (null != writer) { writer.close(); } } } if (null != writer) { writer.close(); } } else { printHelp(shellState); } return 0; }
From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java
public Object eval(ScriptEngine engine, String script, ScriptContext context) throws ScriptException { if (engine instanceof Compilable && ATTEMPT_COMPILATION) { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(script); return context != null ? cs.eval(context) : cs.eval(); }/*from ww w .ja v a2 s . c om*/ return context != null ? engine.eval(script, context) : engine.eval(script); }
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);//from w ww .ja v a 2 s .com 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.github.safrain.remotegsh.server.RgshFilter.java
@Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter("charset") != null) { charset = filterConfig.getInitParameter("charset"); } else {//w w w . j a v a2 s .com charset = DEFAULT_CHARSET; } if (filterConfig.getInitParameter("shellSessionTimeout") != null) { shellSessionTimeout = Long.valueOf(filterConfig.getInitParameter("shellSessionTimeout")); } else { shellSessionTimeout = SESSION_PURGE_INTERVAL; } String scriptExtensionCharset; if (filterConfig.getInitParameter("scriptExtensionCharset") != null) { scriptExtensionCharset = filterConfig.getInitParameter("scriptExtensionCharset"); } else { scriptExtensionCharset = DEFAULT_CHARSET; } //Compile script extensions List<String> scriptExtensionPaths = new ArrayList<String>(); if (filterConfig.getInitParameter("scriptExtensions") != null) { Collections.addAll(scriptExtensionPaths, filterConfig.getInitParameter("scriptExtensions").split(",")); } else { scriptExtensionPaths.add(RESOURCE_PATH + "extension/spring.groovy"); } scriptExtensions = new HashMap<String, CompiledScript>(); for (String path : scriptExtensionPaths) { String scriptContent; try { scriptContent = getResource(path, scriptExtensionCharset); } catch (IOException e) { throw new ServletException(e); } Compilable compilable = (Compilable) createGroovyEngine(); try { CompiledScript compiledScript = compilable.compile(scriptContent); scriptExtensions.put(path, compiledScript); } catch (ScriptException e) { //Ignore exceptions while compiling script extensions,there may be compilation errors due to missing dependency log.log(Level.WARNING, String.format("Error compiling script extension '%s'", path), e); } } // Setup a timer to purge timeout shell sessions Timer timer = new Timer("Remote Groovy Shell session purge daemon", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { purgeTimeOutSessions(); } }, 0, SESSION_PURGE_INTERVAL); }
From source file:com.aionemu.commons.scripting.AionScriptEngineManager.java
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (VERBOSE_LOADING) { log.info("Loading Script: " + file.getAbsolutePath()); }/*from www. j a v a 2 s . co m*/ if (PURGE_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && ATTEMPT_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (USE_COMPILED_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } }
From source file:fr.ens.transcriptome.corsen.calc.CorsenHistoryResults.java
/** * Set the custom expression// ww w .j a va 2 s. c om * @param expression The expression to set * @return true if the expression is correct */ public boolean setCustomExpression(final String expression) { this.script = null; if (expression == null || "".equals(expression.trim())) return true; ScriptEngine engine = new ScriptEngineManager().getEngineByName("js"); Compilable compilable = (Compilable) engine; try { final CompiledScript script = compilable.compile(expression); this.script = script; } catch (ScriptException e) { return false; } return true; }
From source file:com.l2jfree.gameserver.scripting.L2ScriptEngineManager.java
public void executeScript(ScriptEngine engine, File file) throws FileNotFoundException, ScriptException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file))); if (VERBOSE_LOADING) { _log.info("Loading Script: " + file.getAbsolutePath()); }/*w w w . java 2s.c o m*/ if (PURGE_ERROR_LOG) { String name = file.getAbsolutePath() + ".error.log"; File errorLog = new File(name); if (errorLog.isFile()) { errorLog.delete(); } } if (engine instanceof Compilable && ATTEMPT_COMPILATION) { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); ScriptContext ctx = engine.getContext(); try { engine.setContext(context); if (USE_COMPILED_CACHE) { CompiledScript cs = _cache.loadCompiledScript(engine, file); cs.eval(context); } else { Compilable eng = (Compilable) engine; CompiledScript cs = eng.compile(reader); cs.eval(context); } } finally { engine.setContext(ctx); setCurrentLoadingScript(null); context.removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); context.removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); context.removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } else { ScriptContext context = new SimpleScriptContext(); context.setAttribute("mainClass", getClassForFile(file).replace('/', '.').replace('\\', '.'), ScriptContext.ENGINE_SCOPE); context.setAttribute(ScriptEngine.FILENAME, file.getName(), ScriptContext.ENGINE_SCOPE); context.setAttribute("classpath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("sourcepath", SCRIPT_FOLDER.getAbsolutePath(), ScriptContext.ENGINE_SCOPE); context.setAttribute("parentLoader", ClassLoader.getSystemClassLoader(), ScriptContext.ENGINE_SCOPE); setCurrentLoadingScript(file); try { engine.eval(reader, context); } finally { setCurrentLoadingScript(null); engine.getContext().removeAttribute(ScriptEngine.FILENAME, ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("mainClass", ScriptContext.ENGINE_SCOPE); engine.getContext().removeAttribute("parentLoader", ScriptContext.ENGINE_SCOPE); } } }
From source file:org.freeplane.plugin.script.GenericScript.java
private void compileAndCache(Compilable engine) throws Throwable { if (compileTimeStrategy.canUseOldCompiledScript()) return;/* w w w . j av a2s.c o m*/ compiledScript = null; errorsInScript = null; try { scriptSource.rereadFile(); compileTimeStrategy.scriptCompileStart(); compiledScript = engine.compile(scriptSource.getScript()); compileTimeStrategy.scriptCompiled(); } catch (Throwable e) { errorsInScript = e; throw e; } }
From source file:com.netflix.genie.web.services.loadbalancers.script.ScriptLoadBalancer.java
/** * Check if the script file needs to be refreshed. *///from ww w .j a va 2 s . c o m public void refresh() { log.debug("Refreshing"); final long updateStart = System.nanoTime(); final Set<Tag> tags = Sets.newHashSet(); try { this.isUpdating.set(true); // Update the script timeout this.timeoutLength.set(this.environment.getProperty(ScriptLoadBalancerProperties.TIMEOUT_PROPERTY, Long.class, DEFAULT_TIMEOUT_LENGTH)); final String scriptFileSourceValue = this.environment .getProperty(ScriptLoadBalancerProperties.SCRIPT_FILE_SOURCE_PROPERTY); if (StringUtils.isBlank(scriptFileSourceValue)) { throw new IllegalStateException("Invalid empty value for script source file property: " + ScriptLoadBalancerProperties.SCRIPT_FILE_SOURCE_PROPERTY); } final String scriptFileSource = new URI(scriptFileSourceValue).toString(); final String scriptFileDestinationValue = this.environment .getProperty(ScriptLoadBalancerProperties.SCRIPT_FILE_DESTINATION_PROPERTY); if (StringUtils.isBlank(scriptFileDestinationValue)) { throw new IllegalStateException("Invalid empty value for script destination directory property: " + ScriptLoadBalancerProperties.SCRIPT_FILE_DESTINATION_PROPERTY); } final Path scriptDestinationDirectory = Paths.get(new URI(scriptFileDestinationValue)); // Check the validity of the destination directory if (!Files.exists(scriptDestinationDirectory)) { Files.createDirectories(scriptDestinationDirectory); } else if (!Files.isDirectory(scriptDestinationDirectory)) { throw new IllegalStateException("The script destination directory " + scriptDestinationDirectory + " exists but is not a directory"); } final String fileName = StringUtils.substringAfterLast(scriptFileSource, SLASH); if (StringUtils.isBlank(fileName)) { throw new IllegalStateException("No file name found from " + scriptFileSource); } final String scriptExtension = StringUtils.substringAfterLast(fileName, PERIOD); if (StringUtils.isBlank(scriptExtension)) { throw new IllegalStateException("No file extension available in " + fileName); } final Path scriptDestinationPath = scriptDestinationDirectory.resolve(fileName); // Download and cache the file (if it's not already there) this.fileTransferService.getFile(scriptFileSource, scriptDestinationPath.toUri().toString()); final ScriptEngine engine = this.scriptEngineManager.getEngineByExtension(scriptExtension); // We want a compilable engine so we can cache the script if (!(engine instanceof Compilable)) { throw new IllegalArgumentException("Script engine must be of type " + Compilable.class.getName()); } final Compilable compilable = (Compilable) engine; try (InputStream fis = Files.newInputStream(scriptDestinationPath); InputStreamReader reader = new InputStreamReader(fis, UTF_8)) { log.debug("Compiling {}", scriptFileSource); this.script.set(compilable.compile(reader)); } tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_OK)); this.isConfigured.set(true); } catch (final GenieException | IOException | ScriptException | RuntimeException | URISyntaxException e) { tags.add(Tag.of(MetricsConstants.TagKeys.STATUS, STATUS_TAG_FAILED)); tags.add(Tag.of(MetricsConstants.TagKeys.EXCEPTION_CLASS, e.getClass().getName())); log.error("Refreshing the load balancing script for ScriptLoadBalancer failed due to {}", e.getMessage(), e); this.isConfigured.set(false); } finally { this.isUpdating.set(false); this.registry.timer(UPDATE_TIMER_NAME, tags).record(System.nanoTime() - updateStart, TimeUnit.NANOSECONDS); log.debug("Refresh completed"); } }