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:org.jactr.tools.async.message.event.state.ModelStateEvent.java

public ModelStateEvent(String modelName, Throwable exception, double simulationTime) {
    this(modelName, State.STOPPED, simulationTime);
    StringWriter writer = new StringWriter();
    exception.printStackTrace(new PrintWriter(writer));
    writer.flush();
    _exception = writer.toString();/*  www . j  a  v  a2 s  . co  m*/
}

From source file:org.jactr.tools.async.message.event.state.RuntimeStateEvent.java

public RuntimeStateEvent(Exception exception, double simulationTime) {
    this(State.STOPPED, simulationTime);
    StringWriter writer = new StringWriter();
    exception.printStackTrace(new PrintWriter(writer));
    writer.flush();
    _exception = writer.toString();//  w w w.j  a v  a 2s. c  o  m
}

From source file:org.fornax.cartridges.sculptor.smartclient.server.util.UnifiedFormatter.java

@Override
public String format(LogRecord record) {
    String username = "ANONYMOUS";
    if (SecurityContextHolder.getContext() != null
            && SecurityContextHolder.getContext().getAuthentication() != null
            && SecurityContextHolder.getContext().getAuthentication().getPrincipal() != null) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof User) {
            username = ((User) principal).getUsername();
        } else {//w  ww .j  a v a 2  s. c  o  m
            username = principal.toString();
        }
    }

    int dotIndex = record.getSourceClassName().lastIndexOf(".");
    String className = record.getSourceClassName().substring(dotIndex != -1 ? dotIndex + 1 : 0);
    String msg = record.getMessage();
    if (record.getParameters() != null && record.getParameters().length > 0) {
        msg = MessageFormat.format(record.getMessage(), record.getParameters());
    }
    if (record.getThrown() != null) {
        Throwable thrown = record.getThrown();
        StringWriter result = new StringWriter();
        thrown.printStackTrace(new PrintWriter(result));
        result.flush();
        msg += "\n" + result.getBuffer();
    }
    return FST + dateFormat.format(record.getMillis()) + FET + FSEP + RST + FST + record.getLevel() + FET + FSEP
            + FST + className + "." + record.getSourceMethodName() + FET + FSEP + FST + username + FET + FSEP
            + FST + record.getThreadID() + FET + FSEP + FST + msg + FET + RET;
}

From source file:com.eyeq.pivot4j.el.freemarker.FreeMarkerExpressionEvaluator.java

/**
 * @see com.eyeq.pivot4j.el.AbstractExpressionEvaluator#doEvaluate(java.lang.String,
 *      com.eyeq.pivot4j.el.ExpressionContext)
 *//* w  ww .j  a  va2s . c om*/
@Override
protected Object doEvaluate(String expression, ExpressionContext context) throws Exception {
    Template template = getTemplateFromCache(expression);

    if (template == null) {
        template = createTemplate(expression);
    }

    Locale locale = (Locale) context.get("locale");
    if (locale != null) {
        template.setLocale(locale);
    }

    StringWriter writer = new StringWriter();

    template.process(context, writer);
    writer.flush();

    return writer.toString();
}

From source file:com.greenpepper.report.FileReportGenerator.java

/** {@inheritDoc} */
public void closeReport(Report report) throws IOException, URISyntaxException {
    FileWriter out = null;/*ww  w  .ja  v a2  s  .c  o m*/
    try {
        File reportFile = new File(reportsDirectory, outputNameOf(report));
        String documentUri = report.getDocumentUri();
        if (documentUri != null) {
            if (reportFile.equals(new File(new URI(documentUri)))) {
                reportFile = new File(reportFile.getAbsolutePath() + ".out");
            }
        }
        IOUtil.createDirectoryTree(reportFile.getParentFile());
        StringWriter strOut = new StringWriter();
        report.printTo(strOut);
        strOut.flush();
        out = new FileWriter(reportFile);
        String reportString = strOut.toString();
        LOGGER.trace("Final Report to be written :\n {}", reportString);
        IOUtils.write(reportString, out);
        out.flush();
    } finally {
        IOUtil.closeQuietly(out);
    }
}

From source file:com.glaf.template.renderer.freemarker.FreemarkerRenderer.java

public void render(Map<String, Object> model, Writer out) {
    try {//  ww  w.ja va2s . com
        if (parseException != null) {
            Map<String, Object> context = new java.util.HashMap<String, Object>();
            context.put("exception", parseException);
            context.put("exceptionSource", renderTemplate.getTemplateId());
            t.process(context, out);
            return;
        }
        model.put("currentDate", new java.util.Date());
        log.debug(model);
        StringWriter writer = new StringWriter();
        long startTime = System.currentTimeMillis();
        t.process(model, writer);
        writer.flush();
        writer.close();
        out.write(writer.toString());
        long endTime = System.currentTimeMillis();
        long renderTime = (endTime - startTime);
        log.debug("Rendered [" + renderTemplate.getTemplateId() + "] in " + renderTime + " milliseconds");
        // log.debug(out.toString());
    } catch (Exception ex) {
        throw new RuntimeException("Error during rendering", ex);
    }
}

