Example usage for javax.script ScriptContext setWriter

List of usage examples for javax.script ScriptContext setWriter

Introduction

In this page you can find the example usage for javax.script ScriptContext setWriter.

Prototype

public void setWriter(Writer writer);

Source Link

Document

Sets the Writer for scripts to use when displaying output.

Usage

From source file:org.xwiki.rendering.macro.script.AbstractJSR223ScriptMacro.java

/**
 * Execute provided script and return {@link Block} based result.
 * /*from  w  ww  .  j  a  va2s.  c o m*/
 * @param engine the script engine to use to evaluate the script.
 * @param parameters the macro parameters.
 * @param content the script to execute.
 * @param context the context of the macro transformation.
 * @return the result of script execution.
 * @throws ScriptException failed to evaluate script
 * @throws MacroExecutionException failed to evaluate provided content.
 */
protected List<Block> evaluateBlock(ScriptEngine engine, P parameters, String content,
        MacroTransformationContext context) throws ScriptException, MacroExecutionException {
    List<Block> result;

    ScriptContext scriptContext = getScriptContext();

    StringWriter stringWriter = new StringWriter();

    // set writer in script context
    scriptContext.setWriter(stringWriter);

    try {
        Object scriptResult = eval(content, engine, scriptContext);

        if (scriptResult instanceof XDOM) {
            result = ((XDOM) scriptResult).getChildren();
        } else if (scriptResult instanceof Block) {
            result = Collections.singletonList((Block) scriptResult);
        } else if (scriptResult instanceof List && !((List<?>) scriptResult).isEmpty()
                && ((List<?>) scriptResult).get(0) instanceof Block) {
            result = (List<Block>) scriptResult;
        } else {
            // Run the wiki syntax parser on the script-rendered content
            result = parseScriptResult(stringWriter.toString(), parameters, context);
        }
    } finally {
        // remove writer script from context
        scriptContext.setWriter(null);
    }

    return result;
}