You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@ofbiz.apache.org by mr...@apache.org on 2009/04/28 21:45:07 UTC

svn commit: r769510 [2/3] - in /ofbiz/trunk/applications/accounting: servicedef/ src/org/ofbiz/accounting/payment/ webapp/accounting/WEB-INF/ webapp/accounting/WEB-INF/actions/payment/ webapp/accounting/WEB-INF/actions/transaction/ webapp/accounting/co...

Modified: ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentGatewayServices.java
URL: http://svn.apache.org/viewvc/ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentGatewayServices.java?rev=769510&r1=769509&r2=769510&view=diff
==============================================================================
--- ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentGatewayServices.java (original)
+++ ofbiz/trunk/applications/accounting/src/org/ofbiz/accounting/payment/PaymentGatewayServices.java Tue Apr 28 19:45:06 2009
@@ -20,11 +20,9 @@
 
 import java.math.BigDecimal;
 import java.sql.Timestamp;
-import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Collection;
 import java.util.Date;
-import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
@@ -40,6 +38,7 @@
 import org.ofbiz.base.util.GeneralException;
 import org.ofbiz.base.util.StringUtil;
 import org.ofbiz.base.util.UtilDateTime;
+import org.ofbiz.base.util.UtilGenerics;
 import org.ofbiz.base.util.UtilMisc;
 import org.ofbiz.base.util.UtilNumber;
 import org.ofbiz.base.util.UtilProperties;
@@ -82,6 +81,7 @@
     private static BigDecimal ZERO = BigDecimal.ZERO;
     private static int decimals;
     private static int rounding;
+    public static final String resource_error = "OrderErrorUiLabels";
     static {
         decimals = UtilNumber.getBigDecimalScale("order.decimals");
         rounding = UtilNumber.getBigDecimalRoundingMode("order.rounding");
@@ -122,16 +122,16 @@
             return ServiceUtil.returnError("Problems getting required information: orderPaymentPreference [" + orderPaymentPreferenceId + "]");
         }
         OrderReadHelper orh = new OrderReadHelper(orderHeader);
-
+        
         // get the total remaining
         BigDecimal totalRemaining = orh.getOrderGrandTotal();
-
+        
         // get the process attempts so far
         Long procAttempt = orderPaymentPreference.getLong("processAttempt");
         if (procAttempt == null) {
             procAttempt = new Long(0);
         }
