Example usage for org.apache.http.client ClientProtocolException getMessage

List of usage examples for org.apache.http.client ClientProtocolException getMessage

Introduction

In this page you can find the example usage for org.apache.http.client ClientProtocolException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:gov.nih.nci.caxchange.messaging.RegistrationIntegrationTest.java

/**
 * Testcase for sending invalid Study (Study Not Present) during Participant registration
 *//*from ww  w .ja  va  2 s .  c  o  m*/
@Test
public void sendInvalidStudyRegistrationMessage() {
    try {
        final HttpPost httppost = new HttpPost(transcendCaxchangeServiceUrl);
        String msg = getCreateMsg();
        msg = msg.replaceAll("ISPY2", "ISPY2_123");
        msg = msg.replaceAll("1823467", "1823467_123456");

        final StringEntity reqentity = new StringEntity(msg);
        httppost.setEntity(reqentity);
        httppost.setHeader(HttpHeaders.CONTENT_TYPE, XMLTEXT);

        final HttpResponse response = httpclient.execute(httppost);
        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            final String output = EntityUtils.toString(entity);
            Assert.assertNotNull(output);
            Assert.assertEquals(true, output.contains("<errorCode>1009</errorCode>"));
        }
    } catch (ClientProtocolException e) {
        Assert.fail(e.getMessage());
    } catch (IllegalStateException e) {
        Assert.fail(e.getMessage());
    } catch (IOException e) {
        Assert.fail(e.getMessage());
    }
}

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

