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:playground.jbischoff.carsharing.data.VBBRouteCatcher.java

private void run(Coord from, Coord to, long departureTime) {

    Locale locale = new Locale("en", "UK");
    String pattern = "###.000000";

    DecimalFormat df = (DecimalFormat) NumberFormat.getNumberInstance(locale);
    df.applyPattern(pattern);//w w  w . j  av  a2 s . c  o m

    // Construct data
    //X&Y coordinates must be exactly 8 digits, otherwise no proper result is given. They are swapped (x = long, y = lat)

    //Verbindungen 1-n bekommen; Laufweg, Reisezeit & Umstiege ermitteln
    String text = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>"
            + "<ReqC accessId=\"JBischoff2486b558356fa9b81b1rzum\" ver=\"1.1\" requestId=\"7\" prod=\"SPA\" lang=\"DE\">"
            + "<ConReq>" + "<ReqT date=\"" + VBBDAY.format(departureTime) + "\" time=\""
            + VBBTIME.format(departureTime) + "\">" + "</ReqT>" + "<RFlags b=\"0\" f=\"1\" >" + "</RFlags>"
            + "<Start>" + "<Coord name=\"START\" x=\"" + df.format(from.getY()).replace(".", "") + "\" y=\""
            + df.format(from.getX()).replace(".", "") + "\" type=\"WGS84\"/>"
            + "<Prod  prod=\"1111000000000000\" direct=\"0\" sleeper=\"0\" couchette=\"0\" bike=\"0\"/>"
            + "</Start>" + "<Dest>" + "<Coord name=\"ZIEL\" x=\"" + df.format(to.getY()).replace(".", "")
            + "\" y=\"" + df.format(to.getX()).replace(".", "") + "\" type=\"WGS84\"/>" + "</Dest>"
            + "</ConReq>" + "</ReqC>";
    PostMethod post = new PostMethod("http://demo.hafas.de/bin/pub/vbb/extxml.exe/");
    post.setRequestBody(text);
    post.setRequestHeader("Content-type", "text/xml; charset=ISO-8859-1");
    HttpClient httpclient = new HttpClient();
    try {

        int result = httpclient.executeMethod(post);

        // Display status code
        //                     System.out.println("Response status code: " + result);

        // Display response
        //                     System.out.println("Response body: ");
        //                     System.out.println(post.getResponseBodyAsString());

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.parse(post.getResponseBodyAsStream());

        if (writeOutput) {
            BufferedWriter writer = IOUtils.getBufferedWriter(filename);
            Transformer transformer = TransformerFactory.newInstance().newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            //initialize StreamResult with File object to save to file
            StreamResult res = new StreamResult(writer);
            DOMSource source = new DOMSource(document);
            transformer.transform(source, res);
            writer.flush();
            writer.close();

        }

        Node connectionList = document.getFirstChild().getFirstChild().getFirstChild();
        NodeList connections = connectionList.getChildNodes();
        int amount = connections.getLength();
        for (int i = 0; i < amount; i++) {
            Node connection = connections.item(i);
            Node overview = connection.getFirstChild();
            ;

            while (!overview.getNodeName().equals("Overview")) {
                overview = overview.getNextSibling();
            }

            System.out.println(overview.getChildNodes().item(3).getTextContent());
            int transfers = Integer.parseInt(overview.getChildNodes().item(3).getTextContent());
            String time = overview.getChildNodes().item(4).getFirstChild().getTextContent().substring(3);
            System.out.println(time);
            Date rideTime = VBBDATE.parse(time);
            int seconds = rideTime.getHours() * 3600 + rideTime.getMinutes() * 60 + rideTime.getSeconds();
            System.out.println(seconds + "s; transfers: " + transfers);
            if (seconds < this.bestRideTime) {
                this.bestRideTime = seconds;
                this.bestTransfers = transfers;
            }
        }
    } catch (Exception e) {
        this.bestRideTime = -1;
        this.bestTransfers = -1;
    }

    finally {
        // Release current connection to the connection pool 
        // once you are done
        post.releaseConnection();
        post.abort();

    }

}

