Java Code Examples for javax.script.ScriptContext#setWriter()

The following examples show how to use javax.script.ScriptContext#setWriter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: VelocityScriptEngine.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate the given script.
 * If you wish to get a resulting string, call getContext().setWriter(new StringWriter()) then call toString()
 * on the returned writer.
 * @param reader script source reader
 * @param ctx script context
 * @return the script context writer (by default a PrintWriter towards System.out)
 * @throws ScriptException
 */
public Object eval(Reader reader, ScriptContext ctx)
                   throws ScriptException
{
    initVelocityEngine(ctx);
    String fileName = getFilename(ctx);
    VelocityContext vctx = getVelocityContext(ctx);
    Writer out = ctx.getWriter();
    if (out == null)
    {
        out = new StringWriter();
        ctx.setWriter(out);
    }
    try
    {
        velocityEngine.evaluate(vctx, out, fileName, reader);
        out.flush();
    }
    catch (Exception exp)
    {
        throw new ScriptException(exp);
    }
    return out;
}
 
Example 2
Source File: VelocityCompiledScript.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
@Override
public Object eval(ScriptContext scriptContext) throws ScriptException
{
    VelocityContext velocityContext = VelocityScriptEngine.getVelocityContext(scriptContext);
    Writer out = scriptContext.getWriter();
    if (out == null)
    {
        out = new StringWriter();
        scriptContext.setWriter(out);
    }
    try
    {
        template.merge(velocityContext, out);
        out.flush();
    }
    catch (Exception exp)
    {
        throw new ScriptException(exp);
    }
    return out;
}
 
Example 3
Source File: JSR223Tasklet.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	Database database = Factory.getSession(SessionType.CURRENT).getDatabase(databasePath_);

	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByExtension(scriptExt_);

	engine.put("database", database);
	engine.put("session", database.getAncestorSession());

	ScriptContext context = engine.getContext();
	context.setWriter(new PrintWriter(System.out));
	context.setErrorWriter(new PrintWriter(System.err));

	try {
		engine.eval(script_);
	} catch (ScriptException e) {
		throw new RuntimeException(e);
	}
}
 
Example 4
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 6 votes vote down vote up
@Test
public void test_method_invocation() throws Exception {
    ScriptEngine engine = new BshScriptEngineFactory().getScriptEngine();
    ScriptContext ctx = new SimpleScriptContext();
    StringWriter sw = new StringWriter();
    ctx.setWriter(sw);
    engine.setContext(ctx);
    engine.eval(
            "this.interpreter.print(new Object() {"
             + "public String toString() {"
                  +"return \"hello BeanShell\";"
             + "}"
          + "});"
        );
    assertEquals("hello BeanShell", sw.toString());
    sw.close();
}
 
Example 5
Source File: EventToolTest.java    From velocity-engine with Apache License 2.0 6 votes vote down vote up
public void testHelloWorldTool() throws ScriptException {
    ScriptContext context = engine.getContext();
    Properties properties = new Properties();
    properties.put("resource.loader", "class");
    properties.put("class.resource.loader.description", "Template Class Loader");
    properties.put("class.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    CustomEvent event = new CustomEvent("MyEvent");
    context.getBindings(ScriptContext.ENGINE_SCOPE).put("event", event);
    context.setAttribute(VelocityScriptEngine.VELOCITY_PROPERTIES_KEY, properties, ScriptContext.ENGINE_SCOPE);
    context.setAttribute(VelocityScriptEngine.FILENAME, "eventtool.vm", ScriptContext.ENGINE_SCOPE);
    Writer writer = new StringWriter();
    context.setWriter(writer);
    engine.eval("$event;\n" +
            "Event Created by $event.getName()\n" +
            "Event Created on $event.getDate()\n" +
            "Event ID is $event.getID()");
    // check string start
    String check = "This is a test event template: created by MyEvent on ";
    assertEquals(writer.toString().substring(0, check.length()), check);
}
 
Example 6
Source File: REPLPane.java    From sciview with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
   * Constructs an interpreter UI pane for a SciJava scripting REPL.
   *
   * @param context The SciJava application context to use
   */
  public REPLPane(final Context context) {
    context.inject(this);
    output = new OutputPane(log);
    final JScrollPane outputScroll = new JScrollPane(output);
    outputScroll.setPreferredSize(new Dimension(440, 400));

    repl = new ScriptREPL(context, output.getOutputStream());
    repl.initialize();

    final Writer writer = output.getOutputWriter();
    final ScriptContext ctx = repl.getInterpreter().getEngine().getContext();
    ctx.setErrorWriter(writer);
    ctx.setWriter(writer);

    vars = new VarsPane(context, repl);
    vars.setBorder(new EmptyBorder(0, 0, 8, 0));

    prompt = new REPLEditor(repl, vars, output);
    context.inject(prompt);
    prompt.setREPLLanguage("Python");
    final JScrollPane promptScroll = new JScrollPane(prompt);

    final JPanel bottomPane = new JPanel();
    bottomPane.setLayout(new MigLayout("ins 0", "[grow,fill][pref]", "[grow,fill,align top]"));
    bottomPane.add(promptScroll, "spany 2");

    final JSplitPane outputAndPromptPane =
            new JSplitPane(JSplitPane.VERTICAL_SPLIT, outputScroll, bottomPane);
    outputAndPromptPane.setResizeWeight(1);
//    outputAndPromptPane.setDividerSize(2);

    mainPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, vars,
            outputAndPromptPane);
    mainPane.setDividerSize(1);
    mainPane.setDividerLocation(0);
  }
 
