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:org.orbisgis.view.geocatalog.Catalog.java

/**
 * The user can load several WMS layers from the same server.
 *///from  www.  java 2s.c o  m
public void onMenuAddWMSServer() {
    DataManager dm = Services.getService(DataManager.class);
    SourceManager sm = dm.getSourceManager();
    SRSPanel srsPanel = new SRSPanel();
    LayerConfigurationPanel layerConfiguration = new LayerConfigurationPanel(srsPanel);
    WMSConnectionPanel wmsConnection = new WMSConnectionPanel(layerConfiguration);
    if (UIFactory.showDialog(new UIPanel[] { wmsConnection, layerConfiguration, srsPanel })) {
        WMService service = wmsConnection.getServiceDescription();
        Capabilities cap = service.getCapabilities();
        MapImageFormatChooser mfc = new MapImageFormatChooser(service.getVersion());
        mfc.setTransparencyRequired(true);
        String validImageFormat = mfc.chooseFormat(cap.getMapFormats());
        if (validImageFormat == null) {
            LOGGER.error(I18N.tr("Cannot find a valid image format for this WMS server"));
        } else {
            Object[] layers = layerConfiguration.getSelectedLayers();
            for (Object layer : layers) {
                String layerName = ((MapLayer) layer).getName();
                String uniqueLayerName = layerName;
                if (sm.exists(layerName)) {
                    uniqueLayerName = sm.getUniqueName(layerName);
                }
                URI origin = URI.create(service.getServerUrl());
                StringBuilder url = new StringBuilder(origin.getQuery());
                url.append("SERVICE=WMS&REQUEST=GetMap");
                String version = service.getVersion();
                url.append("&VERSION=").append(version);
                if (WMService.WMS_1_3_0.equals(version)) {
                    url.append("&CRS=");
                } else {
                    url.append("&SRS=");
                }
                url.append(srsPanel.getSRS());
                url.append("&LAYERS=").append(layerName);
                url.append("&FORMAT=").append(validImageFormat);
                try {
                    URI streamUri = new URI(origin.getScheme(), origin.getUserInfo(), origin.getHost(),
                            origin.getPort(), origin.getPath(), url.toString(), origin.getFragment());
                    WMSStreamSource wmsSource = new WMSStreamSource(streamUri);
                    StreamSourceDefinition streamSourceDefinition = new StreamSourceDefinition(wmsSource);
                    sm.register(uniqueLayerName, streamSourceDefinition);
                } catch (UnsupportedEncodingException uee) {
                    LOGGER.error(I18N.tr("Can't read the given URI: " + uee.getCause()));
                } catch (URISyntaxException use) {
                    LOGGER.error(I18N.tr("The given URI contains illegal character"), use);
                }
            }
        }
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

private JSONArray sendJson(String url, String data) throws IOException {
    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();

            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }/*  w  ww.  j ava 2  s . com*/

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "sendJson ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    JSONTokener tokener = new JSONTokener(response);
    JSONArray jobj = null;
    try {
        jobj = new JSONArray(tokener);
    } catch (JSONException e) {
        debug.logE(TAG, "sendJson got exception " + response, e.getCause());
        return null;
    }

    debug.logV(TAG, "sendJson got " + jobj);

    return jobj;
}

From source file:com.flipzu.flipzu.FlipInterface.java

private List<BroadcastDataSet> sendRequest(String url, String data) throws IOException {
    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }//from ww w. j a v a 2 s .c o m

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "sendRequest ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        TimelineHandler myTimelineHandler = new TimelineHandler();
        xr.setContentHandler(myTimelineHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        List<BroadcastDataSet> parsedDataSet = myTimelineHandler.getParsedData();

        return parsedDataSet;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

public FlipUser getUser(String username, String token) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url = WSServer + "/api/get_user.xml";

    debug.logV(TAG, "getUser for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }/*w  w  w  .  jav  a2  s. co  m*/

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.flipzu.flipzu.FlipInterface.java

private FlipUser setFollowUnfollow(String username, String token, boolean follow) throws IOException {
    String data = "username=" + username + "&access_token=" + token;
    String url;//from  w  w w  .  j a va  2  s .  c  om
    if (follow) {
        url = WSServer + "/api/set_follow.xml";
    } else {
        url = WSServer + "/api/set_unfollow.xml";
    }

    debug.logV(TAG, "setFollow for username " + username);

    DefaultHttpClient hc = new DefaultHttpClient();

    ResponseHandler<String> res = new ResponseHandler<String>() {
        public String handleResponse(final HttpResponse response) throws HttpResponseException, IOException {
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() >= 300) {
                throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
            }

            HttpEntity entity = response.getEntity();
            return entity == null ? null : EntityUtils.toString(entity, "UTF-8");
        }
    };

    HttpPost postMethod = new HttpPost(url);

    postMethod.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    if (data != null) {
        StringEntity tmp = null;
        try {
            tmp = new StringEntity(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            debug.logE(TAG, "getUser ERROR", e.getCause());
            return null;
        }

        postMethod.setEntity(tmp);
    }

    String response = hc.execute(postMethod, res);

    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        UserHandler myUserHandler = new UserHandler();
        xr.setContentHandler(myUserHandler);

        InputSource inputSource = new InputSource();
        inputSource.setEncoding("UTF-8");
        inputSource.setCharacterStream(new StringReader(response));

        xr.parse(inputSource);

        FlipUser parsedData = myUserHandler.getParsedData();

        return parsedData;

    } catch (ParserConfigurationException e) {
        return null;
    } catch (SAXException e) {
        return null;
    }
}

From source file:com.sitexa.android.data.net.volley.VolleyApi.java

protected Observable<ApiResult> doGet(final String doAction, final Map<String, String> requestParam,
        final boolean shouldCache, final boolean refreshCache, final boolean checkNetwork) {
    final ApiResult result = new ApiResult();

    return Observable.create(new Observable.OnSubscribe<ApiResult>() {
        @Override/*from  w ww. j a  v  a  2  s  . com*/
        public void call(Subscriber<? super ApiResult> subscriber) {

            if (checkNetwork && !isThereInternetConnection()) {
                subscriber.onError(new NetworkConnectionException(
                        CodeConstants.ApiCode.NETWORK_ERROR + ":" + "Network connection error"));
            } else {
                try {

                    final String api = getApi(doAction) + getGetMethodParams(requestParam);
                    Log.d(TAG, String.format("Request url %s", api));

                    StringRequest request = new StringRequest(Request.Method.GET, api, json -> {
                        Map map = gson.fromJson(json, Map.class);
                        Object code = map.get(CodeConstants.HttpCode.CODE);
                        Object value = map.get(CodeConstants.HttpCode.VALUE);
                        if (CodeConstants.HttpCode.SUCCESS_CODE.equals(code)) {
                            result.setCode(CodeConstants.ApiCode.OK);
                            result.setOriginalCode(String.valueOf(code));
                            result.setValue(gson.toJson(value));
                            subscriber.onNext(result);
                            subscriber.onCompleted();
                        } else {
                            subscriber.onError(new NetworkConnectionException(CodeConstants.ApiCode.ERROR + ":"
                                    + String.valueOf(code) + ":" + value.toString()));
                        }
                        Log.d(TAG, String.format("Request %s success. Result code: %s value: %s", api,
                                CodeConstants.ApiCode.ERROR, value.toString()));
                    }, volleyError -> {
                        subscriber.onError(
                                new NetworkConnectionException(CodeConstants.ApiCode.SERVER_CONNECTION_ERROR
                                        + ":" + (volleyError != null ? volleyError.getMessage() : "")));
                        Log.d(TAG,
                                String.format("Request %s failure. Result code: %s message: %s", api,
                                        CodeConstants.ApiCode.SERVER_CONNECTION_ERROR,
                                        volleyError != null ? volleyError.getMessage() : ""));
                    }) {
                        @Override
                        protected Response<String> parseNetworkResponse(NetworkResponse response) {
                            String setCookie = response.headers.get("Set-Cookie");
                            if (StringUtils.isNotEmpty(setCookie)) {
                                mCookie = setCookie;
                            }
                            Log.d(TAG, "Response cookie " + mCookie);
                            String json = "";
                            if (shouldCache) {
                                int maxAge = 7 * 24 * 60 * 60;
                                response.headers.remove("Cache-Control");
                                response.headers.remove("Pragma");
                                response.headers.remove("Expires");
                                if (refreshCache) {
                                    invalidateCached(api);
                                }
                                try {
                                    json = new String(response.data,
                                            HttpHeaderParser.parseCharset(response.headers));
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.getMessage(), e);
                                }
                                return Response.success(json, cache(response, maxAge));
                            }

                            return super.parseNetworkResponse(response);
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            Map<String, String> localHashMap = new HashMap<String, String>();
                            if (StringUtils.isNotEmpty(mCookie)) {
                                localHashMap.put("Cookie", mCookie);
                            }
                            return localHashMap;
                        }
                    };
                    request.setShouldCache(shouldCache);
                    requestQueue.add(request);

                } catch (Exception e) {
                    subscriber.onError(new NetworkConnectionException(e.getCause()));
                }
            }

        }
    });
}

From source file:com.sitexa.android.data.net.volley.VolleyApi.java

protected Observable<ApiResult> doPost(final String doAction, final Map<String, String> requestParam,
        final boolean shouldCache, final boolean refreshCache, final boolean checkNetwork) {
    final ApiResult result = new ApiResult();

    return Observable.create(new Observable.OnSubscribe<ApiResult>() {
        @Override//from   w ww .jav  a2  s.  c om
        public void call(Subscriber<? super ApiResult> subscriber) {

            if (checkNetwork && !isThereInternetConnection()) {
                subscriber.onError(new NetworkConnectionException(
                        CodeConstants.ApiCode.NETWORK_ERROR + ":" + "Network connection error"));
            } else {

                try {

                    final String api = getApi(doAction);
                    Log.d(TAG, String.format("Request url %s", api));

                    StringRequest request = new StringRequest(Request.Method.POST, api, json -> {
                        Log.d(TAG, json);
                        Map map = gson.fromJson(json, Map.class);
                        Object code = map.get(CodeConstants.HttpCode.CODE);
                        Object value = map.get(CodeConstants.HttpCode.VALUE);
                        if (CodeConstants.HttpCode.SUCCESS_CODE.equals(code)) {
                            result.setCode(CodeConstants.ApiCode.OK);
                            result.setOriginalCode(String.valueOf(code));
                            result.setValue(gson.toJson(value));
                            subscriber.onNext(result);
                            subscriber.onCompleted();
                        } else {
                            subscriber.onError(new NetworkConnectionException(CodeConstants.ApiCode.ERROR + ":"
                                    + String.valueOf(code) + ":" + value.toString()));
                        }
                        Log.d(TAG, String.format("Request %s success. Result code: %s value: %s", api,
                                CodeConstants.ApiCode.ERROR, value.toString()));
                    }, volleyError -> {
                        subscriber.onError(
                                new NetworkConnectionException(CodeConstants.ApiCode.SERVER_CONNECTION_ERROR
                                        + ":" + (volleyError != null ? volleyError.getMessage() : "")));
                        Log.d(TAG,
                                String.format("Request %s failure. Result code: %s message: %s", api,
                                        CodeConstants.ApiCode.SERVER_CONNECTION_ERROR,
                                        volleyError != null ? volleyError.getMessage() : ""));
                    }) {

                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            return requestParam;
                        }

                        @Override
                        protected Response<String> parseNetworkResponse(NetworkResponse response) {
                            String setCookie = response.headers.get("Set-Cookie");
                            if (StringUtils.isNotEmpty(setCookie)) {
                                mCookie = setCookie;
                            }
                            Log.d(TAG, "Response cookie " + mCookie);
                            String json = "";
                            if (shouldCache) {
                                int maxAge = 7 * 24 * 60 * 60;
                                response.headers.remove("Cache-Control");
                                response.headers.remove("Pragma");
                                response.headers.remove("Expires");
                                if (refreshCache) {
                                    invalidateCached(api);
                                }
                                try {
                                    json = new String(response.data,
                                            HttpHeaderParser.parseCharset(response.headers));
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.getMessage(), e);
                                }
                                return Response.success(json, cache(response, maxAge));
                            }

                            return super.parseNetworkResponse(response);
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            Map<String, String> localHashMap = new HashMap<String, String>();
                            if (StringUtils.isNotEmpty(mCookie)) {
                                localHashMap.put("Cookie", mCookie);
                            }
                            return localHashMap;
                        }
                    };

                    request.setShouldCache(shouldCache);
                    requestQueue.add(request);

                } catch (Exception e) {
                    subscriber.onError(new NetworkConnectionException(e.getCause()));
                }
            }
        }
    });
}

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/*w  w w.jav  a2  s .  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 String makeStringRequest(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<String> future = RequestFuture.newFuture();
        StringRequest request = new StringRequest(method, url, 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 != null && 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));
            }
        }
    } catch (TimeoutException e) {
        throw new TrelloNotAccessibleException("Network request timed out");
    }

    return null;
}

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  ava  2  s  . c  om*/
 * @throws TrelloNotAccessibleException if Trello API is not accessible
 * @throws TrelloNotAuthorizedException if token is not valid
 * @throws MalformedURLException        if path was not correctly formatted
 */
protected JSONArray makeJSONArrayRequest(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<JSONArray> future = RequestFuture.newFuture();
        JsonArrayRequest request = new JsonArrayRequest(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 || ve.networkResponse.statusCode == 400) {
                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;
}