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.imaginary.home.cloud.CloudTest.java

@Before
public void setUp() throws Exception {
    cloudAPI = System.getProperty("cloudAPI", "http://15.185.177.82:8080");
    File f = new File("target/iha");

    if (!f.exists()) {
        //noinspection ResultOfMethodCallIgnored
        f.mkdir();/*from www .ja va2  s  .c o  m*/
    }
    f = new File(HomeController.CONFIG_FILE);
    if (!f.exists()) {
        HashMap<String, Object> cfg = new HashMap<String, Object>();

        cfg.put("name", "Relay Test");

        ArrayList<Map<String, Object>> systems = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> hue = new HashMap<String, Object>();
        HashMap<String, Object> auth = new HashMap<String, Object>();

        String hueIp = System.getProperty("ip");
        String hueAccessKey = System.getProperty("accessKey");

        auth.put("ipAddress", hueIp);
        auth.put("accessKey", hueAccessKey);

        hue.put("cname", Hue.class.getName());
        hue.put("id", "1");
        hue.put("authenticationProperties", auth);
        hue.put("customProperties", new HashMap<String, Object>());
        systems.add(hue);
        cfg.put("systems", systems);

        cfg.put("services", new ArrayList<Map<String, Object>>());

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));

        writer.write((new JSONObject(cfg)).toString());
        writer.newLine();
        writer.flush();
        writer.close();
    }
    if (name.getMethodName().equals("createLocation") && apiKeyId == null) {
        setupUser();
    }
    if (name.getMethodName().equals("initializePairing") && locationId == null) {
        setupLocation();
    }
    if (name.getMethodName().equals("pair") && pairingCode == null) {
        setupPairing();
    }
    if (name.getMethodName().equals("token") && relayKeyId == null) {
        setupRelay();
    }
    if (name.getMethodName().equals("pushState") && token == null) {
        setupToken();
    }
    if (name.getMethodName().equals("listDevices") && testDeviceId == null) {
        setupDevices();
    }
    if (name.getMethodName().equals("flipOn") && testDeviceId == null) {
        setupDevices();
    }
    if (name.getMethodName().equals("listCommands") && testCommandId == null) {
        setupCommand();
    }
    if (name.getMethodName().equals("fetchWaitingCommands") && testCommandId == null) {
        setupCommand();
    }
}

From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java

public void run() {
    Socket socket;/*from w  w w .j  a  va  2  s. co m*/
    BufferedReader input;
    BufferedWriter output;

    kuc_log.i("Connecting to server at " + server_ip);

    try {
        socket = new Socket();
        socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000);
        input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    } catch (SocketTimeoutException e) {
        kuc_log.e("Connection to server timed out!");
        e.printStackTrace();
        return;
    } catch (ConnectException e) {
        kuc_log.e("Connection to server was refused!");
        e.printStackTrace();
        return;
    } catch (UnknownHostException e) {
        kuc_log.e("You entered an invalid IP address!");
        e.printStackTrace();
        return;
    } catch (IOException e) {
        kuc_log.e("Error connecting to server!");
        e.printStackTrace();
        return;
    }

    try {
        kuc_log.i("Requesting a key update.");
        output.write("302 request key update");
        output.newLine();
        output.flush();

        kuc_log.i("Awaiting response from server.");
        String update = input.readLine();
        switch (update) {
        case "303 update":
            kuc_log.i("Server accepted update request, sending public key.");
            String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded());
            output.write(pubkeyB64);
            output.newLine();
            output.flush();
            output.close();
            break;
        case "304 no update":
            kuc_log.i("Server rejected update request, closing connection.");
            input.close();
            output.close();
            break;
        case "305 update unavailable":
            kuc_log.i("Server cannot update at this time, try again later.");
            input.close();
            output.close();
            break;
        default:
            kuc_log.i("Server sent back invalid response");
            input.close();
            output.close();
            break;
        }
    } catch (IOException e) {
        kuc_log.e("Error in key update request!");
        e.printStackTrace();
    }
}

From source file:de.tudarmstadt.ukp.dkpro.tc.mallet.util.MalletUtils.java

