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.wabacus.config.database.type.Oracle.java

public void setClobValueInSelectMode(Object value, oracle.sql.CLOB clob) throws SQLException {
    if (clob == null)
        return;/* www  .  ja  va2s  .c  om*/
    String strvalue = "";
    if (value != null)
        strvalue = String.valueOf(value);
    BufferedWriter out = new BufferedWriter(clob.getCharacterOutputStream());
    BufferedReader in = new BufferedReader(new StringReader(strvalue));
    try {
        int c;
        while ((c = in.read()) != -1) {
            out.write(c);
        }
        in.close();
        out.flush();
        out.close();
    } catch (IOException e) {
        throw new WabacusRuntimeException("" + value + "CLOB", e);
    }
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

String writePostParams(OutputStream os, String postParams) {

    try {/* w w w .  j  av  a2  s  .co  m*/
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(postParams);
        writer.flush();
        writer.close();
        return postParams;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:io.cloudslang.content.httpclient.consume.HttpResponseConsumer.java

private void consumeToDestinationFile() throws IOException {
    BufferedReader reader;// ww w .j a v  a2 s .  co m
    BufferedWriter fileWriter = null;
    FileOutputStream fos = null;
    try {
        try {
            reader = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), responseCharacterSet));
            fos = new FileOutputStream(new File(destinationFile));
            fileWriter = new BufferedWriter(new OutputStreamWriter(fos, responseCharacterSet));
        } catch (UnsupportedEncodingException e) {
            throw new IllegalArgumentException(
                    "Could not parse '" + HttpClientInputs.RESPONSE_CHARACTER_SET + "'. " + e.getMessage(), e);
        }
        char[] buffer = new char[1024];
        int b;
        while ((b = reader.read(buffer, 0, buffer.length)) != -1) {
            fileWriter.write(buffer, 0, b);
        }
        fileWriter.flush();
    } finally {
        if (fos != null) {
            safeClose(fos);
        }
        if (fileWriter != null) {
            safeClose(fileWriter);
        }
    }
}

From source file:LVCoref.MMAX2.java

