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.MainResource.java

/**
 *  ?? /*  www .  j  a v a 2s  .  co  m*/
 * @param dto
 * @return
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
@RequestMapping("/mainList.do")
public void mainList(HttpServletRequest request, HttpServletResponse response, CommonDto dto) throws Exception {
    log.debug("start - mainList()");

    //iDisplayStart iDisplayLength datatable? ??     
    int pageNumber = Integer.parseInt(Utility.isNullNumber(request.getParameter("iDisplayStart")));
    int nPerPage = Integer.parseInt(Utility.isNullNumber(request.getParameter("iDisplayLength")));
    log.debug("pageNumber=" + pageNumber + ", nPerPage=" + nPerPage);

    Enumeration parameter = request.getParameterNames();
    log.debug(parameter.toString());
    while (parameter.hasMoreElements()) {
        String pName = (String) parameter.nextElement();
        String pValue = request.getParameter(pName);
        log.debug(pName + " = " + pValue);
    }

    try {
        int sEcho = Integer.parseInt(Utility.isNullNumber(request.getParameter(REQ_SECHO)));

        PersonJson result = setPersonJson(sEcho, dto, pageNumber, nPerPage);
        JSONObject jsonObject = JSONObject.fromObject(result);

        Writer writer = setResponse(response).getWriter();
        writer.write(jsonObject.toString());

        log.debug(jsonObject.toString());
        writer.flush();
    } catch (Exception e) {
        log.error(e, e);
    }

    log.debug("end - mainList()");
}

From source file:com.joliciel.csvLearner.features.BestFeatureFinder.java

