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:ch.qos.logback.contrib.jackson.JacksonJsonFormatter.java

@Override
public String toJsonString(Map m) throws IOException {
    StringWriter writer = new StringWriter(BUFFER_SIZE);
    JsonGenerator generator = this.objectMapper.getFactory().createJsonGenerator(writer);

    if (isPrettyPrint()) {
        generator.useDefaultPrettyPrinter();
    }/*from ww  w .j  a v  a  2 s  .  c om*/

    this.objectMapper.writeValue(generator, m);

    writer.flush();

    return writer.toString();
}

From source file:org.josso.selfservices.password.EMailPasswordDistributor.java

protected String createMessageBody(SSOUser user, String clearPassword, ProcessState state)
        throws PasswordManagementException {

    try {//from  w  w  w .j a  va  2s.co  m

        if (logger.isDebugEnabled())
            logger.debug("Creating email body with Velocity template : " + getTemplate());

        // TODO : We should decouple this ..
        String url = (String) ((LostPasswordProcessState) state).getPasswordConfirmUrl();
        assert url == null : "No password confirmation url found in process state, attribute:'passwordConfirmUrl'";

        //create a new instance of the engine
        VelocityEngine ve = new VelocityEngine();

        // configure the engine :

        // Configure engine logger
        ve.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, logger);

        // Use classloader based resource loader
        ve.setProperty(VelocityEngine.RESOURCE_LOADER, "class");
        ve.setProperty("class.resource.loader.description", "Velocity Classpath Resource Loader");
        ve.setProperty("class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");

        //initialize the engine
        ve.init();

        // Build the proper velocity context
        VelocityContext ctx = new VelocityContext();

        ctx.put("jossoUser", user);
        ctx.put("jossoClearPassword", clearPassword);
        ctx.put("jossoProcessState", state);
        ctx.put("jossoConfirmUrl", url);

        // Find our template
        Template template = ve.getTemplate(this.template);

        // Process current template and produce the proper output.
        // 4Kb
        StringWriter w = new StringWriter(1024 * 4);
        template.merge(ctx, w);
        w.flush();
        return w.getBuffer().toString();

    } catch (ParseErrorException e) {
        throw new PasswordManagementException("Cannot generate e-mail : " + e.getMessage(), e);

    } catch (ResourceNotFoundException e) {
        throw new PasswordManagementException("Cannot generate e-mail : " + e.getMessage(), e);

    } catch (Exception e) {
        throw new PasswordManagementException("Cannot generate e-mail : " + e.getMessage(), e);

    }

}

From source file:org.latticesoft.util.common.StringUtil.java

/**
 * Gets the stack trace in string form.//from w w  w.  j  a  v a2s.  co  m
 * @param t the throwable to be parsed
 * @return the string form of the stack trace
 */
public static String getStackTraceMessage(Throwable t) {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);
    pw.flush();
    sw.flush();
    return sw.toString();
}

From source file:com.github.xmltopdf.JasperPdfGenerator.java

private String applyVelocityTemplate(String templateData) throws Exception {
    Properties properties = new Properties();
    properties.setProperty("resource.loader", "string");
    properties.setProperty("string.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.StringResourceLoader");
    properties.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem");
    properties.setProperty("userdirective",
            "com.github.xmltopdf.MoneyUAHDirective," + "com.github.xmltopdf.MoneyToStrDirective,"
                    + "com.github.xmltopdf.DateDirective," + "com.github.xmltopdf.UkrToLatinDirective");
    Velocity.init(properties);//from w  w  w .j  av a 2 s .  c o  m

    StringResourceRepository repo = StringResourceLoader.getRepository();
    repo.putStringResource("template", templateData);
    Template template = Velocity.getTemplate("template", "UTF-8");
    StringWriter writer = new StringWriter();
    VelocityContext context = new VelocityContext();
    context.put("xml", xmlTag);
    template.merge(context, writer);
    writer.flush();
    writer.close();
    return writer.toString();
}

From source file:mx.redhat.jbpm.CustomType.FileCustomType.java

