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.dtolabs.rundeck.core.resources.TestURLResourceModelSource.java

/**
 * Test use of file: url//from ww  w  .  j  av a2s .co m
 */
public void testGetNodesFile() throws Exception {
    URLResourceModelSource provider = new URLResourceModelSource(getFrameworkInstance());
    final URLResourceModelSource.Configuration build = URLResourceModelSource.Configuration.build();

    build.project(PROJ_NAME);
    build.url(new File("src/test/resources/com/dtolabs/rundeck/core/common/test-nodes1.xml").toURI().toURL()
            .toExternalForm());

    provider.configure(build.getProperties());

    final INodeSet nodes = provider.getNodes();
    assertNotNull(nodes);
    assertEquals(2, nodes.getNodes().size());
    assertNotNull(nodes.getNode("test1"));
    assertNotNull(nodes.getNode("testnode2"));

    //write yaml to temp file
    File tempyaml = File.createTempFile("nodes", ".yaml");
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(tempyaml)));
    writer.write(YAML_NODES_TEST);
    writer.flush();
    writer.close();
    tempyaml.deleteOnExit();

    URLResourceModelSource provider2 = new URLResourceModelSource(getFrameworkInstance());
    final URLResourceModelSource.Configuration build2 = URLResourceModelSource.Configuration.build();

    build2.project(PROJ_NAME);
    build2.url(tempyaml.toURI().toURL().toExternalForm());

    provider2.configure(build2.getProperties());

    final INodeSet nodes2 = provider2.getNodes();
    assertNotNull(nodes2);
    assertEquals(1, nodes2.getNodes().size());
    assertNotNull(nodes2.getNode("testnode1"));

}

From source file:playground.christoph.evacuation.analysis.AgentsInEvacuationAreaWriter.java

/**
 * Writes the gathered data tab-separated into a text file.
 *
 * @param filename The name of a file where to write the gathered data.
 *//* ww  w  .  ja va  2s . c  o m*/
