Example usage for java.io UnsupportedEncodingException getCause

List of usage examples for java.io UnsupportedEncodingException getCause

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:ch.gianulli.trelloapi.TrelloAPI.java

/**
 * Utility method to make Trello API requests
 *
 * @param httpMethod       Either GET, POST, PUT or DELETE
 * @param path             e.g. "actions/[idAction]"
 * @param queryArgs        query arguments
 * @param isTokenNecessary is access token necessary?
 * @return server answer/*from  w  ww .  j  av a  2s.c o m*/
 * @throws TrelloNotAccessibleException if Trello API is not accessible
 * @throws TrelloNotAuthorizedException if token is not valid
 * @throws MalformedURLException        if path was not correctly formatted
 */
protected JSONObject makeJSONObjectRequest(String httpMethod, String path, Map<String, String> queryArgs,
        boolean isTokenNecessary) throws TrelloNotAccessibleException, TrelloNotAuthorizedException {
    // Add key and token to arguments
    if (queryArgs == null) {
        queryArgs = new LinkedHashMap<>();
    }
    queryArgs.put("key", getAppKey());
    if (isTokenNecessary) {
        queryArgs.put("token", getToken());
    }

    // Build argument string
    StringBuilder getData = new StringBuilder();
    try {
        for (Map.Entry<String, String> param : queryArgs.entrySet()) {
            if (getData.length() != 0) {
                getData.append('&');
            }
            getData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            getData.append('=');
            getData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
    } catch (UnsupportedEncodingException e) {
        // never happens
    }

    // Check if httpMethod is supported
    int method = -1;
    if (httpMethod.equals("GET")) {
        method = Request.Method.GET;
    } else if (httpMethod.equals("POST")) {
        method = Request.Method.POST;
    } else if (httpMethod.equals("PUT")) {
        method = Request.Method.PUT;
    } else if (httpMethod.equals("DELETE")) {
        method = Request.Method.DELETE;
    } else {
        throw new IllegalArgumentException("HTTP method not supported: " + httpMethod);
    }

    String url = BASE_URL + path + "?" + getData.toString();

    try {
        RequestFuture<JSONObject> future = RequestFuture.newFuture();
        JsonObjectRequest request = new JsonObjectRequest(method, url, null, future, future);
        mRequestQueue.add(request);

        return future.get(30, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new TrelloNotAccessibleException("Network request was interrupted.");
    } catch (ExecutionException e) {
        VolleyError ve = (VolleyError) e.getCause();
        if (ve instanceof NoConnectionError || ve instanceof NetworkError) {
            throw new TrelloNotAccessibleException("Device is not connected to the internet.");
        } else if (ve instanceof ParseError) {
            throw new TrelloNotAccessibleException("Server answer was not in valid JSON format" + ".");
        } else if (ve.networkResponse != null) {
            if (ve.networkResponse.statusCode == 401) {
                throw new TrelloNotAuthorizedException("Server returned error 401");
            } else {
                throw new TrelloNotAccessibleException("Server returned error " + ve.networkResponse.statusCode
                        + ": " + new String(ve.networkResponse.data));
            }
        } else {
            Log.e("Flashcards for Trello", "An unknown exception was thrown.", e);
            e.printStackTrace();
        }
    } catch (TimeoutException e) {
        throw new TrelloNotAccessibleException("Network request timed out");
    }

    return null;
}

From source file:com.google.acre.script.NHttpAsyncUrlfetch.java

public void make_request(String url, String method, long timeout, Map<String, String> headers, Object body,
        final boolean system, final boolean log_to_user, final String response_encoding,
        final boolean no_redirect, final Function callback) {

    String content_charset = "UTF-8";

    StringBuilder request_header_log = new StringBuilder();
    if (headers != null) {
        for (Map.Entry<String, String> header : headers.entrySet()) {
            String key = header.getKey();
            String value = header.getValue();

            if ("content-type".equalsIgnoreCase(key)) {
                Matcher m = CT_RE.matcher(value);
                if (m.find()) {
                    content_charset = m.group(2);
                }//from w ww . ja  v a  2  s .  c  om
            } else if ("content-length".equalsIgnoreCase(key)) {
                // skip it, since it's probably wrong and we
                // calculate it correctly anyway
                headers.remove(key);
            } else if ("user-agent".equalsIgnoreCase(key)) {
                // XXX do we need to do anything special here?
            }

            if (!("x-acre-auth".equalsIgnoreCase(key))) {
                request_header_log.append(key + ": " + value + "\r\n");
            }
        }
    }

    byte[] rbody = null;
    if (body != null) {
        if (body instanceof JSBinary) {
            rbody = ((JSBinary) body).get_data();
        } else if (body instanceof String) {
            try {
                rbody = ((String) body).getBytes(content_charset);
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        // XXX should it be possible to not include content-length?
        if (rbody != null && headers != null) {
            headers.put("content-length", Integer.toString(rbody.length));
            request_header_log.append("content-length: " + rbody.length + "\r\n");
        }
    }

    String httpreqhdr = request_header_log.toString();
    _logger.syslog4j("DEBUG", "urlfetch.request.async", "Method", method, "URL", url, "Headers", httpreqhdr);

    if (!system && log_to_user) {
        _response.userlog4j("DEBUG", "urlfetch.request.async", "Method", method, "URL", url, "Headers",
                httpreqhdr);
    }

    // XXX this is time the request was initiated, not necessarily the
    // time it was actually dispatched
    final long start_time = System.currentTimeMillis();
    try {
        _nhttp.fetch(url, method, headers, rbody, timeout, no_redirect, new NHttpClient.NHttpClientCallback() {
            public void finished(final URL url, final HttpResponse res) {
                Context ctx = Context.getCurrentContext();
                callback.call(ctx, _scope, null, new Object[] { url.toString(),
                        callback_result(start_time, url, res, system, log_to_user, response_encoding) });
            }

            public void error(final URL url, final NHttpClient.NHttpException e) {
                Context ctx = Context.getCurrentContext();

                Throwable cause = e.getCause();
                if (cause == null) {
                    cause = e;
                }
                JSURLError jse = new JSURLError(cause.getMessage());

                callback.call(ctx, _scope, null, new Object[] { url.toString(), jse.toJSError(_scope) });
            }
        });
    } catch (NHttpClient.NHttpException e) {
        Throwable cause = e.getCause();
        if (cause == null) {
            cause = e;
        }

        throw new JSURLError(cause.getMessage()).newJSException(_scope);
    }

}