Example usage for java.io UnsupportedEncodingException getMessage

List of usage examples for java.io UnsupportedEncodingException getMessage

Introduction

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

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.dongwookchung.nutritioncalculator.FatSecretAPI.java

/**
 * Returns the percent-encoded string for the given url
 *
 * @param url/*from  w w  w  .  j a  va2s.  co m*/
 *          URL which is to be encoded using percent-encoding
 *
 * @return encoded url
 */
public String encode(String url) {
    if (url == null)
        return "";

    try {
        return URLEncoder.encode(url, "utf-8").replace("+", "%20").replace("!", "%21").replace("*", "%2A")
                .replace("\\", "%27").replace("(", "%28").replace(")", "%29");
    } catch (UnsupportedEncodingException wow) {
        throw new RuntimeException(wow.getMessage(), wow);
    }
}

From source file:com.osafe.services.sagepay.SagePayTokenServices.java

public static Map<String, Object> paymentAuthentication(DispatchContext ctx, Map<String, Object> context) {
    Debug.logInfo("SagePay Token - Entered paymentAuthentication", module);
    //        Debug.logInfo("SagePay Token paymentAuthentication context : " + context, module);

    Delegator delegator = ctx.getDelegator();
    Map<String, Object> resultMap = new HashMap<String, Object>();

    Map<String, String> props = buildSagePayProperties(context, delegator);

    String vendorTxCode = (String) context.get("vendorTxCode");
    String token = (String) context.get("token");
    String cv2 = (String) context.get("cv2");
    String amount = (String) context.get("amount");
    String currency = (String) context.get("currency");
    String description = (String) context.get("description");
    String billingSurname = (String) context.get("billingSurname");
    String billingFirstnames = (String) context.get("billingFirstnames");
    String billingAddress = (String) context.get("billingAddress");
    String billingAddress2 = (String) context.get("billingAddress2");
    String billingCity = (String) context.get("billingCity");
    String billingPostCode = (String) context.get("billingPostCode");
    String billingCountry = (String) context.get("billingCountry");
    String billingState = (String) context.get("billingState");
    String billingPhone = (String) context.get("billingPhone");

    Boolean isBillingSameAsDelivery = (Boolean) context.get("isBillingSameAsDelivery");

    String deliverySurname = (String) context.get("deliverySurname");
    String deliveryFirstnames = (String) context.get("deliveryFirstnames");
    String deliveryAddress = (String) context.get("deliveryAddress");
    String deliveryAddress2 = (String) context.get("deliveryAddress2");
    String deliveryCity = (String) context.get("deliveryCity");
    String deliveryPostCode = (String) context.get("deliveryPostCode");
    String deliveryCountry = (String) context.get("deliveryCountry");
    String deliveryState = (String) context.get("deliveryState");
    String deliveryPhone = (String) context.get("deliveryPhone");

    String startDate = (String) context.get("startDate");
    String issueNumber = (String) context.get("issueNumber");
    String basket = (String) context.get("basket");
    String clientIPAddress = (String) context.get("clientIPAddress");

    HttpClient httpClient = SagePayUtil.getHttpClient();
    HttpHost host = SagePayUtil.getHost(props);

    //start - authentication parameters
    Map<String, String> parameters = new HashMap<String, String>();

    String vpsProtocol = props.get("protocolVersion");
    String vendor = props.get("vendor");
    String txType = props.get("authenticationTransType");
    String storeToken = props.get("storeToken");
    if (UtilValidate.isEmpty(storeToken)) {
        storeToken = "0";
    }/*from w ww .jav a2 s. c  om*/

    //start - required parameters
    parameters.put("VPSProtocol", vpsProtocol);
    parameters.put("TxType", txType);
    parameters.put("Vendor", vendor);
    //        parameters.put("StoreToken", storeToken);

    if (vendorTxCode != null) {
        parameters.put("VendorTxCode", vendorTxCode);
    }
    if (amount != null) {
        parameters.put("Amount", amount);
    }
    if (currency != null) {
        parameters.put("Currency", currency);
    } //GBP/USD
    if (description != null) {
        parameters.put("Description", description);
    }
    if (token != null) {
        parameters.put("Token", token);
    }
    if (storeToken != null) {
        parameters.put("StoreToken", storeToken);
    }

    //start - billing details
    if (billingSurname != null) {
        parameters.put("BillingSurname", billingSurname);
    }
    if (billingFirstnames != null) {
        parameters.put("BillingFirstnames", billingFirstnames);
    }
    if (billingAddress != null) {
        parameters.put("BillingAddress1", billingAddress);
    }
    if (billingAddress2 != null) {
        parameters.put("BillingAddress2", billingAddress2);
    }
    if (billingCity != null) {
        parameters.put("BillingCity", billingCity);
    }
    if (billingPostCode != null) {
        parameters.put("BillingPostCode", billingPostCode);
    }
    if (billingCountry != null) {
        parameters.put("BillingCountry", billingCountry);
        if ("USA".equals(billingCountry) || "CAN".equals(billingCountry)) {
            if (UtilValidate.isNotEmpty(billingState)) {
                parameters.put("BillingState", billingState);
            }

        }
    }
    if (billingPhone != null) {
        parameters.put("BillingPhone", billingPhone);
    }
    //end - billing details

    //start - delivery details
    if (isBillingSameAsDelivery != null && isBillingSameAsDelivery) {
        if (billingSurname != null) {
            parameters.put("DeliverySurname", billingSurname);
        }
        if (billingFirstnames != null) {
            parameters.put("DeliveryFirstnames", billingFirstnames);
        }
        if (billingAddress != null) {
            parameters.put("DeliveryAddress1", billingAddress);
        }
        if (billingAddress2 != null) {
            parameters.put("DeliveryAddress2", billingAddress2);
        }
        if (billingCity != null) {
            parameters.put("DeliveryCity", billingCity);
        }
        if (billingPostCode != null) {
            parameters.put("DeliveryPostCode", billingPostCode);
        }
        if (billingCountry != null) {
            parameters.put("DeliveryCountry", billingCountry);
        }
        if (billingState != null) {
            parameters.put("DeliveryState", billingState);
        }
        if (billingPhone != null) {
            parameters.put("DeliveryPhone", billingPhone);
        }
    } else {
        if (deliverySurname != null) {
            parameters.put("DeliverySurname", deliverySurname);
        }
        if (deliveryFirstnames != null) {
            parameters.put("DeliveryFirstnames", deliveryFirstnames);
        }
        if (deliveryAddress != null) {
            parameters.put("DeliveryAddress1", deliveryAddress);
        }
        if (deliveryAddress2 != null) {
            parameters.put("DeliveryAddress2", deliveryAddress2);
        }
        if (deliveryCity != null) {
            parameters.put("DeliveryCity", deliveryCity);
        }
        if (deliveryPostCode != null) {
            parameters.put("DeliveryPostCode", deliveryPostCode);
        }
        if (deliveryCountry != null) {
            parameters.put("DeliveryCountry", deliveryCountry);
            if ("USA".equals(deliveryCountry) || "CAN".equals(deliveryCountry)) {
                if (UtilValidate.isNotEmpty(deliveryState)) {
                    parameters.put("DeliveryState", deliveryState);
                }

            }
        }
        if (deliveryPhone != null) {
            parameters.put("DeliveryPhone", deliveryPhone);
        }
    }
    //end - delivery details
    //end - required parameters

    //start - optional parameters
    if (cv2 != null) {
        parameters.put("CV2", cv2);
    }
    if (startDate != null) {
        parameters.put("StartDate", startDate);
    }
    if (issueNumber != null) {
        parameters.put("IssueNumber", issueNumber);
    }
    if (basket != null) {
        parameters.put("Basket", basket);
    }
    if (clientIPAddress != null) {
        parameters.put("ClientIPAddress", clientIPAddress);
    }

    //end - optional parameters
    //end - authentication parameters

    try {

        String successMessage = null;
        HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authenticationUrl"), parameters);
        HttpResponse response = httpClient.execute(host, httpPost);
        Map<String, String> responseData = SagePayUtil.getResponseData(response);

        String status = responseData.get("Status");
        String statusDetail = responseData.get("StatusDetail");

        resultMap.put("status", status);
        resultMap.put("statusDetail", statusDetail);

        //returning the below details back to the calling code, as it not returned back by the payment gateway
        resultMap.put("vendorTxCode", vendorTxCode);
        resultMap.put("amount", amount);
        resultMap.put("transactionType", txType);

        //start - transaction authorized
        if ("OK".equals(status)) {
            resultMap.put("vpsTxId", responseData.get("VPSTxId"));
            resultMap.put("securityKey", responseData.get("SecurityKey"));
            resultMap.put("txAuthNo", responseData.get("TxAuthNo"));
            resultMap.put("avsCv2", responseData.get("AVSCV2"));
            resultMap.put("addressResult", responseData.get("AddressResult"));
            resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
            resultMap.put("cv2Result", responseData.get("CV2Result"));
            successMessage = "Payment authorized";
        }
        //end - transaction authorized

        if ("NOTAUTHED".equals(status)) {
            resultMap.put("vpsTxId", responseData.get("VPSTxId"));
            resultMap.put("securityKey", responseData.get("SecurityKey"));
            resultMap.put("avsCv2", responseData.get("AVSCV2"));
            resultMap.put("addressResult", responseData.get("AddressResult"));
            resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
            resultMap.put("cv2Result", responseData.get("CV2Result"));
            successMessage = "Payment not authorized";
        }

        if ("MALFORMED".equals(status)) {
            //request not formed properly or parameters missing
            resultMap.put("vpsTxId", responseData.get("VPSTxId"));
            resultMap.put("securityKey", responseData.get("SecurityKey"));
            resultMap.put("avsCv2", responseData.get("AVSCV2"));
            resultMap.put("addressResult", responseData.get("AddressResult"));
            resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
            resultMap.put("cv2Result", responseData.get("CV2Result"));
        }

        if ("INVALID".equals(status)) {
            //invalid information in request
            resultMap.put("vpsTxId", responseData.get("VPSTxId"));
            resultMap.put("securityKey", responseData.get("SecurityKey"));
            resultMap.put("avsCv2", responseData.get("AVSCV2"));
            resultMap.put("addressResult", responseData.get("AddressResult"));
            resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
            resultMap.put("cv2Result", responseData.get("CV2Result"));
        }

        if ("REJECTED".equals(status)) {
            //invalid information in request
            resultMap.put("vpsTxId", responseData.get("VPSTxId"));
            resultMap.put("securityKey", responseData.get("SecurityKey"));
            resultMap.put("avsCv2", responseData.get("AVSCV2"));
            resultMap.put("addressResult", responseData.get("AddressResult"));
            resultMap.put("postCodeResult", responseData.get("PostCodeResult"));
            resultMap.put("cv2Result", responseData.get("CV2Result"));
        }

        resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
        resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage);

    } catch (UnsupportedEncodingException uee) {
        //exception in encoding parameters in httpPost
        String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")";
        Debug.logError(uee, errorMsg, module);
        resultMap = ServiceUtil.returnError(errorMsg);
    } catch (ClientProtocolException cpe) {
        //from httpClient execute
        String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")";
        Debug.logError(cpe, errorMsg, module);
        resultMap = ServiceUtil.returnError(errorMsg);
    } catch (IOException ioe) {
        //from httpClient execute or getResponsedata
        String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")";
        Debug.logError(ioe, errorMsg, module);
        resultMap = ServiceUtil.returnError(errorMsg);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return resultMap;
}

