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:com.isencia.passerelle.runtime.repos.impl.filesystem.FlowRepositoryServiceImpl.java

@Override
public FlowHandle update(FlowHandle handle, Flow updatedFlow, boolean activate) throws EntryNotFoundException {
    String flowCode = handle.getCode();
    File flowRootFolder = new File(rootFolder, flowCode);
    if (!flowRootFolder.isDirectory()) {
        throw new EntryNotFoundException(ErrorCode.FLOW_SAVING_ERROR_FUNC, "Flow code unknown " + flowCode,
                null);//  www .  ja  v a  2  s. c om
    } else {
        FlowHandle flowHandle = null;
        ThreeDigitVersionSpecification vSpec = ((ThreeDigitVersionSpecification) handle.getVersion())
                .increaseMinor();
        File versionFolder = new File(flowRootFolder, vSpec.toString());
        while (versionFolder.exists()) {
            vSpec = vSpec.increaseMinor();
            versionFolder = new File(flowRootFolder, vSpec.toString());
        }
        versionFolder.mkdirs();
        File destinationFile = new File(versionFolder, updatedFlow.getName() + ".moml");
        if ((!destinationFile.exists() || destinationFile.canWrite())) {
            BufferedWriter outputWriter = null;
            try {
                outputWriter = new BufferedWriter(new FileWriter(destinationFile));
                updatedFlow.exportMoML(outputWriter);
                flowHandle = new FlowHandleImpl(flowCode, destinationFile, vSpec);
                writeMetaData(flowCode, VERSION_MOSTRECENT, vSpec.toString());
                if (activate) {
                    activateFlowRevision(flowHandle);
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (outputWriter != null) {
                    try {
                        outputWriter.flush();
                        outputWriter.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
            return flowHandle;
        } else {
            throw new RuntimeException(new IOException("File not writable " + destinationFile));
        }
    }
}

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

@Override
public void notifyIterationEnds(IterationEndsEvent event) {

    OutputDirectoryHierarchy outputDirectoryHierarchy = event.getServices().getControlerIO();

    try {// w w  w  . j  a va 2s.c om
        for (String activityType : this.activityCountData.keySet()) {
            String fileName = outputDirectoryHierarchy.getIterationFilename(event.getIteration(),
                    this.activitiesFileName + "_" + activityType + ".txt");
            BufferedWriter activitiesWriter = IOUtils.getBufferedWriter(fileName);

            activitiesWriter.write("TIME");
            activitiesWriter.write("\t");
            activitiesWriter.write(activityType.toUpperCase());
            activitiesWriter.write("\n");

            List<ActivityData> list = this.activityCountData.get(activityType);
            for (ActivityData activityData : list) {
                activitiesWriter.write(String.valueOf(activityData.time));
                activitiesWriter.write("\t");
                activitiesWriter.write(String.valueOf(activityData.activityCount));
                activitiesWriter.write("\n");
            }

            activitiesWriter.flush();
            activitiesWriter.close();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    if (this.createGraphs) {
        // create chart when data of more than one iteration is available.
        XYLineChart chart;

        /*
         * number of performed activities
         */
        chart = new XYLineChart("Number of performed Activities", "time", "# activities");
        for (String activityType : this.activityCountData.keySet()) {
            List<ActivityData> list = this.activityCountData.get(activityType);
            int length = list.size();

            double[] times = new double[length * 2 - 1];
            double[] counts = new double[length * 2 - 1];
            Iterator<ActivityData> iter = list.iterator();
            int i = 0;
            double lastValue = 0.0;
            while (iter.hasNext()) {
                ActivityData activityData = iter.next();
                times[i] = Math.min(activityData.time, this.endTime) / 3600.0;
                counts[i] = activityData.activityCount;
                if (i > 0) {
                    times[i - 1] = Math.min(activityData.time, this.endTime) / 3600.0;
                    counts[i - 1] = lastValue;
                }
                lastValue = activityData.activityCount;
                i += 2;
            }
            chart.addSeries(activityType, times, counts);
        }
        int length = this.overallCount.size();
        double[] times = new double[length * 2 - 1];
        double[] counts = new double[length * 2 - 1];
        Iterator<ActivityData> iter = this.overallCount.iterator();
        int i = 0;
        double lastValue = 0.0;
        while (iter.hasNext()) {
            ActivityData activityData = iter.next();
            times[i] = Math.min(activityData.time, this.endTime) / 3600.0;
            counts[i] = activityData.activityCount;
            if (i > 0) {
                times[i - 1] = Math.min(activityData.time, this.endTime) / 3600.0;
                counts[i - 1] = lastValue;
            }
            lastValue = activityData.activityCount;
            i += 2;
        }
        chart.addSeries("overall", times, counts);

        NumberAxis domainAxis = (NumberAxis) chart.getChart().getXYPlot().getDomainAxis();
        domainAxis.setTickLabelFont(new Font("SansSerif", Font.PLAIN, 11));
        domainAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        domainAxis.setAutoRange(false);
        domainAxis.setRange(0, endTime / 3600.0);

        chart.addMatsimLogo();
        String fileName = outputDirectoryHierarchy.getIterationFilename(event.getIteration(),
                this.activitiesFileName + ".png");
        chart.saveAsPng(fileName, 800, 600);
    }
}

From source file:playground.artemc.socialCost.SocialCostWriter.java

public void writeTable(final String filename, double[] meanData, double[] medianData, double[] quantil25Data,
        double[] quantil75Data) {

    try {/*ww  w.  j ava 2 s  . c  o m*/
        BufferedWriter out = IOUtils.getBufferedWriter(filename);

        StringBuffer sb = new StringBuffer();

        // create and write header
        sb.append("mean");
        sb.append(separator);
        sb.append("median");
        sb.append(separator);
        sb.append("25% quantil");
        sb.append(separator);
        sb.append("75% quantil");
        sb.append(lineEnd);
        out.write(sb.toString());

        // write data
        for (int i = 0; i < meanData.length; i++) {
            sb = new StringBuffer();
            sb.append(meanData[i]);
            sb.append(separator);
            sb.append(medianData[i]);
            sb.append(separator);
            sb.append(quantil25Data[i]);
            sb.append(separator);
            sb.append(quantil75Data[i]);
            sb.append(lineEnd);
            out.write(sb.toString());
        }

        out.flush();
        out.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.eviware.soapui.impl.wsdl.WsdlProject.java

private static void normalizeLineBreak(File target, File tmpFile) throws IOException {
    FileReader fr = new FileReader(tmpFile);
    BufferedReader in = new BufferedReader(fr);
    FileWriter fw = new FileWriter(target);
    BufferedWriter out = new BufferedWriter(fw);
    String line = "";
    while ((line = in.readLine()) != null) {
        out.write(line);/*from  w ww.  j a v a 2s.com*/
        out.newLine();
        out.flush();
    }
    out.close();
    fw.close();
    in.close();
    fr.close();
}

From source file:foam.dao.HTTPSink.java

@Override
public void put(Object obj, Detachable sub) {
    HttpURLConnection conn = null;
    OutputStream os = null;// ww  w  .  jav a2s.c om
    BufferedWriter writer = null;

    try {
        Outputter outputter = null;
        conn = (HttpURLConnection) new URL(url_).openConnection();
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        if (format_ == Format.JSON) {
            outputter = new foam.lib.json.Outputter(OutputterMode.NETWORK);
            conn.addRequestProperty("Accept", "application/json");
            conn.addRequestProperty("Content-Type", "application/json");
        } else if (format_ == Format.XML) {
            // TODO: make XML Outputter
            conn.addRequestProperty("Accept", "application/xml");
            conn.addRequestProperty("Content-Type", "application/xml");
        }
        conn.connect();

        os = conn.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
        writer.write(outputter.stringify((FObject) obj));
        writer.flush();
        writer.close();
        os.close();

        // check response code
        int code = conn.getResponseCode();
        if (code != HttpServletResponse.SC_OK) {
            throw new RuntimeException("Http server did not return 200.");
        }
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        IOUtils.closeQuietly(writer);
        IOUtils.closeQuietly(os);
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.ruforhire.utils.Stopwords.java

/**
 * Writes the current stopwords to the given writer. The writer is closed
 * automatically.//from  ww  w.ja  v a  2 s .co  m
 *
 * @param writer the writer to get the stopwords from
 * @throws Exception if writing fails
 */
public void write(BufferedWriter writer) throws Exception {
    Enumeration enm;

    // header
    writer.write("# generated " + new Date());
    writer.newLine();

    enm = elements();

    while (enm.hasMoreElements()) {
        writer.write(enm.nextElement().toString());
        writer.newLine();
    }

    writer.flush();
    writer.close();
}

From source file:com.isencia.passerelle.runtime.repos.impl.filesystem.FlowRepositoryServiceImpl.java

@Override
public FlowHandle commit(String flowCode, Flow flow) throws DuplicateEntryException {
    File newFlowFolder = new File(rootFolder, flowCode);
    if (newFlowFolder.exists()) {
        throw new DuplicateEntryException(flowCode);
    } else {//  w  ww  . j  a  va2s. com
        FlowHandle flowHandle = null;
        VersionSpecification vSpec = new ThreeDigitVersionSpecification(1, 0, 0);
        File versionFolder = new File(newFlowFolder, vSpec.toString());
        versionFolder.mkdirs();
        File destinationFile = new File(versionFolder, flow.getName() + ".moml");
        if ((!destinationFile.exists() || destinationFile.canWrite())) {
            BufferedWriter outputWriter = null;
            try {
                outputWriter = new BufferedWriter(new FileWriter(destinationFile));
                flow.exportMoML(outputWriter);
                flowHandle = new FlowHandleImpl(flowCode, destinationFile, vSpec);
                writeMetaData(flowCode, VERSION_ACTIVE, vSpec.toString());
                writeMetaData(flowCode, VERSION_MOSTRECENT, vSpec.toString());
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (EntryNotFoundException e) {
                // should not happen
            } finally {
                if (outputWriter != null) {
                    try {
                        outputWriter.flush();
                        outputWriter.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
            return flowHandle;
        } else {
            throw new RuntimeException(new IOException("File not writable " + destinationFile));
        }
    }
}

From source file:at.ac.tuwien.dsg.celar.mela.jCatascopiaClient.JCatascopiaDataSource.java

/**
 * Acts directly on the supplied agent and populates its metric list with
 * values/*w w  w .ja v  a2 s  .  c om*/
 *
 * @param agent the agent for which the latest metric values will be
 * retrieved
 */
private void getLatestMetricsValuesForJCatascopiaAgent(JCatascopiaAgent agent) {
    URL url = null;
    HttpURLConnection connection = null;
    try {
        url = new URL(this.url + "/metrics");
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Accept", "application/json");

        //write message body
        OutputStream os = connection.getOutputStream();
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os));
        String getMetricsInfoQuerry = "metrics=";
        for (JCatascopiaMetric metric : agent.getAgentMetrics()) {
            getMetricsInfoQuerry += metric.getId() + ",";
        }

        //cut the last ","
        getMetricsInfoQuerry = getMetricsInfoQuerry.substring(0, getMetricsInfoQuerry.lastIndexOf(","));

        bufferedWriter.write(getMetricsInfoQuerry);
        bufferedWriter.flush();
        os.flush();
        os.close();

        InputStream errorStream = connection.getErrorStream();
        if (errorStream != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
            String line;
            while ((line = reader.readLine()) != null) {
                Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, line);
            }
        }

        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String availableMetrics = "";

        String line = "";
        while ((line = bufferedReader.readLine()) != null) {
            availableMetrics += line;
        }

        JSONObject object = new JSONObject(availableMetrics);
        if (object.has("metrics")) {
            JSONArray metrics = object.getJSONArray("metrics");
            List<JCatascopiaMetric> agentMetrics = agent.getAgentMetrics();

            //map of metric indexed on IDs to find easier the metrics (avoids for in for)
            Map<String, JCatascopiaMetric> metricsMap = new HashMap<String, JCatascopiaMetric>(0);
            for (JCatascopiaMetric jCatascopiaMetric : agentMetrics) {
                metricsMap.put(jCatascopiaMetric.getId(), jCatascopiaMetric);
            }

            //populate the metrics pool
            for (int i = 0; i < metrics.length(); i++) {
                JSONObject metric = metrics.getJSONObject(i);
                String metricId = null;
                String metricValue = null;

                //get agent metricID
                if (metric.has("metricID")) {
                    metricId = metric.getString("metricID");
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia metricID not found in {0}", availableMetrics);
                }

                //get metric value
                if (metric.has("value")) {
                    metricValue = metric.getString("value");
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "JCatascopia name not found in {0}", availableMetrics);
                }

                if (metricId == null || metricValue == null) {
                    continue;
                }

                if (metricsMap.containsKey(metricId)) {
                    JCatascopiaMetric jCatascopiaMetric = metricsMap.get(metricId);
                    jCatascopiaMetric.setValue(metricValue);
                } else {
                    Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                            "Unrecognized metricId {0} found in {1}",
                            new Object[] { metricId, availableMetrics });
                }

            }

        } else {
            Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE,
                    "No JCatascopia metrics found in {0}", availableMetrics);
        }

    } catch (Exception e) {
        Logger.getLogger(JCatascopiaDataSource.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:caesar.feng.framework.utils.ACache.java

/**
 * ? String?  /*from  w w w  . j av a 2s.com*/
 * 
 * @param key
 *            ?key
 * @param value
 *            ?String?
 */
public void put(String key, String value) {
    File file = mCache.newFile(key);
    BufferedWriter out = null;
    try {
        out = new BufferedWriter(new FileWriter(file), 1024);
        out.write(value);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        mCache.put(file);
    }
}

From source file:es.sotileza.plugin.utils.Utilidades.java

public static void paintMaestroDWR(String file, List<String> tr1, ArquetipoVO arq, List<TablaVO> tablas)
        throws IOException {
    FileWriter output = new FileWriter(file);
    BufferedWriter writer = new BufferedWriter(output);

    writer.write("package " + arq.getPakete() + ".web.dwr;\n\r");

    writer.write("\nimport org.apache.commons.logging.Log;");
    writer.write("\nimport org.apache.commons.logging.LogFactory;");
    writer.write("\nimport org.springframework.context.ApplicationContext;");
    writer.write("\nimport org.springframework.context.support.ClassPathXmlApplicationContext;");
    writer.write("\nimport " + arq.getPakete() + ".business.vo.*;");
    writer.write("\nimport " + arq.getPakete() + ".web.delegate.*;");
    writer.write("\n\r");

    writer.write("\npublic class MaestrosController {\n\r");
    writer.write("\n\tprivate static Log log = LogFactory.getFactory().getInstance(MaestrosController.class);");
    writer.write(//  ww  w .j  a v a2  s . c  o  m
            "\n\tprivate static ApplicationContext contextApplication = new ClassPathXmlApplicationContext(");
    writer.write("\n\t\t\tnew String[] { \"beans/business/dao-beans.xml\",");
    writer.write("\n\t\t\t\"beans/business/datasource-beans.xml\",");
    writer.write("\n\t\t\t\"beans/business/transaction-beans.xml\",");
    writer.write("\n\t\t\t\"beans/business/manager-beans.xml\",");
    writer.write("\n\t\t\t\"beans/web/delegate-beans.xml\"});\n\r");

    for (TablaVO tab : tablas) {
        if (tab.getNivel().equals("maestro")) {
            writer.write("\n\tprivate " + tab.getDelegateClase() + " " + tab.getDelegateVariable() + " = " + "("
                    + tab.getDelegateClase() + ")contextApplication.getBean(\"" + tab.getDelegateVariable()
                    + "\");\n");
        }
    }
    for (String i : tr1)
        writer.write(i + "\n");
    writer.write("\n}");
    System.out.println("Generado el fichero: " + file);
    writer.flush();
}