Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:org.matsim.contrib.analysis.christoph.DistanceDistribution.java

private void writeDistanceDistributionClass(DistributionClass distributionClass, int iteration,
        OutputDirectoryHierarchy outputDirectoryHierarchy) {

    String fileName = outputDirectoryHierarchy.getIterationFilename(iteration,
            "DistanceDistribution_" + distributionClass.name);

    double[] referenceShare = new double[distributionClass.distributionBins.size()];
    double[] simulationShare = new double[distributionClass.distributionBins.size()];

    // accumulate total count
    int count = 0;
    for (DistanceBin distanceBin : distributionClass.distributionBins) {
        count += distanceBin.count;/*  w  ww  . j a v  a  2s. c om*/
    }

    try {
        BufferedWriter writer = IOUtils.getBufferedWriter(fileName + ".txt");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("low" + "\t");
        stringBuffer.append("high" + "\t");
        stringBuffer.append("reference share" + "\t");
        stringBuffer.append("simulation share");

        writer.write(stringBuffer.toString());
        writer.newLine();

        int i = 0;
        log.info("Distance distribution for class " + distributionClass.name);
        for (DistanceBin distanceBin : distributionClass.distributionBins) {

            referenceShare[i] = distanceBin.referenceShare;
            simulationShare[i] = (double) distanceBin.count / (double) count;

            stringBuffer = new StringBuffer();
            stringBuffer.append(distanceBin.low + "\t");
            stringBuffer.append(distanceBin.high + "\t");
            stringBuffer.append(distanceBin.referenceShare + "\t");
            stringBuffer.append(String.valueOf(simulationShare[i]));

            log.info("\t" + stringBuffer.toString());

            writer.write(stringBuffer.toString());
            writer.newLine();

            i++;
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String title = "Distance distribution for class " + distributionClass.name;
    String xAxisLabel = "Distance class";
    String yAxisLabel = "Share";
    String[] categories = new String[distributionClass.distributionBins.size()];
    int i = 0;
    for (DistanceBin distanceBin : distributionClass.distributionBins) {
        categories[i++] = distanceBin.low + "\n" + " .. " + "\n" + distanceBin.high;
    }
    BarChart chart = new BarChart(title, xAxisLabel, yAxisLabel, categories);

    CategoryPlot plot = chart.getChart().getCategoryPlot();
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setMaximumCategoryLabelLines(3);

    chart.addMatsimLogo();
    chart.addSeries("reference share", referenceShare);
    chart.addSeries("simulation share", simulationShare);
    chart.saveAsPng(fileName + ".png", 1024, 768);
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

String refreshTokenWithTIM() {
    // android.os.Debug.waitForDebugger();

    // check initialization
    if (mOcp == null || isEmpty(mOcp.m_server_url))
        return null;

    // get refresh endpoint
    String token_endpoint = getEndpointFromConfigOidc("token_endpoint", mOcp.m_server_url);
    if (isEmpty(token_endpoint)) {
        Logd(TAG, "logout : could not get token_endpoint on server : " + mOcp.m_server_url);
        return null;
    }/* w ww.ja va 2 s . c  o m*/

    // set up connection
    HttpURLConnection huc = getHUC(token_endpoint);
    huc.setDoOutput(true);
    huc.setInstanceFollowRedirects(false);
    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // generate new RSA keys by SIM
    TokensKeys tk = secureStorage.genTimAppKey(mOcp);

    if (tk == null) {
        // no token key found
        return null;
    }

    // check value of refresh token
    if (isEmpty(tk.refresh_token)) {
        // nothing to do
        Log.d("refreshTokenWithTIM", "refresh_token null or empty");
        return null;
    }

    // prepare parameters
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);

    // add authentication assertion
    if (mUsePrivateKeyJWT) {
        String pkj = secureStorage.getPrivateKeyJwt(token_endpoint);
        if (pkj != null && pkj.length() > 0) {
            nameValuePairs.add(new BasicNameValuePair("client_assertion_type",
                    "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"));
            nameValuePairs.add(new BasicNameValuePair("client_assertion", pkj));
        }
    } else {
        String csb = secureStorage.getClientSecretBasic();
        if (csb != null && csb.length() > 0) {
            huc.setRequestProperty("Authorization", "Basic " + csb);
        }
    }

    String clientId = secureStorage.getClientId();
    nameValuePairs.add(new BasicNameValuePair("client_id", clientId));
    nameValuePairs.add(new BasicNameValuePair("grant_type", "refresh_token"));
    nameValuePairs.add(new BasicNameValuePair("refresh_token", tk.refresh_token));
    if (!isEmpty(tk.serverScope)) {
        nameValuePairs.add(new BasicNameValuePair("scope", tk.serverScope));
    } else if (!isEmpty(mOcp.m_scope)) {
        nameValuePairs.add(new BasicNameValuePair("scope", mOcp.m_scope));
    }

    // add public key to request
    nameValuePairs.add(new BasicNameValuePair("tim_app_key", tk.jwkPub));

    try {
        // write parameters to http connection
        OutputStream os = huc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        // get URL encoded string from list of key value pairs
        String postParam = getQuery(nameValuePairs);
        Logd("refreshTokenWithTIM", "url: " + token_endpoint);
        Logd("refreshTokenWithTIM", "POST: " + postParam);
        writer.write(postParam);
        writer.flush();
        writer.close();
        os.close();

        // try to connect
        huc.connect();
        // connexion status
        int responseCode = 0;
        try {
            // Will throw IOException if server responds with 401.
            responseCode = huc.getResponseCode();
        } catch (IOException e) {
            e.printStackTrace();
            // Will return 401, because now connection has the correct internal state.
            responseCode = huc.getResponseCode();
        }

        Logd(TAG, "refreshTokenWithTIM response: " + responseCode);

        // if 200 - OK, read the json string
        if (responseCode == 200) {
            sysout("refreshTokenWithTIM - code " + responseCode);
            InputStream is = huc.getInputStream();
            String result = convertStreamToString(is);
            is.close();
            huc.disconnect();

            Logd("refreshTokenWithTIM", "result: " + result);
            sysout("refreshTokenWithTIM - content: " + result);

            // TODO : verify TIM app key is correct

            return result;
        } else if (responseCode == 401) {
            // remove entry
            Logd("refreshTokenWithTIM", "got 401, remove entry");
            secureStorage.delete_tokens(mOcp.m_server_url, mOcp.m_client_id, mOcp.m_scope);
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;

}

From source file:de.csw.expertfinder.mediawiki.api.MediaWikiAPI.java

private String extractRedirectsAndReturnContinue(BufferedWriter out, Document doc) throws IOException {
    NodeList pElements = doc.getElementsByTagName("p");
    for (int i = 0; i < pElements.getLength(); i++) {
        Element pElement = (Element) pElements.item(i);
        String pageId = pElement.getAttribute("pageid");
        String ns = pElement.getAttribute("ns");
        String pageTitle = pElement.getAttribute("title");

        out.write(pageId);//from   w  w  w  .j  a  va  2  s. c o m
        out.write(";");
        out.write(ns);
        out.write(";");
        out.write(pageTitle);
        out.write("\n");
    }
    out.flush();

    NodeList queryContinueList = doc.getElementsByTagName("query-continue");
    if (queryContinueList.getLength() == 0) {
        // no more items
        return null;
    }

    Element allpageElement = (Element) ((Element) (queryContinueList.item(0))).getElementsByTagName("allpages")
            .item(0);
    return allpageElement.getAttribute("apfrom");
}

From source file:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java

public void writeData(OutputStream out, ServerRequest sr) throws DataAccessException {
    try {//w w w  . j a  v  a 2 s  . co  m
        TableServerRequest request = (TableServerRequest) sr;

        File inf = getDataFile(request);
        if (inf != null && inf.canRead()) {
            int rows = IpacTableUtil.getMetaInfo(inf).getRowCount();

            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out),
                    IpacTableUtil.FILE_IO_BUFFER_SIZE);
            BufferedReader reader = new BufferedReader(new FileReader(inf), IpacTableUtil.FILE_IO_BUFFER_SIZE);

            prepareAttributes(rows, writer, sr);
            String s = reader.readLine();
            while (s != null) {
                if (!(s.startsWith("\\col.") || s.startsWith("\\Loading"))) { // ignore ALL system-use headers
                    if (s.startsWith("|") && getOutputColumnsMap() != null)
                        for (String key : getOutputColumnsMap().keySet()) {
                            s = s.replaceAll(key, getOutputColumnsMap().get(key));
                        }
                    writer.write(s);
                    writer.newLine();
                }
                s = reader.readLine();
            }
            writer.flush();
        } else {
            throw new DataAccessException("Data not accessible.  Check server log for errors.");
        }
    } catch (Exception e) {
        throw new DataAccessException(e);
    }
}

From source file:com.microfocus.application.automation.tools.results.RunResultRecorder.java

private void writeToFile(File file, String contents) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(file));
    writer.write(contents);//  w w w  .j av  a2s . c  o m
    writer.flush();
    writer.close();
}