From source file:fr.haploid.webservices.WebServicesTask.java

@Override
protected JSONObject doInBackground(Void... params) {
    try {//  w ww  .j a v a2 s .com
        if (mSendCacheResult) {
            JSONObject cacheResultMessage = new JSONObject();
            cacheResultMessage.put(Cobalt.kJSType, Cobalt.JSTypePlugin);
            cacheResultMessage.put(Cobalt.kJSPluginName, JSPluginNameWebservices);

            JSONObject storedData = new JSONObject();
            storedData.put(kJSCallId, mCallId);
            cacheResultMessage.put(Cobalt.kJSData, storedData);

            int storageSize = WebServicesData.getCountItem();
            if (storageSize > 0) {
                if (mStorageKey != null) {
                    String storedValue = WebServicesPlugin.storedValueForKey(mStorageKey, mFragment);

                    if (storedValue != null) {
                        try {
                            storedData.put(Cobalt.kJSData, WebServicesPlugin
                                    .treatData(new JSONObject(storedValue), mProcessData, mFragment));

                            cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageResult);
                            //cacheResultMessage.put(Cobalt.kJSData, storedData);
                        } catch (JSONException exception) {
                            if (Cobalt.DEBUG) {
                                Log.e(WebServicesPlugin.TAG,
                                        TAG + " - doInBackground: value parsing failed for key " + mStorageKey
                                                + ". Value: " + storedValue);
                                exception.printStackTrace();
                            }

                            cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                            storedData.put(kJSText, JSTextUnknownError);
                        }
                    } else {
                        if (Cobalt.DEBUG)
                            Log.w(WebServicesPlugin.TAG,
                                    TAG + " - doInBackground: value not found in cache for key " + mStorageKey
                                            + ".");

                        cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                        storedData.put(kJSText, JSTextNotFound);
                    }
                } else {
                    cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                    storedData.put(kJSText, JSTextUnknownError);

                }
            } else {
                if (Cobalt.DEBUG)
                    Log.w(WebServicesPlugin.TAG, TAG + " - doInBackground: cache is empty.");

                cacheResultMessage.put(Cobalt.kJSAction, JSActionOnStorageError);
                storedData.put(kJSText, JSTextEmpty);
            }
            cacheResultMessage.put(Cobalt.kJSData, storedData);

            mFragment.sendMessage(cacheResultMessage);
        }

        if (mUrl != null && mType != null) {
            // TODO: later, use Helper
            /*
            responseData = WebServicesHelper.downloadFromServer(data.getString(URL), data.getJSONObject(PARAMS), data.getString(TYPE));
            if (responseData != null) {
            responseHolder.put(TEXT, responseData.getResponseData());
            responseHolder.put(STATUS_CODE, responseData.getStatusCode());
            responseHolder.put(WS_SUCCESS, responseData.isSuccess());
            responseHolder.put(CALL_WS, true);
            }
            */

            Uri.Builder builder = new Uri.Builder();
            builder.encodedPath(mUrl);

            if (!mParams.equals("") && mType.equalsIgnoreCase(JSTypeGET))
                builder.encodedQuery(mParams);

            JSONObject response = new JSONObject();
            response.put(kJSSuccess, false);

            try {
                URL url = new URL(builder.build().toString());

                try {
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    if (mTimeout > 0)
                        urlConnection.setConnectTimeout(mTimeout);
                    urlConnection.setRequestMethod(mType);
                    urlConnection.setDoInput(true);

                    if (mHeaders != null) {
                        JSONArray names = mHeaders.names();

                        if (names != null) {
                            int length = names.length();

                            for (int i = 0; i < length; i++) {
                                String name = names.getString(i);
                                urlConnection.setRequestProperty(name, mHeaders.get(name).toString());
                            }
                        }
                    }

                    if (!mParams.equals("") && !mType.equalsIgnoreCase(JSTypeGET)) {
                        urlConnection.setDoOutput(true);

                        OutputStream outputStream = urlConnection.getOutputStream();
                        BufferedWriter writer = new BufferedWriter(
                                new OutputStreamWriter(outputStream, "UTF-8"));
                        writer.write(mParams);
                        writer.flush();
                        writer.close();
                        outputStream.close();
                    }

                    urlConnection.connect();

                    int responseCode = urlConnection.getResponseCode();
                    if (responseCode != -1) {
                        response.put(kJSStatusCode, responseCode);
                        if (responseCode < 400)
                            response.put(kJSSuccess, true);
                    }

                    try {
                        InputStream inputStream;
                        if (responseCode >= 400 && responseCode < 600)
                            inputStream = urlConnection.getErrorStream();
                        else
                            inputStream = urlConnection.getInputStream();

                        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuffer buffer = new StringBuffer();
                        String line;

                        while ((line = reader.readLine()) != null) {
                            buffer.append(line).append("\n");
                        }
                        if (buffer.length() != 0)
                            response.put(kJSText, buffer.toString());
                    } catch (IOException exception) {
                        if (Cobalt.DEBUG) {
                            Log.i(WebServicesPlugin.TAG,
                                    TAG + " - doInBackground: no DATA returned by server.");
                            exception.printStackTrace();
                        }
                    }
                } catch (ProtocolException exception) {
                    if (Cobalt.DEBUG) {
                        Log.e(WebServicesPlugin.TAG,
                                TAG + " - doInBackground: not supported request method type " + mType);
                        exception.printStackTrace();
                    }
                } catch (IOException exception) {
                    exception.printStackTrace();
                }
                return response;
            } catch (MalformedURLException exception) {
                if (Cobalt.DEBUG) {
                    Log.e(WebServicesPlugin.TAG,
                            TAG + " - doInBackground: malformed url " + builder.build().toString() + ".");
                    exception.printStackTrace();
                }
            }
        }
    } catch (JSONException exception) {
        exception.printStackTrace();
    }

    return null;
}

