Example usage for java.io FileWriter flush

List of usage examples for java.io FileWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:code.google.restclient.client.HitterClient.java

private File stringToFile(String str, String contentType) throws RCException {

    if (RCUtil.isEmpty(str))
        return null;
    String timeStamp = SDF.format(new Date());
    File tmpFile = new File(Configurator.getTempRespFilesDir(),
            "output_" + timeStamp + "." + RCConstants.TEMP_FILE_EXT);
    File outputFile = null;/*  w  w  w .ja va2s .  c  o  m*/
    FileWriter fw = null;
    try {
        fw = new FileWriter(tmpFile);
        fw.write(str);
        fw.flush();
    } catch (Exception e) {
        throw new RCException("stringToFile(): error occurred while writing to file", e);
    } finally {
        try {
            if (fw != null)
                fw.close();
            outputFile = changeFileExtension(tmpFile, contentType);
        } catch (IOException e) {
            throw new RCException("stringToFile(): error occurred while closing file writer", e);
        }
    }
    return outputFile;
}

From source file:net.mindengine.galen.reports.HtmlSuiteReportingListener.java

@Override
public void done() {
    try {/*from   w w w .j  ava 2 s .com*/
        HtmlReportingListener.makeSureReportFolderExists(reportFolderPath);

        File file = new File(reportFolderPath + File.separator + reportFileName + ".html");
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new RuntimeException("Cannot create file: " + file.getAbsolutePath());
            }
        }
        FileWriter fileWriter = new FileWriter(file);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("suiteName", suiteName);
        model.put("pageTests", pageTests);
        template.process(model, fileWriter);
        fileWriter.flush();
        fileWriter.close();

        moveScreenshots();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:test.gov.nih.nci.cacoresdk.domain.inheritance.implicit.TankResourceTest.java

/**
 * Uses Nested Search Criteria for search
 * Verifies that the results are returned 
 * Verifies size of the result set//w  w w .ja  v a2 s . c o m
 * Verifies that none of the attributes are null
 * 
 * @throws Exception
 */
public void testGet() throws Exception {

    try {

        Tank searchObject = new Tank();
        Collection results = getApplicationService()
                .search("gov.nih.nci.cacoresdk.domain.inheritance.implicit.Tank", searchObject);
        String id = "";

        if (results != null && results.size() > 0) {
            Tank obj = (Tank) ((List) results).get(0);

        } else
            return;

        if (id.equals(""))
            return;

        String url = baseURL + "/rest/Tank/" + id;

        WebClient client = WebClient.create(url);
        client.type("application/xml").accept("application/xml");
        Response response = client.get();

        if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        File myFile = new File("Tank" + "XML.xml");

        System.out.println("writing data to file " + myFile.getAbsolutePath());
        FileWriter myWriter = new FileWriter(myFile);

        BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            myWriter.write(output);
            System.out.println(output);
        }

        myWriter.flush();
        myWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

}

From source file:au.org.ala.spatial.analysis.layers.LayerDistanceIndex.java

/**
 * @param threadcount    number of threads to run analysis.
 * @param onlyThesePairs array of distances to run as fieldId1 + " " +
 *                       fieldId2 where fieldId1.compareTo(fieldId2) &lt 0 or null for all missing
 *                       distances./*from  w  w w.  j a  v  a 2  s  .com*/
 * @throws InterruptedException
 */