Example 7
Source File: JavaPythonInteropUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenPythonScriptEngineIsAvailable_whenScriptInvoked_thenOutputDisplayed() throws Exception {
    StringWriter output = new StringWriter();
    ScriptContext context = new SimpleScriptContext();
    context.setWriter(output);

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("python");
    engine.eval(new FileReader(resolvePythonScriptPath("hello.py")), context);
    assertEquals("Should contain script output: ", "Hello Baeldung Readers!!", output.toString()
        .trim());
}
 
Example 8
Source File: ScriptManager.java    From snap-desktop with GNU General Public License v3.0 5 votes vote down vote up
private void configureEngine() {

        ScriptContext context = new SimpleScriptContext();
        context.setWriter(output);
        context.setErrorWriter(output);

        engine.setContext(context);
        engine.put("out", output);
        engine.put("err", output);

        output.println(MessageFormat.format("Script language set to {0}.", engine.getFactory().getLanguageName()));

        final URL url = findInitScript();
        if (url != null) {
            output.println(MessageFormat.format("Loading initialisation script ''{0}''...", url));
            execute0(url, new Observer() {
                @Override
                public void onSuccess(Object value) {
                }

                @Override
                public void onFailure(Throwable throwable) {
                    output.println("Failed to load initialisation script. " +
                            "BEAM-specific language extensions are disabled.");
                    throwable.printStackTrace(output);
                }
            });
            output.println("Initialisation script loaded. BEAM-specific language extensions are enabled.");
        } else {
            output.println("No initialisation script found. " +
                    "BEAM-specific language extensions are disabled.");
        }
    }
 
Example 9
Source File: ScriptConnection.java    From scriptella-etl with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new connection to JSR 223 scripting engine.
 *
 * @param parameters connection parameters.
 */
public ScriptConnection(ConnectionParameters parameters) {
    super(parameters);
    String lang = parameters.getStringProperty(LANGUAGE);
    ScriptEngineManager scriptEngineManager = new ScriptEngineManager(ScriptConnection.class.getClassLoader());
    if (StringUtils.isEmpty(lang)) { //JavaScript is used by default
        LOG.fine("Script language was not specified. JavaScript is default.");
        lang = "js";
    }

    ScriptEngine engine = scriptEngineManager.getEngineByName(lang);
    if (engine == null) {
        throw new ConfigurationException("Specified " + LANGUAGE + "=" + lang + " not supported. Available values are: " +
                getAvailableEngines(scriptEngineManager));
    }
    engineWrapper = new ScriptEngineWrapper(engine);
    LOG.fine("Script engine selected: " + engine.getFactory().getEngineName());
    if (engineWrapper.isCompilable()) {
        cache = new IdentityHashMap<>();
    } else {
        LOG.info("Engine " + engine.getFactory().getEngineName() + " does not support compilation. Running in interpreted mode.");
    }
    if (engineWrapper.isNashornScriptEngine()) {
        LOG.warning("Nashorn JavaScript Engine is not fully supported. \n" +
                "See https://github.com/scriptella/scriptella-etl/issues/2 for status and workarounds.");
    }
    if (!StringUtils.isEmpty(parameters.getUrl())) { //if url is specified
        url = parameters.getResolvedUrl();
        //setUp reader and writer for it
        ScriptContext ctx = engine.getContext();
        ctx.setReader(new LazyReader());
        //JS engine bug - we have to wrap with PrintWriter, because otherwise print function won't work.
        ctx.setWriter(new PrintWriter(new LazyWriter()));
    }
    encoding = parameters.getCharsetProperty(ENCODING);
    ScriptEngineFactory f = engine.getFactory();
    setDialectIdentifier(new DialectIdentifier(f.getLanguageName(), f.getLanguageVersion()));
}
 