From source file:Interface.MainJFrame.java

private void btnTXTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTXTActionPerformed
    // TODO add your handling code here:

    BufferedWriter output = null;
    try {//  w w  w .  j a v a  2s . c  o  m
        File file = new File("output.txt");
        output = new BufferedWriter(new FileWriter(file));
        output.write("Name:" + txtFullName.getText());
        output.newLine();
        output.write("ID:" + txtEmployeeID.getText());
        output.newLine();
        output.write("Phone:" + txtPhoneNumber.getText());
        output.newLine();
        output.write("Address:" + txtAddress.getText());
        output.newLine();
        output.write("Employee Type:" + txtEmployeeType.getText());
        output.newLine();
        output.write("PayCategory:" + txtPayCategory.getText());
        output.newLine();
        output.write("Salary:" + txtSalary.getText());
        output.newLine();
        output.write("Hours:" + txtHours.getText());
        output.newLine();
        output.write("Bonus:" + txtBonuses.getText());
        output.newLine();
        output.write("Total:" + txtTotal.getText());
        output.newLine();

        output.flush();
        output.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.baomidou.mybatisplus.generator.AutoGenerator.java

/**
 * XML//w ww .  j av  a  2 s  .c  om
 *
 * @param columns
 * @param types
 * @param comments
 * @throws IOException
 */
protected void buildMapperXml(List<String> columns, List<String> types, List<String> comments,
        Map<String, IdInfo> idMap, String mapperName, String mapperXMLName) throws IOException {
    File mapperXmlFile = new File(PATH_XML, mapperXMLName + ".xml");
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mapperXmlFile)));
    bw.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    bw.newLine();
    bw.write(
            "<!DOCTYPE mapper PUBLIC \"-//mybatis.org//DTD Mapper 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-mapper.dtd\">");
    bw.newLine();
    bw.write("<mapper namespace=\"" + config.getMapperPackage() + "." + mapperName + "\">");
    bw.newLine();
    bw.newLine();

    /*
     * ?SqlMapper
     */
    buildSQL(bw, idMap, columns);

    bw.write("</mapper>");
    bw.flush();
    bw.close();
}