public String renderField(String fieldName, String path, String namespace, boolean showInput) {
    /*// w  w w  .j  ava2 s .co m
     * We are using a .ftl template to generate the HTML to show on screen, as it is a sample you can use any other way to do that.
     * To see the template format look at input.ftl on the resources folder.
     */
    String str = null;
    try {
        File file = null;
        if (!StringUtils.isEmpty(path)) {
            file = fileStorageService.getFile(path);
        }

        Map<String, Object> context = new HashMap<String, Object>();

        // if there is a file in the specified path, the input will show a link to download it.
        context.put("inputId", namespace + "_file_" + fieldName);
        if (file != null && file.exists()) {
            /*
             * Building the parameter map for the download link.
             * We are encoding the file path in order to make a download link cleaner
             */
            Map params = new HashMap();
            params.put("content", Base64.encodeBase64String(path.getBytes()));

            /*
             * Building the download link:
             * For this sample we created a FileDownloadHandler that will execute the download action. We used the @Named("fdch") annotation to identify it.
             * To generate the link we are using the URLMarkupGenerator from jbpm-form-modeler-request-dispatcher module. It generates a markup to the FileDownloadHandler
             * using the parameters:
             * "fdch"       -> Identifier of the Bean that will execute the action (you can also use the Canonical Name of the Bean "org.jbpm.formModeler.core.fieldTypes.file.FileDownloadHandler")
             * "download"   -> Action to execute
             * params       -> A map containing the parameters that the action requires. In that case only the file path in Base64.
             */
            String downloadLink = urlMarkupGenerator.getMarkup("fdch", "download", params);

            context.put("showLink", Boolean.TRUE);
            context.put("downloadLink", downloadLink);
            context.put("fileName", file.getName());
            context.put("fileSize", getFileSize(file.length()));
            context.put("fileIcon", getFileIcon(file));
            context.put("dropIcon", dropIcon);
        } else {
            context.put("showLink", Boolean.FALSE);
        }
        // If the field is readonly or we are just showing the field value we will hide the input file.
        context.put("showInput", showInput);

        InputStream src = this.getClass().getResourceAsStream("/input.ftl");
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        BeansWrapper defaultInstance = new BeansWrapper();
        defaultInstance.setSimpleMapWrapper(true);
        cfg.setObjectWrapper(defaultInstance);
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(fieldName, new InputStreamReader(src), cfg);
        StringWriter out = new StringWriter();
        temp.process(context, out);
        out.flush();
        str = out.getBuffer().toString();
    } catch (Exception e) {
        log.warn("Failed to process template for field '{}'", fieldName, e);
    }
    return str;
}

From source file:org.jbpm.formModeler.core.fieldTypes.file.FileCustomType.java

