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:org.benjp.listener.ServerBootstrap.java

private static String postServer(String serviceUri, String params) {
    String serviceUrl = getServerBase() + PropertyManager.getProperty(PropertyManager.PROPERTY_CHAT_SERVER_URL)
            + "/" + serviceUri;
    String allParams = "passphrase=" + PropertyManager.getProperty(PropertyManager.PROPERTY_PASSPHRASE) + "&"
            + params;/*  ww w  .  ja v a  2s .  co  m*/
    String body = "";
    OutputStreamWriter writer = null;
    try {
        URL url = new URL(serviceUrl);
        URLConnection con = url.openConnection();
        con.setDoOutput(true);

        //envoi de la requte
        writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(allParams);
        writer.flush();

        InputStream in = con.getInputStream();
        String encoding = con.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        body = IOUtils.toString(in, encoding);
        if ("null".equals(body))
            body = null;

    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } catch (IOException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.

    } finally {
        try {
            writer.close();
        } catch (Exception e) {
        }
    }
    return body;
}

From source file:org.exoplatform.chat.listener.ServerBootstrap.java

private static String postServer(String serviceUri, String params) {
    String serviceUrl = getServerBase() + PropertyManager.getProperty(PropertyManager.PROPERTY_CHAT_SERVER_URL)
            + "/" + serviceUri;
    String allParams = "passphrase=" + PropertyManager.getProperty(PropertyManager.PROPERTY_PASSPHRASE) + "&"
            + params;/*  w  w w .ja  v a2  s .  co m*/
    String body = "";
    OutputStreamWriter writer = null;
    try {
        URL url = new URL(serviceUrl);
        URLConnection con = url.openConnection();
        con.setDoOutput(true);

        //envoi de la requte
        writer = new OutputStreamWriter(con.getOutputStream());
        writer.write(allParams);
        writer.flush();

        InputStream in = con.getInputStream();
        String encoding = con.getContentEncoding();
        encoding = encoding == null ? "UTF-8" : encoding;
        body = IOUtils.toString(in, encoding);
        if ("null".equals(body))
            body = null;

    } catch (MalformedURLException e) {
        LOG.warning(e.getMessage());
    } catch (IOException e) {
        LOG.warning(e.getMessage());
    } finally {
        try {
            writer.close();
        } catch (Exception e) {
            LOG.warning(e.getMessage());
        }
    }
    return body;
}

From source file:ch.ethz.epics.export.GoogleImageSitemap.java

/**
 * Writes footer and closes sitemap file.
 *//*from   w ww .j a  va 2s. c  o  m*/
public static void writeFooter(OutputStreamWriter out) throws Exception {
    String footer = "\n</urlset>";
    out.write(footer);
    out.flush();
}

From source file:com.beyondb.geocoding.BaiduAPI.java

public static Map<String, String> testPost(String x, String y) throws IOException {
    URL url = new URL("http://api.map.baidu.com/geocoder?" + ak + "="
            + "&callback=renderReverse&location=" + x + "," + y + "&output=json");
    URLConnection connection = url.openConnection();
    /**//from w w  w .  j  ava  2  s  . co  m
     * ??URLConnection?Web
     * URLConnection???Web???
     */
    connection.setDoOutput(true);
    OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
    //        remember to clean up
    out.flush();
    out.close();
    //        ?????
    String res;
    InputStream l_urlStream;
    l_urlStream = connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
    StringBuilder sb = new StringBuilder("");
    while ((res = in.readLine()) != null) {
        sb.append(res.trim());
    }
    String str = sb.toString();
    System.out.println(str);
    Map<String, String> map = null;
    if (StringUtils.isNotEmpty(str)) {
        int addStart = str.indexOf("formatted_address\":");
        int addEnd = str.indexOf("\",\"business");
        if (addStart > 0 && addEnd > 0) {
            String address = str.substring(addStart + 20, addEnd);
            map = new HashMap<String, String>();
            map.put("address", address);
            return map;
        }
    }

    return null;

}

From source file:com.example.cmput301.model.WebService.java

/**
 * Sets up http connection to the web server and returns the connection.
 * @param conn URLConnection//from ww w.  j a  v a2 s . com
 * @param data string to send to web service.
 * @return String response from web service.
 * @throws IOException
 */
private static String getHttpResponse(URLConnection conn, String data) throws IOException {
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    wr.close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, httpResponse = "";
    while ((line = rd.readLine()) != null) {
        // Process line...
        httpResponse += line;
    }
    rd.close();
    return httpResponse;
}

From source file:net.mceoin.cominghome.api.NestUtil.java

/**
 * Make HTTP/JSON call to Nest and set away status.
 *
 * @param access_token OAuth token to allow access to Nest
 * @param structure_id ID of structure with thermostat
 * @param away_status Either "home" or "away"
 * @return Equal to "Success" if successful, otherwise it contains a hint on the error.
 *///from  w ww . java 2  s.c  om