From source file:com.ss.language.model.gibblda.LDADataset.java

private static void readFromDatabase(int total, LDADataset data) throws IOException {
    // ?id/* w w w . java  2s . c om*/
    File docIdxFile = new File(LDACmdOption.curOption.get().dir, LDACmdOption.curOption.get().docIdFile);
    if (docIdxFile.isFile()) {
        FileUtils.forceDelete(docIdxFile);
    }
    if (!docIdxFile.getParentFile().isDirectory()) {
        FileUtils.forceMkdir(docIdxFile.getParentFile());
    }
    docIdxFile.createNewFile();
    BufferedWriter br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docIdxFile),
            LDACmdOption.curOption.get().fileEncoding));
    int perPage = 100;
    int totalPage = (total / perPage) + (total % perPage == 0 ? 0 : 1);
    int index = -1;
    for (int curPage = 0; curPage < totalPage; ++curPage) {
        // ?
        String titleSql = "select document_title,document_content from " + tableName
                + " order by rec_id asc limit " + (curPage * perPage) + "," + perPage;
        List<Map<String, Object>> result = DatabaseConfig.query(titleSql);
        if (result == null || result.isEmpty()) {
            break;
        }
        for (Map<String, Object> record : result) {
            String title = (String) record.get("document_title");
            String content = (String) record.get("document_content");
            if (content == null || content.trim().isEmpty()) {
                continue;
            }
            ++index;
            System.out.println("??" + (curPage + 1) + "" + (index + 1)
                    + "?/" + total + "?");
            data.setDoc(content, index);
            br.write(title + IOUtils.LINE_SEPARATOR);
        }
    }
    br.flush();
    br.close();
}

From source file:madkitgroupextension.export.Export.java

public void createBuildFile(File f) throws IOException {
    FileWriter fw = new FileWriter(f);
    BufferedWriter b = new BufferedWriter(fw);
    b.write(Integer.toString(MadKitGroupExtension.VERSION.getBuildNumber()));
    b.flush();
    b.close();//from   w  ww  .j av a  2 s.  co m
    fw.close();
}

From source file:org.clothocad.phagebook.controllers.MiscControllers.java