public void write(String absoluteFileName, String relativeFileName, Map<String, int[]> legs) {

    try {
        BufferedWriter absoluteWriter = IOUtils.getBufferedWriter(absoluteFileName);
        BufferedWriter relativeWriter = IOUtils.getBufferedWriter(relativeFileName);

        write(absoluteWriter, relativeWriter, legs);

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

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

public static boolean logout(String server_url, String tim_access_token) {

    if (isEmpty(server_url)) {
        Logd(TAG, "logout failed : no server url");
        return false;
    }//from  w w  w.j a v  a 2s .  c  om

    // get revoke_logout endpoint
    String revoke_logout_endpoint = getEndpointFromConfigOidc("revoke_logout_endpoint", server_url);
    if (isEmpty(revoke_logout_endpoint)) {
        Logd(TAG, "logout : could not get revoke_logout_endpoint on server : " + server_url);
        return false;
    }

    // set up connection
    HttpURLConnection huc = getHUC(revoke_logout_endpoint);
    huc.setInstanceFollowRedirects(false);

    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setDoOutput(true);
    huc.setChunkedStreamingMode(0);
    // prepare parameters
    List<NameValuePair> nameValuePairs = null;
    if (tim_access_token != null && tim_access_token.length() > 0) {
        nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("tat", tim_access_token));
    }

    try {
        // write parameters to http connection
        if (nameValuePairs != null) {
            OutputStream os = huc.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            // get URL encoded string from list of key value pairs
            String postParam = getQuery(nameValuePairs);
            Logd("Logout", "url: " + revoke_logout_endpoint);
            Logd("Logout", "POST: " + postParam);
            writer.write(postParam);
            writer.flush();
            writer.close();
            os.close();
        }

        // try to connect
        huc.connect();
        // connection status
        int responseCode = huc.getResponseCode();
        Logd(TAG, "Logout response: " + responseCode);
        // if 200 - OK
        if (responseCode == 200) {
            return true;
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

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

@Override
public String generate() {
    String configBody = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, HUDSON_CONFIG_TEMPLATE,
            getModel());//w ww  .  j a v  a 2 s .co m

    BufferedWriter bufferedWriter = null;
    try {
        File file = new File(outputDirectory);
        //noinspection ResultOfMethodCallIgnored
        file.mkdirs();
        file = new File(outputDirectory + File.separatorChar + CONFIG_FILE_NAME);

        bufferedWriter = new BufferedWriter(new FileWriter(file));
        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:com.masse.mvn.plugin.BuildJsonFromPropertiesMojo.java

private void buidJsonTargetFile(File inputFile) throws MojoExecutionException {

    String inputFileString = inputFile.getAbsolutePath()
            .substring(inputFile.getAbsolutePath().lastIndexOf(SystemUtils.IS_OS_LINUX ? "/" : "\\") + 1);
    String outputFileString = jsonTargetPath + new String(SystemUtils.IS_OS_LINUX ? "/" : "\\")
            + inputFileString.substring(0, inputFileString.lastIndexOf(".")) + ".json";

    getLog().info("Process file " + inputFileString);

    if (!inputFile.exists()) {
        throw new MojoExecutionException("Properties file " + inputFile + " not found !");
    }/*from  www .  ja  v  a  2  s  .c o  m*/

    TreeMap<String, PropertiesToJson> propertiesJson = new TreeMap<String, PropertiesToJson>();
    Properties props = new Properties();

    try {
        FileInputStream inputFileStream = new FileInputStream(inputFile);
        BufferedReader inputFileBufferedReader = new BufferedReader(
                new InputStreamReader(inputFileStream, "UTF-8"));

        File outputTempFile = new File(inputFileString + "-temp");

        FileOutputStream outputTempFileStream = new FileOutputStream(outputTempFile);
        OutputStreamWriter outputTempFileStrWriter = new OutputStreamWriter(outputTempFileStream, "UTF-8");
        BufferedWriter writer = new BufferedWriter(outputTempFileStrWriter);

        String line = "";
        while ((line = inputFileBufferedReader.readLine()) != null) {
            if (!(line.isEmpty() || line.trim().equals("") || line.trim().equals("\n"))) {
                if (line.startsWith("#")) {
                    continue;
                }
                int equalsIndex = line.indexOf("=");
                if (equalsIndex < 0) {
                    continue;
                }
                line = line.replace("\"", "&quot;");
                line = line.replace("\\", "\\\\\\\\");
                line = line.replace("   ", "");
                writer.write(line + "\n");
            }
        }

        writer.close();
        outputTempFileStrWriter.close();
        outputTempFileStream.close();

        inputFileBufferedReader.close();
        inputFileStream.close();

        FileInputStream fis = new FileInputStream(outputTempFile);
        InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
        props.load(isr);
        isr.close();
        fis.close();

        outputTempFile.delete();

        @SuppressWarnings("rawtypes")
        Enumeration e = props.propertyNames();

        while (e.hasMoreElements()) {
            String key = (String) e.nextElement();

            String rootKey = key.split("=")[0];

            propertiesJson.put(rootKey, createMap(propertiesJson, key, props.getProperty(key), 1));

        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    StringBuffer sb = new StringBuffer();
    sb.append(PrintJsonTree(propertiesJson, 0, false));

    File outputFile = new File(outputFileString);

    try {
        FileOutputStream fos = new FileOutputStream(outputFile);
        OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        BufferedWriter bwr = new BufferedWriter(osw);

        //write contents of StringBuffer to a file

        bwr.write(sb.toString());

        //flush the stream
        bwr.flush();

        //close the stream
        bwr.close();
        osw.close();
        fos.close();
    } catch (IOException e) {
        getLog().error(e);
        throw new MojoExecutionException("json file creation error", e);
    }
}

From source file:appmain.AppMain.java

private void writeCSV(File csv, List<String> content) {
    BufferedWriter writer = null;
    try {/*from  ww  w .j av  a 2s  .c  o m*/
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csv, true), "ISO-8859-2"));
        for (String line : content) {
            writer.write(line + System.lineSeparator());
        }
        writer.flush();
    } catch (IOException | HeadlessException e) {
        JOptionPane.showMessageDialog(null,
                "Hiba a CSV fjl rsa kzben!\n" + ExceptionUtils.getStackTrace(e), "Hiba",
                JOptionPane.ERROR_MESSAGE);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

From source file:es.mityc.firmaJava.configuracion.Configuracion.java

/**
  * Este mtodo guarda la configuracin en el fichero SignXML.properties
  * @throws IOException /*from w w  w  . j a  v  a2 s  .  c  om*/
  */
public void guardarConfiguracion() throws IOException {
    StringBuffer paraGrabar = new StringBuffer();
    String linea;

    // La configuracin siempre se guarda en un fichero externo
    File dir = new File(System.getProperty(USER_HOME) + File.separator + getNombreDirExterno());
    if ((!dir.exists()) || (!dir.isDirectory())) {
        if (!dir.mkdir())
            return;
    }
    File fichero = new File(dir, getNombreFicheroExterno());
    log.trace("Salva fichero de configuracin en: " + fichero.getAbsolutePath());
    if (!fichero.exists()) {
        // Si el fichero externo no existe se crea fuera un copia
        // del fichero almacenado dentro del jar
        InputStream fis = getClass().getResourceAsStream(FICHERO_PROPIEDADES);
        BufferedInputStream bis = new BufferedInputStream(fis);
        FileOutputStream fos = new FileOutputStream(fichero);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int length = bis.available();
        byte[] datos = new byte[length];
        bis.read(datos);
        bos.write(datos);
        bos.flush();
        bos.close();
        bis.close();
    }
    // AppPerfect: Falso positivo
    BufferedReader propiedades = new BufferedReader(new FileReader(fichero));

    linea = propiedades.readLine();
    while (linea != null) {
        StringTokenizer token = new StringTokenizer(linea, IGUAL);
        if (token.hasMoreTokens()) {
            String clave = token.nextToken().trim();
            if (configuracion.containsKey(clave)) {
                paraGrabar.append(clave);
                paraGrabar.append(IGUAL_ESPACIADO);
                paraGrabar.append(getValor(clave));
                paraGrabar.append(CRLF);
            } else {
                paraGrabar.append(linea);
                paraGrabar.append(CRLF);

            }
        } else
            paraGrabar.append(CRLF);
        linea = propiedades.readLine();
    }
    propiedades.close();

    //AppPerfect: Falso positivo
    FileWriter fw = new FileWriter(fichero);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(String.valueOf(paraGrabar));
    bw.flush();
    bw.close();

}

From source file:com.sludev.commons.vfs2.provider.s3.SS3FileProviderTest.java

/**
 * Upload a single file to the test bucket.
 * @throws java.lang.Exception/*  www  .  j a v a  2 s  . c o m*/
 */
@Test
public void A001_uploadFile() throws Exception {
    String currAccountStr = testProperties.getProperty("s3.access.id");
    String currKey = testProperties.getProperty("s3.access.secret");
    String currContainerStr = testProperties.getProperty("s3.test0001.bucket.name");
    String currHost = testProperties.getProperty("s3.host");
    String currRegion = testProperties.getProperty("s3.region");
    String currFileNameStr;

    File temp = File.createTempFile("uploadFile01", ".tmp");
    try (FileWriter fw = new FileWriter(temp)) {
        BufferedWriter bw = new BufferedWriter(fw);
        bw.append("testing...");
        bw.flush();
    }

    SS3FileProvider currSS3 = new SS3FileProvider();

    // Optional set endpoint
    //currSS3.setEndpoint(currHost);

    // Optional set region
    //currSS3.setRegion(currRegion);

    DefaultFileSystemManager currMan = new DefaultFileSystemManager();
    currMan.addProvider(SS3Constants.S3SCHEME, currSS3);
    currMan.addProvider("file", new DefaultLocalFileProvider());
    currMan.init();

    StaticUserAuthenticator auth = new StaticUserAuthenticator("", currAccountStr, currKey);
    FileSystemOptions opts = new FileSystemOptions();
    DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);

    currFileNameStr = "test01.tmp";
    String currUriStr = String.format("%s://%s/%s/%s", SS3Constants.S3SCHEME, currHost, currContainerStr,
            currFileNameStr);
    FileObject currFile = currMan.resolveFile(currUriStr, opts);
    FileObject currFile2 = currMan.resolveFile(String.format("file://%s", temp.getAbsolutePath()));

    currFile.copyFrom(currFile2, Selectors.SELECT_SELF);
    temp.delete();
}

From source file:com.tencent.wetest.common.util.ReportUtil.java

@SuppressLint("SimpleDateFormat")
public static synchronized String saveReport() {

    try {/*  w  w  w . j  a  v  a2s.c o  m*/

        path = WTApplication.getContext().getFilesDir().getPath();
        String versionName = ((WTApplication) WTApplication.getContext()).getApkinfo().getVersionName();

        packageName = ((WTApplication) WTApplication.getContext()).getApkinfo().getPackagename();
        appName = ((WTApplication) WTApplication.getContext()).getApkinfo().getAppname();
        ;
        datasource = ((WTApplication) WTApplication.getContext()).getReport();

        if (datasource != null)
            datas = datasource.getDatalist();

        size = datas.size();

        Date now = new Date();

        long timeStart = -1;
        long timeEnd = -1;
        boolean hasBaseTime = false;

        if (datasource.getBaseTime() == -1) {

            hasBaseTime = false;

            timeEnd = (new Date()).getTime();

            if (timeEnd == -1) {

                timeEnd = now.getTime();

                timeStart = (timeEnd - (SystemClock.uptimeMillis() - datasource.getBaseColock()))
                        + (datasource.getTimeStart() - datasource.getBaseColock());

            } else {

                timeStart = (timeEnd - (SystemClock.uptimeMillis() - datasource.getBaseColock()))
                        + (datasource.getTimeStart() - datasource.getBaseColock());

                ((WTApplication) WTApplication.getContext()).getReport().setBaseTime(timeEnd);
                ((WTApplication) WTApplication.getContext()).getReport()
                        .setBaseColock(SystemClock.uptimeMillis());

            }

        } else {

            hasBaseTime = true;

            timeStart = datasource.getBaseTime() + datasource.getTimeStart() - datasource.getBaseColock();

            timeEnd = datasource.getBaseTime() + SystemClock.uptimeMillis() - datasource.getBaseColock();

        }

        File f;
        File indexfile = new File(path + "/wtIndex");

        if (((WTApplication) WTApplication.getContext()).getCurrTestFile() == null) {

            name = "wt" + now.getTime();

            String fileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/wetest";
            ToolUtil.createDir(fileDir);

            f = new File(fileDir + "/" + name);
            ((WTApplication) WTApplication.getContext()).setCurrTestFile(f);

        } else {
            f = ((WTApplication) WTApplication.getContext()).getCurrTestFile();
            name = f.getName();

        }

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        String isRoot = ((WTApplication) WTApplication.getContext()).isRoot() ? "1" : "0";

        String content_index = name + "/" + formatter.format(timeEnd) + "/" + appName.replaceFirst("\\s+", "")
                + "/" + packageName + "/" + (timeEnd - timeStart) / 1000 + "/" + timeStart + "/" + timeEnd + "/"
                + versionName + "/" + isRoot + "/" + "";

        ((WTApplication) WTApplication.getContext()).getTestReports().add(name);

        if (!f.exists()) {
            f.createNewFile();
        }

        if (!indexfile.exists())
            indexfile.createNewFile();

        JsonResult json_res = readFileReport(f);

        JSONObject cpu = new JSONObject();

        JSONObject natived = new JSONObject();
        JSONObject dalvik = new JSONObject();
        JSONObject total = new JSONObject();

        JSONObject networkIn = new JSONObject();
        JSONObject networkOut = new JSONObject();

        JSONObject fps = new JSONObject();

        JSONObject time = new JSONObject();

        JSONObject tag = new JSONObject();

        JSONObject temperature = new JSONObject();

        JSONObject current = new JSONObject();

        for (ReportData data : datas) {

            if (!hasBaseTime) {

                long gap = data.getTime() - datasource.getTimeStart();

                long offset = gap > 0 ? gap : 0;

                json_res.getContent_f_time().put((timeStart + offset) / 1000);

                //Logger.debug("dataTime is " + formatter.format(timeStart + offset));

            } else {

                json_res.getContent_f_time().put((data.getTime()) / 1000);

                //Logger.debug("dataTime is " + formatter.format(data.getTime()));

            }

            json_res.getContent_f_cpu().put(data.getCpu());

            json_res.getContent_f_native().put(data.getpNative());
            json_res.getContent_f_dalvik().put(data.getpDalvik());
            json_res.getContent_f_total().put(data.getpTotal());

            json_res.getContent_f_networkIn().put(data.getpNetworUsagekIn());
            json_res.getContent_f_networkOut().put(data.getpNetworUsagekOut());
            json_res.getContent_f_Fps().put(data.getFps());

            json_res.getContent_f_Tag().put(data.getTag());

            json_res.getContent_f_temperature().put(data.getpTemperature());

            json_res.getContent_f_current().put(data.getpCurrent());

        }

        cpu.put("cpu", json_res.getContent_f_cpu());

        natived.put("native", json_res.getContent_f_native());
        dalvik.put("dalvik", json_res.getContent_f_dalvik());
        total.put("total", json_res.getContent_f_total());

        networkIn.put("networkIn", json_res.getContent_f_networkIn());
        networkOut.put("networkOut", json_res.getContent_f_networkOut());
        time.put("time", json_res.getContent_f_time());

        fps.put("fps", json_res.getContent_f_Fps());
        tag.put("tag", json_res.getContent_f_Tag());

        temperature.put("temperature", json_res.getContent_f_temperature());
        current.put("current", json_res.getContent_f_current());

        BufferedWriter writer = new BufferedWriter(new FileWriter(f, false));

        writer.append(cpu.toString());
        writer.newLine();

        writer.append(natived.toString());
        writer.newLine();

        writer.append(dalvik.toString());
        writer.newLine();

        writer.append(total.toString());
        writer.newLine();

        writer.append(networkIn.toString());
        writer.newLine();

        writer.append(networkOut.toString());
        writer.newLine();

        writer.append(time.toString());
        writer.newLine();

        writer.append(fps.toString());
        writer.newLine();

        writer.append(tag.toString());

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

        updateRecord(indexfile, name, content_index);

    } catch (Exception e) {
        Logger.error("report save exception :" + e.toString());
        e.printStackTrace();
    }

    return name;

}

From source file:com.linkedin.pinot.perf.PerfBenchmarkDriver.java

public JSONObject postQuery(String query) throws Exception {
    final JSONObject json = new JSONObject();
    json.put("pql", query);

    final long start = System.currentTimeMillis();
    final URLConnection conn = new URL(brokerBaseApiUrl + "/query").openConnection();
    conn.setDoOutput(true);//  w ww.  j  a va 2  s.c o  m
    final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
    final String reqStr = json.toString();

    writer.write(reqStr, 0, reqStr.length());
    writer.flush();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }

    final long stop = System.currentTimeMillis();

    final String res = sb.toString();
    final JSONObject ret = new JSONObject(res);
    ret.put("totalTime", (stop - start));
    if ((ret.getLong("numDocsScanned") > 0) && verbose) {
        LOGGER.info("reqStr = " + reqStr);
        LOGGER.info(" Client side time in ms:" + (stop - start));
        LOGGER.info("numDocScanned : " + ret.getLong("numDocsScanned"));
        LOGGER.info("timeUsedMs : " + ret.getLong("timeUsedMs"));
        LOGGER.info("totalTime : " + ret.getLong("totalTime"));
        LOGGER.info("res = " + res);
    }
    return ret;
}