From source file:ca.canucksoftware.ipkpackager.IpkPackagerView.java

private void swapEndlineCharacters(File f) {
    try {/*www  . j a  v a2s. co  m*/
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new FileReader(f));
        String line = br.readLine();
        while (line != null) {
            sb.append(line + "\n");
            line = br.readLine();
        }
        br.close();
        BufferedWriter out = new BufferedWriter(new FileWriter(f));
        out.write(sb.toString());
        out.flush();
        out.close();
    } catch (Exception e) {
    }
}

From source file:de.jlo.talendcomp.json.JsonDocument.java

public void writeToFile(JsonNode node, String filePath, boolean prettyPrint, boolean suppressEmpty)
        throws Exception {
    if (filePath == null || filePath.trim().isEmpty()) {
        throw new IllegalArgumentException("Output file path cannot be null or empty!");
    }//from   w  ww .  j av a  2 s  .  c o  m
    File file = new File(filePath);
    File dir = file.getParentFile();
    if (dir.exists() == false) {
        dir.mkdirs();
    }
    if (dir.exists() == false) {
        throw new Exception("Cannot create output dir: " + dir.getAbsolutePath());
    }
    BufferedWriter br = null;
    try {
        br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        br.write(getJsonString(node, prettyPrint, suppressEmpty));
        br.flush();
    } finally {
        if (br != null) {
            br.close();
        }
    }
}