public String renderField(String fieldName, String path, String namespace, boolean showInput) {
    /*/* w ww.j a  v  a  2 s.  co m*/
     * We are using a .ftl template to generate the HTML to show on screen, as it is a sample you can use any other way to do that.
     * To see the template format look at input.ftl on the resources folder.
     */
    String str = null;
    try {
        File file = null;
        if (!StringUtils.isEmpty(path)) {
            file = fileStorageService.getFile(path);
        }

        Map<String, Object> context = new HashMap<String, Object>();

        // if there is a file in the specified path, the input will show a link to download it.
        context.put("inputId", namespace + "_file_" + fieldName);
        if (file != null && file.exists()) {
            /*
             * Building the parameter map for the download link.
             * We are encoding the file path in order to make a download link cleaner
             */
            Map params = new HashMap();
            params.put("content", Base64.encodeBase64String(path.getBytes()));

            /*
             * Building the download link:
             * For this sample we created a FileDownloadHandler that will execute the download action. We used the @Named("fdch") annotation to identify it.
             * To generate the link we are using the URLMarkupGenerator from jbpm-form-modeler-request-dispatcher module. It generates a markup to the FileDownloadHandler
             * using the parameters:
             * "fdch"       -> Identifier of the Bean that will execute the action (you can also use the Canonical Name of the Bean "org.jbpm.formModeler.core.fieldTypes.file.FileDownloadHandler")
             * "download"   -> Action to execute
             * params       -> A map containing the parameters that the action requires. In that case only the file path in Base64.
             */
            String downloadLink = urlMarkupGenerator.getMarkup("fdch", "download", params);

            context.put("showLink", Boolean.TRUE);
            context.put("downloadLink", downloadLink);
            context.put("fileName", file.getName());
            context.put("fileSize", getFileSize(file.length()));
            context.put("fileIcon", getFileIcon(file));
            context.put("dropIcon", dropIcon);
        } else {
            context.put("showLink", Boolean.FALSE);
        }
        // If the field is readonly or we are just showing the field value we will hide the input file.
        context.put("showInput", showInput);

        InputStream src = this.getClass().getResourceAsStream("input.ftl");
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        BeansWrapper defaultInstance = new BeansWrapper();
        defaultInstance.setSimpleMapWrapper(true);
        cfg.setObjectWrapper(defaultInstance);
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(fieldName, new InputStreamReader(src), cfg);
        StringWriter out = new StringWriter();
        temp.process(context, out);
        out.flush();
        str = out.getBuffer().toString();
    } catch (Exception e) {
        log.warn("Failed to process template for field '{}'", fieldName, e);
    }
    return str;
}

From source file:uk.nhs.cfh.dsp.srth.desktop.uiframework.utils.GoogleFormErrorReporter.java

private String stackTraceToString(Throwable t) {

    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    t.printStackTrace(pw);//from  w ww  . ja  v a 2  s .  c o m
    pw.flush();
    sw.flush();

    return NEW_LINE_CHAR + sw.toString() + NEW_LINE_CHAR;
}

From source file:org.jbpm.formModeler.fieldTypes.document.handling.JBPMDocumentFieldTypeHandler.java

public String renderField(Document document, Field field, String inputName, boolean showInput,
        boolean readonly) {
    String str = null;/*from  w  ww . jav a  2s .  c  o m*/
    try {
        String contextPath = ControllerStatus.lookup().getRequest().getRequestObject().getContextPath();

        Map<String, Object> context = new HashMap<String, Object>();

        // if there is a file in the specified id, the input will show a link to download it.
        context.put("inputId", inputName);
        if (document != null) {

            if (StringUtils.isEmpty(document.getIdentifier())) {
                context.put("showLink", Boolean.FALSE);
            } else {
                context.put("showLink", Boolean.TRUE);
                context.put("downloadLink", document.getLink());
            }

            context.put("showDownload", Boolean.TRUE);
            context.put("fileName", StringEscapeUtils.escapeHtml4(document.getName()));
            context.put("fileSize", getFileSize(document.getSize()));
            context.put("fileIcon", contextPath + getFileIcon(document));
            context.put("dropIcon", contextPath + dropIcon);
        } else {
            context.put("showDownload", Boolean.FALSE);
        }
        context.put("readonly", readonly);
        context.put("showInput", showInput);

        InputStream src = this.getClass().getResourceAsStream("input.ftl");
        freemarker.template.Configuration cfg = new freemarker.template.Configuration();
        BeansWrapper defaultInstance = new BeansWrapper();
        defaultInstance.setSimpleMapWrapper(true);
        cfg.setObjectWrapper(defaultInstance);
        cfg.setTemplateUpdateDelay(0);
        Template temp = new Template(inputName, new InputStreamReader(src), cfg);
        StringWriter out = new StringWriter();
        temp.process(context, out);
        out.flush();
        str = out.getBuffer().toString();
    } catch (Exception e) {
        log.warn("Failed to process template for field '{}': {}", field.getFieldName(), e);
    }
    return str;
}

From source file:org.tequila.template.directive.freemarker.FileSection.java