public void occurrencesUpdate(int threadcount, String[] onlyThesePairs) throws InterruptedException {

    //create distances file if it does not exist.
    File layerDistancesFile = new File(IntersectConfig.getAlaspatialOutputPath() + LAYER_DISTANCE_FILE);
    if (!layerDistancesFile.exists()) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(layerDistancesFile);
            fw.flush();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (fw != null) {
                try {
                    fw.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    Map<String, Double> map = loadDistances();

    LinkedBlockingQueue<String> todo = new LinkedBlockingQueue();

    if (onlyThesePairs != null && onlyThesePairs.length > 0) {
        for (String s : onlyThesePairs) {
            todo.add(s);
        }
    } else {
        //find all environmental layer analysis files
        File root = new File(IntersectConfig.getAlaspatialOutputPath());
        File[] dirs = root.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return pathname != null && pathname.isDirectory();
            }
        });

        HashMap<String, String> domains = new HashMap<String, String>();
        for (File dir : dirs) {
            //iterate through files so we get everything
            File[] files = new File(dir.getPath()).listFiles(new FileFilter() {

                @Override
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".grd") && pathname.getName().startsWith("el");
                }
            });

            for (int i = 0; i < files.length; i++) {
                for (int j = i + 1; j < files.length; j++) {
                    String file1 = files[i].getName().replace(".grd", "");
                    String file2 = files[j].getName().replace(".grd", "");

                    //only operate on file names that are valid fields
                    if (Client.getFieldDao().getFieldById(file1) != null
                            && Client.getFieldDao().getFieldById(file2) != null) {

                        String domain1 = domains.get(file1);
                        if (domain1 == null) {
                            String pid1 = Client.getFieldDao().getFieldById(file1).getSpid();
                            domain1 = Client.getLayerDao().getLayerById(Integer.parseInt(pid1)).getdomain();
                            domains.put(file1, domain1);
                        }
                        String domain2 = domains.get(file2);
                        if (domain2 == null) {
                            String pid2 = Client.getFieldDao().getFieldById(file2).getSpid();
                            domain2 = Client.getLayerDao().getLayerById(Integer.parseInt(pid2)).getdomain();
                            domains.put(file2, domain2);
                        }

                        String key = (file1.compareTo(file2) < 0) ? file1 + " " + file2 : file2 + " " + file1;

                        //domain test
                        if (isSameDomain(parseDomain(domain1), parseDomain(domain2))) {
                            if (!map.containsKey(key) && !todo.contains(key)) {
                                todo.put(key);
                            }
                        }
                    }
                }
            }
        }
    }

    LinkedBlockingQueue<String> toDisk = new LinkedBlockingQueue<String>();
    CountDownLatch cdl = new CountDownLatch(todo.size());
    CalcThread[] threads = new CalcThread[threadcount];
    for (int i = 0; i < threadcount; i++) {
        threads[i] = new CalcThread(cdl, todo, toDisk);
        threads[i].start();
    }

    ToDiskThread toDiskThread = new ToDiskThread(
            IntersectConfig.getAlaspatialOutputPath() + LAYER_DISTANCE_FILE, toDisk);
    toDiskThread.start();

    cdl.await();

    for (int i = 0; i < threadcount; i++) {
        threads[i].interrupt();
    }

    toDiskThread.interrupt();
}

From source file:com.photon.phresco.framework.impl.ApplicationManagerImpl.java

private void writeJson(String json, File path) throws IOException {
    S_LOGGER.debug("Entering Method ProjectAdministratorImpl.writeJson(String json, File path)");
    FileWriter writer = null;
    try {//from   ww w.  j a  v  a2s . c o  m
        S_LOGGER.debug("writeJson()  File path = " + path.getPath());
        writer = new FileWriter(path);
        writer.write(json);
        writer.flush();
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                S_LOGGER.warn("writeJson() > error inside finally");

            }
        }
    }
}

From source file:net.mindengine.galen.reports.HtmlReportingListener.java