From source file:com.microsoft.tfs.core.checkinpolicies.PolicyEvaluator.java

/**
 * Returns a text error message (with newlines) suitable for printing in a
 * console window, log file, or other text area that describes a problem
 * loading a check-in policy implementation so the user can fix the problem.
 * Things like policy type ID, installation instructions, and sometimes
 * stack traces are formatted into the message.
 *
 * @param throwable//from w w w .  j ava  2 s.  c  om
 *        the problem that caused the load failure, usually these are
 *        {@link PolicyLoaderException}, but they can be any kind of
 *        {@link Throwable} and the error message will be as descriptive as
 *        possible (must not be <code>null</code>)
 * @return the formatted error text.
 */
public static String makeTextErrorForLoadException(final Throwable throwable) {
    Check.notNull(throwable, "throwable"); //$NON-NLS-1$

    final StringBuffer sb = new StringBuffer();

    if (throwable instanceof PolicyLoaderException
            && ((PolicyLoaderException) throwable).getPolicyType() != null) {
        /*
         * Additional details for policy loader exceptions with policy type
         * information.
         */

        sb.append(Messages.getString("PolicyEvaluator.RequiredCheckinPolicyFailedToLoad")); //$NON-NLS-1$

        final PolicyLoaderException ple = (PolicyLoaderException) throwable;
        sb.append(Messages.getString("PolicyEvaluator.NameColon") + ple.getPolicyType().getName() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(Messages.getString("PolicyEvaluator.IDColon") + ple.getPolicyType().getID() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
        sb.append(Messages.getString("PolicyEvaluator.InstallationInstructionsColon") //$NON-NLS-1$
                + ple.getPolicyType().getInstallationInstructions() + "\n"); //$NON-NLS-1$

        sb.append(Messages.getString("PolicyEvaluator.ErrorColon") + throwable.getLocalizedMessage() + "\n\n"); //$NON-NLS-1$ //$NON-NLS-2$
    } else {
        /*
         * Run-time errors and other problems not handled during policy
         * loading are wrapped in TECoreException, but some other exception
         * types may come through (very rare).
         */

        sb.append(Messages.getString("PolicyEvaluator.AnErrorOccurredInThePolicyFramework")); //$NON-NLS-1$

        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        pw.flush();
        sw.flush();

        sb.append(Messages.getString("PolicyEvaluator.ErrorColon") + sw.toString() + "\n"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    sb.append(Messages.getString("PolicyEvaluator.MoreDetailsMayBeAvailableInPlatformLogs")); //$NON-NLS-1$

    return sb.toString();
}

From source file:be.dnsbelgium.rdap.jackson.AbstractSerializerTest.java

@SuppressWarnings("unchecked")
public void serializeAndAssertEquals(String expected, S o, SerializerProvider sp) throws IOException {
    JsonFactory factory = new JsonFactory();
    T serializer = getSerializer();/* www. j ava 2s .  c om*/
    StringWriter sw = new StringWriter();
    JsonGenerator jgen = factory.createJsonGenerator(sw);
    serializer.serialize(o, jgen, sp); // unchecked
    jgen.flush();
    sw.flush();
    String result = sw.toString();
    sw.close();
    assertEquals(expected, result);
}

From source file:org.unitime.timetable.util.BlobRoomAvailabilityService.java

protected void sendRequest(Document request) throws IOException {
    try {/*from   w ww .j a  v  a  2 s  .  co  m*/
        StringWriter writer = new StringWriter();
        (new XMLWriter(writer, OutputFormat.createPrettyPrint())).write(request);
        writer.flush();
        writer.close();
        SessionImplementor session = (SessionImplementor) new _RootDAO().getSession();
        Connection connection = session.getJdbcConnectionAccess().obtainConnection();
        try {
            CallableStatement call = connection.prepareCall(iRequestSql);
            call.setString(1, writer.getBuffer().toString());
            call.execute();
            call.close();
        } finally {
            session.getJdbcConnectionAccess().releaseConnection(connection);
        }
    } catch (Exception e) {
        sLog.error("Unable to send request: " + e.getMessage(), e);
    } finally {
        _RootDAO.closeCurrentThreadSessions();
    }
}

From source file:biz.c24.io.spring.batch.writer.C24ItemWriter.java

/**
 * Writes the contents of the StringWriter to our output file
 * //from   w  w  w  .  j av a 2 s  .  c o m
 * @param writer The StringWriter to read the data from
 */
private void write(Sink sink) throws IOException {

    StringWriter writer = (StringWriter) sink.getWriter();

    writer.flush();

    StringBuffer buffer = writer.getBuffer();

    // Sadly StringBuffer doesn't allow us read-only access to its internal array, so we have to copy
    String element = buffer.toString();

    Writer outputWriter = writerSource.getWriter();
    synchronized (outputWriter) {
        outputWriter.write(element);
    }

    // Reset the buffer for next time
    buffer.setLength(0);

}