List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:eu.trentorise.smartcampus.network.RemoteConnector.java
public static String getJSON(String host, String service, String token, Map<String, Object> parameters) throws RemoteException { final HttpResponse resp; try {//from w ww . j a v a2 s . c om String queryString = generateQueryString(parameters); final HttpGet get = new HttpGet(normalizeURL(host + service) + queryString); get.setHeader(RH_ACCEPT, "application/json"); get.setHeader(RH_AUTH_TOKEN, bearer(token)); resp = getHttpClient().execute(get); String response = EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return response; } if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN || resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new SecurityException(); } throw new RemoteException("Error validating " + resp.getStatusLine()); } catch (ClientProtocolException e) { throw new RemoteException(e.getMessage(), e); } catch (ParseException e) { throw new RemoteException(e.getMessage(), e); } catch (IOException e) { throw new RemoteException(e.getMessage(), e); } }
From source file:eu.trentorise.smartcampus.network.RemoteConnector.java
public static String deleteJSON(String host, String service, String token, Map<String, Object> parameters) throws SecurityException, RemoteException { final HttpResponse resp; String queryString = generateQueryString(parameters); final HttpDelete delete = new HttpDelete(normalizeURL(host + service) + queryString); delete.setHeader(RH_ACCEPT, "application/json"); delete.setHeader(RH_AUTH_TOKEN, bearer(token)); try {/* w w w. ja v a2 s .com*/ resp = getHttpClient().execute(delete); String response = EntityUtils.toString(resp.getEntity(), DEFAULT_CHARSET); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return response; } if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN || resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { throw new SecurityException(); } throw new RemoteException("Error validating " + resp.getStatusLine()); } catch (ClientProtocolException e) { throw new RemoteException(e.getMessage(), e); } catch (ParseException e) { throw new RemoteException(e.getMessage(), e); } catch (IOException e) { throw new RemoteException(e.getMessage(), e); } }
From source file:com.example.lilach.alsweekathon_new.MainActivity.java
public static void makeRequest(String uri, String json) { final String uri_final = uri; final String json_final = json; Thread thread = new Thread(new Runnable() { @Override/*from ww w.j a v a 2 s . c o m*/ public void run() { try { //Your code goes here HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(uri_final); httppost.setHeader("Accept", "application/json"); httppost.setHeader("Content-type", "application/json"); try { // Add your data httppost.setEntity(new StringEntity(json_final)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); Log.d("response: ", response.getEntity().toString()); // return response; } catch (ClientProtocolException e) { // TODO Auto-generated catch block Log.d("exception: ", e.getMessage()); } catch (IOException e) { // TODO Auto-generated catch block Log.d("exception: ", e.getMessage()); } catch (Exception e) { Log.d("exception: ", e.getMessage()); } // return null; } catch (Exception e) { e.printStackTrace(); Log.d("exception: ", e.getMessage()); } } }); thread.start(); // //HttpClient httpClient = new DefaultHttpClient(); // // HttpClient httpclient = HttpClientBuilder.create().build(); // // MinimalHttpClient httpclient = new HttpClientBuilder().build(); // // AndroidHttpClient // try { // HttpPost httpPost = new HttpPost(uri); // httpPost.setEntity(new StringEntity(json)); // httpPost.setHeader("Accept", "application/json"); // httpPost.setHeader("Content-type", "application/json"); // return new DefaultHttpClient().execute(httpPost); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } catch (ClientProtocolException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // return null; }
From source file:info.unyttig.helladroid.newzbin.NewzBinController.java
/** * Finds reports based on the paramaters given in searchOptions * //from w w w . j av a2 s. co m * @param searchOptions * @return ArrayList<NewzBinReport> - list of result reports. */ public static ArrayList<NewzBinReport> findReport(final Handler messageHandler, final HashMap<String, String> searchOptions) { String url = NBAPIURL + "reportfind/"; ArrayList<NewzBinReport> searchRes = new ArrayList<NewzBinReport>(); try { HttpResponse response = doPost(url, searchOptions); checkReturnCode(response.getStatusLine().getStatusCode(), false); InputStream is = response.getEntity().getContent(); BufferedInputStream bis = new BufferedInputStream(is); ByteArrayBuffer baf = new ByteArrayBuffer(20); int current = 0; while ((current = bis.read()) != -1) { baf.append((byte) current); } /* Convert the Bytes read to a String. */ String text = new String(baf.toByteArray()); // Log.d(LOG_NAME, text); BufferedReader reader = new BufferedReader(new StringReader(text)); String str = reader.readLine(); totalRes = Integer.parseInt(str.substring(str.indexOf("=") + 1)); while ((str = reader.readLine()) != null) { String[] values = str.split(" "); NewzBinReport temp2 = new NewzBinReport(); temp2.setNzbId(Integer.parseInt(values[0])); temp2.setSize(Long.parseLong(values[1])); temp2.setTitle(values[2]); if (!reports.containsKey(temp2.getNzbId())) { reports.put(temp2.getNzbId(), temp2); searchRes.add(temp2); } else searchRes.add(reports.get(temp2.getNzbId())); } Object[] result = new Object[2]; result[0] = totalRes; result[1] = searchRes; return searchRes; // TODO message handling } catch (ClientProtocolException e) { Log.e(LOG_NAME, "ClientProtocol thrown: ", e); sendUserMsg(messageHandler, e.toString()); } catch (IOException e) { Log.e(LOG_NAME, "IOException thrown: ", e); sendUserMsg(messageHandler, e.toString()); } catch (NewzBinPostReturnCodeException e) { Log.e(LOG_NAME, "POST ReturnCode error: " + e.toString()); sendUserMsg(messageHandler, e.getMessage()); } return searchRes; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Connects to the server, authenticates the provided username and * password./* www . j a v a2 s .com*/ * * @param username The user's username * @param password The user's password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String accessKey, String base_url) { String token = null; String hash = null; authenticate_log_text = "authenticate()\n"; AUTH_URI = base_url + "/webservice.php"; authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username=" + username + "\n"; Log.d(TAG, "AUTH_URI : "); Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); // =========== get challenge token ============================== ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); try { URL url; // HTTP GET REQUEST url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setUseCaches(false); // for some site that redirects based on user agent con.setInstanceFollowRedirects(true); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15"); con.setAllowUserInteraction(false); int timeout = 20000; con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n"; switch (status) { case 200: case 201: case 302: BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "body : " + sb.toString(); if (status == 302) { authenticate_log_text = sb.toString(); return null; } JSONObject result = new JSONObject(sb.toString()); Log.d(TAG, result.getString("result")); JSONObject data = new JSONObject(result.getString("result")); token = data.getString("token"); break; case 401: Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "Server auth error"; return null; default: Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "connection status code :" + status; return null; } } catch (ClientProtocolException e) { Log.i(TAG, "getchallenge:http protocol error"); Log.e(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n"; return null; } catch (IOException e) { Log.e(TAG, "getchallenge: IO Exception"); Log.e(TAG, e.getMessage()); Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n"; return null; } catch (JSONException e) { Log.i(TAG, "json exception"); authenticate_log_text = authenticate_log_text + "JSon exception\n"; // TODO Auto-generated catch block e.printStackTrace(); return null; } // ================= login ================== try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(token.getBytes()); m.update(accessKey.getBytes()); hash = new BigInteger(1, m.digest()).toString(16); Log.i(TAG, "hash"); Log.i(TAG, hash); } catch (NoSuchAlgorithmException e) { authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n"; e.printStackTrace(); } try { String charset; charset = "utf-8"; String query = String.format("operation=login&username=%s&accessKey=%s", URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset)); authenticate_log_text = authenticate_log_text + "login()\n"; URLConnection connection = new URL(AUTH_URI).openConnection(); connection.setDoOutput(true); // Triggers POST. int timeout = 20000; connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); connection.setUseCaches(false); OutputStream output = connection.getOutputStream(); try { output.write(query.getBytes(charset)); } finally { try { output.close(); } catch (IOException logOrIgnore) { } } Log.d(TAG, "Query written"); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message post body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n"; JSONObject result = new JSONObject(sb.toString()); String success = result.getString("success"); Log.i(TAG, success); if (success == "true") { Log.i(TAG, result.getString("result")); Log.i(TAG, "sucesssfully logged in is"); JSONObject data = new JSONObject(result.getString("result")); sessionName = data.getString("sessionName"); Log.i(TAG, sessionName); authenticate_log_text = authenticate_log_text + "successfully logged in\n"; return token; } else { // success is false, retrieve error JSONObject data = new JSONObject(result.getString("error")); authenticate_log_text = "can not login :\n" + data.toString(); return null; } //token = data.getString("token"); //Log.i(TAG,token); } catch (ClientProtocolException e) { Log.d(TAG, "login: http protocol error"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (IOException e) { Log.d(TAG, "login: IO Exception"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "login: IO Exception \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (JSONException e) { Log.d(TAG, "JSON exception"); // TODO Auto-generated catch block authenticate_log_text = authenticate_log_text + "JSON exception "; authenticate_log_text = authenticate_log_text + e.getMessage(); e.printStackTrace(); } return null; // ======================================================================== }
From source file:org.ofbiz.accounting.thirdparty.sagepay.SagePayServices.java
public static Map<String, Object> paymentVoid(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentVoid", module); Debug.logInfo("SagePay paymentVoid 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"); HttpClient httpClient = SagePayUtil.getHttpClient(); HttpHost host = SagePayUtil.getHost(props); //start - void parameters Map<String, String> parameters = new HashMap<String, String>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", "VOID"); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("VPSTxId", vpsTxId); parameters.put("SecurityKey", securityKey); parameters.put("TxAuthNo", txAuthNo); //end - void parameters try {/*ww w.ja v a2 s . co m*/ String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("voidUrl"), 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 void if ("OK".equals(status)) { successMessage = "Payment Voided"; } //end - payment void //start - void request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = "Void request not formed properly or parameters missing"; } //end - void 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:org.ofbiz.accounting.thirdparty.sagepay.SagePayServices.java
public static Map<String, Object> paymentRelease(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentRelease", module); Debug.logInfo("SagePay 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"); 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); //end - release parameters try {/* w w w . ja v a2 s .c o m*/ 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:org.ofbiz.accounting.thirdparty.sagepay.SagePayServices.java
public static Map<String, Object> paymentAuthorisation(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentAuthorisation", module); Debug.logInfo("SagePay paymentAuthorisation 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"); HttpClient httpClient = SagePayUtil.getHttpClient(); HttpHost host = SagePayUtil.getHost(props); //start - authorization parameters Map<String, String> parameters = new HashMap<String, String>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); String txType = props.get("authoriseTransType"); 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("ReleaseAmount", amount); Debug.logInfo("authorization parameters -> " + parameters, module); //end - authorization parameters try {/*from w w w .j a va 2 s .c o m*/ String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("authoriseUrl"), 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 refunded if ("OK".equals(status)) { successMessage = "Payment Released"; } //end - payment refunded //start - refund request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = "Released 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:org.ofbiz.accounting.thirdparty.sagepay.SagePayServices.java
public static Map<String, Object> paymentRefund(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentRefund", module); Debug.logInfo("SagePay 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 amount = (String) context.get("amount"); String currency = (String) context.get("currency"); String description = (String) context.get("description"); String relatedVPSTxId = (String) context.get("relatedVPSTxId"); String relatedVendorTxCode = (String) context.get("relatedVendorTxCode"); String relatedSecurityKey = (String) context.get("relatedSecurityKey"); String relatedTxAuthNo = (String) context.get("relatedTxAuthNo"); 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"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", "REFUND"); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("Amount", amount); parameters.put("Currency", currency); parameters.put("Description", description); parameters.put("RelatedVPSTxId", relatedVPSTxId); parameters.put("RelatedVendorTxCode", relatedVendorTxCode); parameters.put("RelatedSecurityKey", relatedSecurityKey); parameters.put("RelatedTxAuthNo", relatedTxAuthNo); //end - refund parameters try {// ww w . ja va 2s .c o m 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:org.apache.ofbiz.accounting.thirdparty.sagepay.SagePayServices.java
public static Map<String, Object> paymentVoid(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay - Entered paymentVoid", module); Debug.logInfo("SagePay paymentVoid 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"); Locale locale = (Locale) context.get("locale"); HttpHost host = SagePayUtil.getHost(props); //start - void parameters Map<String, String> parameters = new HashMap<String, String>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", "VOID"); parameters.put("Vendor", vendor); parameters.put("VendorTxCode", vendorTxCode); parameters.put("VPSTxId", vpsTxId); parameters.put("SecurityKey", securityKey); parameters.put("TxAuthNo", txAuthNo); //end - void parameters try (CloseableHttpClient httpClient = SagePayUtil.getHttpClient()) { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("voidUrl"), 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 void if ("OK".equals(status)) { successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentVoided", locale); }/*from w ww .j av a 2s. c o m*/ //end - payment void //start - void request not formed properly or parameters missing if ("MALFORMED".equals(status)) { successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentVoidRequestMalformed", locale); } //end - void request not formed properly or parameters missing //start - invalid information passed in parameters if ("INVALID".equals(status)) { successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentInvalidInformationPassed", locale); } //end - invalid information passed in parameters //start - problem at Sagepay if ("ERROR".equals(status)) { successMessage = UtilProperties.getMessage(resource, "AccountingSagePayPaymentError", locale); } //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 Debug.logError(uee, "Error occurred in encoding parameters for HttpPost (" + uee.getMessage() + ")", module); resultMap = ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorEncodingParameters", UtilMisc.toMap("errorString", uee.getMessage()), locale)); } catch (ClientProtocolException cpe) { //from httpClient execute Debug.logError(cpe, "Error occurred in HttpClient execute(" + cpe.getMessage() + ")", module); resultMap = ServiceUtil .returnError(UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecute", UtilMisc.toMap("errorString", cpe.getMessage()), locale)); } catch (IOException ioe) { //from httpClient execute or getResponsedata Debug.logError(ioe, "Error occurred in HttpClient execute or getting response (" + ioe.getMessage() + ")", module); resultMap = ServiceUtil.returnError( UtilProperties.getMessage(resource, "AccountingSagePayErrorHttpClientExecuteOrGettingResponse", UtilMisc.toMap("errorString", ioe.getMessage()), locale)); } return resultMap; }