@Override
public void done() {
    try {// w  w w .  jav a  2s .c o m
        makeSureReportFolderExists(reportFolderPath);

        File file = new File(reportFolderPath + File.separator + "report.html");
        if (!file.exists()) {
            if (!file.createNewFile()) {
                throw new RuntimeException("Cannot create file: " + file.getAbsolutePath());
            }
        }
        FileWriter fileWriter = new FileWriter(file);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("suiteRuns", suiteRunList);
        template.process(model, fileWriter);
        fileWriter.flush();
        fileWriter.close();

        copyHtmlResources();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.google.mist.plot.MainActivity.java

private void dumpSensorData() throws JSONException { //TODO(cjr): do we want JSONException here?
    File dataDir = getOrCreateSessionDir();
    File target = new File(dataDir, String.format("%s.json", mRecordingType));

    JSONObject jsonObject = new JSONObject();
    jsonObject.put("version", "1.0.0");

    boolean isCalibrated = mPullDetector.getCalibrationStatus();
    jsonObject.put("calibrated", isCalibrated);

    // Write system information
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    display.getSize(size);//  ww w . ja v  a  2s  .  c  om
    JSONObject deviceData = new JSONObject();
    deviceData.put("Build.DEVICE", Build.DEVICE);
    deviceData.put("Build.MODEL", Build.MODEL);
    deviceData.put("Build.PRODUCT", Build.PRODUCT);
    deviceData.put("Build.VERSION.SDK_INT", Build.VERSION.SDK_INT);
    deviceData.put("screenResolution.X", size.x);
    deviceData.put("screenResolution.Y", size.y);
    jsonObject.put("systemInfo", deviceData);

    // Write magnetometer data
    JSONArray magnetData = new JSONArray();
    for (int i = 0; i < mSensorData.size(); i++) {
        JSONArray dataPoint = new JSONArray();
        long time = mSensorTime.get(i);
        dataPoint.put(time);
        dataPoint.put(mSensorAccuracy.get(i));
        float[] data = mSensorData.get(i);
        for (float d : data) {
            dataPoint.put(d);
        }
        magnetData.put(dataPoint);
    }
    jsonObject.put("magnetometer", magnetData);

    // Write onAccuracyChanged data
    JSONArray accuracyChangedData = new JSONArray();
    for (int i = 0; i < mAccuracyData.size(); i++) {
        JSONArray dataPoint = new JSONArray();
        long time = mAccuracyTime.get(i);
        dataPoint.put(time);
        dataPoint.put(mAccuracyData.get(i));
        accuracyChangedData.put(dataPoint);
    }
    jsonObject.put("onAccuracyChangedData", accuracyChangedData);

    // Write rotation data
    if (mRecordRotation) {
        JSONArray rotationData = new JSONArray();
        for (int i = 0; i < mSensorData.size(); i++) {
            JSONArray dataPoint = new JSONArray();
            long time = mRotationTime.get(i);
            dataPoint.put(time);
            float[] data = mRotationData.get(i);
            for (float d : data) {
                dataPoint.put(d);
            }
            rotationData.put(dataPoint);
        }
        jsonObject.put("rotation", rotationData);
    }

    // Write event labels
    JSONArray trueLabels = new JSONArray();
    for (int i = 0; i < mPositivesData.size(); i++) {
        JSONArray dataPoint = new JSONArray();
        long time = mPositivesTime.get(i);
        dataPoint.put(time);
        dataPoint.put(mPositivesData.get(i));
        trueLabels.put(dataPoint);
    }
    jsonObject.put("labels", trueLabels);

    try {
        FileWriter fw = new FileWriter(target, true);
        fw.write(jsonObject.toString());
        fw.flush();
        fw.close();
        mDumpPath = target.toString();
    } catch (IOException e) {
        Log.e(TAG, e.toString());
    }
}

From source file:test.gov.nih.nci.cacoresdk.domain.inheritance.abstrakt.PupilResourceTest.java

public void testSearch() throws Exception {

    try {/*w ww .j a  v a  2  s.c  o m*/

        String url = baseURL + "/rest/Pupil/search;id=*";
        WebClient client = WebClient.create(url);
        client.type("application/xml").accept("application/xml");
        Response response = client.get();

        if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        File myFile = new File("Pupil_Search" + "XML.xml");
        System.out.println("writing data to file " + myFile.getAbsolutePath());
        FileWriter myWriter = new FileWriter(myFile);

        BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            myWriter.write(output);
            System.out.println(output);
        }

        myWriter.flush();
        myWriter.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:test.gov.nih.nci.cacoresdk.domain.inheritance.childwithassociation.BankResourceTest.java

public void testSearch() throws Exception {

    try {//from  w ww.  ja v a  2  s .  c o m

        String url = baseURL + "/rest/Bank/search;id=*";
        WebClient client = WebClient.create(url);
        client.type("application/xml").accept("application/xml");
        Response response = client.get();

        if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        File myFile = new File("Bank_Search" + "XML.xml");
        System.out.println("writing data to file " + myFile.getAbsolutePath());
        FileWriter myWriter = new FileWriter(myFile);

        BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            myWriter.write(output);
            System.out.println(output);
        }

        myWriter.flush();
        myWriter.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:test.gov.nih.nci.cacoresdk.domain.inheritance.childwithassociation.CashResourceTest.java

public void testSearch() throws Exception {

    try {/*from w  w w.  ja  v a2  s  .c  o m*/

        String url = baseURL + "/rest/Cash/search;id=*";
        WebClient client = WebClient.create(url);
        client.type("application/xml").accept("application/xml");
        Response response = client.get();

        if (response.getStatus() == Status.NOT_ACCEPTABLE.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() == Status.NOT_FOUND.getStatusCode()) {
            InputStream is = (InputStream) response.getEntity();
            org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder(false);
            org.jdom.Document jDoc = builder.build(is);
            assertEquals(jDoc.getRootElement().getName(), "response");
        } else if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }

        File myFile = new File("Cash_Search" + "XML.xml");
        System.out.println("writing data to file " + myFile.getAbsolutePath());
        FileWriter myWriter = new FileWriter(myFile);

        BufferedReader br = new BufferedReader(new InputStreamReader(((InputStream) response.getEntity())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            myWriter.write(output);
            System.out.println(output);
        }

        myWriter.flush();
        myWriter.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

}