Example usage for java.io Writer flush

List of usage examples for java.io Writer flush

Introduction

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

Prototype

public abstract void flush() throws IOException;

Source Link

Document

Flushes the stream.

Usage

From source file:net.cit.tetrad.resource.CommandResource.java

@RequestMapping("/daemonDetailServerStatus.do")
public void daemonDetailServerStatus(HttpServletResponse response, CommonDto dto) throws Exception {
    String serverStatusFromMongo = comandService.allServerStatus(dto.getDeviceCode());
    JSONObject jsonObj = JSONObject.fromObject(JSONSerializer.toJSON(serverStatusFromMongo));
    JSONObject recordStats = (JSONObject) jsonObj.get("recordStats");
    if (recordStats != null) {
        Object ok = jsonObj.get("ok");
        jsonObj.remove("recordStats");
        jsonObj.remove("ok");

        Object accessNotInMemory = recordStats.get("accessesNotInMemory");
        Object pageFaultExceptionsThrown = recordStats.get("pageFaultExceptionsThrown");
        recordStats.remove("accessesNotInMemory");
        recordStats.remove("pageFaultExceptionsThrown");

        JSONObject recordStatsTotal = new JSONObject();
        recordStatsTotal.put("accessesNotInMemory", accessNotInMemory);
        recordStatsTotal.put("pageFaultExceptionsThrown", pageFaultExceptionsThrown);
        jsonObj.put("totalRecordStats", recordStatsTotal);
        jsonObj.put("recordStats", recordStats);
        jsonObj.put("ok", ok);
    }/*from w ww  . j  a va2 s  .c o  m*/

    response.setContentType("text/html;charset=utf-8");
    response.setCharacterEncoding("UTF-8");

    response.setContentType("text/html");
    response.setHeader("Cache-Control", "no-cache");

    Writer writer = response.getWriter();
    writer.write(jsonObj.toString());

    writer.flush();
}

From source file:com.clican.pluto.cms.ui.servlet.VelocityResourceServlet.java

@SuppressWarnings("unchecked")
@Override// w  ww  . j  a  va  2 s. c o  m
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String prefix = request.getContextPath() + request.getServletPath();
    if (request.getRequestURI().startsWith(prefix)) {
        String path = request.getRequestURI().replaceFirst(prefix, "");
        if (path.startsWith("/")) {
            path = path.substring(1, path.indexOf(";"));
        }
        // request.getSession().setAttribute("propertyDescriptionList", new
        // ArrayList<PropertyDescription>());
        Writer w = new OutputStreamWriter(response.getOutputStream(), "utf-8");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        InputStream is = null;
        try {
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(path);
            byte[] data = new byte[is.available()];
            is.read(data);
            String content = new String(data, "utf-8");
            Template t = null;
            VelocityContext velocityContext = new VelocityContext();
            HttpSession session = request.getSession();
            Enumeration<String> en = session.getAttributeNames();
            while (en.hasMoreElements()) {
                String name = en.nextElement();
                velocityContext.put(name, session.getAttribute(name));
            }
            SimpleNode node = RuntimeSingleton.getRuntimeServices().parse(content, path);
            t = new Template();
            t.setName(path);
            t.setRuntimeServices(RuntimeSingleton.getRuntimeServices());
            t.setData(node);
            t.initDocument();
            Writer wr = new OutputStreamWriter(os);
            t.merge(velocityContext, wr);
            wr.flush();
            byte[] datas = os.toByteArray();
            String s = new String(datas);
            log.info(s);
        } catch (Exception e) {
            log.error("", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } finally {
            if (w != null) {
                w.close();
            }
            if (is != null) {
                is.close();
            }
        }
    } else {
        response.sendError(HttpServletResponse.SC_NOT_FOUND);
    }

}

From source file:org.craftercms.core.util.template.impl.spel.SpElCompiledTemplate.java

@Override
public void process(Object model, Writer output) throws TemplateException {
    try {/*w  w  w.jav a2  s  . c  o  m*/
        String result = expression.getValue(evaluationContext, model, String.class);

        output.write(result);
        output.flush();
    } catch (IOException e) {
        throw new TemplateException("An I/O error occurred while writing to output", e);
    } catch (Exception e) {
        throw new TemplateException("Unable to process SpEL template:\n" + expression.getExpressionString(), e);
    }
}

From source file:com.qcadoo.view.internal.JsonHttpMessageConverter.java

