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:ome.dsl.utests.ExampleUsageTest.java

@Test
public void testWithWriting() throws Exception {
    sr.parse();/*w w  w. jav a  2  s  .c om*/
    List list = sr.process();
    for (Iterator it = list.iterator(); it.hasNext();) {
        SemanticType st = (SemanticType) it.next();
        VelocityHelper vh = new VelocityHelper();
        vh.put("type", st);
        // FileWriter fw = new
        // FileWriter("/tmp/"+st.getId().replaceAll("[.]","_")+".hbm.xml");
        StringWriter sw = new StringWriter();
        vh.invoke(DSLTask.getStream("ome/dsl/object.vm"), sw);
        sw.flush();
        sw.close();
        // fw.flush();
        // fw.close();
    }

}

From source file:org.apache.streams.data.moreover.MoreoverClient.java

private String getArticles(URL url) throws IOException {
    HttpURLConnection cn = (HttpURLConnection) url.openConnection();
    cn.setRequestMethod("GET");
    cn.addRequestProperty("Content-Type", "text/xml;charset=UTF-8");
    cn.setDoInput(true);//from  w  ww  .  jav  a 2  s .  c  om
    cn.setDoOutput(false);
    StringWriter writer = new StringWriter();
    IOUtils.copy(new InputStreamReader(cn.getInputStream(), Charset.forName("UTF-8")), writer);
    writer.flush();
    pullTime = new Date().getTime();

    // added after seeing java.net.SocketException: Too many open files
    cn.disconnect();

    return writer.toString();
}

From source file:org.jbpm.formModeler.core.fieldTypes.auto.AutocompleteCustomType.java

public String renderField(String fieldName, Object value, String namespace, boolean showInput,
        String... params) {// w  w  w  .  ja va2 s  . com
    /*
     * 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 {

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

        context.put("fieldName", fieldName);
        if (value != null && value instanceof String)
            context.put("value", value);
        else
            context.put("value", "");

        context.put("inputId", namespace + "_autocomplete_" + fieldName);
        // TODO Not sure how to use:
        context.put("showInput", showInput);

        // REST URL
        context.put("restURL", params[0]);
        // property
        context.put("property", params[1]);

        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:ome.dsl.utests.ExampleUsageTest.java

/** disabling; need proper logic to find common/ component FIXME */
public void DISABLEDtestReal() throws Exception {
    File currentDir = new File(System.getProperty("user.dir"));// TODO Util
    File mappings = new File(currentDir.getParent() + File.separator + "common" + File.separator + "resources"
            + File.separator + "Mappings.ome.xml"); // FIXME circular deps.
    log.error(mappings);/*from   w ww  . j a  va 2  s.  com*/
    SaxReader nsr = new SaxReader("psql", mappings);
    nsr.parse();
    for (Iterator it = nsr.process().iterator(); it.hasNext();) {
        SemanticType st = (SemanticType) it.next();
        VelocityHelper vh = new VelocityHelper();
        vh.put("type", st);
        // FileWriter fw = new
        // FileWriter("/tmp/"+st.getId().replaceAll("[.]","_")+".hbm.xml");
        StringWriter sw = new StringWriter();
        vh.invoke(DSLTask.getStream("ome/dsl/mapping.vm"), sw);
        sw.flush();
        sw.close();
        // fw.flush();
        // fw.close();
    }
}

From source file:org.slc.sli.dashboard.util.DashboardExceptionResolver.java

/**
 * This method is converts the stack trace to a string
 * @param t, Throwable/*from w  w  w.  j a  v  a  2  s  .com*/
 * @return returns a String of exception stack trace
 */
public String getStackTrace(Throwable t) {
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter, true);
    t.printStackTrace(printWriter);
    printWriter.flush();
    stringWriter.flush();
    return stringWriter.toString();
}

From source file:com.jayway.jsonpath.internal.spi.json.JacksonJsonProvider.java

@Override
public String toJson(Object obj) {
    StringWriter writer = new StringWriter();
    try {/* w  ww  .j av  a  2 s  .  c o  m*/
        JsonGenerator generator = objectMapper.getFactory().createGenerator(writer);
        objectMapper.writeValue(generator, obj);
        writer.flush();
        writer.close();
        generator.close();
        return writer.getBuffer().toString();
    } catch (IOException e) {
        throw new InvalidJsonException();
    }
}

From source file:com.aurel.track.util.event.MailHandler.java

/**
 * Send e-mail to a person/*from  w w  w .  ja va2 s. co  m*/
 * @param sendToPerson
 * @param personLocale
 * @param sendFromPerson
 * @param ccPerson
 * @param replayToPerson
 * @param mailTemplateID
 * @param root
 * @return
 */
