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.zestedesavoir.zestwriter.model.Content.java

public void saveToHtml(File file, MdTextController index) {
    try (FileOutputStream fos = new FileOutputStream(file)) {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
        String mdValue = exportContentToMarkdown(0, getDepth());
        String htmlValue = StringEscapeUtils.unescapeHtml4(index.markdownToHtml(mdValue));
        htmlValue = normalizeHtml(htmlValue);
        writer.append(MainApp.getMdUtils().addHeaderAndFooterStrict(htmlValue, getTitle()));
        writer.flush();
    } catch (Exception e) {
        MainApp.getLogger().error(e.getMessage(), e);
    }/*from   www  .  j  av a2  s  .  c  o m*/
}

From source file:org.jvnet.hudson.generators.JobConfigGenerator.java

/**
 * This returns a String for easier integration with the test cases.
 * Please, note that the actual writing is also handled here.
 *
 * @return//from   w ww.j ava 2 s .  c o m
 */
@Override
public String generate() {
    String configBody = getConfigBody(jobConfig.getBuilderType());

    BufferedWriter bufferedWriter = null;
    try {
        File outputFile = new File(outputDirectory + File.separatorChar + CONFIG_FILE_NAME).getAbsoluteFile();

        if (outputFile.exists())
            getLog().warn("The output file '" + outputFile + "' already exists!");

        bufferedWriter = new BufferedWriter(new FileWriter(outputFile));
        bufferedWriter.write(configBody);
        bufferedWriter.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (bufferedWriter != null) {
            try {
                bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return configBody;
}

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

/**
 * Save the generated en/decryption key.
 *///  w w  w .  j  a  v  a 2 s.  c om
public void saveKeyFile(String file, Key k) throws IOException {
    BufferedWriter bw = null;
    try {
        FileWriter fw = new FileWriter(file);
        bw = new BufferedWriter(fw);
        bw.write(Hex.encodeHexString(k.getEncoded()));
        bw.flush();
    } catch (IOException e) {
        throw new IOException("Error saving key file :'" + file + "': " + e.getMessage());
    } finally {
        bw.close();
    }
}

From source file:com.orange.atk.results.logger.documentGenerator.GraphGenerator.java

/**
 * Generate a graph in png from the provided plot list. The X axis of the
 * graph is in minutes./*from   ww  w  .  j av  a2s. c o m*/
 * 
 * @param plotList
 *            plotlist to save. Xvalues must be stored in milliseconds.
 * @param associatedName
 *            kind of the list
 * @param folderWhereResultsAreSaved
 *            folder where graph while be saved
 * @param yLabel
 *            name of the y label
 * @param pictureFile
 *            name of the file where the picture would be saved (path should
 *            be absolute)
 * @param yDivisor divisor of the measurements
 */
public static void generateGraph(PlotList plotList, String associatedName, String folderWhereResultsAreSaved,
        String yLabel, String pictureFile, float yDivisor) {
    Logger.getLogger("generateGraph").debug(folderWhereResultsAreSaved + associatedName + ".cmd");
    // Store measurements in a file
    try {
        dumpInFile(plotList, folderWhereResultsAreSaved + associatedName + ".csv");

        // Create gnuplot scripts used to generate graphs
        if (plotList.isEmpty()) {
            Logger.getLogger(GraphGenerator.class).warn(associatedName + " plot list is empty");
            return;
        }

        // create a .cmd which will be given to the gnuplot program
        File commandFile = new File(folderWhereResultsAreSaved + associatedName + ".cmd");
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(commandFile)));
        // Picture will be saved in png
        bufferedWriter.write("set terminal png" + Platform.LINE_SEP);
        // Name of the picture
        bufferedWriter.write(
                "set output '" + folderWhereResultsAreSaved + associatedName + ".png'" + Platform.LINE_SEP);
        // format of the number on the y-axis
        bufferedWriter.write("set format y \"%.3s\"" + Platform.LINE_SEP);
        // Names of the axis
        bufferedWriter.write("set xlabel \"Time\"" + Platform.LINE_SEP);
        bufferedWriter.write("set ylabel \"" + yLabel + "\"" + Platform.LINE_SEP);
        // Set the range on y axis
        bufferedWriter.write("set yrange [" + (plotList.getMin() / yDivisor) * 0.9998 + ":"
                + (plotList.getMax() / yDivisor) * 1.0002 + "]" + Platform.LINE_SEP);
        bufferedWriter.write("set xtics autofreq" + Platform.LINE_SEP);
        bufferedWriter.write("set ytics autofreq" + Platform.LINE_SEP);
        bufferedWriter.write("plot '" + folderWhereResultsAreSaved + associatedName + ".csv' with lines"
                + Platform.LINE_SEP);
        bufferedWriter.flush();
        bufferedWriter.close();

        // call gnuplot for generating graphs
        Runtime runtime = Runtime.getRuntime();
        String gnuplotName = null;
        if (Platform.OS_NAME.toLowerCase().contains("windows")) {
            gnuplotName = "wgnuplot";
        } else {
            gnuplotName = "gnuplot";
        }
        String[] cmdsCpu1 = { gnuplotName, folderWhereResultsAreSaved + associatedName + ".cmd" };
        if (!plotList.isEmpty()) {
            // Call gnuplot
            int returnValue = runtime.exec(cmdsCpu1).waitFor();
            if (returnValue != 0) {
                Logger.getLogger(GraphGenerator.class).warn(
                        "Problem while creating graph. Does " + gnuplotName + " program belongs to PATH?");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.idynin.ftbutils.ModPack.java

/**
 * Used to check if the cached items are up to date
 * /*from w w w .ja  v  a2 s.co m*/
 * @param verFile - the version file to check
 * @return checks the version file against the current modpack version
 */
@SuppressWarnings("unused")
private boolean upToDate(File verFile) {
    String storedVersion = getStoredVersion(verFile).replace(".", "");

    if ("".equals(storedVersion)
            || Integer.parseInt(storedVersion) != Integer.parseInt(version.replace(".", ""))) {
        try {
            if (!verFile.exists()) {
                verFile.getParentFile().mkdirs();
                verFile.createNewFile();
            }
            BufferedWriter out = new BufferedWriter(new FileWriter(verFile));
            out.write(version);
            out.flush();
            out.close();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    return true;
}

From source file:org.codehaus.groovy.grails.scaffolding.AbstractGrailsTemplateGenerator.java

@Override
public void generateView(GrailsDomainClass domainClass, String viewName, String destDir) throws IOException {
    File destFile = new File(destDir, viewName + ".gsp");
    if (!canWrite(destFile)) {
        return;/*from ww  w. j  av a  2 s.c  o m*/
    }

    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(destFile));
        generateView(domainClass, viewName, writer);
        try {
            writer.flush();
        } catch (IOException ignored) {
        }
    } finally {
        IOGroovyMethods.closeQuietly(writer);
    }
}

From source file:com.ibm.util.merge.persistence.FilesystemPersistence.java

/**********************************************************************************
 * save provided template to the Template Folder as JSON, and add it to the Cache
 *
 * @param Template template the Template to save
 * @return a cloned copy of the Template ready for Merge Processing
 *//*  w ww .j a  va2  s .com*/
@Override
public void saveTemplate(Template template) {
    deleteTemplate(template);
    String fileName = templateFolder + File.separator + template.getFullName() + ".json";
    File file = new File(fileName);
    BufferedWriter bw = null;
    try {
        if (!file.exists()) {
            file.createNewFile();
        }
        File path = file.getAbsoluteFile();
        log.info("Saving " + template.getFullName() + " to " + path.getAbsolutePath());
        FileWriter fw = new FileWriter(path);
        bw = new BufferedWriter(fw);
        bw.write(jsonProxy.toJson(template));
        bw.flush();
        bw.close();
    } catch (IOException e) {
        throw new RuntimeException(
                "Could not write template " + template.getFullName() + " to JSON folder : " + file.getPath(),
                e);
    } finally {
        IOUtils.closeQuietly(bw);
    }
    return;
}

From source file:org.codehaus.groovy.grails.scaffolding.AbstractGrailsTemplateGenerator.java

private void generateTest(GrailsDomainClass domainClass, String destDir, String templateName)
        throws IOException {
    File destFile = new File(destDir, domainClass.getPackageName().replace('.', '/') + '/'
            + domainClass.getShortName() + "ControllerSpec.groovy");
    if (!canWrite(destFile)) {
        return;/*from  w  w  w.  j  a  v a  2  s. c o  m*/
    }

    String templateText = getTemplateText(templateName);

    Map<String, Object> binding = createBinding(domainClass);
    binding.put("packageName", domainClass.getPackageName());
    binding.put("propertyName", domainClass.getLogicalPropertyName());
    binding.put("modelName", getPropertyName(domainClass));

    destFile.getParentFile().mkdirs();
    BufferedWriter writer = null;
    try {
        writer = new BufferedWriter(new FileWriter(destFile));
        generate(templateText, binding, writer);
        try {
            writer.flush();
        } catch (IOException ignored) {
        }
    } finally {
        IOGroovyMethods.closeQuietly(writer);
    }
}

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

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

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

    writer.write("import " + arq.getPakete() + ".business.vo.*;");
    writer.write("import " + arq.getPakete() + ".business.manager.*;");
    writer.write("import java.util.List;");
    writer.write("import org.apache.commons.logging.Log;");
    writer.write("import org.apache.commons.logging.LogFactory;");
    writer.write("\n\r");

    writer.write("/**\n * Clase Delegate - Maestros\n */");
    writer.write("public class MaestrosDelegate {\n\r");

    writer.write("\tprivate static Log log = LogFactory.getFactory().getInstance(MaestrosDelegate.class);");
    writer.write("\n\tprivate MaestrosManager maestrosManager;\n");
    writer.write("\n\tpublic MaestrosManager getMaestrosManager(){");
    writer.write("\n\t\treturn this.maestrosManager;");
    writer.write("\n\t}");
    writer.write("\n\tpublic void setMaestrosManager( MaestrosManager maestrosManager ){");
    writer.write("\n\t\tthis.maestrosManager = maestrosManager;");
    writer.write("\n\t}\n\r");

    for (String i : tr1)
        writer.write(i + "\n");
    writer.write("}");
    System.out.println("Generado el fichero: " + file);
    writer.flush();
}

From source file:com.iyonger.apm.web.service.MonitorCollectorPlugin.java

@Override
public void startSampling(final ISingleConsole singleConsole, PerfTest perfTest,
        IPerfTestService perfTestService) {
    final List<String> targetHostIP = perfTest.getTargetHostIP();
    final Integer samplingInterval = perfTest.getSamplingInterval();
    for (final String target : targetHostIP) {
        scheduledTaskService.runAsync(new Runnable() {
            @Override//from w  w  w.j av  a2 s  .com
            public void run() {
                LOGGER.info("Start JVM monitoring for IP:{}", target);
                MonitorClientService client = new MonitorClientService(target,
                        MonitorCollectorPlugin.this.port);
                client.init();
                if (client.isConnected()) {
                    File testReportDir = singleConsole.getReportPath();
                    File dataFile = null;
                    FileWriter fw = null;
                    BufferedWriter bw = null;
                    try {
                        dataFile = new File(testReportDir, MONITOR_FILE_PREFIX + target + ".data");
                        fw = new FileWriter(dataFile, false);
                        bw = new BufferedWriter(fw);
                        // write header info
                        bw.write(SystemInfo.HEADER);
                        bw.newLine();
                        bw.flush();
                        clientMap.put(client, bw);
                    } catch (IOException e) {
                        LOGGER.error("Error to write to file:{}, Error:{}", dataFile.getPath(), e.getMessage());
                    } finally {
                        closeQuietly(bw);
                        closeQuietly(fw);
                    }
                }
            }
        });
    }
    assignScheduledTask(samplingInterval);
}