public void writeBestFeatures(Writer writer, String outcome, Collection<NameValuePair> bestFeatures) {
    try {/*w  w  w .  ja v  a  2s.  c om*/
        writer.append(CSVFormatter.format(outcome) + ",");
        for (NameValuePair pair : bestFeatures) {
            if (!pair.getName().equals(TOTAL_ENTROPY))
                writer.append(CSVFormatter.format(pair.getName()) + ",");
            writer.append(CSVFormatter.format(pair.getValue()) + ",");
        }
        writer.append("\n");
        writer.flush();
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:com.ms.commons.test.classloader.IntlTestURLClassPath.java

@SuppressWarnings("unchecked")
public URL findResource(String paramString, boolean paramBoolean) {
    URL resource = super.findResource(paramString, paramBoolean);
    URL newResource = null;/*from w  w w .ja  v  a2s  .  c om*/

    if (resource != null) {
        boolean testcaseLazyInit = IntlTestProperties.isAntxFlagOn(IntlTestGlobalConstants.TESTCASE_LAZY_INIT);
        if (testcaseLazyInit && paramString.contains("spring_") && paramString.endsWith(".xml")) {
            try {
                String nResource = TESTCASE_SPRING_TEMP_DIR + "/"
                        + StringUtil.replaceNoWordChars(resource.toString().hashCode() + paramString) + ".xml";
                File newF = new File(nResource);
                if (!newF.exists()) {
                    InputStream is = resource.openStream();

                    SAXBuilder b = new SAXBuilder();
                    Document document = b.build(new InputStreamReader(is, "UTF-8"));

                    List<Element> elements = XPath.selectNodes(document, "/beans");

                    if (elements != null && elements.size() == 1) {
                        elements.get(0).setAttribute("default-lazy-init", "true");

                        XMLOutputter xmlOutputter = new XMLOutputter();
                        Writer writer = new BufferedWriter(new FileWriter(newF));
                        xmlOutputter.output(document, writer);
                        writer.flush();
                        FileUtil.closeCloseAbleQuitly(writer);

                    }
                }
                newResource = newF.toURI().toURL();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    OUTPUT_WRITER.writeLine("FindResource [" + paramString + "] --> " + resource
            + ((newResource == null) ? "" : " # " + newResource));
    return resource;
}

From source file:appeng.services.export.MinecraftItemCSVExporter.java

@Override
public void export() {
    final Iterable<Item> items = this.itemRegistry.typeSafeIterable();
    final List<Item> itemList = Lists.newArrayList(items);

    final List<String> lines = Lists.transform(itemList,
            new ItemRowExtractFunction(this.itemRegistry, this.mode));

    final Joiner newLineJoiner = Joiner.on('\n');
    final Joiner newLineJoinerIgnoringNull = newLineJoiner.skipNulls();
    final String joined = newLineJoinerIgnoringNull.join(lines);

    final File file = new File(this.exportDirectory, ITEM_CSV_FILE_NAME);

    try {//  w  w w.  java 2  s . com
        FileUtils.forceMkdir(this.exportDirectory);

        final Writer writer = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")));

        final String header = this.mode == ExportMode.MINIMAL ? MINIMAL_HEADER : VERBOSE_HEADER;
        writer.write(header);
        writer.write("\n");
        writer.write(joined);
        writer.flush();
        writer.close();

        AELog.info(EXPORT_SUCCESSFUL_MESSAGE, lines.size(), ITEM_CSV_FILE_NAME);
    } catch (final IOException e) {
        AELog.warn(EXPORT_UNSUCCESSFUL_MESSAGE);
        AELog.debug(e);
    }
}

From source file:br.gov.lexml.server.LexMLOAIHandler.java

/**
 * Peform the http GET action. Note that POST is shunted to here as well. The verb widget is
 * taken from the request and used to invoke an OAIVerb object of the corresponding kind to do
 * the actual work of the verb./*from   w  w  w.j  ava 2  s  . c  o  m*/
 * 
 * @param request the servlet's request information
 * @param response the servlet's response information
 * @exception IOException an I/O error occurred
 */
@Override
public void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Fora gerao do cookie de sesso
    // (necessrio para balanceamento de carga pelo pound do Prodasen)
    request.getSession();

    HashMap attributes = getAttributes(request.getPathInfo());
    if (!filterRequest(request, response)) {
        return;
    }
    log.debug("attributes = " + attributes);
    Properties properties = (Properties) attributes.get("OAIHandler.properties");
    boolean monitor = false;
    if (properties.getProperty("OAIHandler.monitor") != null) {
        monitor = true;
    }
    boolean serviceUnavailable = isServiceUnavailable(properties);
    String extensionPath = properties.getProperty("OAIHandler.extensionPath", "/extension");

    HashMap serverVerbs = ServerVerb.getVerbs(properties);
    HashMap extensionVerbs = ServerVerb.getExtensionVerbs(properties);

    Transformer transformer = (Transformer) attributes.get("OAIHandler.transformer");

    boolean forceRender = false;
    if ("true".equals(properties.getProperty("OAIHandler.forceRender"))) {
        forceRender = true;
    }

    request.setCharacterEncoding("UTF-8");

    Date then = null;
    if (monitor) {
        then = new Date();
    }
    if (debug) {
        Enumeration headerNames = request.getHeaderNames();
        log.debug("OAIHandler.doGet: ");
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            log.debug(headerName + ": " + request.getHeader(headerName));
        }
    }
    if (serviceUnavailable) {
        response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE,
                "Sorry. This server is down for maintenance");
    } else {
        try {
            String userAgent = request.getHeader("User-Agent");
            if (userAgent == null) {
                userAgent = "";
            } else {
                userAgent = userAgent.toLowerCase();
            }
            Transformer serverTransformer = null;
            if (transformer != null) {

                // return HTML if the client is an old browser
                if (forceRender || userAgent.indexOf("opera") != -1
                        || userAgent.startsWith("mozilla") && userAgent.indexOf("msie 6") == -1
                /* && userAgent.indexOf("netscape/7") == -1 */) {
                    serverTransformer = transformer;
                }
            }
            String result = LexMLOAIHandler.getResult(attributes, request, response, serverTransformer,
                    serverVerbs, extensionVerbs, extensionPath);

            Writer out = LexMLOAIHandler.getWriter(request, response);
            out.write(result);
            out.flush();
            IOUtils.closeQuietly(out);
        } catch (FileNotFoundException e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        } catch (Throwable e) {
            log.error("Falha no processamento.", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    }
    if (monitor) {
        StringBuffer reqUri = new StringBuffer(request.getRequestURI());
        String queryString = request.getQueryString(); // d=789
        if (queryString != null) {
            reqUri.append("?").append(queryString);
        }
        Runtime rt = Runtime.getRuntime();
        log.debug(rt.freeMemory() + "/" + rt.totalMemory() + " " + (new Date().getTime() - then.getTime())
                + "ms: " + reqUri.toString());
    }
}

From source file:com.norconex.importer.ImporterConfig.java

private void writeHandlers(Writer out, String listTagName, IImporterHandler[] handlers) throws IOException {
    if (ArrayUtils.isEmpty(handlers)) {
        return;//from   w  w  w  .  ja  va  2  s.c  om
    }
    out.write("<" + listTagName + ">");
    for (IImporterHandler handler : handlers) {
        writeObject(out, null, handler);
    }
    out.write("</" + listTagName + ">");
    out.flush();
}

From source file:be.solidx.hot.JSR223ScriptExecutor.java

@Override
public Object execute(Script<CompiledScript> script, Writer writer) throws ScriptException {
    try {//from  w  w  w .  ja va2 s  .  co m
        ScriptEngine scriptEngine = getEngine();
        CompiledScript compiledScript = getCachedScript(script);
        SimpleScriptContext simpleScriptContext = new SimpleScriptContext();
        executePreExecuteScripts(simpleScriptContext);
        simpleScriptContext.setWriter(writer);
        Object object = compiledScript.eval(simpleScriptContext);
        writer.flush();
        if (object == null)
            return scriptEngine.getBindings(ScriptContext.ENGINE_SCOPE);
        return object;
    } catch (Exception e) {
        throw new ScriptException(e);
    }
}

From source file:com.rodiontsev.maven.plugins.buildinfo.BuildInfoMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    Map<String, String> map = new LinkedHashMap<String, String>();

    for (InfoProvider provider : ServiceLoader.load(InfoProvider.class)) {
        map.putAll(provider.getInfo(project, this));
    }/*from  w  ww .ja v  a  2  s  . c o  m*/

    File buildDir = new File(project.getBuild().getDirectory());
    File file = new File(buildDir, filename);

    Writer out = null;
    try {
        // we may not have target/ yet
        buildDir.mkdir();
        boolean created = file.createNewFile();
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        for (Map.Entry<String, String> entry : map.entrySet()) {
            out.write(entry.getKey());
            out.write(" = ");
            out.write(entry.getValue());
            out.write("\n");
        }
        out.flush();
        getLog().info(created ? "Created " : "Overwrote " + file.getAbsolutePath());
    } catch (IOException e) {
        getLog().warn(e.getMessage());
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:grails.converters.JSON.java

private void finalizeRender(Writer out) {
    try {//  w  w  w. j  av  a2  s.  c  o m
        out.flush();
        out.close();
    } catch (Exception e) {
        log.warn("Unexpected exception while closing a writer: " + e.getMessage());
    }
}

From source file:business.services.PaNumberService.java

public HttpEntity<InputStreamResource> writePaNumbers(List<PathologyItem> items, Integer labNumber,
        String labRequestCode) throws Exception {

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Writer writer = new OutputStreamWriter(out, PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING);
    CSVWriter csvwriter = new CSVWriter(writer, ';', '"');

    csvwriter.writeNext(FILE_HEADER);//from  w  w  w.  jav a2 s  . co m

    for (PathologyItem item : items) {
        log.info(item.getPaNumber());
        String[] toppings = { labNumber.toString(), item.getPaNumber(), "", "" };
        csvwriter.writeNext(toppings);
    }

    String filename = "panumbers_" + labRequestCode + ".csv";

    try {
        csvwriter.flush();
        writer.flush();
        out.flush();
        InputStream in = new ByteArrayInputStream(out.toByteArray());
        csvwriter.close();
        writer.close();
        out.close();
        InputStreamResource resource = new InputStreamResource(in);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("text/csv;charset=" + PA_NUMBERS_DOWNLOAD_CHARACTER_ENCODING));
        headers.set("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        HttpEntity<InputStreamResource> response = new HttpEntity<InputStreamResource>(resource, headers);
        return response;
    } catch (IOException e) {
        throw new Exception(e);
    }
}