Example 10
Source File: GroovyConsoleState.java    From Lemur with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void enable() {

    console = new Console();
    console.setShell(new EnhancedShell(console.getShell())); //, scriptList));
    console.run();        
 
    // See if we have any script text from last time
    Preferences prefs = Preferences.userNodeForPackage(getClass());
    final String lastText = prefs.get(PREF_LAST_SCRIPT, null);
 
    if( lastText != null ) { 
        SwingUtilities.invokeLater( new Runnable() {
            public void run() {
                console.getInputArea().setText(lastText);
            }
        });
    }            
 
    outputWindow = console.getOutputWindow();
    frame = (JFrame)console.getFrame();
    
    GroovyShell shell = console.getShell();
 
    // So now that the console has been "run" we need to set the script
    // engine's stdout to the latest stdout.  This is done through
    // jsr223's ScriptContext.  Many Bothans died to bring us this
    // information.
    ScriptContext context = engine.getContext();
    context.setWriter(new PrintWriter(System.out));
}
 
Example 11
Source File: TestBshScriptEngine.java    From beanshell with Apache License 2.0 5 votes vote down vote up
@Test
public void test_eval_writer_unicode() throws Exception {
    ScriptEngine engine = new BshScriptEngineFactory().getScriptEngine();
    ScriptContext ctx = new SimpleScriptContext();
    StringWriter sw = new StringWriter();
    ctx.setWriter(sw);
    engine.setContext(ctx);
    engine.eval("print('\\u3456');");
    assertEquals(new String("\u3456".getBytes(), "UTF-8").charAt(0),
            new String(sw.toString().getBytes(), "UTF-8").charAt(0));
}
 
Example 12
Source File: JSJavaScriptEngine.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 13
Source File: JSJavaScriptEngine.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 14
Source File: JSJavaScriptEngine.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 15
Source File: JSJavaScriptEngine.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 16
Source File: JSJavaScriptEngine.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 17
Source File: JSJavaScriptEngine.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 18
Source File: JSJavaScriptEngine.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
protected void start(boolean console) {
  ScriptContext context = engine.getContext();
  OutputStream out = getOutputStream();
  if (out != null) {
    context.setWriter(new PrintWriter(out));
  }
  OutputStream err = getErrorStream();
  if (err != null) {
    context.setErrorWriter(new PrintWriter(err));
  }
  // load "sa.js" initialization file
  loadInitFile();
  // load "~/jsdb.js" (if found) to perform user specific
  // initialization steps, if any.
  loadUserInitFile();

  JSJavaFactory fac = getJSJavaFactory();
  JSJavaVM jvm = (fac != null)? fac.newJSJavaVM() : null;
  // call "main" function from "sa.js" -- main expects
  // 'this' object and jvm object
  call("main", new Object[] { this, jvm });

  // if asked, start read-eval-print console
  if (console) {
    processSource(null);
  }
}
 
Example 19
Source File: JavaScriptingDataTransformer.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
protected Object evaluateExpression(Object expression, Map<String, Object> parameters) {
	try {
		Object result = null;
		StringWriter writer = new StringWriter();			
		
		ScriptContext context = new SimpleScriptContext();
		for (Map.Entry<String, Object> property : engineProperties.entrySet()) {
			context.setAttribute(property.getKey(), property.getValue(), ScriptContext.ENGINE_SCOPE);
		}
		Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
		bindings.putAll(parameters);
		context.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
		context.setWriter(writer);
		if (expression instanceof CompiledScript) {
			logger.debug("About to evaluate compiled expression {} with bindings {} on engine", expression, parameters, scriptEngine);
			result = ((CompiledScript) expression).eval(context);
		} else {
			logger.debug("About to evaluate expression {} with bindings {} on engine", expression, parameters, scriptEngine);
			result = scriptEngine.eval(expression.toString(), context);
		}
		if (result == null) {
			result = writer.toString();
		}
		return result;
	} catch (ScriptException e) {
		throw new RuntimeException("Error when evaluating script", e);
	}
}
 
Example 20
Source File: ConsoleContext.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
public void applyTo ( final ScriptContext scriptContext )
{
    scriptContext.setWriter ( new PrintWriter ( new OutputStreamWriter ( this.writerStream ) ) );
    scriptContext.setErrorWriter ( this.errorPrintWriter );
}