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:it.eng.spagobi.engines.talend.client.SpagoBITalendEngineClient_0_5_0.java

public boolean deployJob(JobDeploymentDescriptor jobDeploymentDescriptor, File executableJobFiles)
        throws EngineUnavailableException, AuthenticationFailedException, ServiceInvocationFailedException {

    HttpClient client;// w  ww . j  a  va 2s .c o m
    PostMethod method;
    File deploymentDescriptorFile;
    boolean result = false;

    client = new HttpClient();
    method = new PostMethod(getServiceUrl(JOB_UPLOAD_SERVICE));
    deploymentDescriptorFile = null;

    try {
        deploymentDescriptorFile = File.createTempFile("deploymentDescriptor", ".xml"); //$NON-NLS-1$ //$NON-NLS-2$
        FileWriter writer = new FileWriter(deploymentDescriptorFile);
        writer.write(jobDeploymentDescriptor.toXml());
        writer.flush();
        writer.close();

        Part[] parts = { new FilePart(executableJobFiles.getName(), executableJobFiles),
                new FilePart("deploymentDescriptor", deploymentDescriptorFile) }; //$NON-NLS-1$

        method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));

        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            if (method.getResponseBodyAsString().equalsIgnoreCase("OK")) //$NON-NLS-1$
                result = true;
        } else {
            throw new ServiceInvocationFailedException(
                    Messages.getString("SpagoBITalendEngineClient_0_5_0.serviceExcFailed") + JOB_UPLOAD_SERVICE, //$NON-NLS-1$
                    method.getStatusLine().toString(),
                    method.getResponseBodyAsString());
        }
    } catch (HttpException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.protocolViolation") + e.getMessage()); //$NON-NLS-1$
    } catch (IOException e) {
        throw new EngineUnavailableException(
                Messages.getString("SpagoBITalendEngineClient_0_5_0.transportError") + e.getMessage()); //$NON-NLS-1$
    } finally {
        method.releaseConnection();
        if (deploymentDescriptorFile != null)
            deploymentDescriptorFile.delete();
    }

    return result;
}

From source file:com.tzutalin.configio.JsonConfig.java