From source file:org.grails.datastore.mapping.redis.engine.RedisEntityPersister.java

private String convertByteArrayToString(Object byteArray) {
    String value;/*from  ww  w.j  a v a2 s.c o  m*/
    if (byteArray instanceof byte[]) {
        try {
            value = new String((byte[]) byteArray, UTF_8);
        } catch (UnsupportedEncodingException e) {
            throw new DataRetrievalFailureException("Cannot decode byte[] value: " + e.getMessage(), e);
        }
    } else {
        value = byteArray.toString();
    }
    return value;
}

From source file:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

/**
 * Computes an RFC 2104-compliant HMAC signature and returns the result as a
 * Base64 encoded string./*from w w w.java2s . c  om*/
 */
protected String signAndBase64Encode(String data, String key, SigningAlgorithm algorithm)
        throws AmazonClientException {
    try {
        return signAndBase64Encode(data.getBytes(DEFAULT_ENCODING), key, algorithm);
    } catch (UnsupportedEncodingException e) {
        throw new AmazonClientException("Unable to calculate a request signature: " + e.getMessage(), e);
    }
}

From source file:com.mobiperf.speedometer.Checkin.java

private String speedometerServiceRequest(String url, String jsonString) throws IOException {

    synchronized (this) {
        if (authCookie == null) {
            if (!checkGetCookie()) {
                throw new IOException("No authCookie yet");
            }/*from  w ww.  ja  v a2  s  .  com*/
        }
    }

    HttpClient client = getNewHttpClient();
    String fullurl = serverUrl + "/" + url;
    HttpPost postMethod = new HttpPost(fullurl);

    StringEntity se;
    try {
        se = new StringEntity(jsonString);
    } catch (UnsupportedEncodingException e) {
        throw new IOException(e.getMessage());
    }
    postMethod.setEntity(se);
    postMethod.setHeader("Accept", "application/json");
    postMethod.setHeader("Content-type", "application/json");
    // TODO(mdw): This should not be needed
    postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue());

    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    Logger.i("Sending request: " + fullurl);
    String result = client.execute(postMethod, responseHandler);
    return result;
}