From source file:musite.io.xml.PredictionResultXMLWriter.java

/**
 * {@inheritDoc}/*from   w w w  .  ja v a  2 s  . co m*/
 */
public void write(final OutputStream os, final PredictionResult data) throws IOException {
    if (data == null) {
        throw new IllegalArgumentException();
    }

    int indent = getIndent();
    String prefix0 = StringUtils.repeat("\t", indent);
    String prefix1 = prefix0 + "\t";

    OutputStreamWriter osw = new OutputStreamWriter(os);
    BufferedWriter bufWriter = new BufferedWriter(osw);

    if (root != null)
        bufWriter.write(prefix0 + "<" + root + ">\n");

    bufWriter.write(prefix0 + "<model-list>\n");

    CollectionXMLWriter collectionWriter = new CollectionXMLWriter();
    //collectionWriter.setIndent(indent+3);
    Set<PredictionModel> models = data.getModels();
    for (PredictionModel model : models) {
        String name = model.getName();
        bufWriter.write(prefix0 + "<model name=\"" + name + "\">\n");

        PTM ptm = model.getSupportedPTM();
        if (ptm != null)
            bufWriter.write(prefix1 + "<ptm>" + StringEscapeUtils.escapeXml(ptm.name()) + "</ptm>\n");

        Set<AminoAcid> aminoAcids = model.getSupportedAminoAcid();
        if (aminoAcids != null && !aminoAcids.isEmpty()) {
            bufWriter.write(prefix1 + "<amino-acids>");
            Iterator<AminoAcid> it = aminoAcids.iterator();
            bufWriter.write(StringEscapeUtils.escapeXml(it.next().name()));
            while (it.hasNext())
                bufWriter.write(StringEscapeUtils.escapeXml(";" + it.next().name()));
            bufWriter.write("</amino-acids>\n");
        }

        SpecificityEstimator se = model.getSpecEstimator();
        if (se instanceof SpecificityEstimatorImpl) {
            bufWriter.write(prefix1 + "<spec-estimate-data>");
            bufWriter.flush();
            SpecificityEstimatorImpl sei = (SpecificityEstimatorImpl) se;
            List<Double> train = sei.trainingPredictions();
            collectionWriter.write(os, train);
            bufWriter.write("</spec-estimate-data>\n");
        }

        String comment = model.getComment();
        if (comment != null && comment.length() > 0) {
            comment = comment.replaceAll("\n", "%EOL%");
            bufWriter.write(prefix1 + "<comment>");
            bufWriter.write(StringEscapeUtils.escapeXml(comment));
            bufWriter.write("</comment>\n");
        }

        bufWriter.write(prefix0 + "</model>\n");
    }

    bufWriter.write("</model-list>\n");
    bufWriter.flush();

    proteinsWriter.write(os, data);

    if (root != null)
        bufWriter.write(prefix0 + "</" + root + ">");
    bufWriter.flush();
}