private boolean save() {
    // If  the file exists, load it first
    if (new File(mTargetPath).exists()) {
        loadFromFile();/*from ww  w .  jav  a2s.  c  o m*/
    }

    // Delete keys if the user removes keys but didn't call loadFromFile first
    if (mMap != null && mMap.size() != 0 && mDeleteKeySet.size() != 0) {
        for (String key : mDeleteKeySet) {
            mMap.remove(key);
        }
    }

    // Save to target path
    if (mMap != null && mMap.size() != 0) {
        JSONObject obj = new JSONObject(mMap);
        String jsonStr = obj.toString();
        Log.d(TAG, "save : " + mTargetPath + " json:" + jsonStr);
        try {
            FileWriter file = new FileWriter(mTargetPath);
            file.write(jsonStr);
            file.flush();
            file.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return false;
}

From source file:com.github.wellcomer.query3.core.Autocomplete.java

/**
    ?.   ?,  TreeSet ?  ? ?. ? TreeSet   .
        //from w  ww.  j a  v a2 s  .  c  o m
    @param queryList ?? ?.
    @param scanModifiedOnly ?   ?.
    @param mergePrevious ?? ?  ??  .
*/
public void autolearn(QueryList queryList, boolean scanModifiedOnly, boolean mergePrevious) throws IOException {

    FileTime timestamp;
    long modifiedSince = 0;
    Path timestampFilePath = Paths.get(filePath, ".timestamp");

    if (scanModifiedOnly) { //   
        try { //  ?   ? ?
            timestamp = Files.getLastModifiedTime(timestampFilePath);
            modifiedSince = timestamp.toMillis();
        } catch (IOException e) { //    ?    ? 
            Files.createFile(timestampFilePath);
        }
    }

    HashMap<String, TreeSet<String>> fields = new HashMap<>(); //  - ? ?,  -  ? 
    Iterator<Query> queryIterator = queryList.iterator(modifiedSince); // ? ?? ? ?  ?

    String k, v;

    while (queryIterator.hasNext()) {

        Query query = queryIterator.next();

        for (Map.Entry<String, String> entry : query.entrySet()) {

            k = entry.getKey().toLowerCase();
            v = entry.getValue().trim();

            if (v.length() < 2)
                continue;

            if (!fields.containsKey(k)) {

                TreeSet<String> treeSet = new TreeSet<>();

                try {
                    if (mergePrevious) { // ? ?  
                        List<String> lines = Files.readAllLines(Paths.get(filePath, k), charset);
                        treeSet.addAll(lines);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                fields.put(k, treeSet);
            }
            TreeSet<String> treeSet = fields.get(k);
            treeSet.add(v);
        }
    }

    for (Map.Entry<String, TreeSet<String>> entry : fields.entrySet()) {

        k = entry.getKey();
        ArrayList<String> lines = new ArrayList<>(fields.get(k));

        FileWriter fileWriter = new FileWriter(Paths.get(filePath, k).toString());
        fileWriter.write(StringUtils.join(lines, System.getProperty("line.separator")));
        fileWriter.flush();
        fileWriter.close();
    }

    try {
        Files.setLastModifiedTime(timestampFilePath, FileTime.fromMillis(System.currentTimeMillis()));
    } catch (IOException e) {
        if (e.getClass().getSimpleName().equals("NoSuchFileException"))
            Files.createFile(timestampFilePath);
        e.printStackTrace();
    }
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Servo.java

public void run() {
    try {/*from ww  w .j a va 2 s . co  m*/
        log.debug("starting execution of thread: " + threadName);
        // calls the servoblaster command to move the servo according to the
        // selected angle
        try {
            String servoBlasterDevice = "/dev/servoblaster";
            File servoBlasterDev = new File(servoBlasterDevice);
            if (!servoBlasterDev.exists()) {
                throw new FileNotFoundException("Servoblaster not found at " + servoBlasterDevice
                        + ". Please check https://github.com/richardghirst/PiBits/tree/master/ServoBlaster for details.");
            }
            FileWriter writer = new FileWriter(servoBlasterDev);
            StringBuilder b = new StringBuilder();
            b.append("0").append('=').append(Integer.toString(angle + 150)).append('\n');
            try {
                writer.write(b.toString());
                writer.flush();
            } catch (IOException e) {
                try {
                    writer.close();
                } catch (IOException ignore) {
                }
            }
            try {
                writer.write(b.toString());
                writer.flush();
            } catch (IOException e) {
                throw new RuntimeException("Failed to write to /dev/servoblaster device", e);
            }
        } catch (Exception e) {
            System.err.println(String.format("Could not execute the servoblaster command"));
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        log.debug("finishing execution of thread: " + threadName);
    }
}

From source file:bigtweet.BTSimBatch.java

/**
 * Update the output json object and copy it to the output file
 *
 * @param distances//from w  w  w . j a  v  a 2 s. co m
 * @param get
 */
private void updateOutputJsonFile(int parametersValuesIndex) {
    //calculate elements for update    
    JSONObject parameters = (JSONObject) parametersValues.get(parametersValuesIndex);

    //update attributes and json ouput object
    this.experimentConducted = parametersValuesIndex + 1;
    JSONObject experimentObject = new JSONObject();
    experimentObject.put("experimentID", parametersValuesIndex);
    experimentObject.put("parameters", parameters);

    //read for each experiment results the best values and values for this experiment
    JSONObject results = new JSONObject();
    JSONObject bestResults = new JSONObject();
    for (BatchExperimentsResults r : resultsForDatasets) {
        r.updateMetricsForParametersValues(parametersValues, parametersValuesIndex); //update metrics for one expermioments and for all
        results.put(r.getName(), r.getMetricsForLastExperiment());
        bestResults.put(r.getName(), r.getMetricsForAllExperiments());
    }
    experimentObject.put("results", results);
    experiments.add(experimentObject);
    output.put("experiments", experiments);
    output.put("bestResults", bestResults);

    //write json file
    FileWriter file;
    try {
        file = new FileWriter(batchOutputFile);
        file.write(output.toJSONString());
        file.flush();
        file.close();
    } catch (Exception ex) {
        Logger.getLogger(BTSimBatch.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.googlecode.fascinator.transformer.basicVersioning.BasicVersioningTransformer.java

private void createVersionIndex(String rootPath) {
    String jsonPath = rootPath + "/" + "Version_Index.json";
    log.debug("Indexing a version into: " + jsonPath);

    JSONArray jArr = null;/*from ww w .  java  2  s. c o  m*/
    try {
        File oldf = new File(jsonPath);
        if (oldf.exists()) {
            log.debug("Need to update a version index file: " + jsonPath);
            JsonSimple js = new JsonSimple(oldf);
            jArr = js.getJsonArray();
        } else {
            log.debug("Need to create a new version index file: " + jsonPath);
            jArr = new JSONArray();
        }
        JsonObject newVer = new JsonObject();
        newVer.put("timestamp", getTimestamp());
        newVer.put("file_name", payloadName());
        try {
            jArr.add(newVer);
            try {
                FileWriter fw = new FileWriter(jsonPath);
                fw.write(jArr.toJSONString());
                fw.flush();
                fw.close();
            } catch (IOException e) {
                log.error("Failed to save versioning property file.", e);
            }
        } catch (Exception eStrange) {
            log.error("Failed to add a new version.", eStrange);
        }
    } catch (Exception eOther) {
        log.error("Failed to create/edit versioning property file.", eOther);
    }
}

From source file:com.googlecode.fascinator.transformer.basicVersioning.ExtensionBasicVersioningTransformer.java

private void createVersionIndex(String rootPath, String payloadName, String source) {
    String jsonPath = rootPath + "/" + FilenameUtils.getExtension(source) + "_Version_Index.json";
    log.debug("Indexing a version into: " + jsonPath);

    JSONArray jArr = null;//from   ww  w  .  j av a  2s  . c om
    try {
        File oldf = new File(jsonPath);
        if (oldf.exists()) {
            log.debug("Need to update a version index file: " + jsonPath);
            JsonSimple js = new JsonSimple(oldf);
            jArr = js.getJsonArray();
        } else {
            log.debug("Need to create a new version index file: " + jsonPath);
            jArr = new JSONArray();
        }
        // since the transformer is firing off multiple times, as seen from the logs, we need to check if there's a version recorded already...
        String timestamp = getTimestamp();
        for (Object curEntryObj : jArr) {
            JsonObject curEntry = (JsonObject) curEntryObj;
            String curTs = (String) curEntry.get("timestamp");
            if (timestamp.equalsIgnoreCase(curTs)) {
                log.debug("A duplicate of the timestamp " + timestamp
                        + " is already found in the version index, ignoring.");
                return;
            }
        }
        JsonObject newVer = new JsonObject();
        newVer.put("timestamp", timestamp);
        newVer.put("file_name", payloadName); // adding the payloadName as a parameter in the event that calls between payloadname() takes too long
        try {
            jArr.add(newVer);
            try {
                FileWriter fw = new FileWriter(jsonPath);
                fw.write(jArr.toJSONString());
                fw.flush();
                fw.close();
            } catch (IOException e) {
                log.error("Failed to save versioning property file.", e);
            }
        } catch (Exception eStrange) {
            log.error("Failed to add a new version.", eStrange);
        }
    } catch (Exception eOther) {
        log.error("Failed to create/edit versioning property file.", eOther);
    }
}

From source file:fr.paris.lutece.plugins.rss.service.RssGeneratorService.java

/**
 * Creates the pushrss file in the directory
 *
 * @param strRssFileName The file's name that must be deleted
 * @param strRssDocument The content of the new RSS file
 *//*from w w w .  java2 s .com*/
public static void createFileRss(String strRssFileName, String strRssDocument) {
    FileWriter fileRssWriter;

    try {
        // fetches the pushRss directory path
        String strFolderPath = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH, "");

        // Test if the pushRss directory exist and create it if it doesn't exist
        if (!new File(strFolderPath).exists()) {
            File fileFolder = new File(strFolderPath);
            fileFolder.mkdir();
        }

        // Creates a temporary RSS file
        String strFileRss = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH, "")
                + strRssFileName;
        String strFileDirectory = AppPathService.getPath(RssGeneratorService.PROPERTY_RSS_STORAGE_FOLDER_PATH,
                "");
        File fileRss = new File(strFileRss);
        File fileRssDirectory = new File(strFileDirectory);
        File fileRssTemp = File.createTempFile("tmp", null, fileRssDirectory);
        fileRssWriter = new FileWriter(fileRssTemp);
        fileRssWriter.write(strRssDocument);
        fileRssWriter.flush();
        fileRssWriter.close();

        // Deletes the file if the file exists and renames the temporary file into the file
        if (new File(strFileRss).exists()) {
            File file = new File(strFileRss);
            file.delete();
        }

        fileRssTemp.renameTo(fileRss);
    } catch (IOException e) {
        AppLogService.error(e.getMessage(), e);
    } catch (NullPointerException e) {
        AppLogService.error(e.getMessage(), e);
    }
}

From source file:com.ikon.dao.HibernateUtil.java

/**
 * Replace "create" or "update" by "none" to prevent repository reset on restart
 *//*from  w w  w .  j a v  a2s.c  om*/
@SuppressWarnings("unchecked")
public static void hibernateCreateAutofix(String configFile) throws IOException {
    FileReader fr = null;
    FileWriter fw = null;

    try {
        // Open and close reader
        fr = new FileReader(configFile);
        List<String> lines = IOUtils.readLines(fr);
        IOUtils.closeQuietly(fr);

        // Modify configuration file
        fw = new FileWriter(configFile);

        for (String line : lines) {
            line = line.trim();
            int idx = line.indexOf("=");

            if (idx > -1) {
                String key = line.substring(0, idx).trim();
                String value = line.substring(idx + 1, line.length()).trim();

                if (Config.PROPERTY_HIBERNATE_HBM2DDL.equals(key)) {
                    value = HBM2DDL_NONE;
                }

                fw.write(key + "=" + value + "\n");
            } else {
                fw.write(line + "\n");
            }
        }

        fw.flush();
    } finally {
        IOUtils.closeQuietly(fr);
        IOUtils.closeQuietly(fw);
    }
}

From source file:com.nts.alphamaleWeb.controller.ServiceController.java

@RequestMapping("/exportJobs")
@ResponseBody// ww  w.ja v  a  2  s  . c o  m
public String exportJobs(@RequestParam(required = true) String jobJsons) {
    ResultBody<Boolean> result = new ResultBody<Boolean>();
    try {
        String fileName = "export_" + System.currentTimeMillis() + ".txt";
        File file = new File(fileName);
        FileWriter fw = new FileWriter(file, false);
        fw.write(jobJsons);
        fw.flush();
        fw.close();
        result.setCode(Code.OK, true);
    } catch (Exception e) {
        e.printStackTrace();
        result.setCode(Code.F100);
    }
    return result.toJson();
}