From source file:org.collectionspace.services.client.AbstractServiceClientImpl.java

/**
 * Returns a UTF-8 encode byte array from 'string'
 *
 * @return UTF-8 encoded byte array/*from  w  ww .  j  a  v  a  2s .c  o  m*/
 */
protected byte[] getBytes(String string) {
    byte[] result = null;
    try {
        result = string.getBytes("UTF8");
    } catch (UnsupportedEncodingException e) {
        if (logger.isWarnEnabled() == true) {
            logger.warn(e.getMessage(), e);
        }
    }
    return result;
}

From source file:com.sina.auth.AbstractAWSSigner.java

/**
 * Computes an RFC 2104-compliant HMAC signature and returns the result as a
 * Base64 encoded string.// w ww .  j  a  v  a  2  s . co  m
 */
protected String signAndBase64Encode(String data, String key, SigningAlgorithm algorithm)
        throws SCSClientException {
    try {
        return signAndBase64Encode(data.getBytes(DEFAULT_ENCODING), key, algorithm);
    } catch (UnsupportedEncodingException e) {
        throw new SCSClientException("Unable to calculate a request signature: " + e.getMessage(), e);
    }
}

From source file:edu.asu.msse.sgowdru.moviemediaplayerrpc.SearchMovie.java

public void searchButtonClicked(View view) {
    String searchString = info[0].getText().toString();

    android.util.Log.w(getClass().getSimpleName(), searchString);

    //Check if the movie name is available in RPC server
    boolean isInRPC = isMovieInRPC(searchString);
    //If the movie name is available retrieve its detail
    //Set the video player visibility to VISIBLE
    if (isInRPC) {
        System.out.println(searchString + " Movie in RPC!");
        //Movie not present in local DB, raise a toast message
        text = " being retrieved from RPC Server now.";
        Toast toast = Toast.makeText(context, "Movie " + searchString + text, duration);
        toast.show();/*from w ww.j  a va 2 s  .c  om*/

        playButton.setVisibility(view.VISIBLE);

        getMovieDetails(searchString);
    } else {
        try {
            cur = crsDB.rawQuery("select Title from Movies where Title='" + searchString + "';",
                    new String[] {});
            android.util.Log.w(getClass().getSimpleName(), searchString);

            //If the Movie Exists in the Local Database, we will retrieve it from the Local DB
            if (cur.getCount() != 0) {
                //Raise toast message that the movie is already present in local DB
                text = " already present in DB, Retrieving..";
                Toast toast = Toast.makeText(context, "Movie " + searchString + text, duration);
                toast.show();

                //Retrieving the Movie since we know that the movie exists in DB
                cur = crsDB.rawQuery(
                        "select Title, Genre, Years, Rated, Actors, VideoFile from Movies where Title = ?;",
                        new String[] { searchString });

                //Movie Already present hence disabling the Add Button
                addButton.setEnabled(false);

                //Move the Cursor and set the Fields
                cur.moveToNext();
                info[1].setText(cur.getString(0));
                info[2].setText(cur.getString(1));
                info[3].setText(cur.getString(2));
                info[4].setText(cur.getString(4));

                //Set the Ratings dropdown
                if (cur.getString(3).equals("PG"))
                    dropdown.setSelection(0);
                else if (cur.getString(3).equals("PG-13"))
                    dropdown.setSelection(1);
                else if (cur.getString(3).equals("R"))
                    dropdown.setSelection(2);

                String video = cur.getString(5);
                if (video != null) {
                    playButton.setVisibility(view.VISIBLE);
                }

            }

            //If the Movie Does not exist in the Local Database, we will retrieve it from the OMDB
            else {
                //Movie not present in local DB, raise a toast message
                text = " being retrieved from OMDB now.";
                Toast toast = Toast.makeText(context, "Movie " + searchString + text, duration);
                toast.show();

                //Encode the search string to be appropriate to be placed in a url
                String encodedUrl = null;
                try {
                    encodedUrl = URLEncoder.encode(searchString, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    android.util.Log.e(getClass().getSimpleName(), e.getMessage());
                }

                //ASync thread running the query from OMDB and retrieving the movie details as JSON
                JSONObject result = new MovieGetInfoAsync()
                        .execute("http://www.omdbapi.com/?t=\"" + encodedUrl + "\"&r=json").get();

                //Check if the Movie query was successful
                if (result.getString("Response").equals("True")) {
                    info[1].setText(result.getString("Title"));
                    info[2].setText(result.getString("Genre"));
                    info[3].setText(result.getString("Year"));
                    info[4].setText(result.getString("Actors"));

                    if (result.getString("Rated").equals("PG"))
                        dropdown.setSelection(0);
                    else if (result.getString("Rated").equals("PG-13"))
                        dropdown.setSelection(1);
                    else if (result.getString("Rated").equals("R"))
                        dropdown.setSelection(2);

                    if (result.has("Filename")) {
                        videoFile = result.getString("Filename");
                    } else {
                        playButton.setVisibility(View.GONE);
                        videoFile = null;
                    }
                }
                //Search query was unsuccessful in getting movie with such a name
                else if (result.getString("Response").equals("False")) {
                    //Raise a toast message
                    text = " not present in OMDB, You can add it manually!";
                    toast = Toast.makeText(context, "Movie " + searchString + text, duration);
                    toast.show();
                }
            }
        } catch (Exception e) {
            android.util.Log.w(getClass().getSimpleName(), e.getMessage());
        }
    }
}

From source file:com.aliyun.oss.common.comm.ServiceClient.java

private Request buildRequest(RequestMessage requestMessage, ExecutionContext context) throws ClientException {
    Request request = new Request();
    request.setMethod(requestMessage.getMethod());
    request.setUseChunkEncoding(requestMessage.isUseChunkEncoding());

    if (requestMessage.isUseUrlSignature()) {
        request.setUrl(requestMessage.getAbsoluteUrl().toString());
        request.setUseUrlSignature(true);

        request.setContent(requestMessage.getContent());
        request.setContentLength(requestMessage.getContentLength());
        request.setHeaders(requestMessage.getHeaders());

        return request;
    }/*from   w  w w.j  av  a 2  s . com*/

    request.setHeaders(requestMessage.getHeaders());
    // The header must be converted after the request is signed,
    // otherwise the signature will be incorrect.
    if (request.getHeaders() != null) {
        HttpUtil.convertHeaderCharsetToIso88591(request.getHeaders());
    }

    final String delimiter = "/";
    String uri = requestMessage.getEndpoint().toString();
    if (!uri.endsWith(delimiter) && (requestMessage.getResourcePath() == null
            || !requestMessage.getResourcePath().startsWith(delimiter))) {
        uri += delimiter;
    }

    if (requestMessage.getResourcePath() != null) {
        uri += requestMessage.getResourcePath();
    }

    String paramString = HttpUtil.paramToQueryString(requestMessage.getParameters(), context.getCharset());

    /*
     * For all non-POST requests, and any POST requests that already have a
     * payload, we put the encoded params directly in the URI, otherwise,
     * we'll put them in the POST request's payload.
     */
    boolean requestHasNoPayload = requestMessage.getContent() != null;
    boolean requestIsPost = requestMessage.getMethod() == HttpMethod.POST;
    boolean putParamsInUri = !requestIsPost || requestHasNoPayload;
    if (paramString != null && putParamsInUri) {
        uri += "?" + paramString;
    }

    request.setUrl(uri);

    if (requestIsPost && requestMessage.getContent() == null && paramString != null) {
        // Put the param string to the request body if POSTing and
        // no content.
        try {
            byte[] buf = paramString.getBytes(context.getCharset());
            ByteArrayInputStream content = new ByteArrayInputStream(buf);
            request.setContent(content);
            request.setContentLength(buf.length);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(
                    COMMON_RESOURCE_MANAGER.getFormattedString("EncodingFailed", e.getMessage()));
        }
    } else {
        request.setContent(requestMessage.getContent());
        request.setContentLength(requestMessage.getContentLength());
    }

    return request;
}

From source file:com.fujitsu.dc.test.jersey.DcRestAdapter.java

/**
 * POST?????./*from w  ww  .  j  a v a2  s.co  m*/
 * @param url POST?URL
 * @param data POST?
 * @param contentType 
 * @return POST??
 * @throws DcException DAO
 */
protected final HttpPost makePostRequest(final String url, final String data, final String contentType)
        throws DcException {
    HttpPost request = new HttpPost(url);
    HttpEntity body = null;
    try {
        String bodyStr = toUniversalCharacterNames(data);
        body = new StringEntity(bodyStr);
    } catch (UnsupportedEncodingException e) {
        throw DcException.create("error while request body encoding : " + e.getMessage(), 0);
    }
    request.setEntity(body);
    makeCommonHeaders(request, contentType, contentType, null);
    return request;
}