public static void outputEvaluation(TransducerEvaluator eval, File fileEvaluation) throws IOException {
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(fileEvaluation), "UTF-8"));

    ArrayList<String> labelNames = ((PerClassEvaluator) eval).getLabelNames();

    ArrayList<Double> precisionValues = ((PerClassEvaluator) eval).getPrecisionValues();
    ArrayList<Double> recallValues = ((PerClassEvaluator) eval).getRecallValues();
    ArrayList<Double> f1Values = ((PerClassEvaluator) eval).getF1Values();

    int numLabels = labelNames.size();
    bw.write("Measure,Value");
    bw.write("\n" + MalletReportConstants.CORRECT + ","
            + ((PerClassEvaluator) eval).getNumberOfCorrectPredictions());
    bw.write("\n" + MalletReportConstants.INCORRECT + ","
            + ((PerClassEvaluator) eval).getNumberOfIncorrectPredictions());
    bw.write("\n" + MalletReportConstants.NUMBER_EXAMPLES + ","
            + ((PerClassEvaluator) eval).getNumberOfExamples());
    bw.write("\n" + MalletReportConstants.PCT_CORRECT + ","
            + ((PerClassEvaluator) eval).getPercentageOfCorrectPredictions());
    bw.write("\n" + MalletReportConstants.PCT_INCORRECT + ","
            + ((PerClassEvaluator) eval).getPercentageOfIncorrectPredictions());

    for (int i = 0; i < numLabels; i++) {
        String label = labelNames.get(i);
        bw.write("\n" + MalletReportConstants.PRECISION + "_" + label + "," + precisionValues.get(i));
        bw.write("\n" + MalletReportConstants.RECALL + "_" + label + "," + recallValues.get(i));
        bw.write("\n" + MalletReportConstants.FMEASURE + "_" + label + "," + f1Values.get(i));
        bw.flush();
    }// w w w  .j a  v  a2s. c  o m
    bw.write("\n" + MalletReportConstants.MACRO_AVERAGE_FMEASURE + ","
            + ((PerClassEvaluator) eval).getMacroAverage());
    bw.flush();
    bw.close();
}

From source file:com.st.cms.utils.ACache.java

/**
 * ? String?  /* ww  w  .  j  a v a2 s.  c  o m*/
 * 
 * @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); // ?file?
        out.write(value);// value
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (out != null) {
            try {
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // cacheCountcacheSize lastUsageDates?
        mCache.put(file);
    }
}

From source file:edu.isi.pfindr.learn.util.PairsFileIO.java

