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.orig.gls.security.Encode.java

public String encrypt(String value) {
    try {/*from  ww w. j  a va 2  s  .  co  m*/
        Cipher ecipher = Cipher.getInstance("DESede/CBC/PKCS5Padding", "SunJCE");
        ecipher.init(Cipher.ENCRYPT_MODE, key, iv);
        if (value == null) {
            return null;
        }
        //Encode the String into Bytes Using utf-8
        byte[] utf8 = value.getBytes("UTF-8");
        //Encrypt
        byte[] enc = ecipher.doFinal(utf8);
        //Encode Bytes to Base64 to get a String
        return new String(Base64.encodeBase64(enc), "UTF-8");

    } catch (UnsupportedEncodingException asd) {
        System.out.println(asd.getMessage());
    } catch (InvalidAlgorithmParameterException asd) {
        System.out.println(asd.getMessage());
    } catch (InvalidKeyException asd) {
        System.out.println(asd.getMessage());
    } catch (NoSuchAlgorithmException asd) {
        System.out.println(asd.getMessage());
    } catch (NoSuchProviderException asd) {
        System.out.println(asd.getMessage());
    } catch (BadPaddingException asd) {
        System.out.println(asd.getMessage());
    } catch (IllegalBlockSizeException asd) {
        System.out.println(asd.getMessage());
    } catch (NoSuchPaddingException asd) {
        System.out.println(asd.getMessage());
    }
    return null;
}

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