public static void exportMentions(Document d, String filename) {
    BufferedWriter writer = null;
    try {/*www.  java 2 s  .  c  om*/
        writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename), "UTF-8"));
    } catch (java.io.IOException ex) {
        ex.printStackTrace();
    }
    Utils.toWriter(writer,
            "<?xml version=\"1.0\" encoding=\"" + "UTF-8" + "\"?>\n"
                    + "<!DOCTYPE markables SYSTEM \"markables.dtd\">\n"
                    + "<markables xmlns=\"www.eml.org/NameSpaces/" + "coref" + "\">\n");
    for (Mention m : d.mentions) {
        String span = "";
        if (m.start == m.end)
            span = "word_" + (m.start + 1);
        else
            span = "word_" + (m.start + 1) + ".." + "word_" + (m.end + 1);
        String coref_class = "";
        if (d.corefClusters.get(m.corefClusterID).corefMentions.size() > 1)
            coref_class = "set_" + m.corefClusterID;
        else
            coref_class = "empty";
        String category = "other";
        if (m.category != null) {
            if (m.category.equals("ORG"))
                category = "organization";
            else if (m.category.equals("LOCATION"))
                category = "location";
            else if (m.category.equals("PERSON"))
                category = "person";
        }

        Utils.toWriter(writer,
                "<markable id=\"markable_" + (m.id + 1) + "\" span=\"" + span + "\" coref_class=\""
                        + coref_class + "\" category=\"" + category
                        + "\" mmax_level=\"coref\"  rule=\"none\"  type=\"none\"/>\n");
    }
    Utils.toWriter(writer, "</markables>");
    try {
        writer.flush();
        writer.close();
    } catch (IOException ex) {
        Logger.getLogger(Document.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

public void createNewTestReportFile(FrameworkMethod method, String reportFileName) {
    BufferedWriter bufferedWriter = null;
    try {/*from w w  w  .ja  va2s .c  om*/
        File file = new File(reportDirFile, reportFileName);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        bufferedWriter = new BufferedWriter(new FileWriter(file));
        bufferedWriter.write(getHeader());
        setLogFile(file);

    } catch (IOException e) {
        throw new RuntimeException("Oups, could't create WebDriver Report Log files?!", e);
    } finally {
        try {
            if (bufferedWriter != null) {
                bufferedWriter.flush();
                bufferedWriter.close();
            }
        } catch (IOException ex) {
            // Zucchero says "Nothing To Loose" if this happens - ignore.
        }
    }
}

From source file:de.cismet.cids.custom.objecteditors.utils.VermessungUmleitungPanel.java

/**
 * DOCUMENT ME!/*from   w  w  w. j  a  va 2s  .co m*/
 */
private void createLinkFile() {
    final SwingWorker<Boolean, Void> worker = new SwingWorker<Boolean, Void>() {

        @Override
        protected Boolean doInBackground() throws Exception {
            if (initError) {
                return false;
            }
            final String filename = createFilename();
            final File f = File.createTempFile(filename, ".txt");
            final FileWriter fw = new FileWriter(f);
            final BufferedWriter bfw = new BufferedWriter(fw);
            bfw.write(getLinkDocument(), 0, getLinkDocument().length());
            bfw.flush();
            bfw.close();
            webDavHelper.uploadFileToWebDAV(filename + ".txt", f, createDirName(), editor,
                    getConnectionContext());
            return true;
        }

        @Override
        protected void done() {
            try {
                if (!get()) {
                    final org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo(
                            org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                    "VermessungUmleitungPanel.errorDialog.title"),
                            org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                    "VermessungUmleitungPanel.errorDialog.create.message"),
                            null, null, null, Level.ALL, null);
                    JXErrorPane.showDialog(
                            StaticSwingTools.getParentFrameIfNotNull(VermessungUmleitungPanel.this), ei);
                    showError();
                    return;
                }
                editor.handleUmleitungCreated(lastCheckedURL);
            } catch (InterruptedException ex) {
                LOG.error("Create Link File Worker was interrupted.", ex);
            } catch (Exception ex) {
                LOG.error("Error in Create Link File worker", ex);
                final org.jdesktop.swingx.error.ErrorInfo ei = new ErrorInfo(
                        org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                "VermessungUmleitungPanel.errorDialog.title"),
                        org.openide.util.NbBundle.getMessage(VermessungUmleitungPanel.class,
                                "VermessungUmleitungPanel.errorDialog.create.message"),
                        ex.getMessage(), null, ex, Level.ALL, null);
                JXErrorPane.showDialog(StaticSwingTools.getParentFrameIfNotNull(VermessungUmleitungPanel.this),
                        ei);
            }
        }
    };
    worker.execute();
}

From source file:com.rsltc.profiledata.main.MainActivity.java

private void exportFile(List<JSONObject> jsonObjects, String dataset_name) {
    final String date = new SimpleDateFormat("yyyyMMdd-HHmmss", Locale.getDefault()).format(new Date());
    final String filename = String.format("%s_%s.txt", dataset_name, date);

    final String directory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/AndroidTesting/";

    final File logfile = new File(directory, filename);
    final File logPath = logfile.getParentFile();

    if (!logPath.isDirectory() && !logPath.mkdirs()) {
        Log.e("SensorDashbaord", "Could not create directory for log files");
    }//  ww w  .j a  v a2  s  . c o m

    try {
        FileWriter filewriter = new FileWriter(logfile);
        BufferedWriter bw = new BufferedWriter(filewriter);

        //            for (JSONObject object : jsonObjects) {
        bw.write(jsonObjects.toString());
        //            }
        bw.flush();
        bw.close();

        Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
        emailIntent.setType("*/*");

        emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, dataset_name + ".csv");
        emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(logfile));
        startActivity(Intent.createChooser(emailIntent, "Send mail..."));

        Log.i(TAG, "export finished!");
    } catch (IOException ioe) {
        Log.e(TAG, "IOException while writing Logfile");
        Log.e("Enias", ioe.getMessage());
    }
}

From source file:com.example.android.networkconnect.MainActivity.java