@RequestMapping(value = "/selectColumns", method = RequestMethod.POST)
public void selectColumns(@RequestParam Map<String, String> params, HttpServletResponse response)
        throws IOException, ServletException {
    /*//  w  w  w. j  av a2  s.  com
     String SERIAL_NUMBER = params.get("serialNumber");
     String PRODUCT_NAME = params.get("productName");
     String PRODUCT_URL = params.get("productUrl");
     String PRODUCT_DESCRIPTION = params.get("productDescription");
     String QUANTITY = params.get("quantity");
     String COMPANY_NAME = params.get("companyName");
     String COMPANY_URL = params.get("companyUrl");
     String COMPANY_DESCRIPTION = params.get("companyDescription");
     String COMPANY_CONTACT = params.get("companyContact");
     String COMPANY_PHONE = params.get("companyPhone");
     String UNIT_PRICE = params.get("unitPrice");
     String TOTAL_PRICE = params.get("totalPrice");
     */
    System.out.println("Reached doPost");
    String id = params.get("orderId");
    System.out.println(id);
    if ((id != null) && (!id.equals(""))) {
        System.out.println("ID is not null");
        List<OrderColumns> orderColumns = new ArrayList<>();
        System.out.println("Serial Number " + params.get("serialNumber"));
        System.out.println("Product Name :: " + params.get("productName"));
        if ("true".equals(params.get("serialNumber"))) {
            orderColumns.add(OrderColumns.SERIAL_NUMBER);
        }

        if ("true".equals(params.get("productName"))) {
            orderColumns.add(OrderColumns.PRODUCT_NAME);
        }
        if ("true".equals(params.get("productUrl"))) {
            orderColumns.add(OrderColumns.PRODUCT_URL);
        }
        if ("true".equals(params.get("productDescription"))) {
            orderColumns.add(OrderColumns.PRODUCT_DESCRIPTION);
        }
        if ("true".equals(params.get("quantity"))) {
            orderColumns.add(OrderColumns.QUANTITY);
        }
        if ("true".equals(params.get("companyName"))) {
            orderColumns.add(OrderColumns.COMPANY_NAME);
        }
        if ("true".equals(params.get("companyUrl"))) {
            orderColumns.add(OrderColumns.COMPANY_URL);
        }
        if ("true".equals(params.get("companyDescription"))) {
            orderColumns.add(OrderColumns.COMPANY_DESCRIPTION);
        }
        if ("true".equals(params.get("companyContact"))) {
            orderColumns.add(OrderColumns.COMPANY_CONTACT);
        }
        if ("true".equals(params.get("companyPhone"))) {
            orderColumns.add(OrderColumns.COMPANY_PHONE);
        }
        if ("true".equals(params.get("unitPrice"))) {
            orderColumns.add(OrderColumns.UNIT_PRICE);
        }
        if ("true".equals(params.get("totalPrice"))) {
            orderColumns.add(OrderColumns.TOTAL_PRICE);
        }

        System.out.println("Order Columns " + orderColumns);

        ClothoConnection conn = new ClothoConnection(Args.clothoLocation);
        Clotho clothoObject = new Clotho(conn);
        String username = this.backendPhagebookUser;
        String password = this.backendPhagebookPassword;
        Map loginMap = new HashMap();
        loginMap.put("username", username);
        loginMap.put("credentials", password);

        clothoObject.login(loginMap);
        System.out.println("HERE AT SELECT 1");
        Order order = ClothoAdapter.getOrder(id, clothoObject);
        System.out.println("HERE AT SELECT 2");
        List<String> orderFormLines = createOrderForm(order, orderColumns);
        System.out.println(orderFormLines);

        String filepath = MiscControllers.class.getClassLoader().getResource(".").getPath();
        System.out.println("File path ::" + filepath);
        filepath = filepath.substring(0, filepath.indexOf("/target/"));
        System.out.println("\nTHIS IS THE FILEPATH: " + filepath);

        String filepathOrderForm = filepath + "/orderForm.csv";
        File file = new File(filepathOrderForm);

        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        for (String line : orderFormLines) {
            writer.write(line);
            writer.newLine();
        }

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

        PrintWriter reponseWriter = response.getWriter();
        reponseWriter.println(filepathOrderForm);
        reponseWriter.flush();
        reponseWriter.close();
        clothoObject.logout();
        conn.closeConnection();
    } else {
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    }

}