public static Map<String, Object> paymentRegistration(DispatchContext ctx, Map<String, Object> context) {
    Debug.logInfo("SagePay Token -  Entered paymentRegistration", module);
    //        Debug.logInfo("SagePay Token - paymentRegistration 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 currency = (String) context.get("currency");
    String cardHolder = (String) context.get("cardHolder");
    String cardNumber = (String) context.get("cardNumber");
    String expiryDate = (String) context.get("expiryDate");
    String cv2 = (String) context.get("cv2");
    String cardType = (String) context.get("cardType");
    String paymentMethodId = (String) context.get("paymentMethodId");
    String contactMechId = (String) context.get("contactMechId");

    String startDate = (String) context.get("startDate");
    String issueNumber = (String) context.get("issueNumber");
    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("registrationTransType");

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

    if (currency != null) {
        parameters.put("Currency", currency);
    } //GBP/USD/*from  w w  w. j a  v a  2s  . c  o m*/
    if (cardHolder != null) {
        parameters.put("CardHolder", cardHolder);
    }
    if (cardNumber != null) {
        parameters.put("CardNumber", cardNumber);
    }
    if (expiryDate != null) {
        parameters.put("ExpiryDate", expiryDate);
    }
    if (cardType != null) {
        parameters.put("CardType", cardType.toUpperCase());
    }

    //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 (clientIPAddress != null) {
        parameters.put("ClientIPAddress", clientIPAddress);
    }

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

    try {

        String successMessage = null;
        HttpPost httpPost = SagePayUtil.getHttpPost(props.get("registrationUrl"), 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("transactionType", txType);
        resultMap.put("token", null);
        //start - transaction registered
        if ("OK".equals(status)) {
            resultMap.put("token", responseData.get("Token"));
            successMessage = "Payment Token registered";
        }
        //end - transaction authorized

        if ("MALFORMED".equals(status)) {
            //request not formed properly or parameters missing
        }

        if ("INVALID".equals(status)) {
            //invalid information in request
        }

        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:de.unikassel.android.sdcframework.transmission.SimpleHttpProtocol.java

/**
 * Method for an HTTP upload of file stream
 * /*from  w  ww.  j  av a  2s .  c  om*/
 * @param file
 *          the input file
 * 
 * @return true if successful, false otherwise
 */
private final boolean httpUpload(File file) {
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        String fileName = FileUtils.fileNameFromPath(file.getName());
        String contentType = getContentType(fileName);

        URL url = getURL();
        configureForAuthentication(client, url);

        HttpPost httpPost = new HttpPost(url.toURI());

        FileEntity fileEntity = new FileEntity(file, contentType);
        fileEntity.setContentType(contentType);
        fileEntity.setChunked(true);

        httpPost.setEntity(fileEntity);
        httpPost.addHeader("filename", fileName);
        httpPost.addHeader("uuid", getUuid().toString());

        HttpResponse response = client.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();
        boolean success = statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT;
        Logger.getInstance().debug(this, "Server returned: " + statusCode);

        // clean up if necessary
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        if (!success) {
            doHandleError("Unexpected server response: " + response.getStatusLine());
            success = false;
        }

        return success;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        doHandleError(PROTOCOL_EXCEPTION + ": " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        doHandleError(IO_EXCEPTION + ": " + e.getMessage());
    } catch (URISyntaxException e) {
        setURL(null);
        doHandleError(INVALID_URL);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return false;
}

From source file:com.prasanna.android.http.SecureHttpHelper.java

private <T> T executeRequest(HttpClient client, HttpRequestBase request,
        HttpResponseBodyParser<T> responseBodyParser) {
    LogWrapper.d(TAG, "HTTP request to: " + request.getURI().toString());

    try {/*from  w  ww  .j av a  2s .com*/
        HttpResponse httpResponse = client.execute(request);
        HttpEntity entity = httpResponse.getEntity();
        String responseBody = EntityUtils.toString(entity, HTTP.UTF_8);
        int statusCode = httpResponse.getStatusLine().getStatusCode();

        if (statusCode == HttpStatus.SC_OK)
            return responseBodyParser.parse(responseBody);
        else {
            LogWrapper.d(TAG, "Http request failed: " + statusCode + ", " + responseBody);

            if (statusCode >= HttpErrorFamily.SERVER_ERROR)
                throw new ServerException(statusCode, httpResponse.getStatusLine().getReasonPhrase(),
                        responseBody);
            else if (statusCode >= HttpErrorFamily.CLIENT_ERROR)
                throw new ClientException(statusCode, httpResponse.getStatusLine().getReasonPhrase(),
                        responseBody);
        }
    } catch (ClientProtocolException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (IOException e) {
        LogWrapper.e(TAG, e.getMessage());
    } catch (HttpResponseParseException e) {
        throw new ClientException(ClientErrorCode.RESPONSE_PARSE_ERROR, e.getCause());
    }

    return null;
}

From source file:com.liato.bankdroid.banking.banks.OKQ8.java

public Urllib login() throws LoginException, BankException {
    Matcher matcher;//from  www .  java 2 s .c  o m
    String value = null;
    try {
        LoginPackage lp = preLogin();
        List<NameValuePair> postData = lp.getPostData();
        response = urlopen.open(lp.getLoginTarget(), postData);
        if (!response.contains("LOGON_OK")) {
            throw new LoginException(res.getText(R.string.invalid_username_password).toString());
        }

        /*
         * After login ok we end up at an intermediate login page with a submit
         * form that contains information that must be passed to the next page:
         * <input type="hidden" name="so" value="xxx"/>
         * <input type="hidden" name="last_logon_time" value="xxx"/>
         * <input type="hidden" name="failed_logon_attempts" value="xxx"/>
         * <input type="hidden" name="login_service_url" value="xxx"/>
         */
        matcher = reLoginRedir.matcher(response);
        postData.clear();
        if (!matcher.find()) {
            throw new LoginException("Could not find value for 'so'.");
        }
        value = matcher.group(1);
        postData.add(new BasicNameValuePair("so", value));

        if (!matcher.find()) {
            throw new LoginException("Could not find value for 'last_logon_time'.");
        }
        value = matcher.group(1);
        postData.add(new BasicNameValuePair("last_logon_time", value));

        if (!matcher.find()) {
            throw new LoginException("Could not find value for 'failed_logon_attempts'.");
        }
        value = matcher.group(1);
        postData.add(new BasicNameValuePair("failed_logon_attempts", value));

        if (!matcher.find()) {
            throw new LoginException("Could not find value for 'login_service_url'.");
        }
        value = matcher.group(1);
        postData.add(new BasicNameValuePair("login_service_url", value));

        response = urlopen.open("https://nettbank.edb.com/cardpayment/transigo/logon/done/okq8", postData);

        if (response.contains("HTML REDIRECT")) {
            throw new LoginException("Login failed.");
        }
    } catch (ClientProtocolException e) {
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        throw new BankException(e.getMessage());
    }
    return urlopen;
}

From source file:com.nextgis.firereporter.HttpGetter.java

@Override
protected Void doInBackground(String... urls) {
    if (IsNetworkAvailible(mContext)) {
        try {//from w  w  w. ja  v  a 2s . co m
            String sURL = urls[0];

            httpget = new HttpGet(sURL);

            Log.d("MainActivity", "HTTPGet URL " + sURL);

            if (urls.length > 1) {
                httpget.setHeader("Cookie", urls[1]);
            }

            //TODO: move timeouts to parameters
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 1500;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT) 
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 3000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            HttpClient Client = new DefaultHttpClient(httpParameters);

            HttpResponse response = Client.execute(httpget);
            //ResponseHandler<String> responseHandler = new BasicResponseHandler();
            //mContent = Client.execute(httpget, responseHandler);
            HttpEntity entity = response.getEntity();

            Bundle bundle = new Bundle();
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                bundle.putBoolean(GetFiresService.ERROR, false);
                mContent = EntityUtils.toString(entity);
                bundle.putString(GetFiresService.JSON, mContent);
            } else {
                bundle.putBoolean(GetFiresService.ERROR, true);
                bundle.putString(GetFiresService.ERR_MSG, response.getStatusLine().getStatusCode() + ": "
                        + response.getStatusLine().getReasonPhrase());
            }

            bundle.putInt(GetFiresService.SOURCE, mnType);

            Message msg = new Message();
            msg.setData(bundle);
            if (mEventReceiver != null) {
                mEventReceiver.sendMessage(msg);
            }

        } catch (ClientProtocolException e) {
            mError = e.getMessage();
            cancel(true);
        } catch (IOException e) {
            mError = e.getMessage();
            cancel(true);
        }
    } else {
        Bundle bundle = new Bundle();
        bundle.putBoolean(GetFiresService.ERROR, true);
        bundle.putString(GetFiresService.ERR_MSG, mContext.getString(R.string.noNetwork));
        bundle.putInt(GetFiresService.SOURCE, mnType);

        Message msg = new Message();
        msg.setData(bundle);
        if (mEventReceiver != null) {
            mEventReceiver.sendMessage(msg);
        }
    }
    return null;
}

From source file:ca.ualberta.CMPUT301W15T06.ESClient.java

public UserList getUserList() {
    // TODO Auto-generated method stub
    Hit<UserList> sr = null;//from   w ww  .  jav  a2  s .c o m
    HttpClient httpClient = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(USER_LIST);

    HttpResponse response = null;
    try {
        response = httpClient.execute(httpGet);
    } catch (ClientProtocolException e) {
        throw new RuntimeException(e.getMessage());
    } catch (IOException e) {
        return null;
    }

    Type HitType = new TypeToken<Hit<UserList>>() {
    }.getType();

    try {
        sr = gson.fromJson(new InputStreamReader(response.getEntity().getContent()), HitType);
    } catch (JsonIOException e) {
        throw new RuntimeException(e);
    } catch (JsonSyntaxException e) {
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return sr.getSource();
}

From source file:com.liato.bankdroid.banking.banks.Nordea.java

@Override
public void update() throws BankException, LoginException {
    super.update();
    if (username == null || password == null || username.length() == 0 || password.length() == 0) {
        throw new LoginException(res.getText(R.string.invalid_username_password).toString());
    }//from w ww .j a v  a 2 s  .c om
    urlopen = login();
    String response = null;
    Matcher matcher;
    try {

        Log.d("BankNordea", "Opening: https://mobil.nordea.se/banking-nordea/nordea-c3/accounts.html");
        response = urlopen.open("https://mobil.nordea.se/banking-nordea/nordea-c3/accounts.html");

        matcher = reAccounts.matcher(response);
        while (matcher.find()) {
            accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(),
                    Helpers.parseBalance(matcher.group(3)), matcher.group(1).trim()));
            balance = balance.add(Helpers.parseBalance(matcher.group(3)));
        }

        Log.d("BankNordea",
                "Opening: https://mobil.nordea.se/banking-nordea/nordea-c3/funds/portfolio/funds.html");
        response = urlopen.open("https://mobil.nordea.se/banking-nordea/nordea-c3/funds/portfolio/funds.html");

        matcher = reFundsLoans.matcher(response);
        while (matcher.find()) {
            accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(),
                    Helpers.parseBalance(matcher.group(3)), "f:" + matcher.group(1).trim(), -1L,
                    Account.FUNDS));
        }

        Log.d("BankNordea", "Opening: https://mobil.nordea.se/banking-nordea/nordea-c3/accounts.html?type=lan");
        response = urlopen.open("https://mobil.nordea.se/banking-nordea/nordea-c3/accounts.html?type=lan");

        matcher = reFundsLoans.matcher(response);
        while (matcher.find()) {
            accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(),
                    Helpers.parseBalance(matcher.group(3)), "l:" + matcher.group(1).trim(), -1L,
                    Account.LOANS));
        }
        matcher = reCards.matcher(response);
        Log.d(TAG, "Opening: https://mobil.nordea.se/banking-nordea/nordea-c3/card/list.html");
        response = urlopen.open("https://mobil.nordea.se/banking-nordea/nordea-c3/card/list.html");
        while (matcher.find()) {
            accounts.add(new Account(Html.fromHtml(matcher.group(2)).toString().trim(),
                    Helpers.parseBalance(matcher.group(3)), "c:" + matcher.group(1).trim(), -1L,
                    Account.CCARD));
            balance = balance.add(Helpers.parseBalance(matcher.group(3)));
        }

        if (accounts.isEmpty()) {
            throw new BankException(res.getText(R.string.no_accounts_found).toString());
        }

        // Konungens konto
        //accounts.add(new Account("Personkonto", Helpers.parseBalance("568268.37"), "1"));
        //accounts.add(new Account("Kapitalkonto", Helpers.parseBalance("5789002.00"), "0"));
    } catch (ClientProtocolException e) {
        throw new BankException(e.getMessage());
    } catch (IOException e) {
        throw new BankException(e.getMessage());
    } finally {
        super.updateComplete();
    }
}