public static String tellNestAwayStatusCall(String access_token, String structure_id, String away_status) {

    String urlString = "https://developer-api.nest.com/structures/" + structure_id + "/away?auth="
            + access_token;
    log.info("url=" + urlString);

    StringBuilder builder = new StringBuilder();
    boolean error = false;
    String errorResult = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestProperty("User-Agent", "ComingHomeBackend/1.0");
        urlConnection.setRequestMethod("PUT");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setChunkedStreamingMode(0);

        urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");

        String payload = "\"" + away_status + "\"";

        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(payload);
        wr.flush();
        log.info(payload);

        boolean redirect = false;

        // normally, 3xx is redirect
        int status = urlConnection.getResponseCode();
        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == 307 // Temporary redirect
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        //            System.out.println("Response Code ... " + status);

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = urlConnection.getHeaderField("Location");

            // open the new connnection again
            urlConnection = (HttpURLConnection) new URL(newUrl).openConnection();
            urlConnection.setRequestMethod("PUT");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            urlConnection.setChunkedStreamingMode(0);
            urlConnection.setRequestProperty("Content-Type", "application/json; charset=utf8");
            urlConnection.setRequestProperty("Accept", "application/json");

            //                System.out.println("Redirect to URL : " + newUrl);

            wr = new OutputStreamWriter(urlConnection.getOutputStream());
            wr.write(payload);
            wr.flush();

        }

        int statusCode = urlConnection.getResponseCode();

        log.info("statusCode=" + statusCode);
        if ((statusCode == HttpURLConnection.HTTP_OK)) {
            error = false;
        } else if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            // bad auth
            error = true;
            errorResult = "Unauthorized";
        } else if (statusCode == HttpURLConnection.HTTP_BAD_REQUEST) {
            error = true;
            InputStream response;
            response = urlConnection.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(response));
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            log.info("response=" + builder.toString());
            JSONObject object = new JSONObject(builder.toString());

            Iterator keys = object.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                if (key.equals("error")) {
                    // error = Internal Error on bad structure_id
                    errorResult = object.getString("error");
                    log.info("errorResult=" + errorResult);
                }
            }
        } else {
            error = true;
            errorResult = Integer.toString(statusCode);
        }

    } catch (IOException e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("IOException: " + errorResult);
    } catch (Exception e) {
        error = true;
        errorResult = e.getLocalizedMessage();
        log.warning("Exception: " + errorResult);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    if (error) {
        return "Error: " + errorResult;
    } else {
        return "Success";
    }
}

From source file:com.beyondb.geocoding.BaiduAPI.java

public static String getPointByAddress(String address, String city) throws IOException {
    String resultPoint = "";
    try {//from www.j a v  a  2s  .  com
        URL url = new URL("http://api.map.baidu.com/geocoder/v2/?ak=" + ak + "&output=xml&address=" + address
                + "&" + city);

        URLConnection connection = url.openConnection();
        /**
         * ??URLConnection?Web
         * URLConnection???Web???
         */
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        //        remember to clean up
        out.flush();
        out.close();
        //        ?????

        String res;
        InputStream l_urlStream;
        l_urlStream = connection.getInputStream();
        if (l_urlStream != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
            StringBuilder sb = new StringBuilder("");
            while ((res = in.readLine()) != null) {
                sb.append(res.trim());
            }
            String str = sb.toString();
            System.out.println(str);
            Document doc = DocumentHelper.parseText(str); // XML
            Element rootElt = doc.getRootElement(); // ?
            //            System.out.println("" + rootElt.getName()); // ??
            Element resultElem = rootElt.element("result");
            if (resultElem.hasContent()) {
                Element locationElem = resultElem.element("location");
                Element latElem = locationElem.element("lat");
                //            System.out.print("lat:"+latElem.getTextTrim()+",");
                Element lngElem = locationElem.element("lng");
                //            System.out.println("lng:"+lngElem.getTextTrim());
                resultPoint = lngElem.getTextTrim() + "," + latElem.getTextTrim();
            } else {
                System.out.println("can't compute the coor");
                resultPoint = " , ";
            }
        } else {
            resultPoint = " , ";
        }

    } catch (DocumentException ex) {
        Logger.getLogger(BaiduAPI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return resultPoint;
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, JsonObject json, boolean retry,
        String accessToken) throws IOException, UnsupportedRequestVerbException {

    if (verb == RequestVerb.DELETE || verb == RequestVerb.GET) {
        throw new UnsupportedRequestVerbException();
    }/*from   w  w w . ja  v a2 s.  c  o m*/
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request;

        switch (verb) {
        case POST:
            request = new HttpPost(url);
            break;
        case PUT:
            request = new HttpPut(url);
            break;
        default:
            throw new RuntimeException("RequestVerb not implemented: " + verb);
        }

        ((HttpEntityEnclosingRequestBase) request)
                .setEntity(new StringEntity(json.toString(), ContentType.APPLICATION_JSON));

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));

        request.addHeader("Content-Type", "application/json");
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, json, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String url = BASE_URL + method;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());
    conn.addRequestProperty("Content-Type", "application/json");

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    conn.setDoOutput(true);
    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    writer.write(json.toString());
    writer.flush();
    writer.close();

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, json, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}