From source file:net.sf.mpaxs.spi.server.settings.Settings.java

private void prepareDefaults() {
    //create basedir
    new File(DEFAULT_BASE_DIR).mkdirs();
    //create codebase dir
    File codebase = new File(DEFAULT_CODEBASE);
    codebase.mkdirs();/*from www. j a va  2 s  .  co  m*/
    try {
        DEFAULT_CODEBASE = new File(DEFAULT_CODEBASE).toURI().toURL().toString();
    } catch (MalformedURLException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }

    //create default policyfile
    File policyFile = new File(DEFAULT_POLICY_NAME);
    Logger.getLogger(Settings.class.getName()).log(Level.INFO, "Writing default policy to {0}",
            policyFile.getAbsolutePath());
    BufferedReader br = new BufferedReader(
            new InputStreamReader(getClass().getResourceAsStream("/net/sf/mpaxs/spi/server/wideopen.policy")));
    try {
        BufferedWriter bw = new BufferedWriter(new FileWriter(policyFile));
        String s = null;
        while ((s = br.readLine()) != null) {
            bw.write(s + "\n");
        }
        bw.flush();
        bw.close();
        br.close();
    } catch (IOException ex) {
        Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.paolomoz.zehnkampf.utils.GenHTTPResponse.java

private byte[] createResponseBytes(String statusLine, String[] headers, HttpEntity entity) throws IOException {

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(baos));

    // Write the first line of the response, followed by
    // the RFC-specified line termination sequence.
    writer.write(statusLine + "\r\n");

    // Iterate all the speficied headers and write each of them
    for (int i = 0; i < headers.length; i++) {
        writer.write(headers[i] + "\r\n");
    }//from   ww w . j a va 2s  . co m

    // A blank line is required after the header.
    writer.write("\r\n");
    writer.flush();

    // Write the response entity
    if (entity != null) {
        entity.writeTo(baos);
    }

    byte[] data = baos.toByteArray();
    writer.close();

    return data;
}

From source file:com.opensource.frameworks.processframework.utils.DefaultPropertiesPersister.java

protected void doStore(Properties props, Writer writer, String header) throws IOException {
    BufferedWriter out = new BufferedWriter(writer);
    if (header != null) {
        out.write("#" + header);
        out.newLine();/* ww w.jav  a2s  . c  o  m*/
    }
    out.write("#" + new Date());
    out.newLine();
    for (Enumeration keys = props.keys(); keys.hasMoreElements();) {
        String key = (String) keys.nextElement();
        String val = props.getProperty(key);
        out.write(escape(key, true) + "=" + escape(val, false));
        out.newLine();
    }
    out.flush();
}

From source file:evyframework.common.DefaultPropertiesPersister.java

protected void doStore(Properties props, Writer writer, String header) throws IOException {
    BufferedWriter out = new BufferedWriter(writer);
    if (header != null) {
        out.write("#" + header);
        out.newLine();//  ww w. j  a  v a  2  s . c  o m
    }
    out.write("#" + new Date());
    out.newLine();
    for (Enumeration<?> keys = props.keys(); keys.hasMoreElements();) {
        String key = (String) keys.nextElement();
        String val = props.getProperty(key);
        out.write(escape(key, true) + "=" + escape(val, false));
        out.newLine();
    }
    out.flush();
}

From source file:fr.gouv.finances.dgfip.xemelios.utils.TextWriter.java

/**
 * write writes the node to the OutputStream as text.
 *
 * @param output The OutputStream to write to
 *//*from   ww w.  ja va  2 s . c o m*/
public void write(OutputStream output) throws IOException {
    try {
        OutputStreamWriter o = new OutputStreamWriter(output, "UTF8");
        BufferedWriter buf = new BufferedWriter(o, 4096);
        writeNode(buf, node);
        buf.flush();
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}