Example usage for java.io OutputStreamWriter flush

List of usage examples for java.io OutputStreamWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:crossbear.convergence.ConvergenceConnector.java

/**
 * Contact a ConvergenceNotary and ask it for all information about certificate observations it has made on a specific host.
 * /* w w w .  java  2  s.  co  m*/
 * Please note: Contacting a ConvergenceNotary is possible with and without sending the fingerprint of the observed certificate. In both cases the Notary will send a list of
 * ConvergenceCertificateObservations. The problem is that if no fingerprint is sent or the fingerprint matches the last certificate that the Notary observed for the host, the Notary will just
 * read the list of ConvergenceCertificateObservations from its database. It will not contact the server to see if it the certificate is still the one it uses. The problem with that is that with
 * this algorithm Convergence usually makes only one certificate observation per server. When asked for that server a Notary will therefore reply "I saw that certificate last July". Since
 * Crossbear requires statements like "I saw this certificate since last July" it will send a fake-fingerprint to the Convergence Notaries. This compels the Notary to query the server for
 * its current certificate. After that the Notary will update its database and will then send the updated list of ConvergenceCertificateObservations to Crossbear.
 * 
 * @param notary
 *            The notary to contact
 * @param hostPort
 *            The Hostname and port of the server on which the information about the certificate observations is desired.
 * @return The Response-String that the Notary sent as an answer. It will contain a JSON-encoded list of ConvergenceCertificateObservations
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private static String contactNotary(ConvergenceNotary notary, String hostPort)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {

    // Construct a fake fingerprint to send to the Notary (currently the Hex-String representation of "ConvergenceIsGreat:)")
    String data = "fingerprint=43:6F:6E:76:65:72:67:65:6E:63:65:49:73:47:72:65:61:74:3A:29";

    // Build the url to connect to based on the Notary and the certificate's host
    URL url = new URL("https://" + notary.getHostPort() + "/target/" + hostPort.replace(":", "+"));

    // Open a HttpsURLConnection for that url
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

    /*
     * Set a TrustManager on that connection that forces the use of the Notary's certificate. If the Notary sends any certificate that differs from the one that it is supposed to have (according
     * to the ConvergenceNotaries-table) an Exception will be thrown. This protects against Man-in-the-middle attacks placed between the Crossbear server and the Notary.
     */
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null,
            new TrustManager[] {
                    new TrustSingleCertificateTM(Message.hexStringToByteArray(notary.getCertSHA256Hash())) },
            new java.security.SecureRandom());
    conn.setSSLSocketFactory(sc.getSocketFactory());

    // Set the timeout during which the Notary has to reply
    conn.setConnectTimeout(3000);

    // POST the fake fingerprint to the Notary
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the Notary's response. Since Convergence replies with a 409-error if it has never observed a certificate conn.getInputStream() will be null. The way to get the Notarys reply in that case is to use conn.getErrorStream().
    InputStream is;
    if (conn.getResponseCode() >= 400) {
        is = conn.getErrorStream();

    } else {
        // This line should never be executed since we send a fake fingerprint that should never belong to an actually observed certificate. But who knows ...
        is = conn.getInputStream();
    }

    // Read the Notary's reply and store it
    String response = Message.inputStreamToString(is);

    // Close all opened streams
    wr.close();

    // Return the Notary's reply
    return response;

}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

/**
 * Does an HTTP post for a given form data string.
 *
 * @param data is the form data string./*  w  ww  . j  a  v a2  s. c  om*/
 * @param url  is the url to post to.
 * @return the return string from the server.
 * @throws java.io.IOException
 */
public static String postData(String data, URL url) throws IOException {

    String result = null;

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

    try {
        HttpHelpers.addCommonHeaders(conn);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(data);
        writer.flush();
        writer.close();

        String line;
        BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn);
        while ((line = reader.readLine()) != null) {
            if (result == null)
                result = line;
            else
                result += line;
        }

        reader.close();
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read stream data", ex);

        String error = null;

        // TODO Am not yet sure if the section below should make it in the production release.
        // I mainly use it to get details of a failed http request. I get a FileNotFoundException
        // when actually the url is correct but an exception was thrown at the server and i use this
        // to get the server call stack for debugging purposes.
        try {
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            while ((line = reader.readLine()) != null) {
                if (error == null)
                    error = line;
                else
                    error += line;
            }

            reader.close();
        } catch (Exception e) {
            Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex);
        }
    }

    return result;
}

From source file:eu.digitisation.idiomaident.utils.ExtractTestSamples.java