public static Map<String, Object> paymentRelease(DispatchContext ctx, Map<String, Object> context) {
    Debug.logInfo("SagePay Token -  Entered paymentRelease", module);
    //        Debug.logInfo("SagePay Token - paymentRelease 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 vpsTxId = (String) context.get("vpsTxId");
    String securityKey = (String) context.get("securityKey");
    String txAuthNo = (String) context.get("txAuthNo");
    String amount = (String) context.get("amount");
    String token = (String) context.get("token");
    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");

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

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

    String vpsProtocol = props.get("protocolVersion");
    String vendor = props.get("vendor");
    String txType = props.get("releaseTransType");

    parameters.put("VPSProtocol", vpsProtocol);
    parameters.put("TxType", txType);
    parameters.put("Vendor", vendor);
    parameters.put("VendorTxCode", vendorTxCode);
    parameters.put("VPSTxId", vpsTxId);
    parameters.put("SecurityKey", securityKey);
    parameters.put("TxAuthNo", txAuthNo);
    parameters.put("Amount", amount);
    parameters.put("Description", description);
    parameters.put("Token", token);
    parameters.put("Currency", currency);

    if (description != null) {
        parameters.put("Description", description);
    }//w  w w .j  a v a  2  s .c  o  m
    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 (billingState != null) {
        parameters.put("BillingState", billingState);
    }
    if (billingPhone != null) {
        parameters.put("BillingPhone", billingPhone);
    }
    //end - release parameters

    try {

        String successMessage = null;
        HttpPost httpPost = SagePayUtil.getHttpPost(props.get("releaseUrl"), 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);

        //start - payment released
        if ("OK".equals(status)) {
            successMessage = "Payment Released";
        }
        //end - payment released

        //start - release request not formed properly or parameters missing
        if ("MALFORMED".equals(status)) {
            successMessage = "Release request not formed properly or parameters missing";
        }
        //end - release request not formed properly or parameters missing

        //start - invalid information passed in parameters
        if ("INVALID".equals(status)) {
            successMessage = "Invalid information passed in parameters";
        }
        //end - invalid information passed in parameters

        //start - problem at Sagepay
        if ("ERROR".equals(status)) {
            successMessage = "Problem at SagePay";
        }
        //end - problem at Sagepay

        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:com.mnxfst.testing.client.TSClientPlanExecCallable.java

public TSClientPlanExecCallable(String hostname, int port, String uri, byte[] testplan) {
    this.httpHost = new HttpHost(hostname, port);
    //      this.getMethod = new HttpGet(uri.toString());
    this.postMethod = new HttpPost(uri.toString());
    try {/*from ww  w. j av  a2s.c o  m*/
        String convertedTestplan = new String(testplan, "UTF-8");
        postMethod.setEntity(new StringEntity(
                TSClient.REQUEST_PARAMETER_TESTPLAN + "=" + URLEncoder.encode(convertedTestplan, "UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Unsupported encoding exception. Error: " + e.getMessage());
    }

    // TODO setting?
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
    schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory()));

    ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager(
            schemeRegistry);
    threadSafeClientConnectionManager.setMaxTotal(20);
    threadSafeClientConnectionManager.setDefaultMaxPerRoute(20);
    this.httpClient = new DefaultHttpClient(threadSafeClientConnectionManager);

}

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

/**
 * Signs the specified request with the AWS3 signing protocol by using the
 * AWS account credentials specified when this object was constructed and
 * adding the required AWS3 headers to the request.
 *
 * @param request//from   w  w w  .j  a v a 2  s.c o m
 *            The request to sign.
 */
public void sign(Request<?> request, AWSCredentials credentials) throws AmazonClientException {
    // annonymous credentials, don't sign
    if (credentials instanceof AnonymousAWSCredentials) {
        return;
    }

    AWSCredentials sanitizedCredentials = sanitizeCredentials(credentials);

    SigningAlgorithm algorithm = SigningAlgorithm.HmacSHA256;
    String nonce = UUID.randomUUID().toString();
    Date dateValue = getSignatureDate(request.getTimeOffset());
    String date = dateUtils.formatRfc822Date(dateValue);
    boolean isHttps = false;

    if (overriddenDate != null)
        date = overriddenDate;
    request.addHeader("Date", date);
    request.addHeader("X-Amz-Date", date);

    // AWS3 HTTP requires that we sign the Host header
    // so we have to have it in the request by the time we sign.
    String hostHeader = request.getEndpoint().getHost();
    if (HttpUtils.isUsingNonDefaultPort(request.getEndpoint())) {
        hostHeader += ":" + request.getEndpoint().getPort();
    }
    request.addHeader("Host", hostHeader);

    if (sanitizedCredentials instanceof AWSSessionCredentials) {
        addSessionCredentials(request, (AWSSessionCredentials) sanitizedCredentials);
    }
    byte[] bytesToSign;
    String stringToSign;
    if (isHttps) {
        request.addHeader(NONCE_HEADER, nonce);
        stringToSign = date + nonce;
        try {
            bytesToSign = stringToSign.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new AmazonClientException("Unable to serialize string to bytes: " + e.getMessage(), e);
        }
    } else {
        /*
         * AWS3 requires all query params to be listed on the third line of
         * the string to sign, even if those query params will be sent in
         * the request body and not as a query string. POST formatted query
         * params should *NOT* be included in the request payload.
         */
        stringToSign = request.getHttpMethod().toString() + "\n"
                + getCanonicalizedResourcePath(request.getResourcePath()) + "\n"
                + getCanonicalizedQueryString(request.getParameters()) + "\n"
                + getCanonicalizedHeadersForStringToSign(request) + "\n"
                + getRequestPayloadWithoutQueryParams(request);
        bytesToSign = hash(stringToSign);
    }
    log.debug("Calculated StringToSign: " + stringToSign);

    String signature = signAndBase64Encode(bytesToSign, sanitizedCredentials.getAWSSecretKey(), algorithm);

    StringBuilder builder = new StringBuilder();
    builder.append(isHttps ? HTTPS_SCHEME : HTTP_SCHEME).append(" ");
    builder.append("AWSAccessKeyId=" + sanitizedCredentials.getAWSAccessKeyId() + ",");
    builder.append("Algorithm=" + algorithm.toString() + ",");

    if (!isHttps) {
        builder.append(getSignedHeadersComponent(request) + ",");
    }

    builder.append("Signature=" + signature);
    request.addHeader(AUTHORIZATION_HEADER, builder.toString());
}

From source file:URLCodec.java

/**
 * Encodes a string into its URL safe form using the default string 
 * charset. Unsafe characters are escaped.
 *
 * @param pString string to convert to a URL safe form
 * @return URL safe string/*from  w w  w  .  java 2 s  .  com*/
 * @throws EncoderException Thrown if URL encoding is unsuccessful
 * 
 * @see #getDefaultCharset()
 */
public String encode(String pString) throws Exception {
    if (pString == null) {
        return null;
    }
    try {
        return encode(pString, getDefaultCharset());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:URLCodec.java

/**
 * Decodes a URL safe string into its original form using the default
 * string charset. Escaped characters are converted back to their 
 * original representation.//from  w  w w .  jav  a  2  s  . c  o  m
 *
 * @param pString URL safe string to convert into its original form
 * @return original string 
 * @throws DecoderException Thrown if URL decoding is unsuccessful
 * 
 * @see #getDefaultCharset()
 */
public String decode(String pString) throws Exception {
    if (pString == null) {
        return null;
    }
    try {
        return decode(pString, getDefaultCharset());
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:org.hyperic.hq.plugin.jboss7.JBossAdminHttp.java

private Object post(String api, Type type, Map args) throws PluginException {
    GsonBuilder gsb = new GsonBuilder();
    Gson gson = gsb.create();//from w  w  w . j  a v a 2 s.  c om
    String argsJson = gson.toJson(args);
    log.debug("[post] argsJson=" + argsJson);

    HttpPost post = new HttpPost(prepareURL() + api);
    post.setHeader("Content-Type", "application/json");
    try {
        post.setEntity(new StringEntity(argsJson));
    } catch (UnsupportedEncodingException ex) {
        log.debug(ex.getMessage(), ex);
        throw new PluginException(ex.getMessage(), ex);
    }
    return query(post, api, type);
}

From source file:com.threewks.thundr.http.service.gae.HttpResponseImpl.java

@Override
public String getBody() {
    byte[] data = getBodyAsBytes();
    String characterEncoding = getCharset();
    try {//www . j  av  a 2s  .  c o  m
        return data == null ? "" : new String(data, characterEncoding);
    } catch (UnsupportedEncodingException e) {
        throw new HttpException(e, "Failed to read body as string- character encoding '%s' not supported: %s",
                characterEncoding, e.getMessage());
    }
}

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

public static Map<String, Object> paymentRefund(DispatchContext ctx, Map<String, Object> context) {
    Debug.logInfo("SagePay Token -  Entered paymentRefund", module);
    //        Debug.logInfo("SagePay Token - paymentRefund 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 relatedVPSTxId = (String) context.get("relatedVPSTxId");
    String relatedVendorTxCode = (String) context.get("relatedVendorTxCode");
    String relatedSecurityKey = (String) context.get("relatedSecurityKey");
    String relatedTxAuthNo = (String) context.get("relatedTxAuthNo");

    String amount = (String) context.get("amount");
    String token = (String) context.get("token");
    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");

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

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

    String vpsProtocol = props.get("protocolVersion");
    String vendor = props.get("vendor");
    String txType = props.get("refundTransType");

    parameters.put("VPSProtocol", vpsProtocol);
    parameters.put("TxType", txType);
    parameters.put("Vendor", vendor);
    parameters.put("VendorTxCode", vendorTxCode);
    parameters.put("Amount", amount);
    parameters.put("Description", description);
    parameters.put("RelatedVPSTxId", relatedVPSTxId);
    parameters.put("RelatedVendorTxCode", relatedVendorTxCode);
    parameters.put("RelatedSecurityKey", relatedSecurityKey);
    parameters.put("RelatedTxAuthNo", relatedTxAuthNo);
    parameters.put("Token", token);
    parameters.put("Currency", currency);

    if (description != null) {
        parameters.put("Description", description);
    }/*  w w  w.  j  ava2  s.  c  om*/
    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 (billingState != null) {
        parameters.put("BillingState", billingState);
    }
    if (billingPhone != null) {
        parameters.put("BillingPhone", billingPhone);
    }

    //end - refund parameters

    try {
        String successMessage = null;

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

        Debug.logInfo("response data -> " + responseData, module);

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

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

        //start - payment refunded
        if ("OK".equals(status)) {
            resultMap.put("vpsTxId", responseData.get("VPSTxId"));
            resultMap.put("txAuthNo", responseData.get("TxAuthNo"));
            successMessage = "Payment Refunded";
        }
        //end - payment refunded

        //start - refund not authorized by the acquiring bank
        if ("NOTAUTHED".equals(status)) {
            successMessage = "Refund not authorized by the acquiring bank";
        }
        //end - refund not authorized by the acquiring bank

        //start - refund request not formed properly or parameters missing
        if ("MALFORMED".equals(status)) {
            successMessage = "Refund request not formed properly or parameters missing";
        }
        //end - refund request not formed properly or parameters missing

        //start - invalid information passed in parameters
        if ("INVALID".equals(status)) {
            successMessage = "Invalid information passed in parameters";
        }
        //end - invalid information passed in parameters

        //start - problem at Sagepay
        if ("ERROR".equals(status)) {
            successMessage = "Problem at SagePay";
        }
        //end - problem at Sagepay

        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:com.spectralogic.ds3cli.views.json.CommandExceptionJsonView.java

@Override
public String render(final CommandException obj) throws JsonProcessingException {
    final CommonJsonView view = CommonJsonView.newView(CommonJsonView.Status.ERROR);
    final Map<String, String> jsonBackingMap = new TreeMap<>();

    view.message(obj.getMessage());/*from   w ww.  j a va  2  s.co  m*/

    try {
        final ObjectMapper mapper = new ObjectMapper();
        if (obj.getCause() != null) {
            if (obj.getCause() instanceof FailedRequestException) {
                final FailedRequestException ce = (FailedRequestException) obj.getCause();
                jsonBackingMap.put("StatusCode", Integer.toString(ce.getStatusCode()));
                jsonBackingMap.put("ApiErrorMessage", ce.getResponseString());
            } else {
                final ByteArrayOutputStream out = new ByteArrayOutputStream();
                final PrintWriter pOut = new PrintWriter(out);
                obj.printStackTrace(pOut);
                try {
                    jsonBackingMap.put("StackTrace", out.toString("utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }

        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(view.data(jsonBackingMap));
    } catch (final Exception e) {
        return "Failed to render error: " + e.getMessage();
    }
}