Example usage for java.io UnsupportedEncodingException getLocalizedMessage

List of usage examples for java.io UnsupportedEncodingException getLocalizedMessage

Introduction

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

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:org.hyperic.hq.plugin.rabbitmq.core.HypericRabbitAdmin.java

public RabbitNode getNode(String node) throws PluginException {
    RabbitNode res;/*from   w  w w  .  j av  a  2 s.co m*/
    try {
        node = URLEncoder.encode(node, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
    try {
        res = get("/api/nodes/" + node, RabbitNode.class);
    } catch (PluginException ex) {
        logger.debug("[getVirtualHost] " + ex.getLocalizedMessage(), ex);
        res = get("/api/overview/", RabbitNode.class);
        res.setName(node);
        res.setRunning(true);
    }
    return res;
}

From source file:edu.cmu.cylab.starslinger.transaction.WebEngine.java

private byte[] doPost(String uri, byte[] requestBody) throws ExchangeException {
    mCancelable = false;/*from   w w  w.  j  a va  2 s .  c  o  m*/

    if (!SafeSlinger.getApplication().isOnline()) {
        throw new ExchangeException(mCtx.getString(R.string.error_CorrectYourInternetConnection));
    }

    // sets up parameters
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    if (mHttpClient == null) {
        mHttpClient = new CheckedHttpClient(params, mCtx);
    }
    HttpPost httppost = new HttpPost(uri);
    BasicResponseHandler responseHandler = new BasicResponseHandler();
    byte[] reqData = null;
    HttpResponse response = null;
    long startTime = SystemClock.elapsedRealtime();
    int statCode = 0;
    String statMsg = "";
    String error = "";

    try {
        // Execute HTTP Post Request
        httppost.addHeader("Content-Type", "application/octet-stream");
        httppost.setEntity(new ByteArrayEntity(requestBody));

        mTxTotalBytes = requestBody.length;

        final long totalTxBytes = TrafficStats.getTotalTxBytes();
        final long totalRxBytes = TrafficStats.getTotalRxBytes();
        if (totalTxBytes != TrafficStats.UNSUPPORTED) {
            mTxStartBytes = totalTxBytes;
        }
        if (totalRxBytes != TrafficStats.UNSUPPORTED) {
            mRxStartBytes = totalRxBytes;
        }
        response = mHttpClient.execute(httppost);
        reqData = responseHandler.handleResponse(response).getBytes("8859_1");

    } catch (UnsupportedEncodingException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (HttpResponseException e) {
        // this subclass of java.io.IOException contains useful data for
        // users, do not swallow, handle properly
        statCode = e.getStatusCode();
        statMsg = e.getLocalizedMessage();
        error = (String.format(mCtx.getString(R.string.error_HttpCode), statCode) + ", \'" + statMsg + "\'");
    } catch (java.io.IOException e) {
        // just show a simple Internet connection error, so as not to
        // confuse users
        error = mCtx.getString(R.string.error_CorrectYourInternetConnection);
    } catch (RuntimeException e) {
        error = e.getLocalizedMessage() + " (" + e.getClass().getSimpleName() + ")";
    } catch (OutOfMemoryError e) {
        error = mCtx.getString(R.string.error_OutOfMemoryError);
    } finally {
        long msDelta = SystemClock.elapsedRealtime() - startTime;
        if (response != null) {
            StatusLine status = response.getStatusLine();
            if (status != null) {
                statCode = status.getStatusCode();
                statMsg = status.getReasonPhrase();
            }
        }
        MyLog.d(TAG, uri + ", " + requestBody.length + "b sent, " + (reqData != null ? reqData.length : 0)
                + "b recv, " + statCode + " code, " + msDelta + "ms");
    }

    if (!TextUtils.isEmpty(error) || reqData == null) {
        throw new ExchangeException(error);
    }
    return reqData;
}

From source file:org.hyperic.hq.plugin.rabbitmq.core.HypericRabbitAdmin.java

public RabbitVirtualHost getVirtualHost(String vhName) throws PluginException {
    try {//from  w ww. ja v  a  2  s  . c om
        vhName = URLEncoder.encode(vhName, "UTF-8");
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }

    RabbitVirtualHost res;
    try {
        res = get("/api/vhosts/" + vhName, RabbitVirtualHost.class);
    } catch (PluginException ex) {
        logger.debug("[getVirtualHost] " + ex.getLocalizedMessage(), ex);
        String name = get("/api/vhosts/" + vhName, String.class);
        res = new RabbitVirtualHost(name);
    }
    return res;
}

From source file:com.hybris.mobile.activity.AbstractProductDetailActivity.java

/**
 * Get the NDEF for a product code/*from w  w  w  . ja va  2s. c  o m*/
 * 
 * @param productCode
 * @return
 */
private NdefMessage getNDEF(String productCode) {
    NdefMessage msg = null;
    try {
        NdefRecord uriRecord;
        uriRecord = NdefRecord.createUri(getString(R.string.nfc_url, URLEncoder.encode(productCode, "UTF-8")));
        NdefRecord appRecord = NdefRecord.createApplicationRecord(getPackageName());
        msg = new NdefMessage(new NdefRecord[] { uriRecord, appRecord });
    } catch (UnsupportedEncodingException e) {
        LoggingUtils.e(LOG_TAG, "Error trying to encode product code to UTF-8. " + e.getLocalizedMessage(),
                Hybris.getAppContext());
    }

    return msg;
}

From source file:com.evolveum.polygon.scim.ServiceAccessManager.java

/**
 * Used for login to the service. The data needed for this operation is
 * provided by the configuration.//ww w .j  ava  2  s.c  o  m
 * 
 * @param configuration
 *            The instance of "ScimConnectorConfiguration" which holds all
 *            the provided configuration data.
 * 
 * @return a Map object carrying meta information about the login session.
 */
public void logIntoService(ScimConnectorConfiguration configuration) {

    HttpPost loginInstance = new HttpPost();

    Header authHeader = null;
    String loginAccessToken = null;
    String loginInstanceUrl = null;
    JSONObject jsonObject = null;
    String proxyUrl = configuration.getProxyUrl();
    LOGGER.ok("proxyUrl: {0}", proxyUrl);
    //   LOGGER.ok("Configuration: {0}", configuration);
    if (!"token".equalsIgnoreCase(configuration.getAuthentication())) {

        HttpClient httpClient;

        if (proxyUrl != null && !proxyUrl.isEmpty()) {

            HttpHost proxy = new HttpHost(proxyUrl, configuration.getProxyPortNumber());

            DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

            httpClient = HttpClientBuilder.create().setRoutePlanner(routePlanner).build();

            LOGGER.ok("Proxy enabled: {0}:{1}", proxyUrl, configuration.getProxyPortNumber());
        } else {

            httpClient = HttpClientBuilder.create().build();

        }
        String loginURL = new StringBuilder(configuration.getLoginURL()).append(configuration.getService())
                .toString();

        GuardedString guardedPassword = configuration.getPassword();
        GuardedStringAccessor accessor = new GuardedStringAccessor();
        guardedPassword.access(accessor);

        String contentUri = new StringBuilder("&client_id=").append(configuration.getClientID())
                .append("&client_secret=").append(configuration.getClientSecret()).append("&username=")
                .append(configuration.getUserName()).append("&password=").append(accessor.getClearString())
                .toString();

        loginInstance = new HttpPost(loginURL);
        CloseableHttpResponse response = null;

        StringEntity bodyContent;
        String getResult = null;
        Integer statusCode = null;
        try {
            bodyContent = new StringEntity(contentUri);
            bodyContent.setContentType("application/x-www-form-urlencoded");
            loginInstance.setEntity(bodyContent);

            response = (CloseableHttpResponse) httpClient.execute(loginInstance);

            getResult = EntityUtils.toString(response.getEntity());

            statusCode = response.getStatusLine().getStatusCode();

            if (statusCode == 200) {

                LOGGER.info("Login Successful");

            } else {

                String[] loginUrlParts;
                String providerName = "";

                if (configuration.getLoginURL() != null && !configuration.getLoginURL().isEmpty()) {

                    loginUrlParts = configuration.getLoginURL().split("\\."); // e.g.
                    // https://login.salesforce.com

                } else {

                    loginUrlParts = configuration.getBaseUrl().split("\\."); // e.g.
                }
                // https://login.salesforce.com
                if (loginUrlParts.length >= 2) {
                    providerName = loginUrlParts[1];
                }

                if (!providerName.isEmpty()) {

                    StrategyFetcher fetcher = new StrategyFetcher();
                    HandlingStrategy strategy = fetcher.fetchStrategy(providerName);
                    strategy.handleInvalidStatus(" while loging into service", getResult, "loging into service",
                            statusCode);
                }

            }

            jsonObject = (JSONObject) new JSONTokener(getResult).nextValue();

            loginAccessToken = jsonObject.getString("access_token");
            loginInstanceUrl = jsonObject.getString("instance_url");

        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding: {0}. Occurrence in the process of login into the service",
                    e.getLocalizedMessage());
            LOGGER.info("Unsupported encoding: {0}. Occurrence in the process of login into the service", e);

            throw new ConnectorException(
                    "Unsupported encoding. Occurrence in the process of login into the service", e);
        }

        catch (ClientProtocolException e) {

            LOGGER.error(
                    "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification: {0}",
                    e.getLocalizedMessage());
            LOGGER.info(
                    "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification: {0}",
                    e);

            throw new ConnectionFailedException(
                    "An protocol exception has occurred while processing the http response to the login request. Possible mismatch in interpretation of the HTTP specification",
                    e);

        } catch (IOException ioException) {

            StringBuilder errorBuilder = new StringBuilder(
                    "An error occurred while processing the query http response to the login request. ");

            if ((ioException instanceof SocketTimeoutException
                    || ioException instanceof NoRouteToHostException)) {

                errorBuilder.insert(0, "The connection timed out. ");

                throw new OperationTimeoutException(errorBuilder.toString(), ioException);
            } else {

                LOGGER.error(
                        "An error occurred while processing the query http response to the login request : {0}",
                        ioException.getLocalizedMessage());
                LOGGER.info(
                        "An error occurred while processing the query http response to the login request : {0}",
                        ioException);
                throw new ConnectorIOException(errorBuilder.toString(), ioException);
            }
        } catch (JSONException jsonException) {

            LOGGER.error(
                    "An exception has occurred while setting the \"jsonObject\". Occurrence while processing the http response to the login request: {0}",
                    jsonException.getLocalizedMessage());
            LOGGER.info(
                    "An exception has occurred while setting the \"jsonObject\". Occurrence while processing the http response to the login request: {0}",
                    jsonException);
            throw new ConnectorException("An exception has occurred while setting the \"jsonObject\".",
                    jsonException);
        } finally {
            try {
                response.close();
            } catch (IOException e) {

                if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {

                    throw new OperationTimeoutException(
                            "The connection timed out while closing the http connection. Occurrence in the process of logging into the service",
                            e);
                } else {

                    LOGGER.error(
                            "An error has occurred while processing the http response and closing the http connection. Occurrence in the process of logging into the service: {0}",
                            e.getLocalizedMessage());

                    throw new ConnectorIOException(
                            "An error has occurred while processing the http response and closing the http connection. Occurrence in the process of logging into the service",
                            e);
                }

            }

        }
        authHeader = new BasicHeader("Authorization", "OAuth " + loginAccessToken);
    } else {
        loginInstanceUrl = configuration.getBaseUrl();

        GuardedString guardedToken = configuration.getToken();

        GuardedStringAccessor accessor = new GuardedStringAccessor();
        guardedToken.access(accessor);

        loginAccessToken = accessor.getClearString();

        authHeader = new BasicHeader("Authorization", "Bearer " + loginAccessToken);
    }
    String scimBaseUri = new StringBuilder(loginInstanceUrl).append(configuration.getEndpoint())
            .append(configuration.getVersion()).toString();

    this.baseUri = scimBaseUri;
    this.aHeader = authHeader;
    if (jsonObject != null) {
        this.loginJson = jsonObject;
    }

}

From source file:com.teleca.jamendo.api.impl.JamendoGet2ApiImpl.java

@Override
public PlaylistRemote[] getUserPlaylist(String user) throws JSONException, WSError {
    try {//from  w  w  w  .  j  ava  2s. c  o  m
        user = URLEncoder.encode(user, "UTF-8");
        String jsonString = doGet(
                "id+name+url+duration/playlist/json/playlist_user/?order=starred_desc&user_idstr=" + user);
        return PlaylistFunctions.getPlaylists(new JSONArray(jsonString));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw new JSONException(e.getLocalizedMessage());
    }
}

From source file:com.teleca.jamendo.api.impl.JamendoGet2ApiImpl.java

@Override
public Artist getArtist(String name) throws JSONException, WSError {
    try {//from   www . j  av  a2 s  . co  m
        name = URLEncoder.encode(name, "UTF-8");
        String jsonString = doGet(
                "id+idstr+name+url+image+rating+mbgid+mbid+genre/artist/jsonpretty/?name=" + name);
        JSONArray jsonArrayAlbums = new JSONArray(jsonString);
        return ArtistFunctions.getArtist(jsonArrayAlbums)[0];
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw new JSONException(e.getLocalizedMessage());
    }
}

From source file:com.teleca.jamendo.api.impl.JamendoGet2ApiImpl.java

@Override
public Album[] searchForAlbumsByTag(String tag) throws JSONException, WSError {
    try {//from   ww w  .ja  va 2s  . c  om
        tag = URLEncoder.encode(tag, "UTF-8");
        String jsonString = doGet(
                "id+name+url+image+rating+artist_name/album/json/?order=ratingweek_desc&tag_idstr=" + tag
                        + "&n=50");
        JSONArray jsonArrayAlbums = new JSONArray(jsonString);
        return AlbumFunctions.getAlbums(jsonArrayAlbums);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw new JSONException(e.getLocalizedMessage());
    }
}

From source file:com.teleca.jamendo.api.impl.JamendoGet2ApiImpl.java

@Override
public Album[] searchForAlbumsByArtistName(String artistName) throws JSONException, WSError {
    try {/*www .j  av a 2s .co  m*/
        artistName = URLEncoder.encode(artistName, "UTF-8");
        String jsonString = doGet(
                "id+name+url+image+rating+artist_name/album/json/?order=ratingweek_desc&n=50&artist_name="
                        + artistName);
        JSONArray jsonArrayAlbums = new JSONArray(jsonString);
        return AlbumFunctions.getAlbums(jsonArrayAlbums);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw new JSONException(e.getLocalizedMessage());
    }
}

From source file:com.teleca.jamendo.api.impl.JamendoGet2ApiImpl.java

@Override
public Album[] searchForAlbumsByArtist(String artistName) throws JSONException, WSError {

    try {//w  w w. j a v a2s. c  o m
        artistName = URLEncoder.encode(artistName, "UTF-8");
        String jsonString = doGet(
                "id+name+url+image+rating+artist_name/album/json/?order=ratingweek_desc&n=50&searchquery="
                        + artistName);
        JSONArray jsonArrayAlbums = new JSONArray(jsonString);
        return AlbumFunctions.getAlbums(jsonArrayAlbums);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (NullPointerException e) {
        e.printStackTrace();
        throw new JSONException(e.getLocalizedMessage());
    }
}