Example usage for java.io StringWriter flush

List of usage examples for java.io StringWriter flush

Introduction

In this page you can find the example usage for java.io StringWriter flush.

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:com.netflix.zeno.json.JsonSerializationFramework.java

public <K, V> String serializeJsonMap(String keyType, String valueType, Map<K, V> map, boolean pretty) {
    NFTypeSerializer<K> keySerializer = getSerializer(keyType);
    NFTypeSerializer<V> valueSerializer = getSerializer(valueType);

    MapSerializer<K, V> mapSerializer = new MapSerializer<K, V>(keySerializer, valueSerializer);
    mapSerializer.setSerializationFramework(this);

    StringWriter writer = new StringWriter();
    JsonWriteGenericRecord record = new JsonWriteGenericRecord(writer, pretty);

    record.open();//from   ww  w  .jav  a  2 s  .c  om
    mapSerializer.serialize(map, record);
    record.close();
    writer.flush();
    return writer.toString();
}

From source file:com.yukthi.persistence.NativeQueryFactory.java

/**
 * Fetches the query template with specified "name" and builds the query using specified "context".
 * If the query uses "param" directive, corresponding values will be collected into "paramValues".
 * //  w  ww.ja va2 s. c  o  m
 * @param name Name of the query to be fetched
 * @param paramValues Collected param values that needs to be passed to query as prepared statement params
 * @param context Context to be used to parse template into query
 * @return Built query
 */
public String buildQuery(String name, List<Object> paramValues, Object context) {
    Template template = templateMap.get(name);

    //if template is not found build it from raw query
    if (template == null) {
        String rawQuery = queryMap.get(name);

        //if no query found with specified name
        if (rawQuery == null) {
            throw new InvalidArgumentException("No query found with specified name - {}", name);
        }

        //build the free marker template from raw query
        try {
            template = new Template(name, rawQuery, configuration);
            templateMap.put(name, template);
        } catch (Exception ex) {
            throw new InvalidStateException(ex, "An error occurred while loading query template - {}", name);
        }
    }

    try {
        //process the template into query
        StringWriter writer = new StringWriter();
        template.process(context, writer);

        writer.flush();

        //build the final query (replacing the param expressions)
        String query = writer.toString();
        StringBuffer finalQuery = new StringBuffer();
        Matcher matcher = QUERY_PARAM_PATTERN.matcher(query);
        String property = null;

        while (matcher.find()) {
            property = matcher.group(1);
            matcher.appendReplacement(finalQuery, "?");

            paramValues.add(PropertyUtils.getProperty(context, property));
        }

        matcher.appendTail(finalQuery);

        return finalQuery.toString();
    } catch (Exception ex) {
        throw new InvalidStateException(ex, "An exception occurred while building query: " + name);
    }
}

From source file:com.netflix.zeno.json.JsonSerializationFramework.java

public <T> String serializeAsJson(String type, T object, boolean pretty) {
    StringWriter writer = new StringWriter();

    JsonWriteGenericRecord record = new JsonWriteGenericRecord(writer, pretty);

    record.open();// w  w w .  j  a  v  a 2 s  . c  o m
    getSerializer(type).serialize(object, record);
    record.close();
    writer.flush();

    return writer.toString();
}

From source file:org.j2free.util.ServletUtils.java

/**
 * @return the stack trace of a Throwable object as a String
 * @param t the Throwable item//from   ww  w.  j  a  v a2s.c  o m
 */
public static String throwableToString(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw, true);
    t.printStackTrace(pw);
    pw.flush();
    sw.flush();
    return sw.toString();
}

From source file:org.projectforge.business.scripting.GroovyExecutor.java

public String executeTemplate(final TemplateEngine templateEngine, final String template,
        final Map<String, Object> variables) {
    securityChecks(template);/*  w  ww .j a  v  a 2 s . c  o m*/
    if (template == null) {
        return null;
    }
    try {
        final Template templateObject = templateEngine.createTemplate(template);
        final Writable writable = templateObject.make(variables);
        final StringWriter writer = new StringWriter();
        writable.writeTo(writer);
        writer.flush();
        if (log.isDebugEnabled() == true) {
            log.debug(writer.toString());
        }
        return writer.toString();
    } catch (final CompilationFailedException ex) {
        log.error(ex.getMessage() + " while executing template: " + template, ex);
    } catch (final FileNotFoundException ex) {
        log.error(ex.getMessage() + " while executing template: " + template, ex);
    } catch (final ClassNotFoundException ex) {
        log.error(ex.getMessage() + " while executing template: " + template, ex);
    } catch (final IOException ex) {
        log.error(ex.getMessage() + " while executing template: " + template, ex);
    }
    return null;
}

From source file:de.thischwa.pmcms.view.renderer.VelocityRenderer.java