-
+        
         // update the process attempt count
         orderPaymentPreference.set("processAttempt", new Long(procAttempt.longValue() + 1));
         try {
@@ -203,7 +203,7 @@
                                 // according to the store should we try other cards?
                                 if ("Y".equals(productStore.getString("autoOrderCcTryOtherCards"))) {
                                     // get other credit cards for the bill to party
-                                    List otherPaymentMethodAndCreditCardList = null;
+                                    List<GenericValue> otherPaymentMethodAndCreditCardList = null;
                                     String billToPartyId = null;
                                     GenericValue billToParty = orh.getBillToParty();
                                     if (billToParty != null) {
@@ -219,7 +219,7 @@
                                     }
 
                                     if (UtilValidate.isNotEmpty(otherPaymentMethodAndCreditCardList)) {
-                                        Iterator otherPaymentMethodAndCreditCardIter = otherPaymentMethodAndCreditCardList.iterator();
+                                        Iterator<GenericValue> otherPaymentMethodAndCreditCardIter = otherPaymentMethodAndCreditCardList.iterator();
                                         while (otherPaymentMethodAndCreditCardIter.hasNext()) {
                                             GenericValue otherPaymentMethodAndCreditCard = (GenericValue) otherPaymentMethodAndCreditCardIter.next();
 
@@ -281,7 +281,6 @@
                 results.put("finished", Boolean.FALSE);
                 results.put("errors", Boolean.TRUE);
                 results.put(ModelService.ERROR_MESSAGE, errMsg);
-
                 orderPaymentPreference.set("statusId", "PAYMENT_CANCELLED");
                 try {
                     orderPaymentPreference.store();
@@ -301,26 +300,26 @@
      * Processes payments through service calls to the defined processing service for the ProductStore/PaymentMethodType
      * @return APPROVED|FAILED|ERROR for complete processing of ALL payment methods.
      */
-    public static Map authOrderPayments(DispatchContext dctx, Map context) {
+    public static Map<String, Object> authOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         String orderId = (String) context.get("orderId");
-        Map result = new HashMap();
+        Map<String, Object> result = FastMap.newInstance();
         boolean reAuth = false;
         if (context.get("reAuth") != null) {
             reAuth = ((Boolean)context.get("reAuth")).booleanValue();
         }
         // get the order header and payment preferences
         GenericValue orderHeader = null;
-        List paymentPrefs = null;
+        List<GenericValue> paymentPrefs = null;
 
         try {
             // get the OrderHeader
             orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
 
             // get the payments to auth
-            Map lookupMap = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_AUTH");
-            List orderList = UtilMisc.toList("maxAmount");
+            Map<String, String> lookupMap = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_NOT_AUTH");
+            List<String> orderList = UtilMisc.toList("maxAmount");
             paymentPrefs = delegator.findByAnd("OrderPaymentPreference", lookupMap, orderList);
             if (reAuth) {
                 lookupMap.put("orderId", orderId);
@@ -346,8 +345,8 @@
         // loop through and auth each order payment preference
         int finished = 0;
         int hadError = 0;
-        List messages = FastList.newInstance();
-        Iterator payments = paymentPrefs.iterator();
+        List<String> messages = FastList.newInstance();
+        Iterator<GenericValue> payments = paymentPrefs.iterator();
         while (payments.hasNext()) {
             GenericValue paymentPref = (GenericValue) payments.next();
             if (reAuth && "PAYMENT_AUTHORIZED".equals(paymentPref.getString("statusId"))) {
@@ -366,11 +365,11 @@
                     continue;
                 }
             }
-            Map authContext = new HashMap();
+            Map<String, Object> authContext = FastMap.newInstance();
             authContext.put("orderPaymentPreferenceId", paymentPref.getString("orderPaymentPreferenceId"));
             authContext.put("userLogin", context.get("userLogin"));
 
-            Map results = null;
+            Map<String, Object> results = null;
             try {
                 results = dispatcher.runSync("authOrderPaymentPreference", authContext);
             } catch (GenericServiceException se) {
@@ -600,7 +599,6 @@
         return paymentSettings;
     }
 
-
     private static String getPayToPartyId(GenericValue orderHeader) {
         String payToPartyId = "Company"; // default value
         GenericValue productStore = null;
@@ -618,9 +616,7 @@
         return payToPartyId;
     }
 
-
-
-    private static String getBillingInformation(OrderReadHelper orh, GenericValue paymentPreference, Map toContext) throws GenericEntityException {
+    private static String getBillingInformation(OrderReadHelper orh, GenericValue paymentPreference, Map<String, Object> toContext) throws GenericEntityException {
         // gather the payment related objects.
         String paymentMethodTypeId = paymentPreference.getString("paymentMethodTypeId");
         GenericValue paymentMethod = paymentPreference.getRelatedOne("PaymentMethod");
@@ -653,7 +649,7 @@
         GenericValue billToPersonOrGroup = orh.getBillToParty();
         GenericValue billToEmail = null;
 
-        Collection emails = ContactHelper.getContactMech(billToPersonOrGroup.getRelatedOne("Party"), "PRIMARY_EMAIL", "EMAIL_ADDRESS", false);
+        Collection<GenericValue> emails = ContactHelper.getContactMech(billToPersonOrGroup.getRelatedOne("Party"), "PRIMARY_EMAIL", "EMAIL_ADDRESS", false);
 
         if (UtilValidate.isNotEmpty(emails)) {
             billToEmail = (GenericValue) emails.iterator().next();
@@ -670,33 +666,42 @@
      * Releases authorizations through service calls to the defined processing service for the ProductStore/PaymentMethodType
      * @return COMPLETE|FAILED|ERROR for complete processing of ALL payments.
      */
-    public static Map releaseOrderPayments(DispatchContext dctx, Map context) {
+    public static Map<String, Object> releaseOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
-        String orderId = (String) context.get("orderId");
-
-        Map result = new HashMap();
-
+        String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
+        Map<String, Object> result = ServiceUtil.returnSuccess();
+        // Get the OrderPaymentPreference
+        GenericValue paymentPref = null;
+        try {
+            paymentPref = delegator.findOne("OrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreferenceId), false);
+        } catch ( GenericEntityException e ) {
+            String errMsg = "Problem getting OrderPaymentPreference for orderPaymentPreferenceId " + orderPaymentPreferenceId;
+            Debug.logWarning(e, errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        // Error if no OrderPaymentPreference was found
+        if (paymentPref == null) {
+            String errMsg = "Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId;
+            Debug.logWarning(errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        String orderId = paymentPref.getString("orderId");
         // get the payment preferences
-        List paymentPrefs = null;
-
+        List<GenericValue> paymentPrefs = null;
         try {
             // get the valid payment prefs
-            List othExpr = UtilMisc.toList(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EFT_ACCOUNT"));
+            List<EntityExpr> othExpr = UtilMisc.toList(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EFT_ACCOUNT"));
             othExpr.add(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "GIFT_CARD"));
             othExpr.add(EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "FIN_ACCOUNT"));
             EntityCondition con1 = EntityCondition.makeCondition(othExpr, EntityJoinOperator.OR);
-
             EntityCondition statExpr = EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_SETTLED");
             EntityCondition con2 = EntityCondition.makeCondition(UtilMisc.toList(con1, statExpr), EntityOperator.AND);
-
             EntityCondition authExpr = EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_AUTHORIZED");
             EntityCondition con3 = EntityCondition.makeCondition(UtilMisc.toList(con2, authExpr), EntityOperator.OR);
-
             EntityExpr orderExpr = EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderId);
             EntityCondition con4 = EntityCondition.makeCondition(UtilMisc.toList(con3, orderExpr), EntityOperator.AND);
-
             paymentPrefs = delegator.findList("OrderPaymentPreference", con4, null, null, null, false);
         } catch (GenericEntityException gee) {
             Debug.logError(gee, "Problems getting entity record(s), see stack trace", module);
@@ -714,12 +719,12 @@
         }
 
         // iterate over the prefs and release each one
-        List finished = FastList.newInstance();
-        Iterator payments = paymentPrefs.iterator();
+        List<GenericValue> finished = FastList.newInstance();
+        Iterator<GenericValue> payments = paymentPrefs.iterator();
         while (payments.hasNext()) {
-            GenericValue paymentPref = (GenericValue) payments.next();
-            Map releaseContext = UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPref.getString("orderPaymentPreferenceId"));
-            Map releaseResult = null;
+            paymentPref = (GenericValue) payments.next();
+            Map<String, Object> releaseContext = UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreferenceId", paymentPref.getString("orderPaymentPreferenceId"));
+            Map<String, Object> releaseResult = null;
             try {
                 releaseResult = dispatcher.runSync("releaseOrderPaymentPreference", releaseContext);
             } catch ( GenericServiceException e ) {
@@ -743,20 +748,96 @@
 
         return result;
     }
-
+    
+    public static Map<String, Object> processCreditResult(DispatchContext dctx, Map<String, ? extends Object> context) {
+        GenericDelegator delegator = dctx.getDelegator();
+        LocalDispatcher dispatcher = dctx.getDispatcher();
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
+        String currencyUomId = (String) context.get("currencyUomId");
+        GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
+        Boolean creditResponse = (Boolean) context.get("creditResult");
+        // create the PaymentGatewayResponse
+        String responseId = delegator.getNextSeqId("PaymentGatewayResponse");
+        GenericValue pgCredit = delegator.makeValue("PaymentGatewayResponse");
+        pgCredit.set("paymentGatewayResponseId", responseId);
+        pgCredit.set("paymentServiceTypeEnumId", CREDIT_SERVICE_TYPE);
+        pgCredit.set("orderPaymentPreferenceId", paymentPref.get("orderPaymentPreferenceId"));
+        pgCredit.set("paymentMethodTypeId", paymentPref.get("paymentMethodTypeId"));
+        pgCredit.set("paymentMethodId", paymentPref.get("paymentMethodId"));
+        pgCredit.set("transCodeEnumId", "PGT_CREDIT");
+        // set the credit info
+        pgCredit.set("amount", context.get("creditAmount"));
+        pgCredit.set("referenceNum", context.get("creditRefNum"));
+        pgCredit.set("altReference", context.get("creditAltRefNum"));
+        pgCredit.set("gatewayCode", context.get("creditCode"));
+        pgCredit.set("gatewayFlag", context.get("creditFlag"));
+        pgCredit.set("gatewayMessage", context.get("creditMessage"));
+        pgCredit.set("transactionDate", UtilDateTime.nowTimestamp());
+        pgCredit.set("currencyUomId", currencyUomId);
+        // store the gateway response
+        savePgr(dctx, pgCredit);
+        // create the internal messages
+        List<String> messages = UtilGenerics.cast(context.get("internalRespMsgs"));
+        if (UtilValidate.isNotEmpty(messages)) {
+            Iterator<String> i = messages.iterator();
+            while (i.hasNext()) {
+                GenericValue respMsg = delegator.makeValue("PaymentGatewayRespMsg");
+                String respMsgId = delegator.getNextSeqId("PaymentGatewayRespMsg");
+                String message = (String) i.next();
+                respMsg.set("paymentGatewayRespMsgId", respMsgId);
+                respMsg.set("paymentGatewayResponseId", responseId);
+                respMsg.set("pgrMessage", message);
+                // store the messages
+                savePgr(dctx, respMsg);
+            }
+        }
+        if (creditResponse != null && creditResponse.booleanValue()) {
+            paymentPref.set("statusId", "PAYMENT_CANCELLED");
+            try {
+                paymentPref.store();
+            } catch (GenericEntityException e) {
+                Debug.logError(e, "Problem storing updated payment preference; authorization was credit!", module);
+            }
+            // cancel any payment records
+            List<GenericValue> paymentList = null;
+            try {
+                paymentList = paymentPref.getRelated("Payment");
+            } catch (GenericEntityException e) {
+                Debug.logError(e, "Unable to get Payment records from OrderPaymentPreference : " + paymentPref, module);
+            }
+            if (paymentList != null) {
+                Iterator<GenericValue> pi = paymentList.iterator();
+                while (pi.hasNext()) {
+                    GenericValue pay = (GenericValue) pi.next();
+                    try {
+                        Map<String, Object> cancelResults = dispatcher.runSync("setPaymentStatus", UtilMisc.toMap("userLogin", userLogin, "paymentId", pay.get("paymentId"), "statusId", "PMNT_CANCELLED"));
+                        if (ServiceUtil.isError(cancelResults)) {
+                            throw new GenericServiceException(ServiceUtil.getErrorMessage(cancelResults));
+                        }
+                    } catch (GenericServiceException e) {
+                        Debug.logError(e, "Unable to cancel Payment : " + pay, module);
+                    }
+                }
+            }
+        } else {
+            String errMsg = "Credit failed for pref : " + paymentPref;
+            Debug.logError(errMsg, module);
+            return ServiceUtil.returnFailure(errMsg);
+        }
+        return ServiceUtil.returnSuccess();
+    }
+    
     /**
      *
      * Releases authorization for a single OrderPaymentPreference through service calls to the defined processing service for the ProductStore/PaymentMethodType
      * @return SUCCESS|FAILED|ERROR for complete processing of payment.
      */
-    public static Map releaseOrderPaymentPreference(DispatchContext dctx, Map context) {
+    public static Map<String, Object> releaseOrderPaymentPreference(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
-
-        Map result = ServiceUtil.returnSuccess();
-
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         // Get the OrderPaymentPreference
         GenericValue paymentPref = null;
         try {
@@ -766,39 +847,34 @@
             Debug.logWarning(e, errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
-
         // Error if no OrderPaymentPreference was found
         if (paymentPref == null) {
             String errMsg = "Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId;
             Debug.logWarning(errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
-
         // Get the OrderHeader
         GenericValue orderHeader = null;
+        String orderId = paymentPref.getString("orderId");
         try {
-            orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", paymentPref.getString("orderId")));
+            orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
         } catch ( GenericEntityException e ) {
-            String errMsg = "Problem getting OrderHeader for orderId " + paymentPref.getString("orderId");
+            String errMsg = "Problem getting OrderHeader for orderId " + orderId;
             Debug.logWarning(e, errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
-
         // Error if no OrderHeader was found
         if (orderHeader == null) {
-            String errMsg = "Could not find OrderHeader with orderId: " + paymentPref.getString("orderId") + "; not processing payments.";
+            String errMsg = "Could not find OrderHeader with orderId: " + orderId + "; not processing payments.";
             Debug.logWarning(errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
-
         OrderReadHelper orh = new OrderReadHelper(orderHeader);
         String currency = orh.getCurrency();
-
         // look up the payment configuration settings
         String serviceName = null;
         String paymentConfig = null;
         String paymentGatewayConfigId = null;
-
         // get the payment settings i.e. serviceName and config properties file name
         GenericValue paymentSettings = getPaymentSettings(orderHeader, paymentPref, RELEASE_SERVICE_TYPE, false);
         if (paymentSettings != null) {
@@ -811,7 +887,6 @@
             }
             paymentConfig = paymentSettings.getString("paymentPropertiesPath");
             paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
-            
             if (serviceName == null) {
                 String errMsg = "No payment release service for - " + paymentPref.getString("paymentMethodTypeId");
                 Debug.logWarning(errMsg, module);
@@ -822,22 +897,19 @@
             Debug.logWarning(errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
-
         if (paymentConfig == null || paymentConfig.length() == 0) {
             paymentConfig = "payment.properties";
         }
-
         GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(paymentPref);
-        Map releaseContext = new HashMap();
+        Map<String, Object> releaseContext = FastMap.newInstance();
         releaseContext.put("orderPaymentPreference", paymentPref);
         releaseContext.put("releaseAmount", authTransaction.getBigDecimal("amount"));
         releaseContext.put("currency", currency);
         releaseContext.put("paymentConfig", paymentConfig);
         releaseContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
         releaseContext.put("userLogin", userLogin);
-
         // run the defined service
-        Map releaseResult = null;
+        Map<String, Object> releaseResult = null;
         try {
             releaseResult = dispatcher.runSync(serviceName, releaseContext, TX_TIME, true);
         } catch (GenericServiceException e) {
@@ -845,15 +917,14 @@
             Debug.logError(e,errMsg, module);
             return ServiceUtil.returnError(errMsg);
         }
-
         // get the release result code
         if (releaseResult != null && !ServiceUtil.isError(releaseResult)) {
-            Map releaseResRes;
+            Map<String, Object> releaseResRes;
             try {
                 ModelService model = dctx.getModelService("processReleaseResult");
                 releaseResult.put("orderPaymentPreference", paymentPref);
                 releaseResult.put("userLogin", userLogin);
-                Map resCtx = model.makeValid(releaseResult, ModelService.IN_PARAM);
+                Map<String, Object> resCtx = model.makeValid(releaseResult, ModelService.IN_PARAM);
                 releaseResRes = dispatcher.runSync(model.name,  resCtx);
             } catch (GenericServiceException e) {
                 Debug.logError(e, module);
@@ -866,18 +937,16 @@
             saveError(dispatcher, userLogin, paymentPref, releaseResult, RELEASE_SERVICE_TYPE, "PGT_RELEASE");
             result = ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResult));
         }
-
         return result;
     }
-
-    public static Map processReleaseResult(DispatchContext dctx, Map context) {
+    
+    public static Map<String, Object> processReleaseResult(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
-
+        String currencyUomId = (String) context.get("currencyUomId");
         GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
         Boolean releaseResponse = (Boolean) context.get("releaseResult");
-
         // create the PaymentGatewayResponse
         String responseId = delegator.getNextSeqId("PaymentGatewayResponse");
         GenericValue pgResponse = delegator.makeValue("PaymentGatewayResponse");
@@ -887,22 +956,21 @@
         pgResponse.set("paymentMethodTypeId", paymentPref.get("paymentMethodTypeId"));
         pgResponse.set("paymentMethodId", paymentPref.get("paymentMethodId"));
         pgResponse.set("transCodeEnumId", "PGT_RELEASE");
-
         // set the release info
+        pgResponse.set("amount", context.get("releaseAmount"));
         pgResponse.set("referenceNum", context.get("releaseRefNum"));
         pgResponse.set("altReference", context.get("releaseAltRefNum"));
         pgResponse.set("gatewayCode", context.get("releaseCode"));
         pgResponse.set("gatewayFlag", context.get("releaseFlag"));
         pgResponse.set("gatewayMessage", context.get("releaseMessage"));
         pgResponse.set("transactionDate", UtilDateTime.nowTimestamp());
-
+        pgResponse.set("currencyUomId", currencyUomId);
         // store the gateway response
         savePgr(dctx, pgResponse);
-
         // create the internal messages
-        List messages = (List) context.get("internalRespMsgs");
+        List<String> messages = UtilGenerics.cast(context.get("internalRespMsgs"));
         if (UtilValidate.isNotEmpty(messages)) {
-            Iterator i = messages.iterator();
+            Iterator<String> i = messages.iterator();
             while (i.hasNext()) {
                 GenericValue respMsg = delegator.makeValue("PaymentGatewayRespMsg");
                 String respMsgId = delegator.getNextSeqId("PaymentGatewayRespMsg");
@@ -910,12 +978,11 @@
                 respMsg.set("paymentGatewayRespMsgId", respMsgId);
                 respMsg.set("paymentGatewayResponseId", responseId);
                 respMsg.set("pgrMessage", message);
-
                 // store the messages
                 savePgr(dctx, respMsg);
             }
         }
-
+        
         if (releaseResponse != null && releaseResponse.booleanValue()) {
             paymentPref.set("statusId", "PAYMENT_CANCELLED");
             try {
@@ -923,21 +990,19 @@
             } catch (GenericEntityException e) {
                 Debug.logError(e, "Problem storing updated payment preference; authorization was released!", module);
             }
-
             // cancel any payment records
-            List paymentList = null;
+            List<GenericValue> paymentList = null;
             try {
                 paymentList = paymentPref.getRelated("Payment");
             } catch (GenericEntityException e) {
                 Debug.logError(e, "Unable to get Payment records from OrderPaymentPreference : " + paymentPref, module);
             }
-
             if (paymentList != null) {
-                Iterator pi = paymentList.iterator();
+                Iterator<GenericValue> pi = paymentList.iterator();
                 while (pi.hasNext()) {
                     GenericValue pay = (GenericValue) pi.next();
                     try {
-                        Map cancelResults = dispatcher.runSync("setPaymentStatus", UtilMisc.toMap("userLogin", userLogin, "paymentId", pay.get("paymentId"), "statusId", "PMNT_CANCELLED"));
+                        Map<String, Object> cancelResults = dispatcher.runSync("setPaymentStatus", UtilMisc.toMap("userLogin", userLogin, "paymentId", pay.get("paymentId"), "statusId", "PMNT_CANCELLED"));
                         if (ServiceUtil.isError(cancelResults)) {
                             throw new GenericServiceException(ServiceUtil.getErrorMessage(cancelResults));
                         }
@@ -951,15 +1016,14 @@
             Debug.logError(errMsg, module);
             return ServiceUtil.returnFailure(errMsg);
         }
-
         return ServiceUtil.returnSuccess();
     }
-
+    
     /**
      * Captures payments through service calls to the defined processing service for the ProductStore/PaymentMethodType
      * @return COMPLETE|FAILED|ERROR for complete processing of ALL payment methods.
      */
-    public static Map capturePaymentsByInvoice(DispatchContext dctx, Map context) {
+    public static Map<String, Object> capturePaymentsByInvoice(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
@@ -980,7 +1044,7 @@
         }
 
         // get the OrderItemBilling records for this invoice
-        List orderItemBillings = null;
+        List<GenericValue> orderItemBillings = null;
         try {
             orderItemBillings = invoice.getRelated("OrderItemBilling");
         } catch (GenericEntityException e) {
@@ -995,7 +1059,7 @@
         String testOrderId = null;
         boolean allSameOrder = true;
         if (orderItemBillings != null) {
-            Iterator oii = orderItemBillings.iterator();
+            Iterator<GenericValue> oii = orderItemBillings.iterator();
             while (oii.hasNext()) {
                 GenericValue oib = (GenericValue) oii.next();
                 String orderId = oib.getString("orderId");
@@ -1021,7 +1085,7 @@
         if (Debug.infoOn()) Debug.logInfo("(Capture) Invoice [#" + invoiceId + "] total: " + invoiceTotal, module);
 
         // now capture the order
-        Map serviceContext = UtilMisc.toMap("userLogin", userLogin, "orderId", testOrderId, "invoiceId", invoiceId, "captureAmount", invoiceTotal);
+        Map<String, Object> serviceContext = UtilMisc.toMap("userLogin", userLogin, "orderId", testOrderId, "invoiceId", invoiceId, "captureAmount", invoiceTotal);
         if (UtilValidate.isNotEmpty(billingAccountId)) {
             serviceContext.put("billingAccountId", billingAccountId);
         }
@@ -1037,7 +1101,7 @@
      * Captures payments through service calls to the defined processing service for the ProductStore/PaymentMethodType
      * @return COMPLETE|FAILED|ERROR for complete processing of ALL payment methods.
      */
-    public static Map captureOrderPayments(DispatchContext dctx, Map context) {
+    public static Map<String, Object> captureOrderPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
@@ -1049,15 +1113,15 @@
 
         // get the order header and payment preferences
         GenericValue orderHeader = null;
-        List paymentPrefs = null;
-        List paymentPrefsBa = null;
+        List<GenericValue> paymentPrefs = null;
+        List<GenericValue> paymentPrefsBa = null;
 
         try {
             orderHeader = delegator.findByPrimaryKey("OrderHeader", UtilMisc.toMap("orderId", orderId));
 
             // get the payment prefs
-            Map lookupMap = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_AUTHORIZED");
-            List orderList = UtilMisc.toList("-maxAmount");
+            Map<String, String> lookupMap = UtilMisc.toMap("orderId", orderId, "statusId", "PAYMENT_AUTHORIZED");
+            List<String> orderList = UtilMisc.toList("-maxAmount");
             paymentPrefs = delegator.findByAnd("OrderPaymentPreference", lookupMap, orderList);
 
             if (UtilValidate.isNotEmpty(billingAccountId)) {
@@ -1082,14 +1146,17 @@
         BigDecimal totalPayments = PaymentWorker.getPaymentsTotal(orh.getOrderPayments());
         totalPayments = totalPayments.setScale(decimals, rounding);
         BigDecimal remainingTotal = orderGrandTotal.subtract(totalPayments);
-        if (Debug.infoOn()) Debug.logInfo("The Remaining Total for order: " + orderId + " is: " + remainingTotal, module);
+        if (Debug.infoOn()) {
+            Debug.logInfo("The Remaining Total for order: " + orderId + " is: " + remainingTotal, module);
+        }
         // The amount to capture cannot be greater than the remaining total
         amountToCapture = amountToCapture.min(remainingTotal);
-        if (Debug.infoOn()) Debug.logInfo("Actual Expected Capture Amount : " + amountToCapture, module);
-
+        if (Debug.infoOn()) {
+            Debug.logInfo("Actual Expected Capture Amount : " + amountToCapture, module);
+        }
         // Process billing accounts payments
         if (UtilValidate.isNotEmpty(paymentPrefsBa)) {
-            Iterator paymentsBa = paymentPrefsBa.iterator();
+            Iterator<GenericValue> paymentsBa = paymentPrefsBa.iterator();
             while (paymentsBa.hasNext()) {
                 GenericValue paymentPref = (GenericValue) paymentsBa.next();
 
@@ -1111,7 +1178,7 @@
                 // If we have an invoice, we find unapplied payments associated
                 // to the billing account and we apply them to the invoice
                 if (UtilValidate.isNotEmpty(invoiceId)) {
-                    Map captureResult = null;
+                    Map<String, Object> captureResult = null;
                     try {
                         captureResult = dispatcher.runSync("captureBillingAccountPayments", UtilMisc.<String, Object>toMap("invoiceId", invoiceId,
                                                                                                           "billingAccountId", billingAccountId,
@@ -1155,7 +1222,7 @@
                         if (authAmount.compareTo(amountCaptured) > 0) {
                             BigDecimal splitAmount = authAmount.subtract(amountCaptured);
                             try {
-                                Map splitCtx = UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreference", paymentPref, "splitAmount", splitAmount);
+                                Map<String, Object> splitCtx = UtilMisc.<String, Object>toMap("userLogin", userLogin, "orderPaymentPreference", paymentPref, "splitAmount", splitAmount);
                                 dispatcher.addCommitService("processCaptureSplitPayment", splitCtx, true);
                             } catch (GenericServiceException e) {
                                 Debug.logWarning(e, "Problem processing the capture split payment", module);
@@ -1171,7 +1238,7 @@
 
         // iterate over the prefs and capture each one until we meet our total
         if (UtilValidate.isNotEmpty(paymentPrefs)) {
-            Iterator payments = paymentPrefs.iterator();
+            Iterator<GenericValue> payments = paymentPrefs.iterator();
             while (payments.hasNext()) {
                 // DEJ20060708: Do we really want to just log and ignore the errors like this? I've improved a few of these in a review today, but it is being done all over...
                 GenericValue paymentPref = (GenericValue) payments.next();
@@ -1216,7 +1283,7 @@
                     amountThisCapture = authAmount;
                 }
 
-                Map captureResult = capturePayment(dctx, userLogin, orh, paymentPref, amountThisCapture);
+                Map<String, Object> captureResult = capturePayment(dctx, userLogin, orh, paymentPref, amountThisCapture);
                 if (captureResult != null && !ServiceUtil.isError(captureResult)) {
                     // credit card processors return captureAmount, but gift certificate processors return processAmount
                     BigDecimal amountCaptured = (BigDecimal) captureResult.get("captureAmount");
@@ -1244,7 +1311,7 @@
                     if (authAmount.compareTo(amountCaptured) > 0) {
                         BigDecimal splitAmount = authAmount.subtract(amountCaptured);
                         try {
-                            Map splitCtx = UtilMisc.toMap("userLogin", userLogin, "orderPaymentPreference", paymentPref, "splitAmount", splitAmount);
+                            Map<String, Object> splitCtx = UtilMisc.<String, Object>toMap("userLogin", userLogin, "orderPaymentPreference", paymentPref, "splitAmount", splitAmount);
                             dispatcher.addCommitService("processCaptureSplitPayment", splitCtx, true);
                         } catch (GenericServiceException e) {
                             Debug.logWarning(e, "Problem processing the capture split payment", module);
@@ -1265,17 +1332,17 @@
                     return ServiceUtil.returnError("Cannot ship order because credit card captures were unsuccessful");
                 }
             }
-            Map result = ServiceUtil.returnSuccess();
+            Map<String, Object> result = ServiceUtil.returnSuccess();
             result.put("processResult", "FAILED");
             return result;
         } else {
-            Map result = ServiceUtil.returnSuccess();
+            Map<String, Object> result = ServiceUtil.returnSuccess();
             result.put("processResult", "COMPLETE");
             return result;
         }
     }
 
-    public static Map processCaptureSplitPayment(DispatchContext dctx, Map context) {
+    public static Map<String, Object> processCaptureSplitPayment(DispatchContext dctx, Map<String, ? extends Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericDelegator delegator = dctx.getDelegator();
 
@@ -1302,7 +1369,7 @@
         }
         if (Debug.verboseOn()) Debug.logVerbose("New preference : " + newPref, module);
 
-        Map processorResult = null;
+        Map<String, Object> processorResult = null;
         try {
             // create the new payment preference
             delegator.create(newPref);
@@ -1333,7 +1400,7 @@
     }
 
     // Deprecated: use captureBillingAccountPayments instead of this.
-    public static Map captureBillingAccountPayment(DispatchContext dctx, Map context) {
+    public static Map<String, Object> captureBillingAccountPayment(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
@@ -1341,18 +1408,18 @@
         String billingAccountId = (String) context.get("billingAccountId");
         BigDecimal captureAmount = (BigDecimal) context.get("captureAmount");
         String orderId = (String) context.get("orderId");
-        Map results = ServiceUtil.returnSuccess();
+        Map<String, Object> results = ServiceUtil.returnSuccess();
 
         try {
             // Note that the partyIdFrom of the Payment should be the partyIdTo of the invoice, since you're receiving a payment from the party you billed
             GenericValue invoice = delegator.findByPrimaryKey("Invoice", UtilMisc.toMap("invoiceId", invoiceId));
-            Map paymentParams = UtilMisc.toMap("paymentTypeId", "CUSTOMER_PAYMENT", "paymentMethodTypeId", "EXT_BILLACT",
+            Map<String, Object> paymentParams = UtilMisc.<String, Object>toMap("paymentTypeId", "CUSTOMER_PAYMENT", "paymentMethodTypeId", "EXT_BILLACT",
                     "partyIdFrom", invoice.getString("partyId"), "partyIdTo", invoice.getString("partyIdFrom"),
                     "statusId", "PMNT_RECEIVED", "effectiveDate", UtilDateTime.nowTimestamp());
             paymentParams.put("amount", captureAmount);
             paymentParams.put("currencyUomId", invoice.getString("currencyUomId"));
             paymentParams.put("userLogin", userLogin);
-            Map tmpResult = dispatcher.runSync("createPayment", paymentParams);
+            Map<String, Object> tmpResult = dispatcher.runSync("createPayment", paymentParams);
             if (ServiceUtil.isError(tmpResult)) {
                 return tmpResult;
             }
@@ -1375,7 +1442,7 @@
                     return ServiceUtil.returnError("No paymentGatewayResponse created for invoice [" + invoiceId + "] and billing account [" + billingAccountId + "]: Order with ID [" + orderId + "] not found!");
                 }
                 // See if there's an orderPaymentPreference - there should be only one OPP for EXT_BILLACT per order
-                List orderPaymentPreferences = delegator.findByAnd("OrderPaymentPreference", UtilMisc.toMap("orderId", orderId, "paymentMethodTypeId", "EXT_BILLACT"));
+                List<GenericValue> orderPaymentPreferences = delegator.findByAnd("OrderPaymentPreference", UtilMisc.toMap("orderId", orderId, "paymentMethodTypeId", "EXT_BILLACT"));
                 if (orderPaymentPreferences.size() > 0) {
                     GenericValue orderPaymentPreference = EntityUtil.getFirst(orderPaymentPreferences);
 
@@ -1416,26 +1483,23 @@
         return results;
     }
 
-    public static Map captureBillingAccountPayments(DispatchContext dctx, Map context) {
+    public static Map<String, Object> captureBillingAccountPayments(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
-        LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String invoiceId = (String) context.get("invoiceId");
         String billingAccountId = (String) context.get("billingAccountId");
         BigDecimal captureAmount = (BigDecimal) context.get("captureAmount");
         captureAmount = captureAmount.setScale(decimals, rounding);
-        String orderId = (String) context.get("orderId");
         BigDecimal capturedAmount = BigDecimal.ZERO;
 
         try {
             // Select all the unapplied payment applications associated to the billing account
-            List conditionList = UtilMisc.toList(EntityCondition.makeCondition("billingAccountId", EntityOperator.EQUALS, billingAccountId),
+            List<EntityExpr> conditionList = UtilMisc.toList(EntityCondition.makeCondition("billingAccountId", EntityOperator.EQUALS, billingAccountId),
                                                   EntityCondition.makeCondition("invoiceId", EntityOperator.EQUALS, GenericEntity.NULL_FIELD));
             EntityCondition conditions = EntityCondition.makeCondition(conditionList, EntityOperator.AND);
 
-            List paymentApplications = delegator.findList("PaymentApplication", conditions, null, UtilMisc.toList("-amountApplied"), null, false);
+            List<GenericValue> paymentApplications = delegator.findList("PaymentApplication", conditions, null, UtilMisc.toList("-amountApplied"), null, false);
             if (UtilValidate.isNotEmpty(paymentApplications)) {
-                Iterator paymentApplicationsIt = paymentApplications.iterator();
+                Iterator<GenericValue> paymentApplicationsIt = paymentApplications.iterator();
                 while (paymentApplicationsIt.hasNext()) {
                     if (capturedAmount.compareTo(captureAmount) >= 0) {
                         // we have captured all the amount required
@@ -1475,16 +1539,16 @@
             return ServiceUtil.returnError(ex.getMessage());
         }
         capturedAmount = capturedAmount.setScale(decimals, rounding);
-        Map results = ServiceUtil.returnSuccess();
+        Map<String, Object> results = ServiceUtil.returnSuccess();
         results.put("captureAmount", capturedAmount);
         return results;
     }
 
-    private static Map capturePayment(DispatchContext dctx, GenericValue userLogin, OrderReadHelper orh, GenericValue paymentPref, BigDecimal amount) {
+    private static Map<String, Object> capturePayment(DispatchContext dctx, GenericValue userLogin, OrderReadHelper orh, GenericValue paymentPref, BigDecimal amount) {
         return capturePayment(dctx, userLogin, orh, paymentPref, amount, null);
     }
 
-    private static Map capturePayment(DispatchContext dctx, GenericValue userLogin, OrderReadHelper orh, GenericValue paymentPref, BigDecimal amount, GenericValue authTrans) {
+    private static Map<String, Object> capturePayment(DispatchContext dctx, GenericValue userLogin, OrderReadHelper orh, GenericValue paymentPref, BigDecimal amount, GenericValue authTrans) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         // look up the payment configuration settings
         String serviceName = null;
@@ -1521,7 +1585,7 @@
         if (!PaymentGatewayServices.checkAuthValidity(paymentPref, paymentConfig)) {
             try {
                 // re-auth required before capture
-                Map processorResult = PaymentGatewayServices.authPayment(dispatcher, userLogin, orh, paymentPref, amount, true, null);
+                Map<String, Object> processorResult = PaymentGatewayServices.authPayment(dispatcher, userLogin, orh, paymentPref, amount, true, null);
 
                 boolean authResult = false;
                 if (processorResult != null) {
@@ -1553,7 +1617,7 @@
         }
 
         // prepare the context for the capture service (must follow the ccCaptureInterface
-        Map captureContext = new HashMap();
+        Map<String, Object> captureContext = FastMap.newInstance();
         captureContext.put("userLogin", userLogin);
         captureContext.put("orderPaymentPreference", paymentPref);
         captureContext.put("paymentConfig", paymentConfig);
@@ -1563,7 +1627,7 @@
         // this is necessary because the ccCaptureInterface uses "captureAmount" but the paymentProcessInterface uses "processAmount"
         try {
             ModelService captureService = dctx.getModelService(serviceName);
-            Set inParams = captureService.getInParamNames();
+            Set<String> inParams = captureService.getInParamNames();
             if (inParams.contains("captureAmount")) {
                 captureContext.put("captureAmount", amount);
             } else if (inParams.contains("processAmount")) {
@@ -1583,7 +1647,7 @@
         Debug.logInfo("Capture [" + serviceName + "] : " + captureContext, module);
 
         // now invoke the capture service
-        Map captureResult = null;
+        Map<String, Object> captureResult = null;
         try {
             // NOTE DEJ20070819 calling this with a new transaction synchronously caused a deadlock because in this
             //transaction OrderHeader was updated and with this transaction paused and waiting for the new transaction
@@ -1615,8 +1679,8 @@
         return captureResult;
     }
 
-    private static void saveError(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPref, Map result, String serviceType, String transactionCode) {
-        Map serviceContext = new HashMap();
+    private static void saveError(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPref, Map<String, Object> result, String serviceType, String transactionCode) {
+        Map<String, Object> serviceContext = FastMap.newInstance();
         serviceContext.put("paymentServiceTypeEnumId", serviceType);
         serviceContext.put("orderPaymentPreference", paymentPref);
         serviceContext.put("transCodeEnumId", transactionCode);
@@ -1630,13 +1694,12 @@
         }
     }
 
-    public static Map storePaymentErrorMessage(DispatchContext dctx, Map context) {
+    public static Map<String, Object> storePaymentErrorMessage(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         GenericValue paymentPref = (GenericValue) context.get("orderPaymentPreference");
         String serviceType = (String) context.get("paymentServiceTypeEnumId");
         String transactionCode = (String) context.get("transCodeEnumId");
-        Map result = (Map) context.get("serviceResultMap");
-
+        Map<String, Object> result = UtilGenerics.cast(context.get("serviceResultMap"));
         String responseId = delegator.getNextSeqId("PaymentGatewayResponse");
         GenericValue response = delegator.makeValue("PaymentGatewayResponse");
         String message = ServiceUtil.getErrorMessage(result);
@@ -1664,7 +1727,7 @@
         return ServiceUtil.returnSuccess();
     }
 
-    private static boolean processResult(DispatchContext dctx, Map result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
+    private static boolean processResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
         Boolean authResult = (Boolean) result.get("authResult");
         Boolean captureResult = (Boolean) result.get("captureResult");
         boolean resultPassed = false;
@@ -1684,18 +1747,18 @@
         return resultPassed;
     }
 
-    private static void processAuthResult(DispatchContext dctx, Map result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
+    private static void processAuthResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         result.put("userLogin", userLogin);
         result.put("orderPaymentPreference", paymentPreference);
         ModelService model = dctx.getModelService("processAuthResult");
-        Map context = model.makeValid(result, ModelService.IN_PARAM);
+        Map<String, Object> context = model.makeValid(result, ModelService.IN_PARAM);
 
         // in case we rollback make sure this service gets called
         dispatcher.addRollbackService(model.name, context, true);
 
         // invoke the service
-        Map resResp;
+        Map<String, Object> resResp;
         try {
             resResp = dispatcher.runSync(model.name, context);
         } catch (GenericServiceException e) {
@@ -1707,7 +1770,7 @@
         }
     }
 
-    public static Map processAuthResult(DispatchContext dctx, Map context) {
+    public static Map<String, Object> processAuthResult(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         GenericValue orderPaymentPreference = (GenericValue) context.get("orderPaymentPreference");
         Boolean authResult = (Boolean) context.get("authResult");
@@ -1771,9 +1834,9 @@
             savePgr(dctx, response);
 
             // create the internal messages
-            List messages = (List) context.get("internalRespMsgs");
+            List<String> messages = UtilGenerics.cast(context.get("internalRespMsgs"));
             if (UtilValidate.isNotEmpty(messages)) {
-                Iterator i = messages.iterator();
+                Iterator<String> i = messages.iterator();
                 while (i.hasNext()) {
                     GenericValue respMsg = delegator.makeValue("PaymentGatewayRespMsg");
                     String respMsgId = delegator.getNextSeqId("PaymentGatewayRespMsg");
@@ -1854,7 +1917,7 @@
         return ServiceUtil.returnSuccess();
     }
 
-    private static boolean needsNsfRetry(GenericValue orderPaymentPreference, Map processContext, GenericDelegator delegator) throws GenericEntityException {
+    private static boolean needsNsfRetry(GenericValue orderPaymentPreference, Map<String, ? extends Object> processContext, GenericDelegator delegator) throws GenericEntityException {
         boolean needsNsfRetry = false;
         if (Boolean.TRUE.equals((Boolean) processContext.get("resultNsf"))) {
             // only track this for auto-orders, since we will only not fail and re-try on those
@@ -1886,16 +1949,16 @@
         return needsNsfRetry;
     }
 
-    private static GenericValue processAuthRetryResult(DispatchContext dctx, Map result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
+    private static GenericValue processAuthRetryResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
         processAuthResult(dctx, result, userLogin, paymentPreference);
         return getAuthTransaction(paymentPreference);
     }
 
-    private static void processCaptureResult(DispatchContext dctx, Map result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
+    private static void processCaptureResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
         processCaptureResult(dctx, result, userLogin, paymentPreference, null);
     }
 
-    private static void processCaptureResult(DispatchContext dctx, Map result, GenericValue userLogin, GenericValue paymentPreference, String authServiceType) throws GeneralException {
+    private static void processCaptureResult(DispatchContext dctx, Map<String, Object> result, GenericValue userLogin, GenericValue paymentPreference, String authServiceType) throws GeneralException {
         if (result == null) {
             throw new GeneralException("Null capture result sent to processCaptureResult; fatal error");
         }
@@ -1922,8 +1985,8 @@
         result.put("serviceTypeEnum", authServiceType);
 
         ModelService model = dctx.getModelService("processCaptureResult");
-        Map context = model.makeValid(result, ModelService.IN_PARAM);
-        Map capRes;
+        Map<String, Object> context = model.makeValid(result, ModelService.IN_PARAM);
+        Map<String, Object> capRes;
         try {
             capRes = dispatcher.runSync("processCaptureResult", context);
         } catch (GenericServiceException e) {
@@ -1944,7 +2007,7 @@
         }
     }
 
-    private static void processReAuthFromCaptureFailure(DispatchContext dctx, Map result, BigDecimal amount, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
+    private static void processReAuthFromCaptureFailure(DispatchContext dctx, Map<String, Object> result, BigDecimal amount, GenericValue userLogin, GenericValue paymentPreference) throws GeneralException {
         LocalDispatcher dispatcher = dctx.getDispatcher();
 
         // lookup the order header
@@ -1973,7 +2036,7 @@
         Debug.log("reauth with amount: " + amount, module);
 
         // first re-auth the card
-        Map authPayRes = authPayment(dispatcher, userLogin, orh, paymentPreference, amount, true, null);
+        Map<String, Object> authPayRes = authPayment(dispatcher, userLogin, orh, paymentPreference, amount, true, null);
         if (authPayRes == null) {
             throw new GeneralException("Null result returned from payment re-authorization");
         }
@@ -1988,7 +2051,7 @@
                 processCaptureResult(dctx, result, userLogin, paymentPreference);
             } else {
                 // no auto-capture; do manual capture now
-                Map capPayRes = capturePayment(dctx, userLogin, orh, paymentPreference, amount, authTrans);
+                Map<String, Object> capPayRes = capturePayment(dctx, userLogin, orh, paymentPreference, amount, authTrans);
                 if (capPayRes == null) {
                     throw new GeneralException("Problems trying to capture payment (null result)");
                 }
@@ -2007,7 +2070,7 @@
         }
     }
 
-    public static Map processCaptureResult(DispatchContext dctx, Map context) {
+    public static Map<String, Object> processCaptureResult(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
 
@@ -2080,9 +2143,9 @@
             savePgr(dctx, response);
 
             // create the internal messages
-            List messages = (List) context.get("internalRespMsgs");
+            List<String> messages = UtilGenerics.cast(context.get("internalRespMsgs"));
             if (UtilValidate.isNotEmpty(messages)) {
-                Iterator i = messages.iterator();
+                Iterator<String> i = messages.iterator();
                 while (i.hasNext()) {
                     GenericValue respMsg = delegator.makeValue("PaymentGatewayRespMsg");
                     String respMsgId = delegator.getNextSeqId("PaymentGatewayRespMsg");
@@ -2116,7 +2179,7 @@
             } else {
                 // otherwise get the party from the order's OrderRole
                 String orderId = paymentPreference.getString("orderId");
-                List orl = null;
+                List<GenericValue> orl = null;
                 try {
                     orl = delegator.findByAnd("OrderRole", UtilMisc.toMap("orderId", orderId, "roleTypeId", "BILL_TO_CUSTOMER"));
                 } catch (GenericEntityException e) {
@@ -2144,7 +2207,7 @@
             }
 
 
-            Map paymentCtx = UtilMisc.toMap("paymentTypeId", "CUSTOMER_PAYMENT");
+            Map<String, Object> paymentCtx = UtilMisc.<String, Object>toMap("paymentTypeId", "CUSTOMER_PAYMENT");
             paymentCtx.put("paymentMethodTypeId", paymentPreference.get("paymentMethodTypeId"));
             paymentCtx.put("paymentMethodId", paymentPreference.get("paymentMethodId"));
             paymentCtx.put("paymentGatewayResponseId", responseId);
@@ -2157,7 +2220,7 @@
             paymentCtx.put("userLogin", userLogin);
             paymentCtx.put("paymentRefNum", context.get("captureRefNum"));
 
-            Map payRes;
+            Map<String, Object> payRes;
             try {
                 payRes = dispatcher.runSync("createPayment", paymentCtx);
             } catch (GenericServiceException e) {
@@ -2173,10 +2236,10 @@
             // create the PaymentApplication if invoiceId is available
             if (invoiceId != null) {
                 Debug.logInfo("Processing Invoice #" + invoiceId, module);
-                Map paCtx = UtilMisc.toMap("paymentId", paymentId, "invoiceId", invoiceId);
+                Map<String, Object> paCtx = UtilMisc.<String, Object>toMap("paymentId", paymentId, "invoiceId", invoiceId);
                 paCtx.put("amountApplied", context.get("captureAmount"));
                 paCtx.put("userLogin", userLogin);
-                Map paRes;
+                Map<String, Object> paRes;
                 try {
                     paRes = dispatcher.runSync("createPaymentApplication", paCtx);
                 } catch (GenericServiceException e) {
@@ -2190,8 +2253,36 @@
         }
         return ServiceUtil.returnSuccess();
     }
-
-    public static Map refundPayment(DispatchContext dctx, Map context) {
+    
+    public static Map<String, Object> refundOrderPaymentPreference(DispatchContext dctx, Map<String, ? extends Object> context) {
+        GenericDelegator delegator = dctx.getDelegator();
+        LocalDispatcher dispatcher = dctx.getDispatcher();
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
+        String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
+        BigDecimal amount = (BigDecimal) context.get("amount");
+        GenericValue orderPaymentPreference = null;
+        try {
+            orderPaymentPreference = delegator.findOne("OrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreferenceId), false);
+        } catch (GenericEntityException e) {
+            Debug.logError(e, module);
+            return ServiceUtil.returnError("Problems getting required information: orderPaymentPreference [" + orderPaymentPreferenceId + "]");
+        }
+        // call the service refundPayment
+        Map<String, Object> refundResponse = null;
+        try {
+            Map<String, Object> serviceContext = FastMap.newInstance();
+            serviceContext.put("orderPaymentPreference", orderPaymentPreference);
+            serviceContext.put("refundAmount", amount);
+            serviceContext.put("userLogin", userLogin);
+            refundResponse = dispatcher.runSync("refundPayment", serviceContext, TX_TIME, true);
+        } catch (GenericServiceException e) {
+            Debug.logError(e, "Problem refunding payment through processor", module);
+            return ServiceUtil.returnError("Refund processor problems; see logs");
+        }
+        return refundResponse;
+    }
+    
+    public static Map<String, Object> refundPayment(DispatchContext dctx, Map<String, ? extends Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
 
@@ -2228,7 +2319,7 @@
             paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
             
             if (serviceName != null) {
-                Map serviceContext = new HashMap();
+                Map<String, Object> serviceContext = FastMap.newInstance();
                 serviceContext.put("orderPaymentPreference", paymentPref);
                 serviceContext.put("paymentConfig", paymentConfig);
                 serviceContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
@@ -2237,7 +2328,7 @@
                 // get the creditCard/address/email
                 String payToPartyId = null;
                 try {
-                    payToPartyId = getBillingInformation(orh, paymentPref, new HashMap());
+                    payToPartyId = getBillingInformation(orh, paymentPref, FastMap.<String, Object>newInstance());
                 } catch (GenericEntityException e) {
                     Debug.logError(e, "Problems getting billing information", module);
                     return ServiceUtil.returnError("Problems getting billing information");
@@ -2248,7 +2339,7 @@
                 serviceContext.put("userLogin", userLogin);
 
                 // call the service
-                Map refundResponse = null;
+                Map<String, Object> refundResponse = null;
                 try {
                     refundResponse = dispatcher.runSync(serviceName, serviceContext, TX_TIME, true);
                 } catch (GenericServiceException e) {
@@ -2264,10 +2355,10 @@
                 String payFromPartyId = getPayToPartyId(orderHeader);
 
                 // process the refund result
-                Map refundResRes;
+                Map<String, Object> refundResRes;
                 try {
                     ModelService model = dctx.getModelService("processRefundResult");
-                    Map refundResCtx = model.makeValid(context, ModelService.IN_PARAM);
+                    Map<String, Object> refundResCtx = model.makeValid(context, ModelService.IN_PARAM);
                     refundResCtx.put("currencyUomId", orh.getCurrency());
                     refundResCtx.put("payToPartyId", payToPartyId);
                     refundResCtx.put("payFromPartyId", payFromPartyId);
@@ -2299,7 +2390,7 @@
         }
     }
 
-    public static Map processRefundResult(DispatchContext dctx, Map context) {
+    public static Map<String, Object> processRefundResult(DispatchContext dctx, Map<String, ? extends Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericDelegator delegator = dctx.getDelegator();
 
@@ -2333,9 +2424,9 @@
         savePgr(dctx, response);
 
         // create the internal messages
-        List messages = (List) context.get("internalRespMsgs");
+        List<String> messages = UtilGenerics.cast(context.get("internalRespMsgs"));
         if (UtilValidate.isNotEmpty(messages)) {
-            Iterator i = messages.iterator();
+            Iterator<String> i = messages.iterator();
             while (i.hasNext()) {
                 GenericValue respMsg = delegator.makeValue("PaymentGatewayRespMsg");
                 String respMsgId = delegator.getNextSeqId("PaymentGatewayRespMsg");
@@ -2361,7 +2452,7 @@
             }
 
             // handle the (reverse) payment
-            Map paymentCtx = UtilMisc.toMap("paymentTypeId", "CUSTOMER_REFUND");
+            Map<String, Object> paymentCtx = UtilMisc.<String, Object>toMap("paymentTypeId", "CUSTOMER_REFUND");
             paymentCtx.put("paymentMethodTypeId", paymentPref.get("paymentMethodTypeId"));
             paymentCtx.put("paymentMethodId", paymentPref.get("paymentMethodId"));
             paymentCtx.put("paymentGatewayResponseId", responseId);
@@ -2377,7 +2468,7 @@
 
             String paymentId = null;
             try {
-                Map payRes = dispatcher.runSync("createPayment", paymentCtx);
+                Map<String, Object> payRes = dispatcher.runSync("createPayment", paymentCtx);
                 if (ModelService.RESPOND_ERROR.equals(payRes.get(ModelService.RESPONSE_MESSAGE))) {
                     return ServiceUtil.returnError((String) payRes.get(ModelService.ERROR_MESSAGE));
                 } else {
@@ -2393,7 +2484,7 @@
                 return ServiceUtil.returnError("Create payment failed");
             }
 
-            Map result = ServiceUtil.returnSuccess();
+            Map<String, Object> result = ServiceUtil.returnSuccess();
             result.put("paymentId", paymentId);
             return result;
         } else {
@@ -2401,7 +2492,7 @@
         }
     }
 
-    public static Map retryFailedOrderAuth(DispatchContext dctx, Map context) {
+    public static Map<String, Object>retryFailedOrderAuth(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         String orderId = (String) context.get("orderId");
@@ -2429,7 +2520,7 @@
         }
 
         // run the auth service and check for failure(s)
-        Map serviceResult = null;
+        Map<String, Object> serviceResult = null;
         try {
             serviceResult = dispatcher.runSync("authOrderPayments", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
         } catch (GenericServiceException e) {
@@ -2458,27 +2549,27 @@
             }
         }
 
-        Map result = ServiceUtil.returnSuccess();
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         result.put("processResult", authResp);
 
         return result;
     }
 
 
-    public static Map retryFailedAuths(DispatchContext dctx, Map context) {
+    public static Map<String, Object>retryFailedAuths(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
 
         // get a list of all payment prefs still pending
-        List exprs = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_NOT_AUTH"),
+        List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "PAYMENT_NOT_AUTH"),
                 EntityCondition.makeCondition("processAttempt", EntityOperator.GREATER_THAN, new Long(0)));
 
         EntityListIterator eli = null;
         try {
             eli = delegator.find("OrderPaymentPreference",
                     EntityCondition.makeCondition(exprs, EntityOperator.AND), null, null, UtilMisc.toList("orderId"), null);
-            List processList = new ArrayList();
+            List<String> processList = FastList.newInstance();
             if (eli != null) {
                 Debug.logInfo("Processing failed order re-auth(s)", module);
                 GenericValue value = null;
@@ -2510,7 +2601,7 @@
         return ServiceUtil.returnSuccess();
     }
 
-    public static Map retryFailedAuthNsfs(DispatchContext dctx, Map context) {
+    public static Map<String, Object>retryFailedAuthNsfs(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
@@ -2527,7 +2618,7 @@
                     EntityCondition.makeCondition(EntityCondition.makeCondition("needsNsfRetry", EntityOperator.EQUALS, "Y"), EntityOperator.AND, EntityCondition.makeCondition(ModelEntity.STAMP_FIELD, EntityOperator.LESS_THAN_EQUAL_TO, oneWeekAgo)),
                     null, null, UtilMisc.toList("orderId"), null);
 
-            List processList = FastList.newInstance();
+            List<String> processList = FastList.newInstance();
             if (eli != null) {
                 Debug.logInfo("Processing failed order re-auth(s)", module);
                 GenericValue value = null;
@@ -2555,27 +2646,23 @@
                 }
             }
         }
-
         return ServiceUtil.returnSuccess();
     }
-
+    
     public static GenericValue getCaptureTransaction(GenericValue orderPaymentPreference) {
         GenericValue capTrans = null;
         try {
-            List order = UtilMisc.toList("-transactionDate");
-            List transactions = orderPaymentPreference.getRelated("PaymentGatewayResponse", null, order);
-
-            List exprs = UtilMisc.toList(EntityCondition.makeCondition("paymentServiceTypeEnumId", EntityOperator.EQUALS, CAPTURE_SERVICE_TYPE));
-
-            List capTransactions = EntityUtil.filterByAnd(transactions, exprs);
-
+            List<String> order = UtilMisc.toList("-transactionDate");
+            List<GenericValue> transactions = orderPaymentPreference.getRelated("PaymentGatewayResponse", null, order);
+            List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("paymentServiceTypeEnumId", EntityOperator.EQUALS, CAPTURE_SERVICE_TYPE));
+            List<GenericValue> capTransactions = EntityUtil.filterByAnd(transactions, exprs);
             capTrans = EntityUtil.getFirst(capTransactions);
         } catch (GenericEntityException e) {
             Debug.logError(e, "ERROR: Problem getting capture information from PaymentGatewayResponse", module);
         }
         return capTrans;
     }
-
+    
     /**
      * Gets the chronologically latest PaymentGatewayResponse from an OrderPaymentPreference which is either a PRDS_PAY_AUTH
      * or PRDS_PAY_REAUTH.  Used for capturing.
@@ -2585,14 +2672,11 @@
     public static GenericValue getAuthTransaction(GenericValue orderPaymentPreference) {
         GenericValue authTrans = null;
         try {
-            List order = UtilMisc.toList("-transactionDate");
-            List transactions = orderPaymentPreference.getRelated("PaymentGatewayResponse", null, order);
-
-            List exprs = UtilMisc.toList(EntityCondition.makeCondition("paymentServiceTypeEnumId", EntityOperator.EQUALS, AUTH_SERVICE_TYPE),
+            List<String> order = UtilMisc.toList("-transactionDate");
+            List<GenericValue> transactions = orderPaymentPreference.getRelated("PaymentGatewayResponse", null, order);
+            List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("paymentServiceTypeEnumId", EntityOperator.EQUALS, AUTH_SERVICE_TYPE),
                     EntityCondition.makeCondition("paymentServiceTypeEnumId", EntityOperator.EQUALS, REAUTH_SERVICE_TYPE));
-
-            List authTransactions = EntityUtil.filterByOr(transactions, exprs);
-
+            List<GenericValue> authTransactions = EntityUtil.filterByOr(transactions, exprs);
             authTrans = EntityUtil.getFirst(authTransactions);
         } catch (GenericEntityException e) {
             Debug.logError(e, "ERROR: Problem getting authorization information from PaymentGatewayResponse", module);
@@ -2672,7 +2756,7 @@
 
     // safe payment gateway store
     private static void savePgr(DispatchContext dctx, GenericValue pgr) {
-        Map context = UtilMisc.toMap("paymentGatewayResponse", pgr);
+        Map<String, GenericValue> context = UtilMisc.<String, GenericValue>toMap("paymentGatewayResponse", pgr);
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericDelegator delegator = dctx.getDelegator();
 
@@ -2684,7 +2768,7 @@
         }
     }
 
-    public static Map savePaymentGatewayResponse(DispatchContext dctx, Map context) {
+    public static Map<String, Object> savePaymentGatewayResponse(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericDelegator delegator = dctx.getDelegator();
         GenericValue pgr = (GenericValue) context.get("paymentGatewayResponse");
         String message = pgr.getString("gatewayMessage");
@@ -2700,9 +2784,9 @@
 
         return ServiceUtil.returnSuccess();
     }
-
+    
     // manual auth service
-    public static Map processManualCcAuth(DispatchContext dctx, Map context) {
+    public static Map<String, Object> processManualCcAuth(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericDelegator delegator = dctx.getDelegator();
@@ -2770,7 +2854,6 @@
             }
             paymentConfig = paymentSettings.getString("paymentPropertiesPath");
             paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
-            
             if (UtilValidate.isEmpty(paymentConfig)) {
                 paymentConfig = "payment.properties";
             }
@@ -2806,7 +2889,7 @@
         authContext.put("userLogin", userLogin);
 
         // call the auth service
-        Map response;
+        Map<String, Object> response;
         try {
             Debug.logInfo("Running authorization service: " + paymentService, module);
             response = dispatcher.runSync(paymentService, authContext, TX_TIME, true);
@@ -2826,21 +2909,19 @@
             return ServiceUtil.returnError("Authorization failed");
         }
     }
-
+    
     // manual processing service
-
-    public static Map processManualCcTx(DispatchContext dctx, Map context) {
+    public static Map<String, Object> processManualCcTx(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericDelegator delegator = dctx.getDelegator();
         Security security = dctx.getSecurity();
-
         // security check
         if (!security.hasEntityPermission("MANUAL", "_PAYMENT", userLogin)) {
             Debug.logWarning("**** Security [" + (new Date()).toString() + "]: " + userLogin.get("userLoginId") + " attempt to run manual payment transaction!", module);
             return ServiceUtil.returnError("You do not have permission for this transaction.");
         }
-
+        String orderPaymentPreferenceId = (String) context.get("orderPaymentPreferenceId");
         String paymentMethodTypeId = (String) context.get("paymentMethodTypeId");
         String productStoreId = (String) context.get("productStoreId");
         String transactionType = (String) context.get("transactionType");
@@ -2848,23 +2929,53 @@
         if (referenceCode == null) {
             referenceCode = new Long(System.currentTimeMillis()).toString();
         }
-
+        // Get the OrderPaymentPreference
+        GenericValue paymentPref = null;
+        try {
+            paymentPref = delegator.findOne("OrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreferenceId), false);
+        } catch ( GenericEntityException e ) {
+            String errMsg = "Problem getting OrderPaymentPreference for orderPaymentPreferenceId " + orderPaymentPreferenceId;
+            Debug.logWarning(e, errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        // Error if no OrderPaymentPreference was found
+        if (paymentPref == null) {
+            String errMsg = "Could not find OrderPaymentPreference with orderPaymentPreferenceId: " + orderPaymentPreferenceId;
+            Debug.logWarning(errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        // Get the OrderHeader
+        GenericValue orderHeader = null;
+        String orderId = paymentPref.getString("orderId");
+        try {
+            orderHeader = delegator.findOne("OrderHeader", UtilMisc.toMap("orderId", orderId), false);
+        } catch ( GenericEntityException e ) {
+            String errMsg = "Problem getting OrderHeader for orderId " + orderId;
+            Debug.logWarning(e, errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        // Error if no OrderHeader was found
+        if (orderHeader == null) {
+            String errMsg = "Could not find OrderHeader with orderId: " + orderId + "; not processing payments.";
+            Debug.logWarning(errMsg, module);
+            return ServiceUtil.returnError(errMsg);
+        }
+        OrderReadHelper orh = new OrderReadHelper(orderHeader);
         // check valid implemented types
         if (!transactionType.equals(CREDIT_SERVICE_TYPE)) {
             return ServiceUtil.returnError("This transaction type is not yet supported.");
         }
-
         // transaction request context
-        Map requestContext = new HashMap();
+        Map<String, Object> requestContext = FastMap.newInstance();
         String paymentService = null;
         String paymentConfig = null;
         String paymentGatewayConfigId = null;
-
         // get the transaction settings
         GenericValue paymentSettings = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStoreId, paymentMethodTypeId, transactionType, false);
         if (paymentSettings == null) {
             return ServiceUtil.returnError("No valid payment settings found for : " + productStoreId + "/" + transactionType);
         } else {
+            paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
             String customMethodId = paymentSettings.getString("paymentCustomMethodId");
             if (UtilValidate.isNotEmpty(customMethodId)) {
                 paymentService = getPaymentCustomMethod(delegator, customMethodId);
@@ -2873,16 +2984,17 @@
                 paymentService = paymentSettings.getString("paymentService");
             }
             paymentConfig = paymentSettings.getString("paymentPropertiesPath");
-            paymentGatewayConfigId = paymentSettings.getString("paymentGatewayConfigId");
+            if (paymentConfig == null) {
+                paymentConfig = "payment.properties";
+            }
             requestContext.put("paymentConfig", paymentConfig);
             requestContext.put("paymentGatewayConfigId", paymentGatewayConfigId);
         }
-
         // check the service name
-        if (paymentService == null || paymentConfig == null) {
+        if (paymentService == null || (paymentGatewayConfigId == null && paymentConfig == null)) {
             return ServiceUtil.returnError("Invalid product store payment settings");
         }
-
+        
         if (paymentMethodTypeId.equals("CREDIT_CARD")) {
             GenericValue creditCard = delegator.makeValue("CreditCard");
             creditCard.setAllFields(context, true, null, null);
@@ -2895,63 +3007,69 @@
             creditCard.set("expireDate", expDate);
             requestContext.put("creditCard", creditCard);
             requestContext.put("cardSecurityCode", context.get("cardSecurityCode"));
-
             GenericValue billingAddress = delegator.makeValue("PostalAddress");
             billingAddress.setAllFields(context, true, null, null);
             if (billingAddress.get("address1") == null || billingAddress.get("city") == null || billingAddress.get("postalCode") == null) {
                 return ServiceUtil.returnError("Credit card billing address is missing required fields.");
             }
             requestContext.put("billingAddress", billingAddress);
-
-            /* This is not needed any more, using names on CC as a kludge instead of these kludge names until we get a firstName/lastName on the shipping PostalAddress
-            GenericValue contactPerson = delegator.makeValue("Person");
-            contactPerson.setAllFields(context, true, null, null);
-            if (contactPerson.get("firstName") == null || contactPerson.get("lastName") == null) {
-                return ServiceUtil.returnError("Contact person is missing required fields.");
-            }
-            requestContext.put("contactPerson", contactPerson);
-            */
-
             GenericValue billToEmail = delegator.makeValue("ContactMech");
             billToEmail.set("infoString", context.get("infoString"));
             if (billToEmail.get("infoString") == null) {
                 return ServiceUtil.returnError("Email address field cannot be empty.");
             }
+            requestContext.put("billToParty", orh.getBillToParty());
             requestContext.put("billToEmail", billToEmail);
             requestContext.put("referenceCode", referenceCode);
             String currency = UtilProperties.getPropertyValue("general.properties", "currency.uom.id.default", "USD");
             requestContext.put("currency", currency);
-            requestContext.put("creditAmount", context.get("amount")); // TODO fix me to work w/ other services
+            requestContext.put("creditAmount", context.get("amount")); 
         } else {
             return ServiceUtil.returnError("Payment method type : " + paymentMethodTypeId + " is not yet implemented for manual transactions");
         }
-
         // process the transaction
-        Map response = null;
+        Map<String, Object> response = null;
         try {
             response = dispatcher.runSync(paymentService, requestContext, TX_TIME, true);
         } catch (GenericServiceException e) {
             Debug.logError(e, module);
             return ServiceUtil.returnError("Error calling service : " + paymentService + " / " + requestContext);
         }
-
+        // get the response result code
+        if (response != null && !ServiceUtil.isError(response)) {
+            Map<String, Object> responseRes;
+            try {
+                ModelService model = dctx.getModelService("processCreditResult");
+                response.put("orderPaymentPreference", paymentPref);
+                response.put("userLogin", userLogin);
+                Map<String, Object> resCtx = model.makeValid(response, ModelService.IN_PARAM);
+                responseRes = dispatcher.runSync(model.name,  resCtx);
+            } catch (GenericServiceException e) {
+                Debug.logError(e, module);
+                return ServiceUtil.returnError("Trouble processing the release results: " + e.getMessage());
+            }
+            if (responseRes != null && ServiceUtil.isError(responseRes)) {
+                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(responseRes));
+            }
+        } else if (ServiceUtil.isError(response)) {
+            saveError(dispatcher, userLogin, paymentPref, response, CREDIT_SERVICE_TYPE, "PGT_CREDIT");
+            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(response));
+        }
         // check for errors
         if (ServiceUtil.isError(response)) {
             return ServiceUtil.returnError(ServiceUtil.makeErrorMessage(response, null, null, null, null));
         }
-
-        // get the reference number // TODO add support for other tx types
+        // get the reference number
         String refNum = (String) response.get("creditRefNum");
         String code = (String) response.get("creditCode");
         String msg = (String) response.get("creditMessage");
-        Map returnResults = ServiceUtil.returnSuccess("Transaction result [" + msg + "/" + code +"] Ref#: " + refNum);
+        Map<String, Object> returnResults = ServiceUtil.returnSuccess("Transaction result [" + msg + "/" + code +"] Ref#: " + refNum);
         returnResults.put("referenceNum", refNum);
         return returnResults;
     }
-
+    
     // Verify Credit Card (Manually) Service
-
-    public static Map verifyCreditCard(DispatchContext dctx, Map context) {
+    public static Map<String, Object>verifyCreditCard(DispatchContext dctx, Map<String, ? extends Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericDelegator delegator = dctx.getDelegator();
         String productStoreId = (String) context.get("productStoreId");
@@ -3012,8 +3130,8 @@
     /**
      * Simple test processor; declines all orders < 100.00; approves all orders >= 100.00
      */
-    public static Map testProcessor(DispatchContext dctx, Map context) {
-        Map result = new HashMap();
+    public static Map<String, Object> testProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = FastMap.newInstance();
         BigDecimal processAmount = (BigDecimal) context.get("processAmount");
 
         if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) >= 0)
@@ -3039,8 +3157,8 @@
     /**
      * Simple test processor; declines all orders < 100.00; approves all orders > 100.00
      */
-    public static Map testProcessorWithCapture(DispatchContext dctx, Map context) {
-        Map result = new HashMap();
+    public static Map<String, Object> testProcessorWithCapture(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = FastMap.newInstance();
         BigDecimal processAmount = (BigDecimal) context.get("processAmount");
 
         if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) >= 0)
@@ -3071,8 +3189,8 @@
     /**
      *  Test authorize - does random declines
      */
-    public static Map testRandomAuthorize(DispatchContext dctx, Map context) {
-        Map result = ServiceUtil.returnSuccess();
+    public static Map<String, Object> testRandomAuthorize(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         String refNum = UtilDateTime.nowAsString();
         Random r = new Random();
         int i = r.nextInt(9);
@@ -3096,8 +3214,8 @@
     /**
      * Always approve processor.
      */
-    public static Map alwaysApproveProcessor(DispatchContext dctx, Map context) {
-        Map result = new HashMap();
+    public static Map<String, Object> alwaysApproveProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = FastMap.newInstance();
         Debug.logInfo("Test Processor Approving Credit Card", module);
 
         String refNum = UtilDateTime.nowAsString();
@@ -3112,8 +3230,8 @@
         return result;
     }
 
-    public static Map alwaysApproveWithCapture(DispatchContext dctx, Map context) {
-        Map result = new HashMap();
+    public static Map<String, Object> alwaysApproveWithCapture(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = FastMap.newInstance();
         String refNum = UtilDateTime.nowAsString();
         Debug.logInfo("Test Processor Approving Credit Card with Capture", module);
 
@@ -3135,8 +3253,8 @@
     /**
      * Always decline processor
      */
-    public static Map alwaysDeclineProcessor(DispatchContext dctx, Map context) {
-        Map result = ServiceUtil.returnSuccess();
+    public static Map<String, Object> alwaysDeclineProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         BigDecimal processAmount = (BigDecimal) context.get("processAmount");
         Debug.logInfo("Test Processor Declining Credit Card", module);
 
@@ -3154,8 +3272,8 @@
     /**
      * Always NSF (not sufficient funds) processor
      */
-    public static Map alwaysNsfProcessor(DispatchContext dctx, Map context) {
-        Map result = ServiceUtil.returnSuccess();
+    public static Map<String, Object> alwaysNsfProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         BigDecimal processAmount = (BigDecimal) context.get("processAmount");
         Debug.logInfo("Test Processor NSF Credit Card", module);
 
@@ -3174,8 +3292,8 @@
     /**
      * Always fail/bad expire date processor
      */
-    public static Map alwaysBadExpireProcessor(DispatchContext dctx, Map context) {
-        Map result = ServiceUtil.returnSuccess();
+    public static Map<String, Object> alwaysBadExpireProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         BigDecimal processAmount = (BigDecimal) context.get("processAmount");
         Debug.logInfo("Test Processor Bad Expire Date Credit Card", module);
 
@@ -3194,7 +3312,7 @@
     /**
      * Fail/bad expire date when year is even processor
      */
-    public static Map badExpireEvenProcessor(DispatchContext dctx, Map context) {
+    public static Map<String, Object>badExpireEvenProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
         GenericValue creditCard = (GenericValue) context.get("creditCard");
         String expireDate = creditCard.getString("expireDate");
         String lastNumberStr = expireDate.substring(expireDate.length() - 1);
@@ -3210,8 +3328,8 @@
     /**
      * Always bad card number processor
      */
-    public static Map alwaysBadCardNumberProcessor(DispatchContext dctx, Map context) {
-        Map result = ServiceUtil.returnSuccess();
+    public static Map<String, Object> alwaysBadCardNumberProcessor(DispatchContext dctx, Map<String, ? extends Object> context) {
+        Map<String, Object> result = ServiceUtil.returnSuccess();
         BigDecimal processAmount = (BigDecimal) context.get("processAmount");

[... 81 lines stripped ...]