Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

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

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

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  www . ja  v  a2s. co m
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.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.c om*/
 * @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: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();
    }/*  w  w w .  ja  v a  2 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.dynamobi.db.conn.couchdb.CouchUdx.java

/**
 * Creates a CouchDB view//from w ww  .j  a  va  2  s.c  o  m
 */
public static void makeView(String user, String pw, String url, String viewDef) throws SQLException {
    try {
        URL u = new URL(url);
        HttpURLConnection uc = (HttpURLConnection) u.openConnection();
        uc.setDoOutput(true);
        if (user != null && user.length() > 0) {
            uc.setRequestProperty("Authorization", "Basic " + buildAuthHeader(user, pw));
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setRequestMethod("PUT");
        OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
        wr.write(viewDef);
        wr.close();

        String s = readStringFromConnection(uc);
    } catch (MalformedURLException e) {
        throw new SQLException("Bad URL.");
    } catch (IOException e) {
        throw new SQLException(e.getMessage());
    }
}

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

private static Response doRequest(String url, Object raw, int method) {
    disableSslCheck();//w ww. j a  va 2 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;//from  ww w .j av  a 2s  .  c o  m

        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);
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.AnnotationManager.java

public static String createIntervalAnnotation(String urlString, long startEpoch, long endEpoch, String tsuid,
        String description, String notes) {
    urlString = urlString + API_METHOD;/*from  w w  w  .jav  a 2s  .  c  o m*/
    String result = "";
    try {
        HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
        OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());
        JSONObject requestObject = new JSONObject();
        requestObject.put("startTime", startEpoch);
        requestObject.put("endTime", endEpoch);
        requestObject.put("tsuid", tsuid);
        requestObject.put("description", description);
        requestObject.put("notes", notes);
        wr.write(requestObject.toString());
        wr.close();
        result = TimeSeriesUtility.readHttpResponse(httpConnection);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    } catch (OpenTSDBException e) {
        e.printStackTrace();
        result = String.valueOf(e.responseCode);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return result;
}

From source file:com.google.zxing.client.android.history.HistoryManager.java

static Uri saveHistory(String history) {
    File bsRoot = new File(Environment.getExternalStorageDirectory(), "BarcodeScanner");
    File historyRoot = new File(bsRoot, "History");
    if (!historyRoot.exists() && !historyRoot.mkdirs()) {
        Log.w(TAG, "Couldn't make dir " + historyRoot);
        return null;
    }//from  www .  j a v  a2s  .c o m
    File historyFile = new File(historyRoot, "history-" + System.currentTimeMillis() + ".csv");
    OutputStreamWriter out = null;
    try {
        out = new OutputStreamWriter(new FileOutputStream(historyFile), Charset.forName("UTF-8"));
        out.write(history);
        return Uri.parse("file://" + historyFile.getAbsolutePath());
    } catch (IOException ioe) {
        Log.w(TAG, "Couldn't access file " + historyFile + " due to " + ioe);
        return null;
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:msearch.tool.MSLog.java

private static void printLog() {
    for (String s : logList) {
        System.out.println(s);//from   w  ww.j a v  a  2  s  .  c  o  m
    }
    if (logFile != null) {
        try {
            OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(logFile, true),
                    MSConst.KODIERUNG_UTF);
            for (String s : logList) {
                out.write(s);
                out.write("\n");
            }
            out.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
    logList.clear();
}