@Override
protected void writeInternal(final JSONObject json, final HttpOutputMessage outputMessage) throws IOException {
    Writer writer = null;

    try {/*from  ww w  .  j av  a  2 s .c o m*/
        writer = new OutputStreamWriter(outputMessage.getBody(), CHARSET);
        writer.write(json.toString());
        writer.flush();
    } finally {
        IOUtils.closeQuietly(writer);
    }
}

From source file:au.org.ala.biocache.dao.TaxonDAOImpl.java

void outputNestedLayerEnd(Writer out) throws Exception {
    out.write("</Layer>");
    out.flush();
}

From source file:fi.okm.mpass.shibboleth.profile.impl.WriteMonitoringResult.java

/**
 * Writes the given message to the servlet response and returns a Spring webflow event.
 * @param httpResponse The servlet response.
 * @param message The message to be written to the servlet response.
 * @return The proceed event if the action was successful, IO_ERROR otherwise.
 *//*from   w  ww  .  j a  v  a  2 s  . co m*/
protected Event writeAndReturn(final HttpServletResponse httpResponse, final String message) {
    try {
        final Writer out = new OutputStreamWriter(httpResponse.getOutputStream(), "UTF-8");
        out.append(message);
        out.flush();
    } catch (IOException e) {
        log.error("{}: Could not encode the JSON response", getLogPrefix(), e);
        httpResponse.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE);
        return ActionSupport.buildEvent(this, EventIds.IO_ERROR);
    }
    return ActionSupport.buildProceedEvent(this);
}

From source file:de.andrena.tools.macker.plugin.CommandLineFileTest.java

private void writeArgsFile(List<String> lines) throws IOException {
    Writer out = new OutputStreamWriter(new FileOutputStream(TEST_FILE), "UTF-8");
    IOUtils.writeLines(lines, "\n", out);
    out.flush();
    out.close();//  w w w. j a  v a 2s  .com
}

From source file:com.github.rwitzel.streamflyer.support.ProcessEndOfStreamTest.java

protected long rewriteContent(InputStream input, OutputStream output, String encoding, boolean flush)
        throws IOException {

    Charset charset = Charset.forName(encoding);
    String oldPath = "something";
    String newPath = "anything";
    String regex = "((https?://)([^/]+/))?(" + oldPath + ")";
    String replacement = "$1" + newPath;
    //        FastRegexModifier modifier = new FastRegexModifier(regex, Pattern.CASE_INSENSITIVE | Pattern.CANON_EQ,
    //                replacement);
    RegexModifier modifier = new RegexModifier(regex, Pattern.CASE_INSENSITIVE | Pattern.CANON_EQ, replacement);

    Reader reader = new ModifyingReader(new InputStreamReader(input, charset), modifier);
    Writer writer = new OutputStreamWriter(output, charset);

    int copied = IOUtils.copy(reader, writer);

    if (flush) {//ww  w . j  a  va  2s  . c  o m
        writer.flush();
    }

    return copied;
}

From source file:com.linuxbox.enkive.statistics.StatsReportEmailer.java

private String buildReportWithTemplate() throws IOException, TemplateException, URISyntaxException,
        GathererException, StatsRetrievalException, ParseException, SchedulerException {
    Configuration cfg = new Configuration();
    File templatesDirectory = new File("config/templates");
    cfg.setDirectoryForTemplateLoading(templatesDirectory);

    Map<String, Object> root = new HashMap<String, Object>();
    root.put("date", new Date());
    // TODO: Can this build a report from the previous day or time period
    // rather than gather on demand?
    List<RawStats> statistics = gatherer.gatherStats();

    for (RawStats rawStats : statistics) {
        Map<String, Object> statsMap = rawStats.toMap();
        root.put(rawStats.getGathererName(), statsMap);
    }/*from  ww  w .j a va  2 s . c o m*/
    Template temp = cfg.getTemplate("StatisticsEmailTemplate.ftl");

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Writer out = new OutputStreamWriter(os);
    temp.process(root, out);
    out.flush();
    return os.toString();
}

From source file:com.netxforge.oss2.config.DefaultCapsdConfigManager.java

/** {@inheritDoc} */
protected synchronized void saveXml(String xml) throws IOException {
    if (xml != null) {
        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.CAPSD_CONFIG_FILE_NAME);
        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8");
        fileWriter.write(xml);/*from w  w w.  j  a va 2 s . c  o m*/
        fileWriter.flush();
        fileWriter.close();
    }
}