From source file:org.wso2.carbon.ml.core.impl.BAMInputAdapter.java

@Override
public InputStream readDataset(URI uri) throws MLInputAdapterException {
    try {/*from  w w  w .  ja  va  2s.c  o  m*/
        if (isValidTable(uri)) {
            int sampleSize = MLCoreServiceValueHolder.getInstance().getSummaryStatSettings().getSampleSize();
            // retrieve the data from BAM
            HttpGet get = new HttpGet(getUriWithSampleSize(uri, sampleSize));
            response = httpClient.execute(get);
            // convert the json response to csv format
            BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            JSONArray outputJson = new JSONArray();
            String line;
            while ((line = br.readLine()) != null) {
                JSONArray inputJson = new JSONArray(line);
                for (int i = 0; i < inputJson.length(); i++) {
                    outputJson.put(inputJson.getJSONObject(i).getJSONObject(MLConstants.BAM_DATA_VALUES));
                }
            }
            // Check whether BAM Table contains any data
            if (outputJson.length() == 0) {
                throw new MLInputAdapterException("No data available at: " + uri);
            }
            // create a inputstream from the csv.
            return IOUtils.toInputStream(CDL.toString(outputJson), MLConstants.UTF_8);
        } else {
            throw new MLInputAdapterException("Invalid Data source : " + uri);
        }
    } catch (ClientProtocolException e) {
        throw new MLInputAdapterException("Failed to read the dataset from uri " + uri + " : " + e.getMessage(),
                e);
    } catch (IOException e) {
        throw new MLInputAdapterException("Failed to read the dataset from uri " + uri + " : " + e.getMessage(),
                e);
    } catch (URISyntaxException e) {
        throw new MLInputAdapterException("Failed to read the dataset from uri " + uri + " : " + e.getMessage(),
                e);
    } finally {
        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                throw new MLInputAdapterException("Failed to close the http client:" + e.getMessage(), e);
            }
        }
    }
}