/**
 * Renders a string with respect of possible context objects.
 * /*  ww  w. j a v a2  s.  c om*/
 * @param stringToRender
 *            A string to render.
 * @param contextObjects
 *            Context object. It could be null or empty too.
 * @return The rendered string.
 */
public String renderString(final String stringToRender, final Map<String, Object> contextObjects) {
    if (StringUtils.isBlank(stringToRender))
        return "";

    StringWriter stringWriter = new StringWriter();
    renderString(stringWriter, stringToRender, contextObjects);
    stringWriter.flush();
    IOUtils.closeQuietly(stringWriter);
    return stringWriter.toString();
}

From source file:com.glaf.template.engine.FreemarkerTemplateEngine.java

public void evaluate(String name, String content, Map<String, Object> context, Writer writer) {
    try {/*from w ww .java  2  s  .  com*/
        long startTime = System.currentTimeMillis();
        StringWriter out = new StringWriter();

        freemarker.template.Template t = freemarker.template.Template.getPlainTextTemplate(name, content,
                configuration);
        t.process(context, out);
        out.flush();
        out.close();
        String text = out.toString();
        writer.write(text);
        long endTime = System.currentTimeMillis();
        long renderTime = (endTime - startTime);

        logger.debug("Rendered [" + name + "] in " + renderTime + " milliseconds");
        logger.debug(text);
    } catch (Exception ex) {
        logger.debug("error template content:" + content);
        throw new RuntimeException(ex);
    }
}

From source file:be.solidx.hot.web.deprecated.ScriptExecutorController.java

public String handleScriptPOST(WebRequest webRequest, String scriptName, Writer writer) {
    try {/*from  w w  w .  ja  v  a2 s  .  c o m*/
        scriptName = scriptName + getScriptExtension();
        Script<COMPILED_SCRIPT> script = buildScript(IOUtils.toByteArray(loadResource(scriptName)), scriptName);
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        Object result = scriptExecutor.execute(script, webRequest, dbMap, printWriter);
        printWriter.flush();
        stringWriter.flush();
        if (result == null)
            throw new Exception("POST handling scripts must return a page URL to redirect to");
        return "redirect:/" + (String) result;
    } catch (Exception e) {
        printErrorPage(e, writer);
        return null;
    }
}

From source file:org.springframework.boot.autoconfigure.web.BasicErrorController.java

@Override
public Map<String, Object> extract(RequestAttributes attributes, boolean trace, boolean log) {
    Map<String, Object> map = new LinkedHashMap<String, Object>();
    map.put("timestamp", new Date());
    try {//  w w  w.  ja v a2s . co m
        Throwable error = (Throwable) attributes.getAttribute(ErrorController.class.getName(),
                RequestAttributes.SCOPE_REQUEST);
        Object obj = attributes.getAttribute("javax.servlet.error.status_code",
                RequestAttributes.SCOPE_REQUEST);
        int status = 999;
        if (obj != null) {
            status = (Integer) obj;
            map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
        } else {
            map.put(ERROR_KEY, "None");
        }
        map.put("status", status);
        if (error == null) {
            error = (Throwable) attributes.getAttribute("javax.servlet.error.exception",
                    RequestAttributes.SCOPE_REQUEST);
        }
        if (error != null) {
            while (error instanceof ServletException && error.getCause() != null) {
                error = ((ServletException) error).getCause();
            }
            map.put("exception", error.getClass().getName());
            addMessage(map, error);
            if (trace) {
                StringWriter stackTrace = new StringWriter();
                error.printStackTrace(new PrintWriter(stackTrace));
                stackTrace.flush();
                map.put("trace", stackTrace.toString());
            }
            if (log) {
                this.logger.error(error);
            }
        } else {
            Object message = attributes.getAttribute("javax.servlet.error.message",
                    RequestAttributes.SCOPE_REQUEST);
            map.put("message", message == null ? "No message available" : message);
        }
        String path = (String) attributes.getAttribute("javax.servlet.error.request_uri",
                RequestAttributes.SCOPE_REQUEST);
        map.put("path", path == null ? "No path available" : path);
        return map;
    } catch (Exception ex) {
        map.put(ERROR_KEY, ex.getClass().getName());
        map.put("message", ex.getMessage());
        if (log) {
            this.logger.error(ex);
        }
        return map;
    }
}

From source file:org.apache.axis2.jaxws.message.util.Reader2Writer.java

/**
 * Utility method to write the reader contents to a String
 * @return String/*w  w  w  .  j  ava2s.c  o  m*/
 */
public String getAsString() throws XMLStreamException {
    StringWriter sw = new StringWriter();
    XMLStreamWriter writer = StAXUtils.createXMLStreamWriter(sw);

    // Write the reader to the writer
    outputTo(writer);

    // Flush the writer and get the String
    writer.flush();
    sw.flush();
    String str = sw.toString();
    writer.close();
    return str;
}