Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

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  ww w .  java 2 s  .  co  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: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   ww w.ja v a 2 s  .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.gmobi.poponews.util.HttpHelper.java

private static Response doRequest(String url, Object raw, int method) {
    disableSslCheck();//from  w w  w  . j  a  v  a2s  .c o 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.  jav  a 2 s  . 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:com.eurotong.orderhelperandroid.Common.java

public static void SaveToIsolatedStorage(String fileContent, String fileName) throws Exception {
    //http://stackoverflow.com/questions/4228699/write-and-read-strings-to-from-internal-file
    FileOutputStream fos = MyApplication.getAppContext().openFileOutput(fileName, Context.MODE_PRIVATE);
    OutputStreamWriter osw = new OutputStreamWriter(fos, "Unicode");
    osw.append(fileContent);//from   w  w  w . j  ava2s.c  o m
    osw.close();
}

From source file:msearch.tool.MSLog.java

private static void printLog() {
    for (String s : logList) {
        System.out.println(s);/*from  w ww.  j av  a  2 s  . c om*/
    }
    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();
}

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.//from   www  .j  ava  2s .com
 * @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:fr.simon.marquis.preferencesmanager.util.Utils.java

public static boolean savePreferences(PreferenceFile preferenceFile, String file, String packageName,
        Context ctx) {//from w  w w.j  a v  a  2  s.  c o m
    Log.d(TAG, String.format("savePreferences(%s, %s)", file, packageName));
    if (preferenceFile == null) {
        Log.e(TAG, "Error preferenceFile is null");
        return false;
    }

    if (!preferenceFile.isValid()) {
        Log.e(TAG, "Error preferenceFile is not valid");
        return false;
    }

    String preferences = preferenceFile.toXml();
    if (TextUtils.isEmpty(preferences)) {
        Log.e(TAG, "Error preferences is empty");
        return false;
    }

    File tmpFile = new File(ctx.getFilesDir(), TMP_FILE);
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
                ctx.openFileOutput(TMP_FILE, Context.MODE_PRIVATE));
        outputStreamWriter.write(preferences);
        outputStreamWriter.close();
    } catch (IOException e) {
        Log.e(TAG, "Error writing temporary file", e);
        return false;
    }

    if (!RootTools.copyFile(tmpFile.getAbsolutePath(), file, true, false)) {
        Log.e(TAG, "Error copyFile from temporary file");
        return false;
    }

    if (!fixUserAndGroupId(ctx, file, packageName)) {
        Log.e(TAG, "Error fixUserAndGroupId");
        return false;
    }

    if (!tmpFile.delete()) {
        Log.e(TAG, "Error deleting temporary file");
    }

    RootTools.killProcess(packageName);
    Log.d(TAG, "Preferences correctly updated");
    return true;
}

From source file:Main.java

public static void DocumentToFile(final Document doc, File file) {
    // FileWriter writer = null;
    OutputStreamWriter outputStreamWriter = null;

    try {//from w w w  . j av a2 s  .c  o  m
        // writer = new FileWriter(file);

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");

    } catch (Exception e) {
        System.err.println(e);

        return;
    }

    //Result l_s = new StreamResult(writer);
    Result l_s = new StreamResult(outputStreamWriter);

    doc.normalize();

    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(doc), l_s);

        outputStreamWriter.close();
        //writer.close();
    } catch (Exception e) {
        System.err.println(e);

        return;
    }
}

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();//from  w  w w  .j av  a 2 s  .  c o  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;
}