private void getGoldClassForPairs(String inputFilePath) {

    LinkedMap originalTestPairsClassMap = new LinkedMap();
    String originalTestPairsFile = "data/cohort1/bio_nlp/cohort1_s_test_pairs.txt";
    BufferedReader br = null;/*w  w w  . jav a  2 s  .com*/
    String[] lineArray;
    String thisLine;
    try {
        br = new BufferedReader(new FileReader(originalTestPairsFile));
        while ((thisLine = br.readLine()) != null) {
            thisLine = thisLine.trim();
            if (thisLine.equals(""))
                continue;

            lineArray = thisLine.split("\t");
            originalTestPairsClassMap.put(lineArray[0] + "\t" + lineArray[1], lineArray[2]);
        }
    } catch (IOException io) {
        try {
            if (br != null)
                br.close();
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream " + br);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    List<String> phenotypeList = null;
    StringBuffer resultFileBuffer = new StringBuffer();

    //Read the pairs file, and write the pairs with class from actual test file
    try {
        BufferedWriter resultPairsWriter = new BufferedWriter(
                new FileWriter(inputFilePath.split("\\.")[0] + "_with_gold_class.txt"));
        phenotypeList = FileUtils.readLines(new File(inputFilePath));

        for (int i = 0; i < phenotypeList.size(); i++) {

            lineArray = phenotypeList.get(i).split("\t");
            resultFileBuffer.append(lineArray[0]).append("\t").append(lineArray[1]).append("\t")
                    .append(originalTestPairsClassMap.get(lineArray[0] + "\t" + lineArray[1])).append("\n");
        }

        resultPairsWriter.append(resultFileBuffer.toString());
        resultFileBuffer.setLength(0);
        resultPairsWriter.flush();

    } catch (IOException e) {
        System.out.println("Error while reading/writing file with pairs" + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.tudarmstadt.ukp.dkpro.core.io.web1t.Web1TFormatWriter.java

private void writeNGramFile(ConditionalFrequencyDistribution<Integer, String> cfd, int level)
        throws AnalysisEngineProcessException {
    FrequencyDistribution<String> letterFD = letterFDs.get(level);
    try {/*w  w w.j a  v  a2  s  .  c  o m*/
        BufferedWriter writer = ngramWriters.get(level);
        for (String key : cfd.getFrequencyDistribution(level).getKeys()) {

            // add starting letter to frequency distribution
            if (key.length() > 1) {
                String subsKey = key.substring(0, 2);
                String subsKeyLowered = subsKey.toLowerCase();
                letterFD.addSample(subsKeyLowered, 1);
            } else {
                String subsKey = key.substring(0, 1);
                String subsKeyLowered = subsKey.toLowerCase();
                letterFD.addSample(subsKeyLowered, 1);
            }

            writer.write(key);
            writer.write(TAB);
            writer.write(Long.toString(cfd.getCount(level, key)));
            writer.write(LF);
        }
        writer.flush();
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }

}

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

/**
 * {@inheritDoc}//from  www  .  ja  va2  s  . c o m
 */
public void write(final OutputStream os, final Proteins data) throws IOException {
    if (data == null) {
        throw new IllegalArgumentException();
    }

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

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

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

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

    Iterator<Protein> it = data.proteinIterator();
    while (it.hasNext()) {
        Protein protein = it.next();
        bufWriter.write(prefix0 + "<protein>\n");

        Map<String, Object> infoMap = protein.getInfoMap();

        for (String field : fieldList(infoMap.keySet())) {
            if (proteinFieldFilter != null && proteinFieldFilter.contains(field) != proteinFieldInclude)
                continue;

            Object value = infoMap.get(field);
            if (value == null)
                continue;

            bufWriter.write(prefix1 + "<" + field + ">");

            Writer fieldWriter = proteinFieldWriters.get(field);
            if (fieldWriter == null) {
                fieldWriter = XMLUtil.createDefaultWriter(value);
                bufWriter.flush();
                fieldWriter.write(os, value);
            } else {
                Boolean isIndent = proteinFieldIndent.get(field);
                if (isIndent != null && isIndent)
                    bufWriter.write("\n");
                bufWriter.flush();
                if (isIndent != null && isIndent && fieldWriter instanceof AbstractXMLWriter)
                    ((AbstractXMLWriter) fieldWriter).setIndent(indent + 2);
                fieldWriter.write(os, value);
                if (isIndent != null && isIndent)
                    bufWriter.write(prefix1);
            }

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

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

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

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

    bufWriter.flush();
}

From source file:org.sasabus.export2Freegis.network.DataReadyManager.java

@Override
public void handle(HttpExchange httpExchange) throws IOException {
    long start = System.currentTimeMillis();
    BufferedReader in = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "UTF-8"));
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(httpExchange.getResponseBody()));
    try {/*  w  w w. j  a  v a 2 s  . co m*/
        StringBuilder requestStringBuff = new StringBuilder();
        int b;
        while ((b = in.read()) != -1) {
            requestStringBuff.append((char) b);
        }
        Scanner sc = new Scanner(new File(DATAACKNOWLEDGE));
        String rdyackstring = "";
        while (sc.hasNextLine()) {
            rdyackstring += sc.nextLine();
        }
        sc.close();
        SimpleDateFormat date_date = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat date_time = new SimpleDateFormat("HH:mm:ssZ");

        Date d = new Date();
        String timestamp = date_date.format(d) + "T" + date_time.format(d);
        timestamp = timestamp.substring(0, timestamp.length() - 2) + ":"
                + timestamp.substring(timestamp.length() - 2);

        rdyackstring = rdyackstring.replaceAll(":timestamp", timestamp);

        httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, rdyackstring.length());
        out.write(rdyackstring);
        out.flush();
        long before_elab = System.currentTimeMillis() - start;
        DataRequestManager teqrequest = new DataRequestManager(this.hostname, this.portnumber);
        String datarequest = teqrequest.datarequest();
        ArrayList<TeqObjects> requestelements = TeqXMLUtils.extractFromXML(datarequest);
        int vtcounter = 0;
        if (!requestelements.isEmpty()) {
            Iterator<TeqObjects> iterator = requestelements.iterator();
            System.out.println("Sending List of Elements!");
            String geoJson = "{\"type\":\"FeatureCollection\",\"features\":[";
            while (iterator.hasNext()) {
                TeqObjects object = iterator.next();
                if (object instanceof VehicleTracking) {
                    geoJson += ((VehicleTracking) object).toGeoJson() + ",";
                    ++vtcounter;
                }
            }
            if (geoJson.charAt(geoJson.length() - 1) == ',') {
                geoJson = geoJson.substring(0, geoJson.length() - 1);
            }
            geoJson += "]}";
            System.out.println(
                    "GeoJson sent! (Nr of elements: " + vtcounter + "/" + requestelements.size() + " )");
            HttpPost subrequest = new HttpPost(DATASEND);

            StringEntity requestEntity = new StringEntity(geoJson,
                    ContentType.create("application/json", "UTF-8"));

            CloseableHttpClient httpClient = HttpClients.createDefault();

            subrequest.setEntity(requestEntity);
            long after_elab = System.currentTimeMillis() - start;
            CloseableHttpResponse response = httpClient.execute(subrequest);
            //System.out.println("Stauts JsonSend Response: " + response.getStatusLine().getStatusCode());
            //System.out.println("Status JsonSend Phrase: " + response.getStatusLine().getReasonPhrase());
            httpClient.close();
            long before_db = System.currentTimeMillis() - start;
            dbmanager.insertIntoDatabase(requestelements);
            System.out.format(
                    "Thread time (ms) : Before elab: %d, After Elab (before http sending): %d, Before db: %d, Total: %d, Thread name: %s, Objects elaborated: %d",
                    before_elab, after_elab, before_db, (System.currentTimeMillis() - start),
                    Thread.currentThread().getName(), requestelements.size());
            System.out.println("");
        }

    } catch (IOException e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        System.exit(-1);
        return;
    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
        if (httpExchange != null)
            httpExchange.close();
    }
}

From source file:com.ikon.servlet.frontend.StaplingDownloadServlet.java

/**
 * Generate a zip file from a repository folder path   
 *//*  w  ww  . java 2s.  co  m*/
private void exportZip(int sgId, OutputStream os) throws RepositoryException, IOException, DatabaseException {
    log.debug("exportZip({}, {})", sgId, os);
    File tmpDir = null;
    BufferedWriter bw = null;
    OKMDocument okmDoc = OKMDocument.getInstance();
    OKMRepository okmRepo = OKMRepository.getInstance();

    try {
        tmpDir = FileUtils.createTempDir();
        bw = new BufferedWriter(new FileWriter(new File(tmpDir, "summary.txt")));
        StapleGroup sg = StapleGroupDAO.findByPk(sgId);

        for (Staple s : sg.getStaples()) {
            String uuid = s.getUuid();
            String path = null;

            try {
                path = okmRepo.getNodePath(null, uuid);
                int idx = path.indexOf('/', 1);

                if (idx > 0) {
                    String relPath = path.substring(idx);
                    File expFile = new File(tmpDir, relPath);
                    expFile.getParentFile().mkdirs();
                    FileOutputStream fos = new FileOutputStream(expFile);

                    if (okmDoc.isValid(null, path)) {
                        InputStream is = okmDoc.getContent(null, path, false);
                        IOUtils.copy(is, fos);
                        is.close();
                    }

                    bw.write(path + " - OK\n");
                    bw.flush();
                }
            } catch (PathNotFoundException e) {
                bw.write(path != null ? path : uuid + " - " + e.getMessage() + "\n");
                bw.flush();
            } catch (AccessDeniedException e) {
                bw.write(path != null ? path : uuid + " - " + e.getMessage() + "\n");
                bw.flush();
            }
        }

        // Zip files
        IOUtils.closeQuietly(bw);
        ArchiveUtils.createZip(tmpDir, "stapling", os);
    } catch (IOException e) {
        log.error("Error exporting zip", e);
        throw e;
    } finally {
        if (tmpDir != null) {
            try {
                org.apache.commons.io.FileUtils.deleteDirectory(tmpDir);
            } catch (IOException e) {
                log.error("Error deleting temporal directory", e);
                throw e;
            }
        }
    }

    log.debug("exportZip: void");
}

From source file:org.moeaframework.analysis.plot.Plot.java

/**
 * Saves the plot to an image file.  The format must be one of {@code png},
 * {@code jpeg}, or {@code svg} (requires JFreeSVG).
 * //from   www  .  j  a v a2  s. co m
 * @param file the file
 * @param format the image format
 * @param width the image width
 * @param height the image height
 * @return a reference to this {@code Plot} instance
 * @throws IOException if an I/O error occurred
 */
public Plot save(File file, String format, int width, int height) throws IOException {
    if (format.equalsIgnoreCase("PNG")) {
        ChartUtilities.saveChartAsPNG(file, chart, width, height);
    } else if (format.equalsIgnoreCase("JPG") || format.equalsIgnoreCase("JPEG")) {
        ChartUtilities.saveChartAsJPEG(file, chart, width, height);
    } else if (format.equalsIgnoreCase("SVG")) {
        String svg = generateSVG(width, height);
        BufferedWriter writer = null;

        try {
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(
                    "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n");
            writer.write(svg);
            writer.write("\n");
            writer.flush();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    return this;
}