List of usage examples for javax.script ScriptContext setWriter
public void setWriter(Writer writer);
Writer
for scripts to use when displaying output. From source file:Main.java
public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("JavaScript"); File outputFile = new File("jsoutput.txt"); System.out.println("Script output will be written to " + outputFile.getAbsolutePath()); FileWriter writer = new FileWriter(outputFile); ScriptContext defaultCtx = engine.getContext(); defaultCtx.setWriter(writer); String script = "print('Hello custom output writer')"; engine.eval(script);/* www .j ava2 s . c o m*/ writer.close(); }
From source file:Main.java
public static void main(String[] args) throws Exception { ScriptContext ctx = new SimpleScriptContext(); // Get the reader and writers from the script context Reader inputReader = ctx.getReader(); Writer outputWriter = ctx.getWriter(); Writer errWriter = ctx.getErrorWriter(); // Write all script outputs to an out.txt file Writer fileWriter = new FileWriter("out.txt"); ctx.setWriter(fileWriter); }
From source file:jp.toastkid.script.runner.JavaScriptRunner.java
@Override public Optional<String> run(final String script) { if (StringUtils.isEmpty(script)) { return Optional.empty(); }//from ww w. j a v a2 s.c o m final StringBuilder result = new StringBuilder(); try (final StringWriter writer = new StringWriter();) { final ScriptContext context = engine.getContext(); context.setWriter(writer); context.setErrorWriter(writer); final java.lang.Object run = engine.eval(script); result.append(writer.toString()).append(LINE_SEPARATOR); if (run != null) { result.append("return = ").append(run.toString()); } writer.close(); } catch (final CompilationFailedException | IOException | ScriptException e) { e.printStackTrace(); result.append("Occurred Exception.").append(LINE_SEPARATOR).append(e.getMessage()); } return Optional.of(result.toString()); }
From source file:jp.toastkid.script.runner.GroovyRunner.java
@Override public Optional<String> run(final String script) { if (StringUtils.isEmpty(script)) { return Optional.empty(); }// w w w .j av a2s.c o m if (engine == null) { System.out.println("groovy null"); } final StringBuilder result = new StringBuilder(); try (final StringWriter writer = new StringWriter();) { if (engine != null) { final ScriptContext context = engine.getContext(); context.setWriter(new PrintWriter(writer)); context.setErrorWriter(new PrintWriter(writer)); } final java.lang.Object run = engine.eval(script); result.append(writer.toString()).append(LINE_SEPARATOR); if (run != null) { result.append("return = ").append(run.toString()); } writer.close(); } catch (final CompilationFailedException | IOException | javax.script.ScriptException e) { e.printStackTrace(); result.append("Occurred Exception.").append(LINE_SEPARATOR).append(e.getMessage()); } return Optional.of(result.toString()); }
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 w ww . j a v a 2 s .c om*/ 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 av a 2s . 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:org.jahia.ajax.gwt.helper.UIConfigHelper.java
/** * Get resources/* www . ja va 2 s. com*/ * * @param key * @param locale * @param site * @param jahiaUser * @return */ private String getResources(String key, Locale locale, JCRSiteNode site, JahiaUser jahiaUser) { if (key == null || key.length() == 0) { return key; } if (logger.isDebugEnabled()) { logger.debug("Resources key: " + key); } String baseName = null; String value = null; if (key.contains("@")) { baseName = StringUtils.substringAfter(key, "@"); key = StringUtils.substringBefore(key, "@"); } value = Messages.get(baseName, site != null ? site.getTemplatePackage() : null, key, locale, null); if (value == null || value.length() == 0) { value = Messages.getInternal(key, locale); } if (logger.isDebugEnabled()) { logger.debug("Resources value: " + value); } if (value.contains("${")) { try { ScriptEngine scriptEngine = scriptEngineUtils.getEngineByName("velocity"); ScriptContext scriptContext = new SimpleScriptContext(); final Bindings bindings = new SimpleBindings(); bindings.put("currentSite", site); bindings.put("currentUser", jahiaUser); bindings.put("currentLocale", locale); bindings.put("PrincipalViewHelper", PrincipalViewHelper.class); scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE); scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE), ScriptContext.GLOBAL_SCOPE); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); scriptEngine.eval(value, scriptContext); //String error = scriptContext.getErrorWriter().toString(); return scriptContext.getWriter().toString().trim(); } catch (ScriptException e) { logger.error("Error while executing script [" + value + "]", e); } } return value; }
From source file:org.jahia.modules.docrules.EmailDocumentRule.java
private String evaluate(String subject, JCRNodeWrapper document) { if (subject.contains("${")) { try {/*from ww w . j av a 2s .c om*/ ScriptEngine byName = ScriptEngineUtils.getInstance().getEngineByName("velocity"); ScriptContext scriptContext = byName.getContext(); final Bindings bindings = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE); bindings.put("document", document); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); byName.eval(subject, bindings); return scriptContext.getWriter().toString().trim(); } catch (ScriptException e) { logger.error("Error while evaluating value [" + subject + "]", e); } } return null; }
From source file:org.jahia.modules.macros.filter.MacrosFilter.java
@Override public String execute(String previousOut, RenderContext renderContext, Resource resource, RenderChain chain) throws Exception { if (StringUtils.isEmpty(previousOut)) { return previousOut; }/* w w w . j a v a 2s .co m*/ long timer = System.currentTimeMillis(); boolean evaluated = false; Matcher matcher = macrosPattern.matcher(previousOut); while (matcher.find()) { evaluated = true; String macroName = matcher.group(1); String[] macro = getMacro(macroName); if (macro != null) { try { // execute macro ScriptEngine scriptEngine = scriptEngineUtils.scriptEngine(macro[1]); ScriptContext scriptContext = scriptEngine.getContext(); scriptContext.setWriter(new StringWriter()); scriptContext.setErrorWriter(new StringWriter()); scriptEngine.eval(macro[0], getBindings(renderContext, resource, scriptContext, matcher)); String scriptResult = scriptContext.getWriter().toString().trim(); previousOut = matcher.replaceFirst(scriptResult); } catch (ScriptException e) { logger.warn("Error during execution of macro " + macroName + " with message " + e.getMessage(), e); previousOut = matcher.replaceFirst(macroName); } matcher = macrosPattern.matcher(previousOut); } else if (replaceByErrorMessageOnMissingMacros) { previousOut = matcher.replaceFirst("macro " + macroName + " not found"); logger.warn("Unknown macro '{}'", macroName); matcher = macrosPattern.matcher(previousOut); } } if (evaluated && logger.isDebugEnabled()) { logger.debug("Evaluation of macros took {} ms", (System.currentTimeMillis() - timer)); } return previousOut; }