private static void extractSamples(int numSamples, File inFolder, File outFile) {
    FileOutputStream fileOS = null;
    OutputStreamWriter outSWriter = null;

    try {/* www  .  j  a  v  a  2 s . co  m*/
        fileOS = new FileOutputStream(outFile);
        outSWriter = new OutputStreamWriter(fileOS, Charset.forName("UTF8"));

        int num = 0;
        while (num < numSamples) {
            String sample = nextSample(inFolder);

            if (sample == null)
                continue;

            outSWriter.write(sample);
            num++;
            System.out.println("Generating " + num + " of " + numSamples + " samples");
        }

        outSWriter.flush();

    } catch (IOException ex) {
        System.out.println(ex.toString());
    } finally {
        try {
            if (outSWriter != null) {
                outSWriter.close();
            }
        } catch (IOException ex) {
            System.out.println(ex.toString());
        }
    }

}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static int attemptSendReceipt(String op, Receipt r) {
    // Here we may want to check the network status.
    checkNetwork();/*w  w  w  .  j  a  va  2 s.co m*/
    try {
        JSONObject jsonstr = new JSONObject();

        if (op.equals(METHOD_SEND_RECEIPT)) {
            // Add your data
            JSONObject basicInfo = new JSONObject();
            basicInfo.put("store_account", r.getEntry(ENTRY_STORE_ACC));// store name
            basicInfo.put("currency_mark", r.getEntry(ENTRY_CURRENCY));
            basicInfo.put("store_define_id", r.getEntry(ENTRY_RECEIPT_ID));
            basicInfo.put("source", r.getEntry(ENTRY_SOURCE));
            basicInfo.put("tax", r.getEntry(ENTRY_TAX)); // tax
            basicInfo.put("total_cost", r.getEntry(ENTRY_TOTAL)); // total price
            basicInfo.put("user_account", UserProfile.getUsername());
            JSONObject receipt = new JSONObject();
            receipt.put("receipt", basicInfo);
            receipt.put("items", r.getItemsJsonArray());
            receipt.put("opcode", op);
            receipt.put("acc", UserProfile.getUsername());
            jsonstr.put("json", receipt);
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();
        System.out.println(s);
        if (Integer.valueOf(s) > 0) {
            return Integer.valueOf(s);
        } else
            return 0;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static String attemptGetReceipt(String op, String id) {
    // Here we may want to check the network status.
    checkNetwork();//from  ww  w .  j ava  2  s.c o m

    try {
        JSONObject jsonstr = new JSONObject();
        JSONObject param = new JSONObject();
        try {
            param.put("opcode", op);
            param.put("acc", UserProfile.getUsername());
            if (op.equals(METHOD_RECEIVE_ALL)) {
                // Add your data
                param.put("limitStart", "0");
                param.put("limitOffset", "7");
            } else if (op.equals(METHOD_RECEIVE_RECEIPT_DETAIL)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);

            } else if (op.equals(METHOD_RECEIVE_RECEIPT_ITEMS)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);
            }
            jsonstr.put("json", param);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();

        System.out.println("get " + s);

        return s;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.orc.tools.PrintData.java

static void printJsonData(PrintStream printStream, Reader reader) throws IOException, JSONException {
    OutputStreamWriter out = new OutputStreamWriter(printStream, "UTF-8");
    RecordReader rows = reader.rows();/*w ww  .  j  a  va  2  s.co m*/
    try {
        TypeDescription schema = reader.getSchema();
        VectorizedRowBatch batch = schema.createRowBatch();
        while (rows.nextBatch(batch)) {
            for (int r = 0; r < batch.size; ++r) {
                JSONWriter writer = new JSONWriter(out);
                printRow(writer, batch, schema, r);
                out.write("\n");
                out.flush();
                if (printStream.checkError()) {
                    throw new IOException("Error encountered when writing to stdout.");
                }
            }
        }
    } finally {
        rows.close();
    }
}

From source file:Main.java

/**
 * Encode a path as required by the URL specification (<a href="http://www.ietf.org/rfc/rfc1738.txt">
 * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according
 * to the <code>x-www-form-urlencoded</code> MIME format.
 *
 * @param path the path to encode//from   w w w  .ja  v a 2s  . c  o  m
 * @return the encoded path
 */
public static String encodePath(String path) {
    // stolen from org.apache.catalina.servlets.DefaultServlet ;)

    /**
     * Note: Here, ' ' should be encoded as "%20"
     * and '/' shouldn't be encoded.
     */

    int maxBytesPerChar = 10;
    StringBuffer rewrittenPath = new StringBuffer(path.length());
    ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
    OutputStreamWriter writer;
    try {
        writer = new OutputStreamWriter(buf, "UTF8");
    } catch (Exception e) {
        e.printStackTrace();
        writer = new OutputStreamWriter(buf);
    }

    for (int i = 0; i < path.length(); i++) {
        int c = path.charAt(i);
        if (safeCharacters.get(c)) {
            rewrittenPath.append((char) c);
        } else {
            // convert to external encoding before hex conversion
            try {
                writer.write(c);
                writer.flush();
            } catch (IOException e) {
                buf.reset();
                continue;
            }
            byte[] ba = buf.toByteArray();
            for (int j = 0; j < ba.length; j++) {
                // Converting each byte in the buffer
                byte toEncode = ba[j];
                rewrittenPath.append('%');
                int low = (toEncode & 0x0f);
                int high = ((toEncode & 0xf0) >> 4);
                rewrittenPath.append(hexadecimal[high]);
                rewrittenPath.append(hexadecimal[low]);
            }
            buf.reset();
        }
    }
    return rewrittenPath.toString();
}

From source file:org.geoserver.wfs.json.JSONType.java

private static void writeJsonpException(ServiceException exception, Request request, OutputStream out,
        String charset, boolean verbose) throws IOException {

    OutputStreamWriter outWriter = new OutputStreamWriter(out, charset);
    final String callback;
    if (request == null) {
        callback = JSONType.CALLBACK_FUNCTION;
    } else {// www .  jav a  2  s  .c om
        callback = JSONType.getCallbackFunction(request.getKvp());
    }
    outWriter.write(callback + "(");

    writeJsonException(exception, request, outWriter, verbose);

    outWriter.write(")");
    outWriter.flush();
    IOUtils.closeQuietly(outWriter);
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static String attemptSearch(String op, int range, String[] terms) {
    // Here we may want to check the network status.
    checkNetwork();/*from w w  w.  j av a  2  s  . c  om*/

    try {
        JSONObject param = new JSONObject();
        param.put("acc", UserProfile.getUsername());
        param.put("opcode", "search");
        param.put("mobile", true);
        JSONObject jsonstr = new JSONObject();
        if (op == METHOD_KEY_SEARCH) {
            // Add your data
            // Add keys if there is any.
            if (terms != null) {
                JSONArray keys = new JSONArray();
                int numTerm = terms.length;
                for (int i = 0; i < numTerm; i++) {
                    keys.put(terms[i]);
                }
                param.put("keys", keys);
            }
            // Calculate the Search Range by last N days
            Calendar c = Calendar.getInstance();
            if (range == -SEVEN_DAYS || range == -FOURTEEN_DAYS) {
                // 7 days or 14 days
                c.add(Calendar.DAY_OF_MONTH, range);
            } else if (range == -ONE_MONTH || range == -THREE_MONTHS) {
                // 1 month or 6 month
                c.add(Calendar.MONTH, range);
            }

            String timeStart = String.valueOf(c.get(Calendar.YEAR));
            timeStart += ("-" + String.valueOf(c.get(Calendar.MONTH) + 1));
            timeStart += ("-" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)));
            Calendar current = Calendar.getInstance();
            current.add(Calendar.DAY_OF_MONTH, 1);
            String timeEnd = String.valueOf(current.get(Calendar.YEAR));
            timeEnd += ("-" + String.valueOf(current.get(Calendar.MONTH) + 1));
            timeEnd += ("-" + String.valueOf(current.get(Calendar.DAY_OF_MONTH)));

            JSONObject timeRange = new JSONObject();
            timeRange.put("start", timeStart);
            timeRange.put("end", timeEnd);
            param.put("timeRange", timeRange);

            jsonstr.put("json", param);
        } else if (op == METHOD_TAG_SEARCH) {

        } else if (op == METHOD_KEY_DATE_SEARCH) {
            if (terms.length > 2) {
                // Add keys if there is any.
                JSONArray keys = new JSONArray();
                int numTerm = terms.length - 2;
                for (int i = 0; i < numTerm; i++) {
                    keys.put(terms[i]);
                }
                param.put("keys", keys);
            } else if (terms.length < 2) {
                System.out.println("Wrong terms: no start or end date.");
                return null;
            }
            JSONObject timeRange = new JSONObject();
            timeRange.put("start", terms[terms.length - 2]);
            timeRange.put("end", terms[terms.length - 1]);
            param.put("timeRange", timeRange);
            jsonstr.put("json", param);
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        return in.readLine();
        //           String s = in.readLine();
        //           System.out.println(s);
        //           return s;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:org.geoserver.wfs.json.JSONType.java

/**
 * Handle Exception in JSON and JSONP format
 * /*from  w  ww .j a va  2 s.c o  m*/
 * @param LOGGER the logger to use (can be null)
 * @param exception the exception to write to the response outputStream
 * @param request the request generated the exception
 * @param charset the desired charset
 * @param verbose be verbose
 * @param isJsonp switch writing json (false) or jsonp (true)
 */
public static void handleJsonException(Logger LOGGER, ServiceException exception, Request request,
        String charset, boolean verbose, boolean isJsonp) {

    final HttpServletResponse response = request.getHttpResponse();
    // TODO: server encoding options?
    response.setCharacterEncoding(charset);

    ServletOutputStream os = null;
    try {
        os = response.getOutputStream();
        if (isJsonp) {
            // jsonp
            response.setContentType(JSONType.jsonp);
            JSONType.writeJsonpException(exception, request, os, charset, verbose);
        } else {
            // json
            OutputStreamWriter outWriter = null;
            try {
                outWriter = new OutputStreamWriter(os, charset);
                response.setContentType(JSONType.json);
                JSONType.writeJsonException(exception, request, outWriter, verbose);
            } finally {
                if (outWriter != null) {
                    try {
                        outWriter.flush();
                    } catch (IOException ioe) {
                    }
                    IOUtils.closeQuietly(outWriter);
                }
            }

        }
    } catch (Exception e) {
        if (LOGGER != null && LOGGER.isLoggable(Level.SEVERE))
            LOGGER.severe(e.getLocalizedMessage());
    } finally {
        if (os != null) {
            try {
                os.flush();
            } catch (IOException ioe) {
            }
            IOUtils.closeQuietly(os);
        }
    }
}