From source file:com.liato.bankdroid.banking.banks.CSN.java

@Override
protected LoginPackage preLogin() throws BankException, ClientProtocolException, IOException {
    urlopen = new Urllib(context, CertificateReader.getCertificates(context, R.raw.cert_csn));
    urlopen.setAllowCircularRedirects(true);
    urlopen.setContentCharset(HTTP.ISO_8859_1);
    urlopen.addHeader("Referer", "https://www.csn.se/bas/");
    response = urlopen.open("https://www.csn.se/bas/inloggning/pinkod.do");
    List<NameValuePair> postData = new ArrayList<NameValuePair>();
    postData.add(new BasicNameValuePair("javascript", "on"));
    try {// w w  w.j av a 2s  .  c o m
        response = urlopen.open("https://www.csn.se/bas/javascript", postData);
    } catch (ClientProtocolException e) {
        throw new BankException("pl:CPE:" + e.getMessage());
    } catch (IOException e) {
        throw new BankException("pl:IOE:" + e.getMessage());
    }
    postData.clear();

    postData.add(new BasicNameValuePair("metod", "validerapinkod"));
    postData.add(new BasicNameValuePair("pnr", username));
    postData.add(new BasicNameValuePair("pinkod", password));
    return new LoginPackage(urlopen, postData, response, "https://www.csn.se/bas/inloggning/Pinkod.do");
}