Example usage for javax.script SimpleScriptContext setReader

List of usage examples for javax.script SimpleScriptContext setReader

Introduction

In this page you can find the example usage for javax.script SimpleScriptContext setReader.

Prototype

public void setReader(Reader reader) 

Source Link

Usage

From source file:org.apache.felix.webconsole.plugins.scriptconsole.internal.ScriptConsolePlugin.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    final String contentType = getContentType(req);
    resp.setContentType(contentType);/*from ww w  . j  av a  2s . c o  m*/
    if (contentType.startsWith("text/")) {
        resp.setCharacterEncoding("UTF-8");
    }
    final String script = getCodeValue(req);
    final Bindings bindings = new SimpleBindings();
    final PrintWriter pw = resp.getWriter();
    final ScriptHelper osgi = new ScriptHelper(getBundleContext());
    final Writer errorWriter = new LogWriter(log);
    final Reader reader = new StringReader(script);
    //Populate bindings
    bindings.put("request", req);
    bindings.put("reader", reader);
    bindings.put("response", resp);
    bindings.put("out", pw);
    bindings.put("osgi", osgi);

    //Also expose the bundleContext to simplify scripts interaction with the
    //enclosing OSGi container
    bindings.put("bundleContext", getBundleContext());

    final String lang = WebConsoleUtil.getParameter(req, "lang");
    final boolean webClient = "webconsole".equals(WebConsoleUtil.getParameter(req, "client"));

    SimpleScriptContext sc = new SimpleScriptContext();
    sc.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
    sc.setWriter(pw);
    sc.setErrorWriter(errorWriter);
    sc.setReader(reader);

    try {
        log.log(LogService.LOG_DEBUG, "Executing script" + script);
        eval(script, lang, sc);
    } catch (Throwable t) {
        if (!webClient) {
            resp.setStatus(500);
        }
        pw.println(exceptionToString(t));
        log.log(LogService.LOG_ERROR, "Error in executing script", t);
    } finally {
        if (osgi != null) {
            osgi.cleanup();
        }
    }
}