@Override
public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) {
    log.debug("Executing <@" + getDirectiveName() + " .../>");

    // Check if params were given
    if (params.isEmpty()) {
        throw new DirectiveException(
                "<@" + getDirectiveName() + " .../> 'path, name' are required parameters.");
    }//from   w w w . ja v  a 2  s. c o  m

    if (loopVars.length != 0) {
        throw new DirectiveException("<@" + getDirectiveName() + " .../> doesn't allow loop variables.");
    }

    // If there is non-empty nested content:
    if (body != null) {
        try {
            // Executes the nested body. Same as <#nested> in FTL, except
            // that we use our own writer instead of the current output writer.
            String path = null;
            String name = null;
            String appendBeforeLast = null;
            Set<Entry<String, SimpleScalar>> entrySet = params.entrySet();
            for (Entry<String, SimpleScalar> entry : entrySet) {
                String key = entry.getKey();
                SimpleScalar value = entry.getValue();
                if (key.equals(PATH)) {
                    path = value.getAsString();
                } else if (key.equals(NAME)) {
                    name = value.getAsString();
                } else if (key.equals(APPEND_BEFORE_LAST)) {
                    appendBeforeLast = value.getAsString();
                } else {
                    throw new DirectiveException(
                            "<@" + getDirectiveName() + " .../> doesn't allow " + key + " parameter");
                }
            }

            // write the file
            StringWriter sw = new StringWriter();
            BufferedWriter bw = new BufferedWriter(sw);
            body.render(bw);
            env.getOut().flush();
            bw.flush();
            sw.flush();
            bw.close();
            sw.close();
            TemplateProcessed tp = new TemplateProcessed();
            tp.setTemplateResult(sw.toString());
            tp.setOutputFolder(path);
            tp.setOutputFileName(name);

            // notificar a los observadores
            super.setChanged();
            super.notifyObservers(tp);

        } catch (TemplateException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        } catch (IOException ex) {
            throw new DirectiveException("Error al ejecutar la directiva '" + getDirectiveName() + "'", ex);
        }

    } else {
        throw new DirectiveException("missing body");
    }
}

From source file:org.apache.ode.utils.xsl.XslTransformHandler.java

/**
 * Transforms a Source document to a result using the XSL stylesheet referenced
 * by the provided URI. The stylesheet MUST have been parsed previously.
 * @param uri referencing the stylesheet
 * @param source XML document//from w w w.ja v a  2s  .co m
 * @param parameters passed to the stylesheet
 * @param resolver used to resolve includes and imports
 * @return result of the transformation (XSL, HTML or text depending of the output method specified in stylesheet.
 */
public Object transform(QName processQName, URI uri, Source source, Map<QName, Object> parameters,
        URIResolver resolver) {
    Templates tm;
    synchronized (_templateCache) {
        tm = (Templates) _templateCache.get(processQName, uri);
    }
    if (tm == null)
        throw new XslTransformException("XSL sheet" + uri + " has not been parsed before transformation!");
    try {
        Transformer tf = tm.newTransformer();
        tf.setURIResolver(resolver);
        if (parameters != null) {
            for (Map.Entry<QName, Object> param : parameters.entrySet()) {
                tf.setParameter(param.getKey().getLocalPart(), param.getValue());
            }
        }
        String method = tf.getOutputProperties().getProperty("method");
        if (method == null || "xml".equals(method)) {
            DOMResult result = new DOMResult();
            tf.transform(source, result);
            Node node = result.getNode();
            if (node.getNodeType() == Node.DOCUMENT_NODE)
                node = ((Document) node).getDocumentElement();
            if (__log.isDebugEnabled())
                __log.debug("Returned node: type=" + node.getNodeType() + ", " + DOMUtils.domToString(node));
            return node;
        } else {
            // text and html outputs are handled the same way
            StringWriter writerResult = new StringWriter();
            StreamResult result = new StreamResult(writerResult);
            tf.transform(source, result);
            writerResult.flush();
            String output = writerResult.toString();
            if (__log.isDebugEnabled())
                __log.debug("Returned string: " + output);
            return output;
        }
    } catch (TransformerConfigurationException e) {
        throw new XslTransformException(e);
    } catch (TransformerException e) {
        throw new XslTransformException("XSL Transformation failed!", e);
    }
}