private String https_test(String urlString) throws IOException {

    String token = "";
    URL url = new URL(urlString);

    Log.i(TAG, "Protocol: " + url.getProtocol().toString());

    // if (url.getProtocol().toLowerCase().equals("https")) {
    trustAllHosts();/*  www  .j a  v a2s . c om*/

    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    conn.setReadTimeout(20000 /* milliseconds */);
    conn.setConnectTimeout(25000 /* milliseconds */);
    // conn.setRequestMethod("GET");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    conn.setChunkedStreamingMode(0);

    conn.setRequestProperty("User-Agent", "e-venement-app/");

    // OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    //writer.getEncoding();
    //writer.write("&signin[username]=antoine");
    //writer.write("&signin[password]=android2015@");
    //writer.write("?control[id]=");
    //writer.write("&control[ticket_id]=2222");
    //writer.write("&control[checkpoint_id]=1");
    //  writer.write("&control[comment]=");

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); //On cre la liste qui contiendra tous nos paramtres

    //Et on y rajoute nos paramtres
    nameValuePairs.add(new BasicNameValuePair("signin[username]", "antoine"));
    nameValuePairs.add(new BasicNameValuePair("signin[password]", "android2015@"));
    //nameValuePairs.add(new BasicNameValuePair("control[id]", ""));
    //nameValuePairs.add(new BasicNameValuePair("control[ticket_id]", "2222"));
    //nameValuePairs.add(new BasicNameValuePair("control[checkpoint_id]", "1"));
    //nameValuePairs.add(new BasicNameValuePair("control[comment]", ""));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer2.write(getQuery(nameValuePairs));
    writer2.flush();
    //writer2.close();
    //os.close();

    // conn.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    //writer.write("&signin[_csrf_token]="+CSRFTOKEN);
    //writer.flush();

    conn.connect();

    String headerName = null;

    for (int i = 1; (headerName = conn.getHeaderFieldKey(i)) != null; i++) {
        //data=data+"Header Nme : " + headerName;
        //data=data+conn.getHeaderField(i);
        // Log.i (TAG,headerName);
        Log.i(TAG, headerName + ": " + conn.getHeaderField(i));

    }

    int responseCode = conn.getResponseCode();

    if (responseCode == conn.HTTP_OK) {
        final String COOKIES_HEADER = "Set-Cookie";
        cookie = conn.getHeaderField(COOKIES_HEADER);
    }

    if (conn.getInputStream() != null) {

        // token =getStringFromInputStream(conn.getInputStream());
        Log.i(TAG, readIt(conn.getInputStream(), 15000));
        token = readIt(conn.getInputStream(), 15000);
        Log.i(TAG, getStringFromInputStream(conn.getInputStream()));
        //data=readIt(conn.getInputStream(),7500);
        //Log.i(TAG,token);
        //token=readIt(conn.getInputStream(),7500);
    }
    //conn.connect();
    // List<String> cookiesList = conn.getHeaderFields().get("Set-Cookie");

    // }
    //conn.disconnect();
    return token;
}

From source file:org.envirocar.tools.TrackToCSV.java

public InputStream convert(InputStream in) throws IOException {
    FeatureCollection fc = new ObjectMapper().readValue(in, FeatureCollection.class);

    List<String> properties = new ArrayList<String>();

    for (Feature feature : fc.getFeatures()) {
        for (String key : feature.getProperties().getPhenomenons().keySet()) {
            if (!properties.contains(key)) {
                properties.add(key);/*  w ww . j  av a  2 s . c  om*/
            }
        }
    }

    List<String> spaceTimeProperties = new ArrayList<String>();
    spaceTimeProperties.add("longitude");
    spaceTimeProperties.add("latitude");
    spaceTimeProperties.add("time");

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));

    bw.append(createCSVHeader(properties, spaceTimeProperties));
    bw.newLine();

    for (Feature feature : fc.getFeatures()) {
        for (int i = 0; i < properties.size(); i++) {
            String key = properties.get(i);
            Map<?, ?> value = (Map<?, ?>) feature.getProperties().getPhenomenons().get(key);
            bw.append(value != null ? value.get("value").toString() : Double.toString(Double.NaN));
            bw.append(delimiter);
        }

        Point coord = (Point) feature.getGeometry();
        bw.append(Double.toString(coord.getCoordinates().getLongitude()));
        bw.append(delimiter);
        bw.append(Double.toString(coord.getCoordinates().getLatitude()));
        bw.append(delimiter);
        bw.append(feature.getProperties().getTime());

        bw.newLine();
    }

    bw.flush();
    bw.close();

    return new ByteArrayInputStream(out.toByteArray());
}