public static boolean sendEmailOnPerson(TPersonBean sendToPerson, Locale personLocale,
        TPersonBean sendFromPerson, TPersonBean ccPerson, TPersonBean replayToPerson, Integer mailTemplateID,
        Map<String, Object> root) {
    boolean plainEmail = sendToPerson.isPreferredEmailTypePlain();
    Integer personID = sendToPerson.getObjectID();
    MailPartTemplates mailPartTemplates = EmailTemplatesContainer.getMailPartTemplates(mailTemplateID,
            plainEmail, personLocale);
    if (mailPartTemplates == null) {
        LOGGER.warn("No mail template found for mailTemplateID " + mailTemplateID + " plain " + plainEmail
                + " locale " + personLocale);
        return false;
    }
    Template subjectTemplate = mailPartTemplates.getSubjectTemplate();
    if (subjectTemplate == null) {
        if (plainEmail) {
            LOGGER.warn("No plain subject template found for person " + sendToPerson.getObjectID());
        } else {
            LOGGER.warn("No HTML subject template found for person " + sendToPerson.getObjectID());
        }
        return false;
    }
    Template bodyTemplate = mailPartTemplates.getBodyTemplate();
    if (bodyTemplate == null) {
        if (plainEmail) {
            LOGGER.warn("No plain body template found for person " + sendToPerson.getObjectID() + ": "
                    + sendToPerson.getFullName() + ": " + personLocale);
        } else {
            LOGGER.warn("No HTML body template found for person " + sendToPerson.getObjectID() + ": "
                    + sendToPerson.getFullName() + ": " + personLocale);
        }
        return false;
    }
    if (root == null) {
        //do not send mail (no notification needed)
        LOGGER.debug("Root context is null for person " + sendToPerson.getName() + " (" + personID + ")");
        return false;
    }
    StringWriter subjectWriter = new StringWriter();
    try {
        LOGGER.debug("Processing the subject template...");
        subjectTemplate.process(root, subjectWriter);
        LOGGER.debug("Subject template processed.");
    } catch (Exception e) {
        LOGGER.warn(
                "Processing the subject template " + bodyTemplate.getName() + " failed with " + e.getMessage());
        LOGGER.debug("Processed template: " + subjectWriter.toString());
        return false;
    }
    subjectWriter.flush();
    String messageSubject = subjectWriter.toString();
    StringWriter bodyWriter = new StringWriter();
    try {
        LOGGER.debug("Processing the body template...");
        bodyTemplate.process(root, bodyWriter);
        LOGGER.debug("Body template processed.");
    } catch (Exception e) {
        LOGGER.warn(
                "Processing the body template " + bodyTemplate.getName() + " failed with " + e.getMessage());
        LOGGER.debug("Processed template: " + bodyWriter.toString());
        return false;
    }
    bodyWriter.flush();
    String messageBody = bodyWriter.toString();
    String emailTo = sendToPerson.getEmail();
    //Assemble and send the mail
    try {
        LOGGER.debug("Just before sending...");
        LOGGER.debug("From: " + sendFromPerson.getLabel() + " " + sendFromPerson.getEmail());
        LOGGER.debug("To: " + emailTo);
        LOGGER.debug("Subject: " + messageSubject);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Body " + messageBody);
        }
        LOGGER.debug("Is plain: " + plainEmail);
        mailBean.sendMailInThread(sendToPerson, messageSubject, sendFromPerson, ccPerson, replayToPerson,
                messageBody, plainEmail);
        LOGGER.debug("Mail sent to " + emailTo);
        return true;
    } catch (Exception e) { // SMTPException
        // add code to propagate Email problems to user interface or
        // system log
        LOGGER.error("Sending the e-mail failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return false;
    }
}

From source file:nl.clockwork.common.util.XMLMessageBuilder.java

public String handle(JAXBElement<T> e) throws JAXBException {
    if (e == null)
        return null;
    StringWriter result = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(e, result);/*from w  w w.j a v a 2  s  . co  m*/
    result.flush();
    return result.toString();
}

From source file:de.metas.ui.web.config.WebuiExceptionHandler.java

private void addStackTrace(final Map<String, Object> errorAttributes, final Throwable error) {
    final StringWriter stackTrace = new StringWriter();
    error.printStackTrace(new PrintWriter(stackTrace));
    stackTrace.flush();
    errorAttributes.put(ATTR_Stacktrace, stackTrace.toString());
}

From source file:nl.clockwork.common.util.XMLMessageBuilder.java

public String handle(T object) throws JAXBException {
    if (object == null)
        return null;
    StringWriter result = new StringWriter();
    Marshaller marshaller = context.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    marshaller.marshal(object, result);//from  w w w .  j  av a 2s  .c o m
    result.flush();
    return result.toString();
}