From source file:com.gmobi.poponews.util.HttpHelper.java

private static Response doRequest(String url, Object raw, int method) {
    disableSslCheck();//from   www .ja va2 s .  co m
    boolean isJson = raw instanceof JSONObject;
    String body = raw == null ? null : raw.toString();
    Response response = new Response();
    HttpURLConnection connection = null;
    try {
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setUseCaches(false);
        if (method == HTTP_POST)
            connection.setRequestMethod("POST");
        if (body != null) {
            if (isJson) {
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("Content-Type", "application/json");
            }
            OutputStream os = connection.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(os);
            osw.write(body);
            osw.flush();
            osw.close();
        }
        InputStream in = connection.getInputStream();
        response.setBody(FileHelper.readText(in, "UTF-8"));
        response.setStatusCode(connection.getResponseCode());
        in.close();
        connection.disconnect();
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
        try {
            if ((connection != null) && (response.getBody() == null) && (connection.getErrorStream() != null)) {
                response.setBody(FileHelper.readText(connection.getErrorStream(), "UTF-8"));
            }
        } catch (Exception ex) {
            Logger.error(ex);
        }
    }
    return response;
}

From source file:com.createtank.payments.coinbase.RequestClient.java

private static JsonObject call(CoinbaseApi api, String method, RequestVerb verb, Map<String, String> params,
        boolean retry, String accessToken) throws IOException {
    if (api.allowSecure()) {

        HttpClient client = HttpClientBuilder.create().build();
        String url = BASE_URL + method;
        HttpUriRequest request = null;/*w  ww.j ava2s .  c  om*/

        if (verb == RequestVerb.POST || verb == RequestVerb.PUT) {
            switch (verb) {
            case POST:
                request = new HttpPost(url);
                break;
            case PUT:
                request = new HttpPut(url);
                break;
            default:
                throw new RuntimeException("RequestVerb not implemented: " + verb);
            }

            List<BasicNameValuePair> paramsBody = new ArrayList<BasicNameValuePair>();

            if (params != null) {
                List<BasicNameValuePair> convertedParams = convertParams(params);
                paramsBody.addAll(convertedParams);
            }

            ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(paramsBody, "UTF-8"));
        } else {
            if (params != null) {
                url = url + "?" + createRequestParams(params);
            }

            if (verb == RequestVerb.GET) {
                request = new HttpGet(url);
            } else if (verb == RequestVerb.DELETE) {
                request = new HttpDelete(url);
            }
        }
        if (request == null)
            return null;

        if (accessToken != null)
            request.addHeader("Authorization", String.format("Bearer %s", accessToken));
        System.out.println("auth header: " + request.getFirstHeader("Authorization"));
        HttpResponse response = client.execute(request);
        int code = response.getStatusLine().getStatusCode();

        if (code == 401) {
            if (retry) {
                api.refreshAccessToken();
                call(api, method, verb, params, false, api.getAccessToken());
            } else {
                throw new IOException("Account is no longer valid");
            }
        } else if (code != 200) {
            throw new IOException("HTTP response " + code + " to request " + method);
        }

        String responseString = EntityUtils.toString(response.getEntity());
        if (responseString.startsWith("[")) {
            // Is an array
            responseString = "{response:" + responseString + "}";
        }

        JsonParser parser = new JsonParser();
        JsonObject resp = (JsonObject) parser.parse(responseString);
        System.out.println(resp.toString());
        return resp;
    }

    String paramStr = createRequestParams(params);
    String url = BASE_URL + method;

    if (paramStr != null && verb == RequestVerb.GET || verb == RequestVerb.DELETE)
        url += "?" + paramStr;

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestMethod(verb.name());

    if (accessToken != null)
        conn.setRequestProperty("Authorization", String.format("Bearer %s", accessToken));

    if (verb != RequestVerb.GET && verb != RequestVerb.DELETE && paramStr != null) {
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(paramStr);
        writer.flush();
        writer.close();
    }

    int code = conn.getResponseCode();
    if (code == 401) {

        if (retry) {
            api.refreshAccessToken();
            return call(api, method, verb, params, false, api.getAccessToken());
        } else {
            throw new IOException("Account is no longer valid");
        }

    } else if (code != 200) {
        throw new IOException("HTTP response " + code + " to request " + method);
    }

    String responseString = getResponseBody(conn.getInputStream());
    if (responseString.startsWith("[")) {
        responseString = "{response:" + responseString + "}";
    }

    JsonParser parser = new JsonParser();
    return (JsonObject) parser.parse(responseString);
}