From source file:net.sf.smbt.touchosc.utils.TouchOSCUtils.java

public void dumpTouchOsc(TOP top, String destDirname, String destFilename) {

    reverseZOrders(top);/*from w ww  .j  a  v a 2s . c om*/
    //
    // Get tests for TouchOSC legacy compliances : need precise version info
    //
    //applyBase64Transformation(top);

    // Create a resource set.
    //
    ResourceSet resourceSet = new ResourceSetImpl();

    //
    // Register the default resource factory -- only needed for stand-alone!
    //
    resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put(TouchoscPackage.eNS_PREFIX,
            new TouchoscResourceFactoryImpl());
    resourceSet.getPackageRegistry().put(TouchoscPackage.eNS_URI, TouchoscPackage.eINSTANCE);
    resourceSet.getPackageRegistry().put(TouchoscappPackage.eNS_URI, TouchoscappPackage.eINSTANCE);

    String dirname;
    if (destDirname == null) {
        dirname = Platform.getInstanceLocation().getURL().getPath() + "/" + UUID.randomUUID().toString();

        if (Platform.inDebugMode()) {
            System.out.println("creating " + dirname + " directory");
        }

        new File(dirname).mkdir();
    } else {
        dirname = destDirname;
    }

    //
    // Get the URI of the model file.
    //
    URI touchoscURI = URI.createFileURI(dirname + "/" + "index.xml");

    //
    // Demand load the resource for this file.
    //
    Resource resource = resourceSet.createResource(touchoscURI);

    resource.getContents().add(top);

    try {
        Map<Object, Object> options = new HashMap<Object, Object>();
        options.put(XMLResource.OPTION_ENCODING, "UTF-8");
        resource.save(options);
    } catch (IOException e) {
        e.printStackTrace();
    }

    String TOUCHOSC_HEADER = "<touchosc:TOP xmi:version=\"2.0\" xmlns:xmi=\"http://www.omg.org/XMI\" xmlns:touchosc=\"http:///net.sf.smbt.touchosc/src/net/sf/smbt/touchosc/model/touchosc.xsd\">";
    String TOUCHOSC_FOOTER = "</touchosc:TOP>";

    String path = touchoscURI.path().toString();
    String outputZipFile = dirname + "/" + destFilename + ".touchosc";

    try {
        FileInputStream touchoscFile = new FileInputStream(path);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(touchoscFile, Charset.forName("ASCII")));
        CharBuffer charBuffer = CharBuffer.allocate(65535);
        while (reader.read(charBuffer) != -1)

            charBuffer.flip();

        String content = charBuffer.toString();
        content = content.replace(TOUCHOSC_HEADER, "<touchosc>");
        content = content.replace(TOUCHOSC_FOOTER, "</touchosc>");
        content = content.replace("<layout>", "<layout version=\"10\" mode=\"" + top.getLayout().getMode()
                + "\" orientation=\"" + top.getLayout().getOrientation() + "\">");
        content = content.replace("numberX=", "number_x=");
        content = content.replace("numberY=", "number_y=");
        content = content.replace("invertedX=", "inverted_x=");
        content = content.replace("invertedY=", "inverted_y=");
        content = content.replace("localOff=", "local_off=");
        content = content.replace("oscCs=", "osc_cs=");
        content = content.replace("xypad", "xy");

        touchoscFile.close();

        FileOutputStream os = new FileOutputStream(path);

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));

        writer.write(content);
        writer.flush();

        os.flush();
        os.close();

        FileOutputStream fos = new FileOutputStream(outputZipFile);
        ZipOutputStream fileOS = new ZipOutputStream(fos);

        ZipEntry ze = new ZipEntry("index.xml");
        fileOS.putNextEntry(ze);
        fileOS.write(content.getBytes(Charset.forName("UTF-8")));
        fileOS.flush();
        fileOS.close();
        fos.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        File f = new File(path);
        if (f.exists() && f.canWrite()) {
            if (!f.delete()) {
                throw new IllegalArgumentException(path + " deletion failed");
            }
        }
    }
}