[ofbiz-framework] branch trunk updated: Improved: Corrected all incorrect indentation level issues in application component, also fixed some case indentation checkstyle issues. (OFBIZ-11922)

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[ofbiz-framework] branch trunk updated: Improved: Corrected all incorrect indentation level issues in application component, also fixed some case indentation checkstyle issues. (OFBIZ-11922)

surajk
This is an automated email from the ASF dual-hosted git repository.

surajk pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/ofbiz-framework.git


The following commit(s) were added to refs/heads/trunk by this push:
     new 3929ff1  Improved: Corrected all incorrect indentation level issues in application component, also fixed some case indentation checkstyle issues. (OFBIZ-11922)
     new f8a0a83  Merge branch 'trunk' of https://gitbox.apache.org/repos/asf/ofbiz-framework into trunk
3929ff1 is described below

commit 3929ff1bd7fd3e04b7c2dbe16a01cd24e19d86d3
Author: Suraj Khurana <[hidden email]>
AuthorDate: Sun Jul 26 20:25:35 2020 +0530

    Improved: Corrected all incorrect indentation level issues in application component, also fixed some case indentation checkstyle issues.
    (OFBIZ-11922)
---
 .../java/org/apache/ofbiz/accounting/GlEvents.java | 162 ++--
 .../ofbiz/accounting/invoice/InvoiceServices.java  | 944 ++++++++++++---------
 .../ofbiz/accounting/invoice/InvoiceWorker.java    |  60 +-
 .../payment/GiftCertificateServices.java           |  18 +-
 .../accounting/payment/PaymentGatewayServices.java |  40 +-
 .../accounting/payment/PaymentMethodServices.java  |  29 +-
 .../ofbiz/accounting/tax/TaxAuthorityServices.java |  26 +-
 .../authorizedotnet/AIMPaymentServices.java        |  45 +-
 .../thirdparty/orbital/OrbitalPaymentServices.java |  18 +-
 .../accounting/thirdparty/paypal/PayPalEvents.java |  14 +-
 .../thirdparty/paypal/PayPalServices.java          |   2 +-
 .../thirdparty/sagepay/SagePayPaymentServices.java |   2 +-
 .../thirdparty/sagepay/SagePayServices.java        | 163 +++-
 .../accounting/thirdparty/sagepay/SagePayUtil.java | 152 +++-
 .../thirdparty/securepay/SecurePayServiceTest.java |   2 +-
 .../thirdparty/valuelink/ValueLinkApi.java         |   2 +-
 .../accounting/thirdparty/verisign/PayflowPro.java |  18 +-
 .../ofbiz/content/ContentManagementEvents.java     |  20 +-
 .../ofbiz/content/ContentManagementServices.java   |  66 +-
 .../ofbiz/content/ContentManagementWorker.java     |  32 +-
 .../org/apache/ofbiz/content/cms/CmsEvents.java    | 381 +++++----
 .../ofbiz/content/cms/ContentJsonEvents.java       |  22 +-
 .../ofbiz/content/compdoc/CompDocEvents.java       |   4 +-
 .../content/content/ContentPermissionServices.java |  59 +-
 .../content/content/ContentServicesComplex.java    |  46 +-
 .../ofbiz/content/content/ContentWorker.java       |  41 +-
 .../ofbiz/content/content/ContentWrapper.java      |   2 +-
 .../org/apache/ofbiz/content/data/DataEvents.java  |   6 +-
 .../ofbiz/content/data/DataResourceWorker.java     |  37 +-
 .../apache/ofbiz/content/data/DataServices.java    |   2 +-
 .../ofbiz/content/survey/PdfSurveyServices.java    |   6 +-
 .../apache/ofbiz/content/survey/SurveyWrapper.java |  51 +-
 .../content/view/SimpleContentViewHandler.java     |   2 +-
 .../ftl/EditRenderSubContentCacheTransform.java    |   2 +-
 .../webapp/ftl/InjectNodeTrailCsvTransform.java    |  14 +-
 .../content/webapp/ftl/RenderContentAsText.java    |   2 +-
 .../content/webapp/ftl/RenderSubContentAsText.java |   2 +-
 .../ftl/TraverseSubContentCacheTransform.java      |   2 +-
 .../webapp/ftl/WrapSubContentCacheTransform.java   |   2 +-
 .../apache/ofbiz/manufacturing/bom/BOMHelper.java  |  95 ++-
 .../apache/ofbiz/manufacturing/bom/BOMNode.java    |   4 +-
 .../ofbiz/manufacturing/bom/BOMServices.java       |   2 +-
 .../apache/ofbiz/manufacturing/bom/BOMTree.java    |   4 +-
 .../manufacturing/jobshopmgt/ProductionRun.java    |   2 +-
 .../jobshopmgt/ProductionRunServices.java          | 471 ++++++----
 .../mrp/InventoryEventPlannedServices.java         |   4 +-
 .../ofbiz/manufacturing/mrp/MrpServices.java       | 199 +++--
 .../ofbiz/manufacturing/mrp/ProposedOrder.java     |   4 +-
 .../manufacturing/techdata/TechDataServices.java   |  15 +-
 .../marketing/tracking/TrackingCodeEvents.java     |   3 +-
 .../ofbiz/order/finaccount/FinAccountHelper.java   | 247 +++---
 .../ofbiz/order/order/OrderChangeHelper.java       |  48 +-
 .../org/apache/ofbiz/order/order/OrderEvents.java  |   2 +-
 .../apache/ofbiz/order/order/OrderListState.java   |   2 +-
 .../ofbiz/order/order/OrderLookupServices.java     |   2 +-
 .../apache/ofbiz/order/order/OrderReadHelper.java  |  10 +-
 .../ofbiz/order/order/OrderReturnServices.java     |   4 +-
 .../apache/ofbiz/order/order/OrderServices.java    | 173 ++--
 .../ofbiz/order/shoppingcart/CheckOutEvents.java   |   2 +-
 .../ofbiz/order/shoppingcart/CheckOutHelper.java   | 106 +--
 .../ofbiz/order/shoppingcart/ShoppingCart.java     | 215 +++--
 .../order/shoppingcart/ShoppingCartHelper.java     |  59 +-
 .../ofbiz/order/shoppingcart/ShoppingCartItem.java | 102 +--
 .../shoppingcart/product/ProductDisplayWorker.java |  20 +-
 .../communication/CommunicationEventServices.java  |  14 +-
 .../ofbiz/party/content/PartyContentWrapper.java   |   4 +-
 .../apache/ofbiz/party/party/PartyServices.java    |   2 +-
 .../org/apache/ofbiz/party/party/PartyWorker.java  |   4 +-
 .../ofbiz/product/category/CatalogUrlServlet.java  | 110 +--
 .../product/category/CategoryContentWrapper.java   |   2 +-
 .../ofbiz/product/category/CategoryWorker.java     |   2 +-
 .../config/ProductConfigItemContentWrapper.java    |   4 +-
 .../ofbiz/product/config/ProductConfigWorker.java  |   6 +-
 .../ofbiz/product/config/ProductConfigWrapper.java |  44 +-
 .../ofbiz/product/imagemanagement/FrameImage.java  |  16 +-
 .../imagemanagement/ImageManagementServices.java   |   2 +-
 .../ofbiz/product/inventory/InventoryServices.java | 112 +--
 .../apache/ofbiz/product/price/PriceServices.java  |  53 +-
 .../product/product/ProductContentWrapper.java     |  35 +-
 .../product/ProductPromoContentWrapper.java        |   4 +-
 .../ofbiz/product/product/ProductSearch.java       |  10 +-
 .../ofbiz/product/product/ProductSearchEvents.java | 363 ++++----
 .../ofbiz/product/product/ProductServices.java     |   2 +-
 .../ofbiz/product/product/ProductWorker.java       |  26 +-
 .../apache/ofbiz/product/promo/PromoServices.java  |   3 +-
 .../product/subscription/SubscriptionServices.java |  11 +-
 .../ofbiz/shipment/packing/PackingEvent.java       |  16 +-
 .../ofbiz/shipment/packing/PackingServices.java    |   2 +-
 .../ofbiz/shipment/packing/PackingSession.java     |  32 +-
 .../ofbiz/shipment/shipment/ShipmentServices.java  |  46 +-
 .../ofbiz/shipment/thirdparty/dhl/DhlServices.java |   7 +-
 .../shipment/thirdparty/fedex/FedexServices.java   |  25 +-
 .../ofbiz/shipment/thirdparty/ups/UpsServices.java | 693 +++++++++------
 .../shipment/thirdparty/usps/UspsServices.java     |   2 +-
 .../ofbiz/shipment/verify/VerifyPickSession.java   |   2 +-
 .../content/WorkEffortContentWrapper.java          |   8 +-
 .../workeffort/workeffort/WorkEffortSearch.java    |  25 +-
 .../workeffort/WorkEffortSearchSession.java        |  19 +-
 98 files changed, 3386 insertions(+), 2613 deletions(-)

diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java
index e8ce54b..232ffc0 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/GlEvents.java
@@ -38,94 +38,100 @@ import org.apache.ofbiz.service.ServiceUtil;
 
 public class GlEvents {
 
-private static final String MODULE = GlEvents.class.getName();
-public static String createReconcileAccount(HttpServletRequest request, HttpServletResponse response) {
-    LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
-    final Delegator delegator = (Delegator) request.getAttribute("delegator");
-    GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
-    Map<String, Object> ctx = UtilHttp.getParameterMap(request);
-    String acctgTransId;
-    String acctgTransEntrySeqId;
-    String glAccountId = null;
-    String organizationPartyId = null;
-    BigDecimal reconciledBalance = BigDecimal.ZERO;
-    boolean isSelected;
-    String debitCreditFlag;
-    // The number of multi form rows is retrieved
-    int rowCount = UtilHttp.getMultiFormRowCount(ctx);
-    for (int i = 0; i < rowCount; i++) {  //for calculating amount per glAccountId
-        String suffix = UtilHttp.getMultiRowDelimiter() + i;
-        isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix)));
-        if (!isSelected) {
-            continue;
+    private static final String MODULE = GlEvents.class.getName();
+
+    public static String createReconcileAccount(HttpServletRequest request, HttpServletResponse response) {
+        LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
+        final Delegator delegator = (Delegator) request.getAttribute("delegator");
+        GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
+        Map<String, Object> ctx = UtilHttp.getParameterMap(request);
+        String acctgTransId;
+        String acctgTransEntrySeqId;
+        String glAccountId = null;
+        String organizationPartyId = null;
+        BigDecimal reconciledBalance = BigDecimal.ZERO;
+        boolean isSelected;
+        String debitCreditFlag;
+        // The number of multi form rows is retrieved
+        int rowCount = UtilHttp.getMultiFormRowCount(ctx);
+        for (int i = 0; i < rowCount; i++) {  //for calculating amount per glAccountId
+            String suffix = UtilHttp.getMultiRowDelimiter() + i;
+            isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix)));
+            if (!isSelected) {
+                continue;
+            }
+            acctgTransId = (String) ctx.get("acctgTransId" + suffix);
+            acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix);
+            organizationPartyId = (String) ctx.get("organizationPartyId" + suffix);
+            glAccountId = (String) ctx.get("glAccountId" + suffix);
+            try {
+                GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId,
+                        "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne();
+                if (acctgTransEntry != null) {
+                    //calculate amount for each AcctgTransEntry according to glAccountId based on debit and credit
+                    debitCreditFlag = acctgTransEntry.getString("debitCreditFlag");
+                    if ("D".equalsIgnoreCase(debitCreditFlag)) {
+                        reconciledBalance = reconciledBalance.add(acctgTransEntry.getBigDecimal("amount"));  //total balance per glAccountId
+                    } else {
+                        reconciledBalance = reconciledBalance.subtract(acctgTransEntry.getBigDecimal("amount"));  //total balance per glAccountId
+                    }
+                }
+            } catch (GenericEntityException e) {
+                Debug.logError(e, MODULE);
+                return "error";
+            }
+
         }
-        acctgTransId = (String) ctx.get("acctgTransId" + suffix);
-        acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix);
-        organizationPartyId = (String) ctx.get("organizationPartyId" + suffix);
-        glAccountId = (String) ctx.get("glAccountId" + suffix);
+        Map<String, Object> fieldMap = UtilMisc.toMap("glReconciliationName", "Reconciliation at date " + UtilDateTime.nowTimestamp(), "glAccountId"
+                , glAccountId, "organizationPartyId", organizationPartyId, "reconciledDate", UtilDateTime.nowTimestamp(), "reconciledBalance",
+                reconciledBalance, "userLogin", userLogin);
+        Map<String, Object> glReconResult = null;
         try {
-            GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne();
-            if (acctgTransEntry != null) {
-                //calculate amount for each AcctgTransEntry according to glAccountId based on debit and credit
-                debitCreditFlag = acctgTransEntry.getString("debitCreditFlag");
-                if ("D".equalsIgnoreCase(debitCreditFlag)) {
-                    reconciledBalance = reconciledBalance.add(acctgTransEntry.getBigDecimal("amount"));  //total balance per glAccountId
-                } else {
-                    reconciledBalance = reconciledBalance.subtract(acctgTransEntry.getBigDecimal("amount"));  //total balance per glAccountId
-                }
+            glReconResult = dispatcher.runSync("createGlReconciliation", fieldMap); //create GlReconciliation for the glAccountId
+            if (ServiceUtil.isError(glReconResult)) {
+                return "error";
             }
-        } catch (GenericEntityException e) {
+        } catch (GenericServiceException e) {
             Debug.logError(e, MODULE);
             return "error";
         }
-
-    }
-    Map<String, Object> fieldMap = UtilMisc.toMap("glReconciliationName", "Reconciliation at date " + UtilDateTime.nowTimestamp(), "glAccountId", glAccountId, "organizationPartyId", organizationPartyId, "reconciledDate", UtilDateTime.nowTimestamp(), "reconciledBalance", reconciledBalance, "userLogin", userLogin);
-    Map<String, Object> glReconResult = null;
-    try {
-        glReconResult = dispatcher.runSync("createGlReconciliation", fieldMap); //create GlReconciliation for the glAccountId
-        if (ServiceUtil.isError(glReconResult)) {
-            return "error";
-         }
-    } catch (GenericServiceException e) {
-        Debug.logError(e, MODULE);
-        return "error";
-    }
-    String glReconciliationId = (String) glReconResult.get("glReconciliationId");
-    String reconciledAmount;
-    for (int i = 0; i < rowCount; i++) {
-        String suffix = UtilHttp.getMultiRowDelimiter() + i;
-        isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix)));
-        if (!isSelected) {
-            continue;
-        }
-        acctgTransId = (String) ctx.get("acctgTransId" + suffix);
-        acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix);
-        try {
-            GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne();
-            if (acctgTransEntry != null) {
-                reconciledAmount = acctgTransEntry.getString("amount");
-                acctgTransId = acctgTransEntry.getString("acctgTransId");
-                acctgTransEntrySeqId = acctgTransEntry.getString("acctgTransEntrySeqId");
-                Map<String, Object> glReconEntryMap = UtilMisc.toMap("glReconciliationId", glReconciliationId, "acctgTransId", acctgTransId, "acctgTransEntrySeqId", acctgTransEntrySeqId, "reconciledAmount", reconciledAmount, "userLogin", userLogin);
-                Map<String, Object> glReconEntryResult = null;
-                try {
-                    glReconEntryResult = dispatcher.runSync("createGlReconciliationEntry", glReconEntryMap);
-                    if (ServiceUtil.isError(glReconEntryResult)) {
+        String glReconciliationId = (String) glReconResult.get("glReconciliationId");
+        String reconciledAmount;
+        for (int i = 0; i < rowCount; i++) {
+            String suffix = UtilHttp.getMultiRowDelimiter() + i;
+            isSelected = (ctx.containsKey("_rowSubmit" + suffix) && "Y".equalsIgnoreCase((String) ctx.get("_rowSubmit" + suffix)));
+            if (!isSelected) {
+                continue;
+            }
+            acctgTransId = (String) ctx.get("acctgTransId" + suffix);
+            acctgTransEntrySeqId = (String) ctx.get("acctgTransEntrySeqId" + suffix);
+            try {
+                GenericValue acctgTransEntry = EntityQuery.use(delegator).from("AcctgTransEntry").where("acctgTransId", acctgTransId,
+                        "acctgTransEntrySeqId", acctgTransEntrySeqId).queryOne();
+                if (acctgTransEntry != null) {
+                    reconciledAmount = acctgTransEntry.getString("amount");
+                    acctgTransId = acctgTransEntry.getString("acctgTransId");
+                    acctgTransEntrySeqId = acctgTransEntry.getString("acctgTransEntrySeqId");
+                    Map<String, Object> glReconEntryMap = UtilMisc.toMap("glReconciliationId", glReconciliationId, "acctgTransId", acctgTransId,
+                            "acctgTransEntrySeqId", acctgTransEntrySeqId, "reconciledAmount", reconciledAmount, "userLogin", userLogin);
+                    Map<String, Object> glReconEntryResult = null;
+                    try {
+                        glReconEntryResult = dispatcher.runSync("createGlReconciliationEntry", glReconEntryMap);
+                        if (ServiceUtil.isError(glReconEntryResult)) {
+                            return "error";
+                        }
+                    } catch (GenericServiceException e) {
+                        Debug.logError(e, MODULE);
                         return "error";
                     }
-                } catch (GenericServiceException e) {
-                    Debug.logError(e, MODULE);
-                    return "error";
                 }
+            } catch (GenericEntityException e) {
+                Debug.logError(e, MODULE);
+                return "error";
             }
-        } catch (GenericEntityException e) {
-            Debug.logError(e, MODULE);
-            return "error";
         }
+        ctx.put("glReconciliationId", glReconciliationId);
+        request.setAttribute("glReconciliationId", glReconciliationId);
+        return "success";
     }
-    ctx.put("glReconciliationId", glReconciliationId);
-    request.setAttribute("glReconciliationId", glReconciliationId);
-    return "success";
-  }
 }
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java
index 3330108..198c58f 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceServices.java
@@ -68,39 +68,39 @@ import org.apache.ofbiz.service.ServiceUtil;
 
 /**
  * InvoiceServices - Services for creating invoices
- *
+ * <p>
  * Note that throughout this file we use BigDecimal to do arithmetic. It is
  * critical to understand the way BigDecimal works if you wish to modify the
  * computations in this file. The most important things to keep in mind:
- *
+ * <p>
  * Critically important: BigDecimal arithmetic methods like add(),
  * multiply(), divide() do not modify the BigDecimal itself. Instead, they
  * return a new BigDecimal. For example, to keep a running total of an
  * amount, make sure you do this:
- *
- *      amount = amount.add(subAmount);
- *
+ * <p>
+ * amount = amount.add(subAmount);
+ * <p>
  * and not this,
- *
- *      amount.add(subAmount);
- *
+ * <p>
+ * amount.add(subAmount);
+ * <p>
  * Use .setScale(scale, roundingMode) after every computation to scale and
  * round off the decimals. Check the code to see how the scale and
  * roundingMode are obtained and how the function is used.
- *
+ * <p>
  * use .compareTo() to compare big decimals
- *
- *      ex.  (amountOne.compareTo(amountTwo) == 1)
- *           checks if amountOne is greater than amountTwo
- *
+ * <p>
+ * ex.  (amountOne.compareTo(amountTwo) == 1)
+ * checks if amountOne is greater than amountTwo
+ * <p>
  * Use .signum() to test if value is negative, zero, or positive
- *
- *      ex.  (amountOne.signum() == 1)
- *           checks if the amount is a positive non-zero number
- *
+ * <p>
+ * ex.  (amountOne.signum() == 1)
+ * checks if the amount is a positive non-zero number
+ * <p>
  * Never use the .equals() function becaues it considers 2.0 not equal to 2.00 (the scale is different)
  * Instead, use .compareTo() or .signum(), which handles scale correctly.
- *
+ * <p>
  * For reference, check the official Sun Javadoc on java.math.BigDecimal.
  */
 public class InvoiceServices {
@@ -140,7 +140,7 @@ public class InvoiceServices {
             result.remove("invoiceTypeId");  //remove extra parameter
             return result;
         } catch (GenericServiceException | GenericEntityException e) {
-            Debug.logError (e, "Entity/data problem creating invoice from order items: " + e.toString(), MODULE);
+            Debug.logError(e, "Entity/data problem creating invoice from order items: " + e.toString(), MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                     "AccountingEntityDataProblemCreatingInvoiceFromOrderItems",
                     UtilMisc.toMap("reason", e.toString()), locale));
@@ -296,11 +296,12 @@ public class InvoiceServices {
                 createInvoiceTerms(delegator, dispatcher, invoiceId, billingAccountTerms, userLogin, locale);
                 */
                 // set the invoice bill_to_customer from the billing account
-                List<GenericValue> billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), null, false);
+                List<GenericValue> billToRoles = billingAccount.getRelated("BillingAccountRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"),
+                        null, false);
                 for (GenericValue billToRole : billToRoles) {
                     if (!(billToRole.getString("partyId").equals(billToCustomerPartyId))) {
                         createInvoiceRoleContext = UtilMisc.toMap("invoiceId", invoiceId, "partyId", billToRole.get("partyId"),
-                                                                           "roleTypeId", "BILL_TO_CUSTOMER", "userLogin", userLogin);
+                                "roleTypeId", "BILL_TO_CUSTOMER", "userLogin", userLogin);
                         Map<String, Object> createInvoiceRoleResult = dispatcher.runSync("createInvoiceRole", createInvoiceRoleContext);
                         if (ServiceUtil.isError(createInvoiceRoleResult)) {
                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -311,9 +312,11 @@ public class InvoiceServices {
 
                 // set the bill-to contact mech as the contact mech of the billing account
                 if (UtilValidate.isNotEmpty(billingAccount.getString("contactMechId"))) {
-                    Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", billingAccount.getString("contactMechId"),
-                                                                       "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin);
-                    Map<String, Object> createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext);
+                    Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId",
+                            billingAccount.getString("contactMechId"),
+                            "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin);
+                    Map<String, Object> createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech",
+                            createBillToContactMechContext);
                     if (ServiceUtil.isError(createBillToContactMechResult)) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                                 "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult);
@@ -323,16 +326,19 @@ public class InvoiceServices {
                 List<GenericValue> billingLocations = orh.getBillingLocations();
                 if (UtilValidate.isNotEmpty(billingLocations)) {
                     for (GenericValue ocm : billingLocations) {
-                        Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString("contactMechId"),
-                                                                           "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin);
-                        Map<String, Object> createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createBillToContactMechContext);
+                        Map<String, Object> createBillToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", ocm.getString(
+                                "contactMechId"),
+                                "contactMechPurposeTypeId", "BILLING_LOCATION", "userLogin", userLogin);
+                        Map<String, Object> createBillToContactMechResult = dispatcher.runSync("createInvoiceContactMech",
+                                createBillToContactMechContext);
                         if (ServiceUtil.isError(createBillToContactMechResult)) {
                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                                     "AccountingErrorCreatingInvoiceContactMechFromOrder", locale), null, null, createBillToContactMechResult);
                         }
                     }
                 } else {
-                    Debug.logWarning("No billing locations found for order [" + orderId +"] and none were created for Invoice [" + invoiceId + "]", MODULE);
+                    Debug.logWarning("No billing locations found for order [" + orderId + "] and none were created for Invoice [" + invoiceId + "]"
+                            , MODULE);
                 }
             }
 
@@ -345,7 +351,8 @@ public class InvoiceServices {
                 // for purchase orders, the pay to address is the BILLING_LOCATION of the vendor
                 GenericValue billFromVendor = orh.getPartyFromRole("BILL_FROM_VENDOR");
                 if (billFromVendor != null) {
-                    List<GenericValue> billingContactMechs = billFromVendor.getRelatedOne("Party", false).getRelated("PartyContactMechPurpose", UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false);
+                    List<GenericValue> billingContactMechs = billFromVendor.getRelatedOne("Party", false).getRelated("PartyContactMechPurpose",
+                            UtilMisc.toMap("contactMechPurposeTypeId", "BILLING_LOCATION"), null, false);
                     if (UtilValidate.isNotEmpty(billingContactMechs)) {
                         payToAddress = EntityUtil.getFirst(EntityUtil.filterByDate(billingContactMechs));
                     }
@@ -355,8 +362,9 @@ public class InvoiceServices {
                 payToAddress = PaymentWorker.getPaymentAddress(delegator, productStore.getString("payToPartyId"));
             }
             if (payToAddress != null) {
-                Map<String, Object> createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString("contactMechId"),
-                                                                   "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin);
+                Map<String, Object> createPayToContactMechContext = UtilMisc.toMap("invoiceId", invoiceId, "contactMechId", payToAddress.getString(
+                        "contactMechId"),
+                        "contactMechPurposeTypeId", "PAYMENT_LOCATION", "userLogin", userLogin);
                 Map<String, Object> createPayToContactMechResult = dispatcher.runSync("createInvoiceContactMech", createPayToContactMechContext);
                 if (ServiceUtil.isError(createPayToContactMechResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -430,14 +438,16 @@ public class InvoiceServices {
                 }
 
                 BigDecimal billingAmount = BigDecimal.ZERO;
-                GenericValue OrderAdjustment = EntityUtil.getFirst(orderItem.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", "VAT_TAX"), null, false));
+                GenericValue OrderAdjustment = EntityUtil.getFirst(orderItem.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId",
+                        "VAT_TAX"), null, false));
                 /* Apply formula to get actual product price to set amount in invoice item
                     Formula is: productPrice = (productPriceWithTax.multiply(100)) / (orderAdj sourcePercentage + 100))
                     product price = (43*100) / (20+100) = 35.83 (Here product price is 43 with VAT)
                  */
                 if (UtilValidate.isNotEmpty(OrderAdjustment) && (OrderAdjustment.getBigDecimal("amount").signum() == 0) && UtilValidate.isNotEmpty(OrderAdjustment.getBigDecimal("amountAlreadyIncluded")) && OrderAdjustment.getBigDecimal("amountAlreadyIncluded").signum() != 0) {
                     BigDecimal sourcePercentageTotal = OrderAdjustment.getBigDecimal("sourcePercentage").add(new BigDecimal(100));
-                    billingAmount = orderItem.getBigDecimal("unitPrice").divide(sourcePercentageTotal, 100, ROUNDING).multiply(new BigDecimal(100)).setScale(invoiceTypeDecimals, ROUNDING);
+                    billingAmount =
+                            orderItem.getBigDecimal("unitPrice").divide(sourcePercentageTotal, 100, ROUNDING).multiply(new BigDecimal(100)).setScale(invoiceTypeDecimals, ROUNDING);
                 } else {
                     billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING);
                 }
@@ -445,7 +455,8 @@ public class InvoiceServices {
                 Map<String, Object> createInvoiceItemContext = new HashMap<>();
                 createInvoiceItemContext.put("invoiceId", invoiceId);
                 createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")), (product == null ? null : product.getString("productTypeId")), invoiceType, "INV_FPROD_ITEM"));
+                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, (orderItem.getString("orderItemTypeId")),
+                        (product == null ? null : product.getString("productTypeId")), invoiceType, "INV_FPROD_ITEM"));
                 createInvoiceItemContext.put("description", orderItem.get("itemDescription"));
                 createInvoiceItemContext.put("quantity", billingQuantity);
                 createInvoiceItemContext.put("amount", billingAmount);
@@ -511,7 +522,8 @@ public class InvoiceServices {
                        In that case ShipmentItemBilling was creating only for one invoice item. Fixed under OFBIZ-6806.
                     */
                     List<GenericValue> shipmentItemBillings = EntityQuery.use(delegator).from("ShipmentItemBilling")
-                            .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId", currentValue.get("shipmentItemSeqId"), "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId)
+                            .where("shipmentId", currentValue.get("shipmentId"), "shipmentItemSeqId", currentValue.get("shipmentItemSeqId"),
+                                    "invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId)
                             .queryList();
                     if (UtilValidate.isEmpty(shipmentItemBillings)) {
 
@@ -535,7 +547,8 @@ public class InvoiceServices {
                 invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
 
                 // Get the original order item from the DB, in case the quantity has been overridden
-                GenericValue originalOrderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", orderItem.get("orderItemSeqId")).queryOne();
+                GenericValue originalOrderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId",
+                        orderItem.get("orderItemSeqId")).queryOne();
 
                 // create the item adjustment as line items
                 List<GenericValue> itemAdjustments = OrderReadHelper.getOrderItemAdjustmentList(orderItem, orh.getAdjustments());
@@ -544,11 +557,12 @@ public class InvoiceServices {
                     // Check against OrderAdjustmentBilling to see how much of this adjustment has already been invoiced
                     BigDecimal adjAlreadyInvoicedAmount = null;
                     try {
-                        Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj));
+                        Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment",
+                                adj));
                         if (ServiceUtil.isError(checkResult)) {
                             Debug.logError("Accounting trouble calling calculateInvoicedAdjustmentTotal service", MODULE);
                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                                "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
+                                    "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
                         }
                         adjAlreadyInvoicedAmount = (BigDecimal) checkResult.get("invoicedTotal");
                     } catch (GenericServiceException e) {
@@ -558,12 +572,15 @@ public class InvoiceServices {
                     }
 
                     // Set adjustment amount as amountAlreadyIncluded to continue invoice item creation process
-                    Boolean isTaxIncludedInPrice = "VAT_TAX".equals(adj.getString("orderAdjustmentTypeId")) && UtilValidate.isNotEmpty(adj.getBigDecimal("amountAlreadyIncluded")) && adj.getBigDecimal("amountAlreadyIncluded").signum() != 0;
+                    Boolean isTaxIncludedInPrice =
+                            "VAT_TAX".equals(adj.getString("orderAdjustmentTypeId")) && UtilValidate.isNotEmpty(adj.getBigDecimal("amountAlreadyIncluded")) && adj.getBigDecimal("amountAlreadyIncluded").signum() != 0;
                     if (isTaxIncludedInPrice && (adj.getBigDecimal("amount").signum() == 0)) {
                         adj.set("amount", adj.getBigDecimal("amountAlreadyIncluded"));
                     }
-                    // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this adjustment
-                    if (isTaxIncludedInPrice && adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) > 0) {
+                    // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this
+                    // adjustment
+                    if (isTaxIncludedInPrice && adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals,
+                            ROUNDING).abs()) > 0) {
                         continue;
                     }
 
@@ -571,52 +588,61 @@ public class InvoiceServices {
                     BigDecimal amount = BigDecimal.ZERO;
                     if (originalOrderItemQuantity.signum() != 0) {
                         if (adj.get("amount") != null) {
-                                if ("PROMOTION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId")) && adj.get("productPromoId") != null) {
+                            if ("PROMOTION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId")) && adj.get("productPromoId") != null) {
                                     /* Find negative amountAlreadyIncluded in OrderAdjustment to subtract it from discounted amount.
-                                                                          As we stored negative sales tax amount in order adjustment for discounted item.
+                                                                          As we stored negative sales tax amount in order adjustment for discounted
+                                                                           item.
                                      */
-                                    List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItem.getString("orderId")),
-                                            EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.getString("orderItemSeqId")),
-                                            EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "VAT_TAX"),
-                                            EntityCondition.makeCondition("amountAlreadyIncluded", EntityOperator.LESS_THAN, BigDecimal.ZERO));
-                                    EntityCondition andCondition = EntityCondition.makeCondition(exprs, EntityOperator.AND);
-                                    GenericValue orderAdjustment = EntityUtil.getFirst(delegator.findList("OrderAdjustment", andCondition, null, null, null, false));
-                                    if (UtilValidate.isNotEmpty(orderAdjustment)) {
-                                        amount = adj.getBigDecimal("amount").subtract(orderAdjustment.getBigDecimal("amountAlreadyIncluded")).setScale(100, ROUNDING);
-                                    } else {
-                                        amount = adj.getBigDecimal("amount");
-                                    }
+                                List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("orderId", EntityOperator.EQUALS,
+                                        orderItem.getString("orderId")),
+                                        EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItem.getString("orderItemSeqId")),
+                                        EntityCondition.makeCondition("orderAdjustmentTypeId", EntityOperator.EQUALS, "VAT_TAX"),
+                                        EntityCondition.makeCondition("amountAlreadyIncluded", EntityOperator.LESS_THAN, BigDecimal.ZERO));
+                                EntityCondition andCondition = EntityCondition.makeCondition(exprs, EntityOperator.AND);
+                                GenericValue orderAdjustment = EntityUtil.getFirst(delegator.findList("OrderAdjustment", andCondition, null, null,
+                                        null, false));
+                                if (UtilValidate.isNotEmpty(orderAdjustment)) {
+                                    amount =
+                                            adj.getBigDecimal("amount").subtract(orderAdjustment.getBigDecimal("amountAlreadyIncluded")).setScale(100,
+                                                    ROUNDING);
                                 } else {
-                                    // pro-rate the amount
-                                    // set decimals = 100 means we don't round this intermediate value, which is very important
-                                    if (isTaxIncludedInPrice) {
-                                        BigDecimal priceWithTax = originalOrderItem.getBigDecimal("unitPrice");
-                                        // Get tax included in item price
-                                        amount = priceWithTax.subtract(billingAmount);
-                                        amount = amount.multiply(billingQuantity);
-                                        // get adjustment amount
-                                        /* Get tax amount of other invoice and calculate remaining amount need to store in invoice item(Handle case of of partial shipment and promotional item)
+                                    amount = adj.getBigDecimal("amount");
+                                }
+                            } else {
+                                // pro-rate the amount
+                                // set decimals = 100 means we don't round this intermediate value, which is very important
+                                if (isTaxIncludedInPrice) {
+                                    BigDecimal priceWithTax = originalOrderItem.getBigDecimal("unitPrice");
+                                    // Get tax included in item price
+                                    amount = priceWithTax.subtract(billingAmount);
+                                    amount = amount.multiply(billingQuantity);
+                                    // get adjustment amount
+                                        /* Get tax amount of other invoice and calculate remaining amount need to store in invoice item(Handle case
+                                         of of partial shipment and promotional item)
                                                                               to adjust tax amount in invoice item.
                                          */
-                                        BigDecimal otherInvoiceTaxAmount = BigDecimal.ZERO;
-                                        GenericValue orderAdjBilling = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where("orderAdjustmentId", adj.getString("orderAdjustmentId")).queryFirst();
-                                        if (UtilValidate.isNotEmpty(orderAdjBilling)) {
-                                            //FIXME: Need to check here isTaxIncludedInPrice pass to use cache
-                                            List<GenericValue> invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", orderAdjBilling.getString("invoiceId"), "invoiceItemTypeId", "ITM_SALES_TAX", "productId", originalOrderItem.getString("productId")).cache(isTaxIncludedInPrice).queryList();
-                                            for (GenericValue invoiceItem : invoiceItems) {
-                                                otherInvoiceTaxAmount = otherInvoiceTaxAmount.add(invoiceItem.getBigDecimal("amount"));
-                                            }
-                                            if (otherInvoiceTaxAmount.compareTo(BigDecimal.ZERO) > 0) {
-                                                BigDecimal remainingAmount = adj.getBigDecimal("amountAlreadyIncluded").subtract(otherInvoiceTaxAmount);
-                                                amount = amount.min(remainingAmount);
-                                            }
+                                    BigDecimal otherInvoiceTaxAmount = BigDecimal.ZERO;
+                                    GenericValue orderAdjBilling = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where(
+                                            "orderAdjustmentId", adj.getString("orderAdjustmentId")).queryFirst();
+                                    if (UtilValidate.isNotEmpty(orderAdjBilling)) {
+                                        //FIXME: Need to check here isTaxIncludedInPrice pass to use cache
+                                        List<GenericValue> invoiceItems = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId",
+                                                orderAdjBilling.getString("invoiceId"), "invoiceItemTypeId", "ITM_SALES_TAX", "productId",
+                                                originalOrderItem.getString("productId")).cache(isTaxIncludedInPrice).queryList();
+                                        for (GenericValue invoiceItem : invoiceItems) {
+                                            otherInvoiceTaxAmount = otherInvoiceTaxAmount.add(invoiceItem.getBigDecimal("amount"));
+                                        }
+                                        if (otherInvoiceTaxAmount.compareTo(BigDecimal.ZERO) > 0) {
+                                            BigDecimal remainingAmount = adj.getBigDecimal("amountAlreadyIncluded").subtract(otherInvoiceTaxAmount);
+                                            amount = amount.min(remainingAmount);
                                         }
-                                        amount = amount.min(adj.getBigDecimal("amountAlreadyIncluded")).setScale(100, ROUNDING);
-                                    } else {
-                                        amount = adj.getBigDecimal("amount").divide(originalOrderItemQuantity, 100, ROUNDING);
-                                        amount = amount.multiply(billingQuantity);
                                     }
+                                    amount = amount.min(adj.getBigDecimal("amountAlreadyIncluded")).setScale(100, ROUNDING);
+                                } else {
+                                    amount = adj.getBigDecimal("amount").divide(originalOrderItemQuantity, 100, ROUNDING);
+                                    amount = amount.multiply(billingQuantity);
                                 }
+                            }
                             // Tax needs to be rounded differently from other order adjustments
                             if ("SALES_TAX".equals(adj.getString("orderAdjustmentTypeId"))) {
                                 amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING);
@@ -638,7 +664,8 @@ public class InvoiceServices {
                         Map<String, Object> createInvoiceItemAdjContext = new HashMap<>();
                         createInvoiceItemAdjContext.put("invoiceId", invoiceId);
                         createInvoiceItemAdjContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                        createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceType, "INVOICE_ITM_ADJ"));
+                        createInvoiceItemAdjContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"),
+                                null, invoiceType, "INVOICE_ITM_ADJ"));
                         createInvoiceItemAdjContext.put("quantity", BigDecimal.ONE);
                         createInvoiceItemAdjContext.put("amount", amount);
                         createInvoiceItemAdjContext.put("productId", orderItem.get("productId"));
@@ -652,7 +679,8 @@ public class InvoiceServices {
                         createInvoiceItemAdjContext.put("taxAuthorityRateSeqId", adj.get("taxAuthorityRateSeqId"));
 
                         // some adjustments fill out the comments field instead
-                        String description = (UtilValidate.isEmpty(adj.getString("description")) ? adj.getString("comments") : adj.getString("description"));
+                        String description = (UtilValidate.isEmpty(adj.getString("description")) ? adj.getString("comments") : adj.getString(
+                                "description"));
                         createInvoiceItemAdjContext.put("description", description);
 
                         // invoice items for sales tax are not taxable themselves
@@ -690,10 +718,12 @@ public class InvoiceServices {
                         createOrderAdjustmentBillingContext.put("amount", amount);
                         createOrderAdjustmentBillingContext.put("userLogin", userLogin);
 
-                        Map<String, Object> createOrderAdjustmentBillingResult = dispatcher.runSync("createOrderAdjustmentBilling", createOrderAdjustmentBillingContext);
+                        Map<String, Object> createOrderAdjustmentBillingResult = dispatcher.runSync("createOrderAdjustmentBilling",
+                                createOrderAdjustmentBillingContext);
                         if (ServiceUtil.isError(createOrderAdjustmentBillingResult)) {
                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                                    "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale), null, null, createOrderAdjustmentBillingContext);
+                                    "AccountingErrorCreatingOrderAdjustmentBillingFromOrder", locale), null, null,
+                                    createOrderAdjustmentBillingContext);
                         }
 
                         // this adjustment amount
@@ -731,7 +761,7 @@ public class InvoiceServices {
                     Map<String, Object> checkResult = dispatcher.runSync("calculateInvoicedAdjustmentTotal", UtilMisc.toMap("orderAdjustment", adj));
                     if (ServiceUtil.isError(checkResult)) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                            "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
+                                "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
                     }
                     adjAlreadyInvoicedAmount = ((BigDecimal) checkResult.get("invoicedTotal")).setScale(invoiceTypeDecimals, ROUNDING);
                 } catch (GenericServiceException e) {
@@ -740,7 +770,8 @@ public class InvoiceServices {
                             "AccountingTroubleCallingCalculateInvoicedAdjustmentTotalService", locale));
                 }
 
-                // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this adjustment
+                // If the absolute invoiced amount >= the abs of the adjustment amount, the full amount has already been invoiced, so skip this
+                // adjustment
                 if (adjAlreadyInvoicedAmount.abs().compareTo(adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING).abs()) >= 0) {
                     continue;
                 }
@@ -762,7 +793,8 @@ public class InvoiceServices {
                     }
 
                     calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId, divisor, multiplier,
-                            adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING), invoiceTypeDecimals, ROUNDING, userLogin, dispatcher, locale);
+                            adj.getBigDecimal("amount").setScale(invoiceTypeDecimals, ROUNDING), invoiceTypeDecimals, ROUNDING, userLogin,
+                            dispatcher, locale);
                     // invoiceShipProRateAmount += adjAmount;
                     // do adjustments compound or are they based off subtotal? Here we will (unless commented)
                     // invoiceSubTotal += adjAmount;
@@ -773,7 +805,8 @@ public class InvoiceServices {
                 }
             }
 
-            // next do the shipping adjustments.  Note that we do not want to add these to the invoiceSubTotal or orderSubTotal for pro-rating tax later, as that would cause
+            // next do the shipping adjustments.  Note that we do not want to add these to the invoiceSubTotal or orderSubTotal for pro-rating tax
+            // later, as that would cause
             // numerator/denominator problems when the shipping is not pro-rated but rather charged all on the first invoice
             for (Map.Entry<GenericValue, BigDecimal> set : shipAdjustments.entrySet()) {
                 BigDecimal adjAlreadyInvoicedAmount = set.getValue();
@@ -833,7 +866,7 @@ public class InvoiceServices {
                     //  it won't be prorated
                     BigDecimal baseAmount = adj.getBigDecimal("amount").setScale(TAX_DECIMALS, TAX_ROUNDING).subtract(adjAlreadyInvoicedAmount);
                     adjAmount = calcHeaderAdj(delegator, adj, invoiceType, invoiceId, invoiceItemSeqId,
-                             divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale);
+                            divisor, multiplier, baseAmount, TAX_DECIMALS, TAX_ROUNDING, userLogin, dispatcher, locale);
                 } else {
 
                     // Pro-rate the tax amount based on shippable information
@@ -882,11 +915,13 @@ public class InvoiceServices {
                 }
             }
 
-            // Should all be in place now. Depending on the ProductStore.autoApproveInvoice setting, set status to INVOICE_READY (unless it's a purchase invoice, which we set to INVOICE_IN_PROCESS)
+            // Should all be in place now. Depending on the ProductStore.autoApproveInvoice setting, set status to INVOICE_READY (unless it's a
+            // purchase invoice, which we set to INVOICE_IN_PROCESS)
             String autoApproveInvoice = productStore != null ? productStore.getString("autoApproveInvoice") : "Y";
             if (!"N".equals(autoApproveInvoice)) {
                 String nextStatusId = "PURCHASE_INVOICE".equals(invoiceType) ? "INVOICE_IN_PROCESS" : "INVOICE_READY";
-                Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
+                Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId",
+                        invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
                 if (ServiceUtil.isError(setInvoiceStatusResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                             "AccountingErrorCreatingInvoiceFromOrder", locale), null, null, setInvoiceStatusResult);
@@ -923,7 +958,8 @@ public class InvoiceServices {
             List<String> salesRepPartyIds = UtilGenerics.cast(context.get("partyIds"));
             BigDecimal amountTotal = InvoiceWorker.getInvoiceTotal(delegator, salesInvoiceId);
             if (amountTotal.signum() == 0) {
-                Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be created", MODULE);
+                Debug.logWarning("Invoice [" + salesInvoiceId + "] has an amount total of [" + amountTotal + "], so no commission invoice will be " +
+                        "created", MODULE);
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                         "AccountingInvoiceCommissionZeroInvoiceAmount", locale));
             }
@@ -947,10 +983,11 @@ public class InvoiceServices {
                     salesRepPartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
                     if (UtilValidate.isEmpty(salesRepPartyIds)) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                        "No party found with role sales representative for sales invoice "+ salesInvoiceId, locale));
+                                "No party found with role sales representative for sales invoice " + salesInvoiceId, locale));
                     }
                 } else {
-                    List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(), "partyId", true);
+                    List<String> salesInvoiceRolePartyIds = EntityUtil.getFieldListFromEntityList(roleQuery.where(invoiceRoleConds).queryList(),
+                            "partyId", true);
                     if (UtilValidate.isNotEmpty(salesInvoiceRolePartyIds)) {
                         salesRepPartyIds = UtilGenerics.cast(CollectionUtils.intersection(salesRepPartyIds, salesInvoiceRolePartyIds));
                     }
@@ -1053,7 +1090,7 @@ public class InvoiceServices {
                 createInvoiceResult = dispatcher.runSync("createInvoice", createInvoiceMap);
                 if (ServiceUtil.isError(createInvoiceResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                        "AccountingInvoiceCommissionError", locale), null, null, null);
+                            "AccountingInvoiceCommissionError", locale), null, null, null);
                 }
             } catch (GenericServiceException e) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -1154,7 +1191,8 @@ public class InvoiceServices {
         String nextStatusId = "INVOICE_READY";
         try {
             for (String invoiceId : invoicesCreated) {
-                Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
+                Map<String, Object> setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId",
+                        invoiceId, "statusId", nextStatusId, "userLogin", userLogin));
                 if (ServiceUtil.isError(setInvoiceStatusResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                             "AccountingInvoiceCommissionError", locale), null, null, setInvoiceStatusResult);
@@ -1203,17 +1241,19 @@ public class InvoiceServices {
         }
 
         if ("Y".equals(invoicePerShipment)) {
-            Map<String, Object> serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin"));
+            Map<String, Object> serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "eventDate", context.get("eventDate"),
+                    "userLogin", context.get("userLogin"));
             try {
                 Map<String, Object> result = dispatcher.runSync("createInvoicesFromShipments", serviceContext);
                 if (ServiceUtil.isError(result)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                        "AccountingTroubleCallingCreateInvoicesFromShipmentService",
-                        UtilMisc.toMap("shipmentId", shipmentId), locale));
+                            "AccountingTroubleCallingCreateInvoicesFromShipmentService",
+                            UtilMisc.toMap("shipmentId", shipmentId), locale));
                 }
                 invoicesCreated = UtilGenerics.cast(result.get("invoicesCreated"));
             } catch (GenericServiceException e) {
-                Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment [" + shipmentId + "]", MODULE);
+                Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment [" + shipmentId + "]",
+                        MODULE);
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                         "AccountingTroubleCallingCreateInvoicesFromShipmentService",
                         UtilMisc.toMap("shipmentId", shipmentId), locale));
@@ -1298,12 +1338,13 @@ public class InvoiceServices {
             }
         }
 
-     // For In-Process invoice, move the status to ready and capture the payment
+        // For In-Process invoice, move the status to ready and capture the payment
         for (GenericValue invoice : ordersWithInProcessInvoice.values()) {
             String invoiceId = invoice.getString("invoiceId");
             Map<String, Object> setInvoiceStatusResult;
             try {
-                setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin));
+                setInvoiceStatusResult = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId",
+                        "INVOICE_READY", "userLogin", userLogin));
             } catch (GenericServiceException e) {
                 Debug.logError(e, MODULE);
                 return ServiceUtil.returnError(e.getMessage());
@@ -1321,15 +1362,16 @@ public class InvoiceServices {
         String shipmentId = (String) context.get("shipmentId");
         Locale locale = (Locale) context.get("locale");
 
-        Map<String, Object> serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "createSalesInvoicesForDropShipments", Boolean.TRUE, "userLogin", context.get("userLogin"));
+        Map<String, Object> serviceContext = UtilMisc.toMap("shipmentIds", UtilMisc.toList(shipmentId), "createSalesInvoicesForDropShipments",
+                Boolean.TRUE, "userLogin", context.get("userLogin"));
 
         Map<String, Object> serviceResult;
         try {
             serviceResult = dispatcher.runSync("createInvoicesFromShipments", serviceContext);
             if (ServiceUtil.isError(serviceResult)) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                    "AccountingTroubleCallingCreateInvoicesFromShipmentService",
-                    UtilMisc.toMap("shipmentId", shipmentId), locale));
+                        "AccountingTroubleCallingCreateInvoicesFromShipmentService",
+                        UtilMisc.toMap("shipmentId", shipmentId), locale));
             }
         } catch (GenericServiceException e) {
             Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId, MODULE);
@@ -1381,7 +1423,8 @@ public class InvoiceServices {
                         UtilMisc.toMap("tmpShipmentId", tmpShipmentId), locale));
             }
         }
-        EntityQuery shipmentQuery = EntityQuery.use(delegator).where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, shipmentIds)).orderBy("shipmentId");
+        EntityQuery shipmentQuery =
+                EntityQuery.use(delegator).where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, shipmentIds)).orderBy("shipmentId");
         // check the status of the shipment
 
         // get the items of the shipment.  They can come from ItemIssuance if the shipment were from a sales order, ShipmentReceipt
@@ -1391,7 +1434,8 @@ public class InvoiceServices {
         try {
             if (purchaseShipmentFound) {
                 items = shipmentQuery.from("ShipmentReceipt").queryList();
-                // filter out items which have been received but are not actually owned by an internal organization, so they should not be on a purchase invoice
+                // filter out items which have been received but are not actually owned by an internal organization, so they should not be on a
+                // purchase invoice
                 Iterator<GenericValue> itemsIter = items.iterator();
                 while (itemsIter.hasNext()) {
                     GenericValue item = itemsIter.next();
@@ -1523,7 +1567,8 @@ public class InvoiceServices {
                         if (dropShipmentFound && createSalesInvoicesForDropShipments) {
 
                             // Override the issueQty with the quantity from the purchase order item
-                            GenericValue orderItemAssoc = EntityUtil.getFirst(EntityUtil.filterByAnd(orderItemAssocs, UtilMisc.toMap("orderId", issue.getString("orderId"), "orderItemSeqId", issue.getString("orderItemSeqId"))));
+                            GenericValue orderItemAssoc = EntityUtil.getFirst(EntityUtil.filterByAnd(orderItemAssocs, UtilMisc.toMap("orderId",
+                                    issue.getString("orderId"), "orderItemSeqId", issue.getString("orderItemSeqId"))));
                             GenericValue purchaseOrderItem = orderItemAssoc.getRelatedOne("ToOrderItem", false);
                             orderItem.set("quantity", purchaseOrderItem.getBigDecimal("quantity"));
                             issueQty = purchaseOrderItem.getBigDecimal("quantity");
@@ -1600,9 +1645,11 @@ public class InvoiceServices {
                             // Get the IDs for orders which have billable items
                             List<String> invoiceableLinkedOrderIds = EntityUtil.getFieldListFromEntityList(toBillItems, "orderId", true);
 
-                            // Get back the IDs of the purchase orders - this will be a list of the purchase order items which are billable by virtue of not having been
+                            // Get back the IDs of the purchase orders - this will be a list of the purchase order items which are billable by
+                            // virtue of not having been
                             //  invoiced in a previous sales invoice
-                            List<GenericValue> reverseOrderItemAssocs = EntityUtil.filterByCondition(orderItemAssocs, EntityCondition.makeCondition("orderId", EntityOperator.IN, invoiceableLinkedOrderIds));
+                            List<GenericValue> reverseOrderItemAssocs = EntityUtil.filterByCondition(orderItemAssocs,
+                                    EntityCondition.makeCondition("orderId", EntityOperator.IN, invoiceableLinkedOrderIds));
                             invoiceablePrimaryOrderIds = EntityUtil.getFieldListFromEntityList(reverseOrderItemAssocs, "toOrderId", true);
 
                         } else {
@@ -1622,7 +1669,8 @@ public class InvoiceServices {
                     } else {
                         List<String> invoiceableShipmentIds = EntityUtil.getFieldListFromEntityList(toBillItems, "shipmentId", true);
                         if (UtilValidate.isNotEmpty(invoiceableShipmentIds)) {
-                            invoiceableShipments = EntityQuery.use(delegator).from("Shipment").where(EntityCondition.makeCondition("shipmentId", EntityOperator.IN, invoiceableShipmentIds)).queryList();
+                            invoiceableShipments = EntityQuery.use(delegator).from("Shipment").where(EntityCondition.makeCondition("shipmentId",
+                                    EntityOperator.IN, invoiceableShipmentIds)).queryList();
                         }
                     }
                 } catch (GenericEntityException e) {
@@ -1639,7 +1687,8 @@ public class InvoiceServices {
                         if (shipment.get("additionalShippingCharge") == null) {
                             continue;
                         }
-                        BigDecimal shipmentAdditionalShippingCharges = shipment.getBigDecimal("additionalShippingCharge").setScale(DECIMALS, ROUNDING);
+                        BigDecimal shipmentAdditionalShippingCharges = shipment.getBigDecimal("additionalShippingCharge").setScale(DECIMALS,
+                                ROUNDING);
                         additionalShippingCharges.put(shipment, shipmentAdditionalShippingCharges);
                         totalAdditionalShippingCharges = totalAdditionalShippingCharges.add(shipmentAdditionalShippingCharges);
                     }
@@ -1658,7 +1707,8 @@ public class InvoiceServices {
                         createOrderAdjustmentContext.put("orderAdjustmentTypeId", "SHIPPING_CHARGES");
                         String addtlChargeDescription = shipment.getString("addtlShippingChargeDesc");
                         if (UtilValidate.isEmpty(addtlChargeDescription)) {
-                            addtlChargeDescription = UtilProperties.getMessage(RESOURCE, "AccountingAdditionalShippingChargeForShipment", UtilMisc.toMap("shipmentId", shipmentId), locale);
+                            addtlChargeDescription = UtilProperties.getMessage(RESOURCE, "AccountingAdditionalShippingChargeForShipment",
+                                    UtilMisc.toMap("shipmentId", shipmentId), locale);
                         }
                         createOrderAdjustmentContext.put("description", addtlChargeDescription);
                         createOrderAdjustmentContext.put("sourceReferenceId", shipmentId);
@@ -1666,7 +1716,8 @@ public class InvoiceServices {
                         createOrderAdjustmentContext.put("userLogin", context.get("userLogin"));
                         String shippingOrderAdjustmentId = null;
                         try {
-                            Map<String, Object> createOrderAdjustmentResult = dispatcher.runSync("createOrderAdjustment", createOrderAdjustmentContext);
+                            Map<String, Object> createOrderAdjustmentResult = dispatcher.runSync("createOrderAdjustment",
+                                    createOrderAdjustmentContext);
                             if (ServiceUtil.isError(createOrderAdjustmentResult)) {
                                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(createOrderAdjustmentResult));
                             }
@@ -1684,7 +1735,8 @@ public class InvoiceServices {
                         try {
                             destinationContactMech = shipment.getRelatedOne("DestinationPostalAddress", false);
                         } catch (GenericEntityException e) {
-                            Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId, MODULE);
+                            Debug.logError(e, "Trouble calling createInvoicesFromShipment service; invoice not created for shipment " + shipmentId,
+                                    MODULE);
                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
                                     "AccountingTroubleCallingCreateInvoicesFromShipmentService", locale));
                         }
@@ -1709,7 +1761,7 @@ public class InvoiceServices {
                             calcTaxResult = dispatcher.runSync("calcTax", calcTaxContext);
                             if (ServiceUtil.isError(calcTaxResult)) {
                                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                                    "AccountingTroubleCallingCalcTaxService", locale));
+                                        "AccountingTroubleCallingCalcTaxService", locale));
                             }
                         } catch (GenericServiceException e) {
                             Debug.logError(e, "Trouble calling calcTaxService", MODULE);
@@ -1721,7 +1773,8 @@ public class InvoiceServices {
                         // If we have any OrderAdjustments due to tax on shipping, store them and add them to the total
                         if (orderAdjustments != null) {
                             for (GenericValue orderAdjustment : orderAdjustments) {
-                                totalAdditionalShippingCharges = totalAdditionalShippingCharges.add(orderAdjustment.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
+                                totalAdditionalShippingCharges =
+                                        totalAdditionalShippingCharges.add(orderAdjustment.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
                                 orderAdjustment.set("orderAdjustmentId", delegator.getNextSeqId("OrderAdjustment"));
                                 orderAdjustment.set("orderId", orderId);
                                 orderAdjustment.set("orderItemSeqId", "_NA_");
@@ -1768,12 +1821,15 @@ public class InvoiceServices {
                                     if (authTransaction != null && authTransaction.get("amount") != null) {
 
                                         // Update the total authorized amount
-                                        totalNewAuthAmount = totalNewAuthAmount.add(authTransaction.getBigDecimal("amount").setScale(DECIMALS, ROUNDING));
+                                        totalNewAuthAmount = totalNewAuthAmount.add(authTransaction.getBigDecimal("amount").setScale(DECIMALS,
+                                                ROUNDING));
 
                                         // Release the authorization for the OrderPaymentPreference
                                         Map<String, Object> prefReleaseResult = null;
                                         try {
-                                            prefReleaseResult = dispatcher.runSync("releaseOrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), "userLogin", context.get("userLogin")));
+                                            prefReleaseResult = dispatcher.runSync("releaseOrderPaymentPreference", UtilMisc.toMap(
+                                                    "orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"),
+                                                    "userLogin", context.get("userLogin")));
                                         } catch (GenericServiceException e) {
                                             Debug.logError(e, "Trouble calling releaseOrderPaymentPreference service", MODULE);
                                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -1790,13 +1846,14 @@ public class InvoiceServices {
 
                             // Create a new OrderPaymentPreference for the order to handle the new (totalled) charge. Don't
                             //  set the maxAmount so that it doesn't interfere with other authorizations
-                            Map<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "paymentMethodId", paymentMethodId, "paymentMethodTypeId", "CREDIT_CARD", "userLogin", context.get("userLogin"));
+                            Map<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "paymentMethodId", paymentMethodId,
+                                    "paymentMethodTypeId", "CREDIT_CARD", "userLogin", context.get("userLogin"));
                             String orderPaymentPreferenceId = null;
                             try {
                                 Map<String, Object> result = dispatcher.runSync("createOrderPaymentPreference", serviceContext);
                                 if (ServiceUtil.isError(result)) {
                                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                                        "AccountingTroubleCallingCreateOrderPaymentPreferenceService", locale));
+                                            "AccountingTroubleCallingCreateOrderPaymentPreferenceService", locale));
                                 }
                                 orderPaymentPreferenceId = (String) result.get("orderPaymentPreferenceId");
                             } catch (GenericServiceException e) {
@@ -1809,10 +1866,11 @@ public class InvoiceServices {
                             Map<String, Object> authResult = null;
                             try {
                                 // Use an overrideAmount because the maxAmount wasn't set on the OrderPaymentPreference
-                                authResult = dispatcher.runSync("authOrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId", orderPaymentPreferenceId, "overrideAmount", totalNewAuthAmount, "userLogin", context.get("userLogin")));
+                                authResult = dispatcher.runSync("authOrderPaymentPreference", UtilMisc.toMap("orderPaymentPreferenceId",
+                                        orderPaymentPreferenceId, "overrideAmount", totalNewAuthAmount, "userLogin", context.get("userLogin")));
                                 if (ServiceUtil.isError(authResult)) {
                                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                                        "AccountingTroubleCallingAuthOrderPaymentPreferenceService", locale));
+                                            "AccountingTroubleCallingAuthOrderPaymentPreferenceService", locale));
                                 }
                             } catch (GenericServiceException e) {
                                 Debug.logError(e, "Trouble calling authOrderPaymentPreference service", MODULE);
@@ -1824,7 +1882,9 @@ public class InvoiceServices {
                             boolean authFinished = (Boolean) authResult.get("finished");
                             boolean authErrors = (Boolean) authResult.get("errors");
                             if (authErrors || !authFinished) {
-                                String errMsg = UtilProperties.getMessage(RESOURCE, "AccountingUnableToAuthAdditionalShipCharges", UtilMisc.toMap("shipmentId", shipmentId, "paymentMethodId", paymentMethodId, "orderPaymentPreferenceId", orderPaymentPreferenceId), locale);
+                                String errMsg = UtilProperties.getMessage(RESOURCE, "AccountingUnableToAuthAdditionalShipCharges", UtilMisc.toMap(
+                                        "shipmentId", shipmentId, "paymentMethodId", paymentMethodId, "orderPaymentPreferenceId",
+                                        orderPaymentPreferenceId), locale);
                                 Debug.logError(errMsg, MODULE);
                             }
 
@@ -1832,7 +1892,8 @@ public class InvoiceServices {
                     }
                 }
             } else {
-                Debug.logInfo(UtilProperties.getMessage(RESOURCE, "AccountingIgnoringAdditionalShipCharges", UtilMisc.toMap("productStoreId", orh.getProductStoreId()), locale), MODULE);
+                Debug.logInfo(UtilProperties.getMessage(RESOURCE, "AccountingIgnoringAdditionalShipCharges", UtilMisc.toMap("productStoreId",
+                        orh.getProductStoreId()), locale), MODULE);
             }
 
             String invoiceId = null;
@@ -1849,12 +1910,13 @@ public class InvoiceServices {
             }
 
             // call the createInvoiceForOrder service for each order
-            Map<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "billItems", toBillItems, "invoiceId", invoiceId, "eventDate", context.get("eventDate"), "userLogin", context.get("userLogin"));
+            Map<String, Object> serviceContext = UtilMisc.toMap("orderId", orderId, "billItems", toBillItems, "invoiceId", invoiceId, "eventDate",
+                    context.get("eventDate"), "userLogin", context.get("userLogin"));
             try {
                 Map<String, Object> result = dispatcher.runSync("createInvoiceForOrder", serviceContext);
                 if (ServiceUtil.isError(result)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                        "AccountingTroubleCallingCreateInvoiceForOrderService", locale));
+                            "AccountingTroubleCallingCreateInvoiceForOrderService", locale));
                 }
                 invoicesCreated.add((String) result.get("invoiceId"));
             } catch (GenericServiceException e) {
@@ -1873,10 +1935,12 @@ public class InvoiceServices {
         GenericValue itemMap = null;
         try {
             if (UtilValidate.isNotEmpty(key1)) {
-                itemMap = EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key1, "invoiceTypeId", invoiceTypeId).cache().queryOne();
+                itemMap =
+                        EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key1, "invoiceTypeId", invoiceTypeId).cache().queryOne();
             }
             if (itemMap == null && UtilValidate.isNotEmpty(key2)) {
-                itemMap = EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key2, "invoiceTypeId", invoiceTypeId).cache().queryOne();
+                itemMap =
+                        EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key2, "invoiceTypeId", invoiceTypeId).cache().queryOne();
             }
         } catch (GenericEntityException e) {
             Debug.logError(e, "Trouble getting InvoiceItemTypeMap entity record", MODULE);
@@ -1914,10 +1978,11 @@ public class InvoiceServices {
                 purchaseReturnFound = true;
             }
             if (!(salesReturnFound || purchaseReturnFound)) {
-                 return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
-                         "AccountingShipmentNotSalesReturnAndPurchaseReturn", locale));
+                return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
+                        "AccountingShipmentNotSalesReturnAndPurchaseReturn", locale));
             }
-            // get the items of the shipment. They can come from ItemIssuance if the shipment were from a purchase return, ShipmentReceipt if it were from a sales return
+            // get the items of the shipment. They can come from ItemIssuance if the shipment were from a purchase return, ShipmentReceipt if it
+            // were from a sales return
             List<GenericValue> shippedItems = null;
             if (salesReturnFound) {
                 shippedItems = shipment.getRelated("ShipmentReceipt", null, null, false);
@@ -1952,9 +2017,10 @@ public class InvoiceServices {
                             .where("shipmentReceiptId", item.get("receiptId"),
                                     "returnId", returnId,
                                     "returnItemSeqId", item.get("returnItemSeqId"))
-                                    .queryCount();
+                            .queryCount();
                 } else if ("ItemIssuance".equals(item.getEntityName())) {
-                    billingCount = EntityQuery.use(delegator).from("ReturnItemBilling").where("returnId", returnId, "returnItemSeqId", returnItemSeqId).queryCount();
+                    billingCount = EntityQuery.use(delegator).from("ReturnItemBilling").where("returnId", returnId, "returnItemSeqId",
+                            returnItemSeqId).queryCount();
                 }
                 // if there are billings, we have already billed the item, so skip it
                 if (billingCount > 0) {
@@ -2004,9 +2070,10 @@ public class InvoiceServices {
         GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
 
-        String returnId= (String) context.get("returnId");
+        String returnId = (String) context.get("returnId");
         List<GenericValue> billItems = UtilGenerics.cast(context.get("billItems"));
-        String errorMsg = UtilProperties.getMessage(RESOURCE, "AccountingErrorCreatingInvoiceForReturn", UtilMisc.toMap("returnId", returnId), locale);
+        String errorMsg = UtilProperties.getMessage(RESOURCE, "AccountingErrorCreatingInvoiceForReturn", UtilMisc.toMap("returnId", returnId),
+                locale);
         // List invoicesCreated = new ArrayList();
         try {
             String invoiceTypeId;
@@ -2014,7 +2081,7 @@ public class InvoiceServices {
             // get the return header
             GenericValue returnHeader = EntityQuery.use(delegator).from("ReturnHeader").where("returnId", returnId).queryOne();
             if (returnHeader == null || returnHeader.get("returnHeaderTypeId") == null) {
-                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingReturnTypeCannotBeNull", locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingReturnTypeCannotBeNull", locale));
             }
 
             if (returnHeader.getString("returnHeaderTypeId").startsWith("CUSTOMER_")) {
@@ -2057,174 +2124,231 @@ public class InvoiceServices {
 
             Map<String, Object> results = ServiceUtil.returnSuccess();
             if (UtilValidate.isNotEmpty(billItems)) {
-            // set the invoice data
-            Map<String, Object> input = UtilMisc.<String, Object>toMap("invoiceTypeId", invoiceTypeId, "statusId", "INVOICE_IN_PROCESS");
-            input.put("partyId", returnHeader.get("toPartyId"));
-            input.put("partyIdFrom", returnHeader.get("fromPartyId"));
-            input.put("currencyUomId", returnHeader.get("currencyUomId"));
-            input.put("invoiceDate", UtilDateTime.nowTimestamp());
-            input.put("description", description);
-            input.put("billingAccountId", returnHeader.get("billingAccountId"));
-            input.put("userLogin", userLogin);
-
-            // call the service to create the invoice
-            Map<String, Object> serviceResults = dispatcher.runSync("createInvoice", input);
-            if (ServiceUtil.isError(serviceResults)) {
-                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
-            }
-            String invoiceId = (String) serviceResults.get("invoiceId");
-
-            // keep track of the invoice total vs the promised return total (how much the customer promised to return)
-            BigDecimal invoiceTotal = BigDecimal.ZERO;
-            BigDecimal promisedTotal = BigDecimal.ZERO;
-
-            // loop through shipment receipts to create invoice items and return item billings for each item and adjustment
-            int invoiceItemSeqNum = 1;
-            String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
-
-            for (GenericValue item : billItems) {
-                boolean shipmentReceiptFound = false;
-                boolean itemIssuanceFound = false;
-                GenericValue returnItem = null;
-                BigDecimal quantity = BigDecimal.ZERO;
-
-                if ("ShipmentReceipt".equals(item.getEntityName())) {
-                    shipmentReceiptFound = true;
-                } else if ("ItemIssuance".equals(item.getEntityName())) {
-                    itemIssuanceFound = true;
-                } else if ("ReturnItem".equals(item.getEntityName())) {
-                    quantity = item.getBigDecimal("returnQuantity");
-                    returnItem = item;
-                } else {
-                    Debug.logError("Unexpected entity " + item + " of type " + item.getEntityName(), MODULE);
-                }
-                // we need the related return item and product
-                if (shipmentReceiptFound) {
-                    returnItem = item.getRelatedOne("ReturnItem", true);
-                } else if (itemIssuanceFound) {
-                    GenericValue shipmentItem = item.getRelatedOne("ShipmentItem", true);
-                    GenericValue returnItemShipment = EntityUtil.getFirst(shipmentItem.getRelated("ReturnItemShipment", null, null, false));
-                    returnItem = returnItemShipment.getRelatedOne("ReturnItem", true);
-                }
-                if (returnItem == null)
-                 {
-                    continue; // Just to prevent NPE
-                }
-                GenericValue product = returnItem.getRelatedOne("Product", true);
-
-                // extract the return price as a big decimal for convenience
-                BigDecimal returnPrice = returnItem.getBigDecimal("returnPrice");
-
-                // determine invoice item type from the return item type
-                String invoiceItemTypeId = getInvoiceItemType(delegator, returnItem.getString("returnItemTypeId"), null, invoiceTypeId, null);
-                if (invoiceItemTypeId == null) {
-                    return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
-                            "AccountingNoKnownInvoiceItemTypeReturnItemType",
-                            UtilMisc.toMap("returnItemTypeId", returnItem.getString("returnItemTypeId")), locale));
-                }
-                if (shipmentReceiptFound) {
-                    quantity = item.getBigDecimal("quantityAccepted");
-                } else if (itemIssuanceFound) {
-                    quantity = item.getBigDecimal("quantity");
-                }
-
-                // create the invoice item for this shipment receipt
-                input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", quantity);
-                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
-                input.put("amount", returnItem.get("returnPrice"));
-                input.put("productId", returnItem.get("productId"));
-                input.put("taxableFlag", product.get("taxable"));
-                input.put("description", returnItem.get("description"));
-                // TODO: what about the productFeatureId?
+                // set the invoice data
+                Map<String, Object> input = UtilMisc.<String, Object>toMap("invoiceTypeId", invoiceTypeId, "statusId", "INVOICE_IN_PROCESS");
+                input.put("partyId", returnHeader.get("toPartyId"));
+                input.put("partyIdFrom", returnHeader.get("fromPartyId"));
+                input.put("currencyUomId", returnHeader.get("currencyUomId"));
+                input.put("invoiceDate", UtilDateTime.nowTimestamp());
+                input.put("description", description);
+                input.put("billingAccountId", returnHeader.get("billingAccountId"));
                 input.put("userLogin", userLogin);
-                serviceResults = dispatcher.runSync("createInvoiceItem", input);
-                if (ServiceUtil.isError(serviceResults)) {
-                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
-                }
 
-                // copy the return item information into ReturnItemBilling
-                input = UtilMisc.toMap("returnId", returnId, "returnItemSeqId", returnItem.get("returnItemSeqId"),
-                        "invoiceId", invoiceId);
-                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
-                input.put("quantity", quantity);
-                input.put("amount", returnItem.get("returnPrice"));
-                input.put("userLogin", userLogin);
-                if (shipmentReceiptFound) {
-                    input.put("shipmentReceiptId", item.get("receiptId"));
-                }
-                serviceResults = dispatcher.runSync("createReturnItemBilling", input);
+                // call the service to create the invoice
+                Map<String, Object> serviceResults = dispatcher.runSync("createInvoice", input);
                 if (ServiceUtil.isError(serviceResults)) {
                     return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
                 }
-                if (Debug.verboseOn()) {
-                    Debug.logVerbose("Creating Invoice Item with amount " + returnPrice + " and quantity " + quantity
-                            + " for shipment [" + item.getString("shipmentId") + ":" + item.getString("shipmentItemSeqId") + "]", MODULE);
-                }
+                String invoiceId = (String) serviceResults.get("invoiceId");
+
+                // keep track of the invoice total vs the promised return total (how much the customer promised to return)
+                BigDecimal invoiceTotal = BigDecimal.ZERO;
+                BigDecimal promisedTotal = BigDecimal.ZERO;
+
+                // loop through shipment receipts to create invoice items and return item billings for each item and adjustment
+                int invoiceItemSeqNum = 1;
+                String invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
+
+                for (GenericValue item : billItems) {
+                    boolean shipmentReceiptFound = false;
+                    boolean itemIssuanceFound = false;
+                    GenericValue returnItem = null;
+                    BigDecimal quantity = BigDecimal.ZERO;
+
+                    if ("ShipmentReceipt".equals(item.getEntityName())) {
+                        shipmentReceiptFound = true;
+                    } else if ("ItemIssuance".equals(item.getEntityName())) {
+                        itemIssuanceFound = true;
+                    } else if ("ReturnItem".equals(item.getEntityName())) {
+                        quantity = item.getBigDecimal("returnQuantity");
+                        returnItem = item;
+                    } else {
+                        Debug.logError("Unexpected entity " + item + " of type " + item.getEntityName(), MODULE);
+                    }
+                    // we need the related return item and product
+                    if (shipmentReceiptFound) {
+                        returnItem = item.getRelatedOne("ReturnItem", true);
+                    } else if (itemIssuanceFound) {
+                        GenericValue shipmentItem = item.getRelatedOne("ShipmentItem", true);
+                        GenericValue returnItemShipment = EntityUtil.getFirst(shipmentItem.getRelated("ReturnItemShipment", null, null, false));
+                        returnItem = returnItemShipment.getRelatedOne("ReturnItem", true);
+                    }
+                    if (returnItem == null) {
+                        continue; // Just to prevent NPE
+                    }
+                    GenericValue product = returnItem.getRelatedOne("Product", true);
 
-                String parentInvoiceItemSeqId = invoiceItemSeqId;
-                // increment the seqId counter after creating the invoice item and return item billing
-                invoiceItemSeqNum += 1;
-                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
+                    // extract the return price as a big decimal for convenience
+                    BigDecimal returnPrice = returnItem.getBigDecimal("returnPrice");
 
-                // keep a running total (note: a returnItem may have many receipts. hence, the promised total quantity is the receipt quantityAccepted + quantityRejected)
-                BigDecimal cancelQuantity = BigDecimal.ZERO;
-                if (shipmentReceiptFound) {
-                    cancelQuantity = item.getBigDecimal("quantityRejected");
-                } else if (itemIssuanceFound) {
-                    cancelQuantity = item.getBigDecimal("cancelQuantity");
+                    // determine invoice item type from the return item type
+                    String invoiceItemTypeId = getInvoiceItemType(delegator, returnItem.getString("returnItemTypeId"), null, invoiceTypeId, null);
+                    if (invoiceItemTypeId == null) {
+                        return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
+                                "AccountingNoKnownInvoiceItemTypeReturnItemType",
+                                UtilMisc.toMap("returnItemTypeId", returnItem.getString("returnItemTypeId")), locale));
+                    }
+                    if (shipmentReceiptFound) {
+                        quantity = item.getBigDecimal("quantityAccepted");
+                    } else if (itemIssuanceFound) {
+                        quantity = item.getBigDecimal("quantity");
+                    }
+
+                    // create the invoice item for this shipment receipt
+                    input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", quantity);
+                    input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
+                    input.put("amount", returnItem.get("returnPrice"));
+                    input.put("productId", returnItem.get("productId"));
+                    input.put("taxableFlag", product.get("taxable"));
+                    input.put("description", returnItem.get("description"));
+                    // TODO: what about the productFeatureId?
+                    input.put("userLogin", userLogin);
+                    serviceResults = dispatcher.runSync("createInvoiceItem", input);
+                    if (ServiceUtil.isError(serviceResults)) {
+                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
+                    }
+
+                    // copy the return item information into ReturnItemBilling
+                    input = UtilMisc.toMap("returnId", returnId, "returnItemSeqId", returnItem.get("returnItemSeqId"),
+                            "invoiceId", invoiceId);
+                    input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
+                    input.put("quantity", quantity);
+                    input.put("amount", returnItem.get("returnPrice"));
+                    input.put("userLogin", userLogin);
+                    if (shipmentReceiptFound) {
+                        input.put("shipmentReceiptId", item.get("receiptId"));
+                    }
+                    serviceResults = dispatcher.runSync("createReturnItemBilling", input);
+                    if (ServiceUtil.isError(serviceResults)) {
+                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
+                    }
+                    if (Debug.verboseOn()) {
+                        Debug.logVerbose("Creating Invoice Item with amount " + returnPrice + " and quantity " + quantity
+                                + " for shipment [" + item.getString("shipmentId") + ":" + item.getString("shipmentItemSeqId") + "]", MODULE);
+                    }
+
+                    String parentInvoiceItemSeqId = invoiceItemSeqId;
+                    // increment the seqId counter after creating the invoice item and return item billing
+                    invoiceItemSeqNum += 1;
+                    invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
+
+                    // keep a running total (note: a returnItem may have many receipts. hence, the promised total quantity is the receipt
+                    // quantityAccepted + quantityRejected)
+                    BigDecimal cancelQuantity = BigDecimal.ZERO;
+                    if (shipmentReceiptFound) {
+                        cancelQuantity = item.getBigDecimal("quantityRejected");
+                    } else if (itemIssuanceFound) {
+                        cancelQuantity = item.getBigDecimal("cancelQuantity");
+                    }
+                    if (cancelQuantity == null) {
+                        cancelQuantity = BigDecimal.ZERO;
+                    }
+                    BigDecimal actualAmount = returnPrice.multiply(quantity).setScale(DECIMALS, ROUNDING);
+                    BigDecimal promisedAmount = returnPrice.multiply(quantity.add(cancelQuantity)).setScale(DECIMALS, ROUNDING);
+                    invoiceTotal = invoiceTotal.add(actualAmount).setScale(DECIMALS, ROUNDING);
+                    promisedTotal = promisedTotal.add(promisedAmount).setScale(DECIMALS, ROUNDING);
+
+                    // for each adjustment related to this ReturnItem, create a separate invoice item
+                    List<GenericValue> adjustments = returnItem.getRelated("ReturnAdjustment", null, null, true);
+                    for (GenericValue adjustment : adjustments) {
+
+                        if (adjustment.get("amount") == null) {
+                            Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId") + "] has null amount and will be skipped"
+                                    , MODULE);
+                            continue;
+                        }
+
+                        // determine invoice item type from the return item type
+                        invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
+                        if (invoiceItemTypeId == null) {
+                            return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
+                                    "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
+                                    UtilMisc.toMap("returnAdjustmentTypeId", adjustment.getString("returnAdjustmentTypeId")), locale));
+                        }
+
+                        // prorate the adjustment amount by the returned amount; do not round ratio
+                        BigDecimal ratio = quantity.divide(returnItem.getBigDecimal("returnQuantity"), 100, ROUNDING);
+                        BigDecimal amount = adjustment.getBigDecimal("amount");
+                        amount = amount.multiply(ratio).setScale(DECIMALS, ROUNDING);
+                        if (Debug.verboseOn()) {
+                            Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount") + " prorated to " + amount
+                                    + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]", MODULE);
+                        }
+
+                        // prepare invoice item data for this adjustment
+                        input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", BigDecimal.ONE);
+                        input.put("amount", amount);
+                        input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
+                        input.put("productId", returnItem.get("productId"));
+                        input.put("description", adjustment.get("description"));
+                        input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
+                        input.put("parentInvoiceId", invoiceId);
+                        input.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
+                        input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
+                        input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
+                        input.put("userLogin", userLogin);
+
+                        // only set taxable flag when the adjustment is not a tax
+                        // TODO: Note that we use the value of Product.taxable here. This is not an ideal solution. Instead, use returnAdjustment
+                        // .includeInTax
+                        if ("RET_SALES_TAX_ADJ".equals(adjustment.get("returnAdjustmentTypeId"))) {
+                            input.put("taxableFlag", "N");
+                        }
+
+                        // create the invoice item
+                        serviceResults = dispatcher.runSync("createInvoiceItem", input);
+                        if (ServiceUtil.isError(serviceResults)) {
+                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
+                        }
+
+                        // increment the seqId counter
+                        invoiceItemSeqNum += 1;
+                        invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
+
+                        // keep a running total (promised adjustment in this case is the same as the invoice adjustment)
+                        invoiceTotal = invoiceTotal.add(amount).setScale(DECIMALS, ROUNDING);
+                        promisedTotal = promisedTotal.add(amount).setScale(DECIMALS, ROUNDING);
+                    }
                 }
-                if (cancelQuantity == null) {
-                    cancelQuantity = BigDecimal.ZERO;
+
+                // ratio of the invoice total to the promised total so far or zero if the amounts were zero
+                BigDecimal actualToPromisedRatio = BigDecimal.ZERO;
+                if (invoiceTotal.signum() != 0) {
+                    actualToPromisedRatio = invoiceTotal.divide(promisedTotal, 100, ROUNDING);  // do not round ratio
                 }
-                BigDecimal actualAmount = returnPrice.multiply(quantity).setScale(DECIMALS, ROUNDING);
-                BigDecimal promisedAmount = returnPrice.multiply(quantity.add(cancelQuantity)).setScale(DECIMALS, ROUNDING);
-                invoiceTotal = invoiceTotal.add(actualAmount).setScale(DECIMALS, ROUNDING);
-                promisedTotal = promisedTotal.add(promisedAmount).setScale(DECIMALS, ROUNDING);
 
-                // for each adjustment related to this ReturnItem, create a separate invoice item
-                List<GenericValue> adjustments = returnItem.getRelated("ReturnAdjustment", null, null, true);
+                // loop through return-wide adjustments and create invoice items for each
+                List<GenericValue> adjustments = returnHeader.getRelated("ReturnAdjustment", UtilMisc.toMap("returnItemSeqId", "_NA_"), null, true);
                 for (GenericValue adjustment : adjustments) {
 
-                    if (adjustment.get("amount") == null) {
-                         Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId") + "] has null amount and will be skipped", MODULE);
-                         continue;
-                    }
-
                     // determine invoice item type from the return item type
-                    invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
+                    String invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId,
+                            null);
                     if (invoiceItemTypeId == null) {
                         return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
                                 "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
                                 UtilMisc.toMap("returnAdjustmentTypeId", adjustment.getString("returnAdjustmentTypeId")), locale));
                     }
 
-                    // prorate the adjustment amount by the returned amount; do not round ratio
-                    BigDecimal ratio = quantity.divide(returnItem.getBigDecimal("returnQuantity"), 100, ROUNDING);
-                    BigDecimal amount = adjustment.getBigDecimal("amount");
-                    amount = amount.multiply(ratio).setScale(DECIMALS, ROUNDING);
+                    // prorate the adjustment amount by the actual to promised ratio
+                    BigDecimal amount = adjustment.getBigDecimal("amount").multiply(actualToPromisedRatio).setScale(DECIMALS, ROUNDING);
                     if (Debug.verboseOn()) {
                         Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount") + " prorated to " + amount
                                 + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]", MODULE);
                     }
 
-                    // prepare invoice item data for this adjustment
+                    // prepare the invoice item for the return-wide adjustment
                     input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", BigDecimal.ONE);
                     input.put("amount", amount);
                     input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
-                    input.put("productId", returnItem.get("productId"));
                     input.put("description", adjustment.get("description"));
                     input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
-                    input.put("parentInvoiceId", invoiceId);
-                    input.put("parentInvoiceItemSeqId", parentInvoiceItemSeqId);
                     input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
                     input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
                     input.put("userLogin", userLogin);
 
-                    // only set taxable flag when the adjustment is not a tax
-                    // TODO: Note that we use the value of Product.taxable here. This is not an ideal solution. Instead, use returnAdjustment.includeInTax
-                    if ("RET_SALES_TAX_ADJ".equals(adjustment.get("returnAdjustmentTypeId"))) {
-                        input.put("taxableFlag", "N");
-                    }
+                    // XXX TODO Note: we need to implement ReturnAdjustment.includeInTax for this to work properly
+                    input.put("taxableFlag", adjustment.get("includeInTax"));
 
                     // create the invoice item
                     serviceResults = dispatcher.runSync("createInvoiceItem", input);
@@ -2235,70 +2359,17 @@ public class InvoiceServices {
                     // increment the seqId counter
                     invoiceItemSeqNum += 1;
                     invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
-
-                    // keep a running total (promised adjustment in this case is the same as the invoice adjustment)
-                    invoiceTotal = invoiceTotal.add(amount).setScale(DECIMALS, ROUNDING);
-                    promisedTotal = promisedTotal.add(amount).setScale(DECIMALS, ROUNDING);
                 }
-            }
-
-            // ratio of the invoice total to the promised total so far or zero if the amounts were zero
-            BigDecimal actualToPromisedRatio = BigDecimal.ZERO;
-            if (invoiceTotal.signum() != 0) {
-                actualToPromisedRatio = invoiceTotal.divide(promisedTotal, 100, ROUNDING);  // do not round ratio
-            }
-
-            // loop through return-wide adjustments and create invoice items for each
-            List<GenericValue> adjustments = returnHeader.getRelated("ReturnAdjustment", UtilMisc.toMap("returnItemSeqId", "_NA_"), null, true);
-            for (GenericValue adjustment : adjustments) {
 
-                // determine invoice item type from the return item type
-                String invoiceItemTypeId = getInvoiceItemType(delegator, adjustment.getString("returnAdjustmentTypeId"), null, invoiceTypeId, null);
-                if (invoiceItemTypeId == null) {
-                    return ServiceUtil.returnError(errorMsg + UtilProperties.getMessage(RESOURCE,
-                            "AccountingNoKnownInvoiceItemTypeReturnAdjustmentType",
-                            UtilMisc.toMap("returnAdjustmentTypeId", adjustment.getString("returnAdjustmentTypeId")), locale));
-                }
-
-                // prorate the adjustment amount by the actual to promised ratio
-                BigDecimal amount = adjustment.getBigDecimal("amount").multiply(actualToPromisedRatio).setScale(DECIMALS, ROUNDING);
-                if (Debug.verboseOn()) {
-                    Debug.logVerbose("Creating Invoice Item with amount " + adjustment.getBigDecimal("amount") + " prorated to " + amount
-                            + " for return adjustment [" + adjustment.getString("returnAdjustmentId") + "]", MODULE);
-                }
-
-                // prepare the invoice item for the return-wide adjustment
-                input = UtilMisc.toMap("invoiceId", invoiceId, "invoiceItemTypeId", invoiceItemTypeId, "quantity", BigDecimal.ONE);
-                input.put("amount", amount);
-                input.put("invoiceItemSeqId", "" + invoiceItemSeqId); // turn the int into a string with ("" + int) hack
-                input.put("description", adjustment.get("description"));
-                input.put("overrideGlAccountId", adjustment.get("overrideGlAccountId"));
-                input.put("taxAuthPartyId", adjustment.get("taxAuthPartyId"));
-                input.put("taxAuthGeoId", adjustment.get("taxAuthGeoId"));
-                input.put("userLogin", userLogin);
-
-                // XXX TODO Note: we need to implement ReturnAdjustment.includeInTax for this to work properly
-                input.put("taxableFlag", adjustment.get("includeInTax"));
-
-                // create the invoice item
-                serviceResults = dispatcher.runSync("createInvoiceItem", input);
+                // Set the invoice to READY
+                serviceResults = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId",
+                        "INVOICE_READY", "userLogin", userLogin));
                 if (ServiceUtil.isError(serviceResults)) {
                     return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
                 }
 
-                // increment the seqId counter
-                invoiceItemSeqNum += 1;
-                invoiceItemSeqId = UtilFormatOut.formatPaddedNumber(invoiceItemSeqNum, INVOICE_ITEM_SEQUENCE_ID_DIGITS);
-            }
-
-            // Set the invoice to READY
-            serviceResults = dispatcher.runSync("setInvoiceStatus", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "statusId", "INVOICE_READY", "userLogin", userLogin));
-            if (ServiceUtil.isError(serviceResults)) {
-                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
-            }
-
-            // return the invoiceId
-            results.put("invoiceId", invoiceId);
+                // return the invoiceId
+                results.put("invoiceId", invoiceId);
             }
             return results;
         } catch (GenericServiceException | GenericEntityException e) {
@@ -2337,8 +2408,9 @@ public class InvoiceServices {
         List<GenericValue> paymentAppl = null;
         try {
             paymentAppl = EntityQuery.use(delegator).from("PaymentAndApplication").where("invoiceId", invoiceId).queryList();
-            // For each payment application, select only those that are RECEIVED or SENT based on whether the payment is a RECEIPT or DISBURSEMENT respectively
-            for (Iterator<GenericValue> iter = paymentAppl.iterator(); iter.hasNext();) {
+            // For each payment application, select only those that are RECEIVED or SENT based on whether the payment is a RECEIPT or DISBURSEMENT
+            // respectively
+            for (Iterator<GenericValue> iter = paymentAppl.iterator(); iter.hasNext(); ) {
                 GenericValue payment = iter.next();
                 if ("PMNT_RECEIVED".equals(payment.get("statusId")) && UtilAccounting.isReceipt(payment)) {
                     continue; // keep
@@ -2392,8 +2464,8 @@ public class InvoiceServices {
                     Map<String, Object> serviceResults = dispatcher.runSync("setInvoiceStatus", svcCtx);
                     if (ServiceUtil.isError(serviceResults)) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                            "AccountingProblemChangingInvoiceStatusTo",
-                            UtilMisc.toMap("newStatus", "INVOICE_PAID"), locale));
+                                "AccountingProblemChangingInvoiceStatusTo",
+                                UtilMisc.toMap("newStatus", "INVOICE_PAID"), locale));
                     }
                 } catch (GenericServiceException e) {
                     Debug.logError(e, "Problem changing invoice status to INVOICE_PAID" + svcCtx, MODULE);
@@ -2410,15 +2482,17 @@ public class InvoiceServices {
     }
 
     private static BigDecimal calcHeaderAdj(Delegator delegator, GenericValue adj, String invoiceTypeId, String invoiceId, String invoiceItemSeqId,
-            BigDecimal divisor, BigDecimal multiplier, BigDecimal baseAmount, int decimals, RoundingMode rounding, GenericValue userLogin, LocalDispatcher dispatcher, Locale locale) {
+                                            BigDecimal divisor, BigDecimal multiplier, BigDecimal baseAmount, int decimals, RoundingMode rounding,
+                                            GenericValue userLogin, LocalDispatcher dispatcher, Locale locale) {
         BigDecimal adjAmount = BigDecimal.ZERO;
         if (adj.get("amount") != null) {
 
             // pro-rate the amount
             BigDecimal amount = BigDecimal.ZERO;
             if ("DONATION_ADJUSTMENT".equals(adj.getString("orderAdjustmentTypeId"))) {
-                amount=baseAmount;
-            } else if (divisor.signum() != 0) { // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in essense
+                amount = baseAmount;
+            } else if (divisor.signum() != 0) { // make sure the divisor is not 0 to avoid NaN problems; just leave the amount as 0 and skip it in
+                // essense
                 // multiply first then divide to avoid rounding errors
                 amount = baseAmount.multiply(multiplier).divide(divisor, decimals, rounding);
             }
@@ -2426,7 +2500,8 @@ public class InvoiceServices {
                 Map<String, Object> createInvoiceItemContext = new HashMap<>();
                 createInvoiceItemContext.put("invoiceId", invoiceId);
                 createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ"));
+                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null,
+                        invoiceTypeId, "INVOICE_ADJ"));
                 createInvoiceItemContext.put("description", adj.get("description"));
                 createInvoiceItemContext.put("quantity", BigDecimal.ONE);
                 createInvoiceItemContext.put("amount", amount);
@@ -2461,13 +2536,13 @@ public class InvoiceServices {
                         return adjAmount;
                     }
                 } catch (GenericServiceException e) {
-                    return adjAmount;                }
+                    return adjAmount;
+                }
 
             }
             amount = amount.setScale(decimals, rounding);
             adjAmount = amount;
-        }
-        else if (adj.get("sourcePercentage") != null) {
+        } else if (adj.get("sourcePercentage") != null) {
             // pro-rate the amount
             BigDecimal percent = adj.getBigDecimal("sourcePercentage");
             percent = percent.divide(new BigDecimal(100), 100, rounding);
@@ -2481,7 +2556,8 @@ public class InvoiceServices {
                 Map<String, Object> createInvoiceItemContext = new HashMap<>();
                 createInvoiceItemContext.put("invoiceId", invoiceId);
                 createInvoiceItemContext.put("invoiceItemSeqId", invoiceItemSeqId);
-                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null, invoiceTypeId, "INVOICE_ADJ"));
+                createInvoiceItemContext.put("invoiceItemTypeId", getInvoiceItemType(delegator, adj.getString("orderAdjustmentTypeId"), null,
+                        invoiceTypeId, "INVOICE_ADJ"));
                 createInvoiceItemContext.put("description", adj.get("description"));
                 createInvoiceItemContext.put("quantity", BigDecimal.ONE);
                 createInvoiceItemContext.put("amount", amount);
@@ -2524,14 +2600,15 @@ public class InvoiceServices {
             adjAmount = amount;
         }
 
-        Debug.logInfo("adjAmount: " + adjAmount + ", divisor: " + divisor + ", multiplier: " + multiplier +
-                ", invoiceTypeId: " + invoiceTypeId + ", invoiceId: " + invoiceId + ", itemSeqId: " + invoiceItemSeqId +
-                ", decimals: " + decimals + ", rounding: " + rounding + ", adj: " + adj, MODULE);
+        Debug.logInfo("adjAmount: " + adjAmount + ", divisor: " + divisor + ", multiplier: " + multiplier
+                + ", invoiceTypeId: " + invoiceTypeId + ", invoiceId: " + invoiceId + ", itemSeqId: " + invoiceItemSeqId
+                + ", decimals: " + decimals + ", rounding: " + rounding + ", adj: " + adj, MODULE);
         return adjAmount;
     }
 
     /* Creates InvoiceTerm entries for a list of terms, which can be BillingAccountTerms, OrderTerms, etc. */
-    private static void createInvoiceTerms(Delegator delegator, LocalDispatcher dispatcher, String invoiceId, List<GenericValue> terms, GenericValue userLogin, Locale locale) {
+    private static void createInvoiceTerms(Delegator delegator, LocalDispatcher dispatcher, String invoiceId, List<GenericValue> terms,
+                                           GenericValue userLogin, Locale locale) {
         if (terms != null) {
             for (GenericValue term : terms) {
 
@@ -2586,7 +2663,7 @@ public class InvoiceServices {
      * have been paid/received. For invoice processing, this service works on
      * the invoice level when 'invoiceProcessing' parameter is set to "Y" else
      * it works on the invoice item level.
-     *
+     * <p>
      * This version will apply as much as possible when no amountApplied is provided.
      */
     public static Map<String, Object> updatePaymentApplicationDef(DispatchContext dctx, Map<String, Object> context) {
@@ -2740,7 +2817,8 @@ public class InvoiceServices {
                         "AccountingPaymentRecordNotFound", UtilMisc.toMap("paymentId", toPaymentId), locale));
                 return ServiceUtil.returnError(errorMessageList);
             }
-            toPaymentApplyAvailable = toPayment.getBigDecimal("amount").subtract(PaymentWorker.getPaymentApplied(toPayment)).setScale(DECIMALS, ROUNDING);
+            toPaymentApplyAvailable = toPayment.getBigDecimal("amount").subtract(PaymentWorker.getPaymentApplied(toPayment)).setScale(DECIMALS,
+                    ROUNDING);
 
             if ("PMNT_CANCELLED".equals(toPayment.getString("statusId"))) {
                 errorMessageList.add(UtilProperties.getMessage(RESOURCE,
@@ -2760,18 +2838,18 @@ public class InvoiceServices {
                     // check here for too much application if a new record is
                     // added (paymentApplicationId == null)
                     if (amountApplied.compareTo(toPaymentApplyAvailable) > 0) {
-                            errorMessageList.add(UtilProperties.getMessage(RESOURCE,
-                                    "AccountingPaymentLessRequested",
-                                    UtilMisc.<String, Object>toMap("paymentId", toPaymentId,
-                                                "paymentApplyAvailable", toPaymentApplyAvailable,
-                                                "amountApplied", amountApplied, "isoCode", currencyUomId), locale));
+                        errorMessageList.add(UtilProperties.getMessage(RESOURCE,
+                                "AccountingPaymentLessRequested",
+                                UtilMisc.<String, Object>toMap("paymentId", toPaymentId,
+                                        "paymentApplyAvailable", toPaymentApplyAvailable,
+                                        "amountApplied", amountApplied, "isoCode", currencyUomId), locale));
                     }
                 }
             }
 
             // check if at least one send is the same as one receiver on the other payment
             if (!payment.getString("partyIdFrom").equals(toPayment.getString("partyIdTo"))
-                    && !payment.getString("partyIdTo").equals(toPayment.getString("partyIdFrom")))    {
+                    && !payment.getString("partyIdTo").equals(toPayment.getString("partyIdFrom"))) {
                 errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                         "AccountingFromPartySameToParty", locale));
             }
@@ -2855,7 +2933,8 @@ public class InvoiceServices {
                 if (currencyUomId != null && invoice.get("currencyUomId") != null &&
                         !currencyUomId.equals(invoice.getString("currencyUomId"))) {
                     Debug.logInfo(UtilProperties.getMessage(RESOURCE, "AccountingInvoicePaymentCurrencyProblem",
-                            UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"), "paymentCurrency", payment.getString("currencyUomId")), locale), MODULE);
+                            UtilMisc.toMap("invoiceCurrency", invoice.getString("currencyUomId"), "paymentCurrency", payment.getString(
+                                    "currencyUomId")), locale), MODULE);
                     Debug.logInfo("will try to apply payment on the actualCurrency amount on payment", MODULE);
 
                     if (payment.get("actualCurrencyAmount") == null || payment.get("actualCurrencyUomId") == null) {
@@ -2866,7 +2945,8 @@ public class InvoiceServices {
                             errorMessageList.add("actual currency on payment (" + currencyUomId + ") not the same as original invoice currency (" + invoice.getString("currencyUomId") + ")");
                         }
                     }
-                    paymentApplyAvailable = payment.getBigDecimal("actualCurrencyAmount").subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING);
+                    paymentApplyAvailable =
+                            payment.getBigDecimal("actualCurrencyAmount").subtract(PaymentWorker.getPaymentApplied(payment)).setScale(DECIMALS, ROUNDING);
                 }
 
                 // check if the invoice already covered by payments
@@ -2887,15 +2967,15 @@ public class InvoiceServices {
                     else if (amountApplied.compareTo(invoiceApplyAvailable) > 0) {
                         errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceLessRequested",
                                 UtilMisc.<String, Object>toMap("invoiceId", invoiceId,
-                                            "invoiceApplyAvailable", invoiceApplyAvailable,
-                                            "amountApplied", amountApplied,
-                                            "isoCode", invoice.getString("currencyUomId")), locale));
+                                        "invoiceApplyAvailable", invoiceApplyAvailable,
+                                        "amountApplied", amountApplied,
+                                        "isoCode", invoice.getString("currencyUomId")), locale));
                     }
                 }
 
                 // check if at least one sender is the same as one receiver on the invoice
                 if (!payment.getString("partyIdFrom").equals(invoice.getString("partyId"))
-                        && !payment.getString("partyIdTo").equals(invoice.getString("partyIdFrom")))    {
+                        && !payment.getString("partyIdTo").equals(invoice.getString("partyIdFrom"))) {
                     errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                             "AccountingFromPartySameToParty", locale));
                 }
@@ -2909,7 +2989,8 @@ public class InvoiceServices {
             if (invoiceItemSeqId != null) {
                 // when itemSeqNr not provided delay checking on invoiceItemSeqId
                 try {
-                    invoiceItem = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId).queryOne();
+                    invoiceItem = EntityQuery.use(delegator).from("InvoiceItem").where("invoiceId", invoiceId, "invoiceItemSeqId",
+                            invoiceItemSeqId).queryOne();
                 } catch (GenericEntityException e) {
                     return ServiceUtil.returnError(e.getMessage());
                 }
@@ -2933,16 +3014,18 @@ public class InvoiceServices {
                     } else {
                         quantity = invoiceItem.getBigDecimal("quantity").setScale(DECIMALS, ROUNDING);
                     }
-                    invoiceItemApplyAvailable = invoiceItem.getBigDecimal("amount").multiply(quantity).setScale(DECIMALS, ROUNDING).subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem));
+                    invoiceItemApplyAvailable =
+                            invoiceItem.getBigDecimal("amount").multiply(quantity).setScale(DECIMALS, ROUNDING).subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem));
                     // check here for too much application if a new record is added
                     if (paymentApplicationId == null && amountApplied.compareTo(invoiceItemApplyAvailable) > 0) {
                         // new record
-                        errorMessageList.add("Invoice(" + invoiceId + ") item(" + invoiceItemSeqId + ") has  " + invoiceItemApplyAvailable + " to apply but " + amountApplied + " is requested\n");
+                        errorMessageList.add("Invoice(" + invoiceId + ") item(" + invoiceItemSeqId + ") has  " + invoiceItemApplyAvailable + " to " +
+                                "apply but " + amountApplied + " is requested\n");
                         String uomId = invoice.getString("currencyUomId");
                         errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceItemLessRequested",
                                 UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "invoiceItemSeqId", invoiceItemSeqId,
-                                            "invoiceItemApplyAvailable", invoiceItemApplyAvailable,
-                                            "amountApplied", amountApplied, "isoCode", uomId), locale));
+                                        "invoiceItemApplyAvailable", invoiceItemApplyAvailable,
+                                        "amountApplied", amountApplied, "isoCode", uomId), locale));
                     }
                 }
                 if (debug) {
@@ -2963,8 +3046,8 @@ public class InvoiceServices {
                 if (amountApplied.compareTo(paymentApplyAvailable) > 0) {
                     errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingPaymentLessRequested",
                             UtilMisc.<String, Object>toMap("paymentId", paymentId,
-                                        "paymentApplyAvailable", paymentApplyAvailable,
-                                        "amountApplied", amountApplied, "isoCode", currencyUomId), locale));
+                                    "paymentApplyAvailable", paymentApplyAvailable,
+                                    "amountApplied", amountApplied, "isoCode", currencyUomId), locale));
                 }
             }
         }
@@ -2984,7 +3067,8 @@ public class InvoiceServices {
             // prepare for creation
         } else { // retrieve existing paymentApplication
             try {
-                paymentApplication = EntityQuery.use(delegator).from("PaymentApplication").where("paymentApplicationId", paymentApplicationId).queryOne();
+                paymentApplication =
+                        EntityQuery.use(delegator).from("PaymentApplication").where("paymentApplicationId", paymentApplicationId).queryOne();
             } catch (GenericEntityException e) {
                 return ServiceUtil.returnError(e.getMessage());
             }
@@ -3023,7 +3107,9 @@ public class InvoiceServices {
                 // check if the payment for too much application if an existing
                 // application record is changed
                 if (paymentApplyAvailable.compareTo(BigDecimal.ZERO) == 0) {
-                    newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING);
+                    newPaymentApplyAvailable =
+                            paymentApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS,
+                                    ROUNDING);
                 } else {
                     newPaymentApplyAvailable = paymentApplyAvailable.add(paymentApplyAvailable).subtract(amountApplied).setScale(DECIMALS, ROUNDING);
                 }
@@ -3038,11 +3124,13 @@ public class InvoiceServices {
                 if (invoiceId != null) {
                     // only when we are processing an invoice on existing paymentApplication check invoice item for to much application if the invoice
                     // number did not change
-                    if (invoiceId.equals(paymentApplication .getString("invoiceId"))) {
+                    if (invoiceId.equals(paymentApplication.getString("invoiceId"))) {
                         // check if both the itemNumbers are null then this is a
                         // record for the whole invoice
                         if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") == null) {
-                            newInvoiceApplyAvailable = invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING);
+                            newInvoiceApplyAvailable =
+                                    invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS
+                                            , ROUNDING);
                             if (invoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) {
                                 errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                                         "AccountingInvoiceNotEnough",
@@ -3051,7 +3139,9 @@ public class InvoiceServices {
                             }
                         } else if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") != null) {
                             // check if the item number changed from a real Item number to a null value
-                            newInvoiceApplyAvailable = invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING);
+                            newInvoiceApplyAvailable =
+                                    invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS
+                                            , ROUNDING);
                             if (invoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) {
                                 errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                                         "AccountingInvoiceNotEnough",
@@ -3072,7 +3162,8 @@ public class InvoiceServices {
                         } else if (invoiceItemSeqId.equals(paymentApplication.getString("invoiceItemSeqId"))) {
                             // check if the real item numbers the same
                             // item number the same numeric value
-                            newInvoiceItemApplyAvailable = invoiceItemApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING);
+                            newInvoiceItemApplyAvailable =
+                                    invoiceItemApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS, ROUNDING);
                             if (newInvoiceItemApplyAvailable.compareTo(BigDecimal.ZERO) < 0) {
                                 errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                                         "AccountingItemInvoiceNotEnough",
@@ -3105,11 +3196,14 @@ public class InvoiceServices {
                         }
 
                         // check the invoice
-                        newInvoiceApplyAvailable = invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied)).setScale(DECIMALS, ROUNDING);
+                        newInvoiceApplyAvailable =
+                                invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied)).setScale(DECIMALS,
+                                        ROUNDING);
                         if (newInvoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) {
                             errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                                     "AccountingInvoiceNotEnough",
-                                    UtilMisc.<String, Object>toMap("tooMuch", invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied),
+                                    UtilMisc.<String, Object>toMap("tooMuch", invoiceApplyAvailable.add(paymentApplication.getBigDecimal(
+                                            "amountApplied")).subtract(amountApplied),
                                             "invoiceId", invoiceId), locale));
                         }
                     }
@@ -3118,7 +3212,9 @@ public class InvoiceServices {
                 // check the toPayment account when only the amountApplied has
                 // changed,
                 if (toPaymentId != null && toPaymentId.equals(paymentApplication.getString("toPaymentId"))) {
-                    newToPaymentApplyAvailable = toPaymentApplyAvailable.subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied).setScale(DECIMALS, ROUNDING);
+                    newToPaymentApplyAvailable =
+                            toPaymentApplyAvailable.subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied).setScale(DECIMALS,
+                                    ROUNDING);
                     if (newToPaymentApplyAvailable.compareTo(BigDecimal.ZERO) < 0) {
                         errorMessageList.add(UtilProperties.getMessage(RESOURCE,
                                 "AccountingPaymentNotEnough",
@@ -3154,7 +3250,7 @@ public class InvoiceServices {
             }
             Debug.logInfo("checking finished, start processing with the following data... ", MODULE);
             if (invoiceId != null) {
-                Debug.logInfo(" Invoice(" + invoiceId + ") amount not yet applied: " + newInvoiceApplyAvailable + extra + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable +  " Requested amount to apply:" + amountApplied, MODULE);
+                Debug.logInfo(" Invoice(" + invoiceId + ") amount not yet applied: " + newInvoiceApplyAvailable + extra + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE);
                 toMessage = UtilProperties.getMessage(RESOURCE,
                         "AccountingApplicationToInvoice",
                         UtilMisc.toMap("invoiceId", invoiceId), locale);
@@ -3165,7 +3261,8 @@ public class InvoiceServices {
                 }
             }
             if (toPaymentId != null) {
-                Debug.logInfo(" toPayment(" + toPaymentId + ") amount not yet applied: " + newToPaymentApplyAvailable + " Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE);
+                Debug.logInfo(" toPayment(" + toPaymentId + ") amount not yet applied: " + newToPaymentApplyAvailable + " Payment(" + paymentId +
+                        ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE);
                 toMessage = UtilProperties.getMessage(RESOURCE,
                         "AccountingApplicationToPayment",
                         UtilMisc.toMap("paymentId", toPaymentId), locale);
@@ -3178,7 +3275,7 @@ public class InvoiceServices {
             }
         }
         // if the amount to apply was not provided or was zero fill it with the maximum possible and provide information to the user
-        if (amountApplied.signum() == 0 &&  "Y".equals(useHighestAmount)) {
+        if (amountApplied.signum() == 0 && "Y".equals(useHighestAmount)) {
             amountApplied = newPaymentApplyAvailable;
             if (invoiceId != null && newInvoiceApplyAvailable.compareTo(amountApplied) < 0) {
                 amountApplied = newInvoiceApplyAvailable;
@@ -3211,7 +3308,7 @@ public class InvoiceServices {
         }
 
         // ============ start processing ======================
-           // if the application is specified it is easy, update the existing record only
+        // if the application is specified it is easy, update the existing record only
         if (paymentApplicationId != null) {
             // record is already retrieved previously
             if (debug) {
@@ -3261,11 +3358,12 @@ public class InvoiceServices {
                 return ServiceUtil.returnError(e.getMessage());
             }
             if (invoiceItems.size() == 0) {
-                errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingNoInvoiceItemsFoundForInvoice", UtilMisc.toMap("invoiceId", invoiceId), locale));
+                errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingNoInvoiceItemsFoundForInvoice", UtilMisc.toMap("invoiceId",
+                        invoiceId), locale));
                 return ServiceUtil.returnError(errorMessageList);
             }
             // check if the user want to apply a smaller amount than the maximum possible on the payment
-            if (amountApplied.signum() != 0 && amountApplied.compareTo(paymentApplyAvailable) < 0)    {
+            if (amountApplied.signum() != 0 && amountApplied.compareTo(paymentApplyAvailable) < 0) {
                 paymentApplyAvailable = amountApplied;
             }
             for (GenericValue currentInvoiceItem : invoiceItems) {
@@ -3306,7 +3404,8 @@ public class InvoiceServices {
                     tobeApplied = itemTotal;
                 }
                 if (debug) {
-                    Debug.logInfo("tobeApplied:(" + tobeApplied + ") = " + "itemTotal(" + itemTotal + ") - alreadyApplied(" + alreadyApplied + ") but not more then (nonapplied) paymentAmount(" + paymentApplyAvailable + ")", MODULE);
+                    Debug.logInfo("tobeApplied:(" + tobeApplied + ") = " + "itemTotal(" + itemTotal + ") - alreadyApplied(" + alreadyApplied + ") "
+                            + "but not more then (nonapplied) paymentAmount(" + paymentApplyAvailable + ")", MODULE);
                 }
 
                 if (tobeApplied.signum() == 0) {
@@ -3324,7 +3423,8 @@ public class InvoiceServices {
                 // create application payment record but check currency
                 // first if supplied
                 if (invoice.get("currencyUomId") != null && currencyUomId != null && !invoice.getString("currencyUomId").equals(currencyUomId)) {
-                    errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency(" + invoice.getString("currencyUomId") + ") not the same\n");
+                    errorMessageList.add("Payment currency (" + currencyUomId + ") and invoice currency(" + invoice.getString("currencyUomId") + ")"
+                            + " not the same\n");
                 } else {
                     paymentApplication.set("paymentApplicationId", null);
                     // make sure we get a new record
@@ -3372,7 +3472,8 @@ public class InvoiceServices {
         BigDecimal invoicedTotal = BigDecimal.ZERO;
         List<GenericValue> invoicedAdjustments = null;
         try {
-            invoicedAdjustments = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where("orderAdjustmentId", orderAdjustment.get("orderAdjustmentId")).queryList();
+            invoicedAdjustments = EntityQuery.use(delegator).from("OrderAdjustmentBilling").where("orderAdjustmentId",
+                    orderAdjustment.get("orderAdjustmentId")).queryList();
         } catch (GenericEntityException e) {
             Debug.logError(e, "Accounting trouble calling calculateInvoicedAdjustmentTotal service", MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -3427,7 +3528,7 @@ public class InvoiceServices {
             // 1 record exists just update and if different ID delete other record and add together.
             GenericValue checkAppl = checkAppls.get(0);
             // if new record  add to the already existing one.
-            if (paymentApplication.get("paymentApplicationId") == null)    {
+            if (paymentApplication.get("paymentApplicationId") == null) {
                 // add 2 amounts together
                 checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied").
                         add(checkAppl.getBigDecimal("amountApplied")).setScale(DECIMALS, ROUNDING));
@@ -3450,13 +3551,14 @@ public class InvoiceServices {
                 } catch (GenericEntityException e) {
                     return ServiceUtil.returnError(e.getMessage());
                 }
-            } else    { // two existing records, an updated one added to the existing one
+            } else { // two existing records, an updated one added to the existing one
                 // add 2 amounts together
                 checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied").
                         add(checkAppl.getBigDecimal("amountApplied")).setScale(DECIMALS, ROUNDING));
                 // delete paymentApplication record and update the checkAppls one.
                 if (debug) {
-                    Debug.logInfo("Delete paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE);
+                    Debug.logInfo("Delete paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with "
+                            + "appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE);
                 }
                 try {
                     paymentApplication.remove();
@@ -3480,18 +3582,21 @@ public class InvoiceServices {
             // create record if ID null;
             if (paymentApplication.get("paymentApplicationId") == null) {
                 paymentApplication.set("paymentApplicationId", delegator.getNextSeqId("PaymentApplication"));
-                    if (debug) {
-                        Debug.logInfo("Create new paymentAppication record: " + paymentApplication.getString("paymentApplicationId") + " with appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE);
-                    }
+                if (debug) {
+                    Debug.logInfo("Create new paymentAppication record: " + paymentApplication.getString("paymentApplicationId") + " with "
+                            + "appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE);
+                }
                 try {
                     paymentApplication.create();
                 } catch (GenericEntityException e) {
                     return ServiceUtil.returnError(e.getMessage());
                 }
             } else {
-                // update existing record (could not be found because a non existing combination of paymentId/invoiceId/invoiceSeqId/ etc... was provided
+                // update existing record (could not be found because a non existing combination of paymentId/invoiceId/invoiceSeqId/ etc... was
+                // provided
                 if (debug) {
-                    Debug.logInfo("Update existing paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE);
+                    Debug.logInfo("Update existing paymentApplication record: " + paymentApplication.getString("paymentApplicationId") + " with "
+                            + "appliedAmount:" + paymentApplication.getBigDecimal("amountApplied"), MODULE);
                 }
                 try {
                     paymentApplication.store();
@@ -3512,7 +3617,7 @@ public class InvoiceServices {
         try {
             GenericValue payment = EntityQuery.use(delegator).from("Payment").where("paymentId", paymentId).queryOne();
             if (payment == null) {
-                throw new GenericServiceException("Payment with ID [" + paymentId  + "] not found!");
+                throw new GenericServiceException("Payment with ID [" + paymentId + "] not found!");
             }
 
             List<GenericValue> paymentApplications = payment.getRelated("PaymentApplication", null, null, false);
@@ -3520,11 +3625,13 @@ public class InvoiceServices {
                 return ServiceUtil.returnSuccess();
             }
 
-            // TODO: this is inefficient -- instead use HashSet to construct a distinct Set of invoiceIds, then iterate over it and call checkInvoicePaymentAppls
+            // TODO: this is inefficient -- instead use HashSet to construct a distinct Set of invoiceIds, then iterate over it and call
+            // checkInvoicePaymentAppls
             for (GenericValue paymentApplication : paymentApplications) {
                 String invoiceId = paymentApplication.getString("invoiceId");
                 if (invoiceId != null) {
-                    Map<String, Object> serviceResult = dispatcher.runSync("checkInvoicePaymentApplications", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "userLogin", userLogin));
+                    Map<String, Object> serviceResult = dispatcher.runSync("checkInvoicePaymentApplications", UtilMisc.<String, Object>toMap(
+                            "invoiceId", invoiceId, "userLogin", userLogin));
                     if (ServiceUtil.isError(serviceResult)) {
                         return serviceResult;
                     }
@@ -3536,8 +3643,9 @@ public class InvoiceServices {
             return ServiceUtil.returnError(se.getMessage());
         }
     }
+
     public static Map<String, Object> importInvoice(DispatchContext dctx, Map<String, Object> context) {
-         Locale locale = (Locale) context.get("locale");
+        Locale locale = (Locale) context.get("locale");
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
         GenericValue userLogin = (GenericValue) context.get("userLogin");
@@ -3585,28 +3693,36 @@ public class InvoiceServices {
                     newErrMsgs = new LinkedList<>();
                     try {
                         if (UtilValidate.isEmpty(invoice.get("partyIdFrom"))) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id From and Party Id From Trans missing for invoice: " + currentInvoiceId);
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id From and Party Id From Trans missing for "
+                                    + "invoice: " + currentInvoiceId);
                         } else if (EntityQuery.use(delegator).from("Party").where("partyId", invoice.get("partyIdFrom")).queryOne() == null) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyIdFrom: " + invoice.get("partyIdFrom") + " not found for invoice: " + currentInvoiceId);
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyIdFrom: " + invoice.get("partyIdFrom") + " not found "
+                                    + "for invoice: " + currentInvoiceId);
                         }
                         if (UtilValidate.isEmpty(invoice.get("partyId"))) {
                             newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Party Id and Party Id Trans missing for invoice: " + currentInvoiceId);
                         } else if (EntityQuery.use(delegator).from("Party").where("partyId", invoice.get("partyId")).queryOne() == null) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + invoice.get("partyId") + " not found for invoice: " + currentInvoiceId);
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": partyId: " + invoice.get("partyId") + " not found for "
+                                    + "invoice: " + currentInvoiceId);
                         }
                         if (UtilValidate.isEmpty(invoice.get("invoiceTypeId"))) {
                             newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory Invoice Type missing for invoice: " + currentInvoiceId);
                         } else if (EntityQuery.use(delegator).from("InvoiceType").where("invoiceTypeId", invoice.get("invoiceTypeId")).queryOne() == null) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem type id: " + invoice.get("invoiceTypeId") + " not found for invoice: " + currentInvoiceId);
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem type id: " + invoice.get("invoiceTypeId") + " "
+                                    + "not found for invoice: " + currentInvoiceId);
                         }
 
-                        Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get("invoiceTypeId"), "parentTypeId", "PURCHASE_INVOICE");
-                        Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get("invoiceTypeId"), "parentTypeId", "SALES_INVOICE");
+                        Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get(
+                                "invoiceTypeId"), "parentTypeId", "PURCHASE_INVOICE");
+                        Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get(
+                                "invoiceTypeId"), "parentTypeId", "SALES_INVOICE");
                         if (isPurchaseInvoice && !invoice.get("partyId").equals(organizationPartyId)) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A purchase type invoice should have the partyId 'To' being the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyId") +"! invoice: " + currentInvoiceId);
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A purchase type invoice should have the partyId 'To' being "
+                                    + "the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyId") + "! invoice: " + currentInvoiceId);
                         }
                         if (isSalesInvoice && !invoice.get("partyIdFrom").equals(organizationPartyId)) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A sales type invoice should have the partyId 'from' being the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyIdFrom") +"! invoice: " + currentInvoiceId);
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": A sales type invoice should have the partyId 'from' being "
+                                    + "the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyIdFrom") + "! invoice: " + currentInvoiceId);
                         }
 
 
@@ -3621,7 +3737,7 @@ public class InvoiceServices {
                         try {
                             invoiceResult = dispatcher.runSync("createInvoice", invoice);
                             if (ServiceUtil.isError(invoiceResult)) {
-                               return ServiceUtil.returnError(ServiceUtil.getErrorMessage(invoiceResult));
+                                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(invoiceResult));
                             }
                         } catch (GenericServiceException e) {
                             csvReader.close();
@@ -3657,17 +3773,23 @@ public class InvoiceServices {
                         }
                         if (UtilValidate.isEmpty(invoiceItem.get("invoiceItemTypeId"))) {
                             newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory invoice item type missing for invoice: " + currentInvoiceId);
-                        } else if (EntityQuery.use(delegator).from("InvoiceItemType").where("invoiceItemTypeId", invoiceItem.get("invoiceItemTypeId")).queryOne() == null) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem Item type id: " + invoiceItem.get("invoiceItemTypeId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId"));
+                        } else if (EntityQuery.use(delegator).from("InvoiceItemType").where("invoiceItemTypeId", invoiceItem.get("invoiceItemTypeId"
+                        )).queryOne() == null) {
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": InvoiceItem Item type id: " + invoiceItem.get(
+                                    "invoiceItemTypeId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get(
+                                            "invoiceItemSeqId"));
                         }
                         if (UtilValidate.isEmpty(invoiceItem.get("productId")) && UtilValidate.isEmpty(invoiceItem.get("description"))) {
                             newErrMsgs.add("Line number " + rec.getRecordNumber() + ": no Product Id given, no description given");
                         }
-                        if (UtilValidate.isNotEmpty(invoiceItem.get("productId")) && EntityQuery.use(delegator).from("Product").where("productId", invoiceItem.get("productId")).queryOne() == null) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Product Id: " + invoiceItem.get("productId") + " not found for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId"));
+                        if (UtilValidate.isNotEmpty(invoiceItem.get("productId")) && EntityQuery.use(delegator).from("Product").where("productId",
+                                invoiceItem.get("productId")).queryOne() == null) {
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Product Id: " + invoiceItem.get("productId") + " not found "
+                                    + "for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId"));
                         }
                         if (UtilValidate.isEmpty(invoiceItem.get("amount")) && UtilValidate.isEmpty(invoiceItem.get("quantity"))) {
-                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Either or both quantity and amount is required for invoice: " + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId"));
+                            newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Either or both quantity and amount is required for invoice: "
+                                    + currentInvoiceId + " Item seqId:" + invoiceItem.get("invoiceItemSeqId"));
                         }
                     } catch (GenericEntityException e) {
                         Debug.logError("Validation checking problem against database. due to " + e.getMessage(), MODULE);
@@ -3679,7 +3801,7 @@ public class InvoiceServices {
                         try {
                             Map<String, Object> result = dispatcher.runSync("createInvoiceItem", invoiceItem);
                             if (ServiceUtil.isError(result)) {
-                               return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
+                                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                             }
                         } catch (GenericServiceException e) {
                             csvReader.close();
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java
index 22ab5f8..df4ba2d 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/invoice/InvoiceWorker.java
@@ -58,8 +58,8 @@ public final class InvoiceWorker {
 
     private static final int DECIMALS = UtilNumber.getBigDecimalScale("invoice.decimals");
     private static final RoundingMode ROUNDING = UtilNumber.getRoundingMode("invoice.rounding");
-    private static final int taxDecimals = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
-    private static final RoundingMode taxRounding = UtilNumber.getRoundingMode("salestax.rounding");
+    private static final int TAX_DECIMALS = UtilNumber.getBigDecimalScale("salestax.calc.decimals");
+    private static final RoundingMode TAX_ROUNDING = UtilNumber.getRoundingMode("salestax.rounding");
 
     private InvoiceWorker() { }
 
@@ -95,7 +95,7 @@ public final class InvoiceWorker {
         }
 
         if (invoice == null) {
-            throw new IllegalArgumentException("The passed invoiceId [" +invoiceId + "] does not match an existing invoice");
+            throw new IllegalArgumentException("The passed invoiceId [" + invoiceId + "] does not match an existing invoice");
         }
 
         return getInvoiceTotal(invoice, actualCurrency);
@@ -162,7 +162,8 @@ public final class InvoiceWorker {
         return description;
     }
 
-    /** Method to get the taxable invoice item types as a List of invoiceItemTypeIds.  These are identified in Enumeration with enumTypeId TAXABLE_INV_ITM_TY. */
+    /** Method to get the taxable invoice item types as a List of invoiceItemTypeIds.
+     * These are identified in Enumeration with enumTypeId TAXABLE_INV_ITM_TY. */
     public static List<String> getTaxableInvoiceItemTypeIds(Delegator delegator) throws GenericEntityException {
         List<String> typeIds = new LinkedList<>();
         List<GenericValue> invoiceItemTaxTypes = EntityQuery.use(delegator).from("Enumeration").where("enumTypeId", "TAXABLE_INV_ITM_TY")
@@ -217,7 +218,7 @@ public final class InvoiceWorker {
             invoiceItems = invoice.getRelated("InvoiceItem", null, null, false);
             invoiceItems = EntityUtil.filterByAnd(
                     invoiceItems, UtilMisc.toList(
-                            EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.NOT_IN, getTaxableInvoiceItemTypeIds(invoice.getDelegator()))));
+                    EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.NOT_IN, getTaxableInvoiceItemTypeIds(invoice.getDelegator()))));
         } catch (GenericEntityException e) {
             Debug.logError(e, "Trouble getting InvoiceItem list", MODULE);
         }
@@ -251,7 +252,8 @@ public final class InvoiceWorker {
         // remaining code is the old method, which we leave here for compatibility purposes
         List<GenericValue> billToRoles = null;
         try {
-            billToRoles = invoice.getRelated("InvoiceRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"), UtilMisc.toList("-datetimePerformed"), false);
+            billToRoles = invoice.getRelated("InvoiceRole", UtilMisc.toMap("roleTypeId", "BILL_TO_CUSTOMER"),
+                    UtilMisc.toList("-datetimePerformed"), false);
         } catch (GenericEntityException e) {
             Debug.logError(e, "Trouble getting InvoiceRole list", MODULE);
         }
@@ -330,7 +332,7 @@ public final class InvoiceWorker {
                         .where("invoiceId", invoice.get("invoiceId")).queryFirst();
                 if (shipmentView != null) {
                     GenericValue shipment = EntityQuery.use(delegator).from("Shipment")
-                        .where("shipmentId", shipmentView.get("shipmentId")).queryOne();
+                            .where("shipmentId", shipmentView.get("shipmentId")).queryOne();
                     postalAddress = shipment.getRelatedOne("DestinationPostalAddress", false);
                 }
             } catch (GenericEntityException e) {
@@ -372,7 +374,7 @@ public final class InvoiceWorker {
             Debug.logError("Touble getting InvoiceContactMech entity list", MODULE);
         }
 
-        if (UtilValidate.isEmpty(locations) && fetchPartyAddress)    {
+        if (UtilValidate.isEmpty(locations) && fetchPartyAddress) {
             // if no locations found get it from the PartyAndContactMech using the from and to party on the invoice
             String destinationPartyId = null;
             Timestamp now = UtilDateTime.nowTimestamp();
@@ -391,7 +393,7 @@ public final class InvoiceWorker {
                 Debug.logError("Trouble getting contact party purpose list", MODULE);
             }
             //if still not found get it from the general location
-            if (UtilValidate.isEmpty(locations))    {
+            if (UtilValidate.isEmpty(locations)) {
                 try {
                     locations = EntityQuery.use(delegator).from("PartyContactWithPurpose")
                             .where("partyId", destinationPartyId, "contactMechPurposeTypeId", "GENERAL_LOCATION").queryList();
@@ -413,7 +415,7 @@ public final class InvoiceWorker {
                 Debug.logError(e, "Trouble getting Contact for contactMechId: " + locations.get(0).getString("contactMechId"), MODULE);
             }
 
-            if (contactMech != null && "POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId")))    {
+            if (contactMech != null && "POSTAL_ADDRESS".equals(contactMech.getString("contactMechTypeId"))) {
                 try {
                     postalAddress = contactMech.getRelatedOne("PostalAddress", false);
                     return postalAddress;
@@ -433,7 +435,7 @@ public final class InvoiceWorker {
      * @return the invoice total as BigDecimal
      */
     public static BigDecimal getInvoiceNotApplied(Delegator delegator, String invoiceId, Boolean actualCurrency) {
-        return InvoiceWorker.getInvoiceTotal(delegator, invoiceId, actualCurrency).subtract(getInvoiceApplied(delegator, invoiceId,  UtilDateTime.nowTimestamp(), actualCurrency));
+        return InvoiceWorker.getInvoiceTotal(delegator, invoiceId, actualCurrency).subtract(getInvoiceApplied(delegator, invoiceId, UtilDateTime.nowTimestamp(), actualCurrency));
     }
     public static BigDecimal getInvoiceNotApplied(Delegator delegator, String invoiceId) {
         return InvoiceWorker.getInvoiceTotal(delegator, invoiceId).subtract(getInvoiceApplied(delegator, invoiceId));
@@ -580,9 +582,9 @@ public final class InvoiceWorker {
         String otherCurrencyUomId = null;
         // find the organization party currencyUomId which different from the invoice currency
         try {
-            GenericValue party  = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyIdFrom")).queryOne();
+            GenericValue party = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyIdFrom")).queryOne();
             if (UtilValidate.isEmpty(party) || party.getString("baseCurrencyUomId").equals(invoice.getString("currencyUomId"))) {
-                party  = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyId")).queryOne();
+                party = EntityQuery.use(delegator).from("PartyAcctgPreference").where("partyId", invoice.get("partyId")).queryOne();
             }
             if (UtilValidate.isNotEmpty(party) && party.getString("baseCurrencyUomId") != null) {
                 otherCurrencyUomId = party.getString("baseCurrencyUomId");
@@ -703,9 +705,9 @@ public final class InvoiceWorker {
                                 if (amount == null) {
                                     amount = BigDecimal.ZERO;
                                 }
-                                totalAmount = totalAmount.add(amount).setScale(taxDecimals, taxRounding);
+                                totalAmount = totalAmount.add(amount).setScale(TAX_DECIMALS, TAX_ROUNDING);
                             }
-                            totalAmount = totalAmount.setScale(taxDecimals, taxRounding);
+                            totalAmount = totalAmount.setScale(TAX_DECIMALS, TAX_ROUNDING);
                             taxByTaxAuthGeoAndPartyList.add(UtilMisc.<String, Object>toMap("taxAuthPartyId", taxAuthPartyId, "taxAuthGeoId", taxAuthGeoId, "totalAmount", totalAmount));
                             taxGrandTotal = taxGrandTotal.add(totalAmount);
                         }
@@ -736,7 +738,7 @@ public final class InvoiceWorker {
             Delegator delegator = invoice.getDelegator();
             invoiceTaxItems = EntityQuery.use(delegator).from("InvoiceItem")
                     .where(EntityCondition.makeCondition("invoiceId", invoice.getString("invoiceId")),
-                            EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator))).queryList();
+                    EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator))).queryList();
         } catch (GenericEntityException e) {
             Debug.logError(e, "Trouble getting InvoiceItem list", MODULE);
             return null;
@@ -779,7 +781,7 @@ public final class InvoiceWorker {
             Debug.logError(e, "Trouble getting InvoiceItem list", MODULE);
             return null;
         }
-       return getTaxTotalForInvoiceItems(invoiceTaxItems);
+        return getTaxTotalForInvoiceItems(invoiceTaxItems);
     }
 
     /** Returns the invoice tax total for unattributed tax items, that is items which have no taxAuthPartyId value
@@ -787,17 +789,17 @@ public final class InvoiceWorker {
      * @return Returns the invoice tax total for unattributed tax items
      */
     public static BigDecimal getInvoiceUnattributedTaxTotal(GenericValue invoice) {
-         List<GenericValue> invoiceTaxItems = null;
-         try {
-             Delegator delegator = invoice.getDelegator();
-             invoiceTaxItems = EntityQuery.use(delegator).from("InvoiceItem")
-                     .where(EntityCondition.makeCondition("invoiceId", invoice.get("invoiceId")),
-                             EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator)),
-                             EntityCondition.makeCondition("taxAuthPartyId", null)).queryList();
-         } catch (GenericEntityException e) {
-             Debug.logError(e, "Trouble getting InvoiceItem list", MODULE);
-             return null;
-         }
+        List<GenericValue> invoiceTaxItems = null;
+        try {
+            Delegator delegator = invoice.getDelegator();
+            invoiceTaxItems = EntityQuery.use(delegator).from("InvoiceItem")
+                    .where(EntityCondition.makeCondition("invoiceId", invoice.get("invoiceId")),
+                            EntityCondition.makeCondition("invoiceItemTypeId", EntityOperator.IN, getTaxableInvoiceItemTypeIds(delegator)),
+                            EntityCondition.makeCondition("taxAuthPartyId", null)).queryList();
+        } catch (GenericEntityException e) {
+            Debug.logError(e, "Trouble getting InvoiceItem list", MODULE);
+            return null;
+        }
         return getTaxTotalForInvoiceItems(invoiceTaxItems);
     }
 
@@ -820,7 +822,7 @@ public final class InvoiceWorker {
                 quantity = BigDecimal.ONE;
             }
             amount = amount.multiply(quantity);
-            amount = amount.setScale(taxDecimals, taxRounding);
+            amount = amount.setScale(TAX_DECIMALS, TAX_ROUNDING);
             taxTotal = taxTotal.add(amount);
         }
         return taxTotal.setScale(DECIMALS, ROUNDING);
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java
index caa759c..d6be139 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/GiftCertificateServices.java
@@ -120,7 +120,7 @@ public class GiftCertificateServices {
                 createAccountCtx.put("finAccountTypeId", FinAccountHelper.getGiftCertFinAccountTypeId());
                 createAccountCtx.put("productStoreId", productStoreId);
                 createAccountCtx.put("currencyUomId", currency);
-                createAccountCtx.put("finAccountName", accountName + " for party ["+partyId+"]");
+                createAccountCtx.put("finAccountName", accountName + " for party [" + partyId + "]");
                 createAccountCtx.put("userLogin", userLogin);
                 acctResult = dispatcher.runSync("createFinAccountForStore", createAccountCtx);
                 if (ServiceUtil.isError(acctResult)) {
@@ -460,7 +460,7 @@ public class GiftCertificateServices {
                     "AccountingGiftCertificateNumberCannotProcess",
                     UtilMisc.toMap("errorString", ex.getMessage()), locale));
         }
-}
+    }
 
 
     public static Map<String, Object> giftCertificateAuthorize(DispatchContext dctx, Map<String, ? extends Object> context) {
@@ -496,13 +496,13 @@ public class GiftCertificateServices {
                         finAccount = EntityQuery.use(delegator).from("FinAccount").where("finAccountId", finAccountId).queryOne();
                     }
                 } else {
-                        finAccount = FinAccountHelper.getFinAccountFromCode(giftCard.getString("cardNumber"), delegator);
-                        if (finAccount == null) {
-                            return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR,
-                                    "AccountingGiftCertificateNumberNotFound",
-                                    UtilMisc.toMap("finAccountId", ""), locale));
-                        }
-                        finAccountId = finAccount.getString("finAccountId");
+                    finAccount = FinAccountHelper.getFinAccountFromCode(giftCard.getString("cardNumber"), delegator);
+                    if (finAccount == null) {
+                        return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR,
+                                "AccountingGiftCertificateNumberNotFound",
+                                UtilMisc.toMap("finAccountId", ""), locale));
+                    }
+                    finAccountId = finAccount.getString("finAccountId");
                 }
             } else {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR,
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java
index 1ee57de..3e056fd 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentGatewayServices.java
@@ -985,7 +985,7 @@ public class PaymentGatewayServices {
                 releaseResult.put("orderPaymentPreference", paymentPref);
                 releaseResult.put("userLogin", userLogin);
                 Map<String, Object> resCtx = model.makeValid(releaseResult, ModelService.IN_PARAM);
-                releaseResRes = dispatcher.runSync(model.name,  resCtx);
+                releaseResRes = dispatcher.runSync(model.name, resCtx);
             } catch (GenericServiceException e) {
                 Debug.logError(e, "Trouble processing the release results", MODULE);
                 return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER,
@@ -1392,21 +1392,21 @@ public class PaymentGatewayServices {
                     try {
                         amountCaptured = (BigDecimal) ObjectType.simpleTypeOrObjectConvert(captureResult.get("captureAmount"), "BigDecimal", null, locale);
 
-                    if (amountCaptured == null) {
-                        amountCaptured = (BigDecimal) captureResult.get("processAmount");
-                    }
+                        if (amountCaptured == null) {
+                            amountCaptured = (BigDecimal) captureResult.get("processAmount");
+                        }
 
-                    amountCaptured = amountCaptured.setScale(DECIMALS, ROUNDING);
+                        amountCaptured = amountCaptured.setScale(DECIMALS, ROUNDING);
 
-                    // decrease amount of next payment preference to capture
-                    amountToCapture = amountToCapture.subtract(amountCaptured);
+                        // decrease amount of next payment preference to capture
+                        amountToCapture = amountToCapture.subtract(amountCaptured);
 
-                    // add the invoiceId to the result for processing, not for a replacement order
-                    if (!isReplacementOrder(orderHeader)) {
-                        captureResult.put("invoiceId", invoiceId);
-                    }
+                        // add the invoiceId to the result for processing, not for a replacement order
+                        if (!isReplacementOrder(orderHeader)) {
+                            captureResult.put("invoiceId", invoiceId);
+                        }
 
-                    // process the capture's results
+                        // process the capture's results
                         processResult(dctx, captureResult, userLogin, paymentPref, locale);
                     } catch (GeneralException e) {
                         Debug.logError(e, "Trouble processing the result; captureResult: " + captureResult, MODULE);
@@ -3214,7 +3214,7 @@ public class PaymentGatewayServices {
                 response.put("orderPaymentPreference", paymentPref);
                 response.put("userLogin", userLogin);
                 Map<String, Object> resCtx = model.makeValid(response, ModelService.IN_PARAM);
-                responseRes = dispatcher.runSync(model.name,  resCtx);
+                responseRes = dispatcher.runSync(model.name, resCtx);
             } catch (GenericServiceException e) {
                 Debug.logError(e, MODULE);
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -3244,7 +3244,7 @@ public class PaymentGatewayServices {
     }
 
     // Verify Credit Card (Manually) Service
-    public static Map<String, Object>verifyCreditCard(DispatchContext dctx, Map<String, ? extends Object> context) {
+    public static Map<String, Object> verifyCreditCard(DispatchContext dctx, Map<String, ? extends Object> context) {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         Delegator delegator = dctx.getDelegator();
         String productStoreId = (String) context.get("productStoreId");
@@ -3319,8 +3319,8 @@ public class PaymentGatewayServices {
         if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) < 0) {
             result.put("authResult", Boolean.FALSE);
         }
-            result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE,
-                    "AccountingPaymentTestProcessorMinimumPurchase", locale)));
+        result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE,
+                "AccountingPaymentTestProcessorMinimumPurchase", locale)));
         if (processAmount == null) {
             result.put("authResult", null);
         }
@@ -3349,13 +3349,13 @@ public class PaymentGatewayServices {
         if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) >= 0) {
             result.put("authResult", Boolean.TRUE);
         }
-            result.put("captureResult", Boolean.TRUE);
+        result.put("captureResult", Boolean.TRUE);
         if (processAmount != null && processAmount.compareTo(new BigDecimal("100.00")) < 0) {
             result.put("authResult", Boolean.FALSE);
         }
-            result.put("captureResult", Boolean.FALSE);
-            result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE,
-                    "AccountingPaymentTestProcessorMinimumPurchase", locale)));
+        result.put("captureResult", Boolean.FALSE);
+        result.put("customerRespMsgs", UtilMisc.toList(UtilProperties.getMessage(RESOURCE,
+                "AccountingPaymentTestProcessorMinimumPurchase", locale)));
         if (processAmount == null) {
             result.put("authResult", null);
         }
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java
index 3525740..97ad5c0 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/payment/PaymentMethodServices.java
@@ -48,8 +48,8 @@ import org.apache.ofbiz.service.ServiceUtil;
  */
 public class PaymentMethodServices {
 
-    public final static String MODULE = PaymentMethodServices.class.getName();
-    public final static String RESOURCE = "AccountingUiLabels";
+    private static final String MODULE = PaymentMethodServices.class.getName();
+    private static final String RESOURCE = "AccountingUiLabels";
     private static final String RES_ERROR = "AccountingUiLabels";
 
     /**
@@ -152,15 +152,15 @@ public class PaymentMethodServices {
         context.put("cardNumber", StringUtil.removeSpaces((String) context.get("cardNumber")));
         if (!UtilValidate.isCardMatch((String) context.get("cardType"), (String) context.get("cardNumber"))) {
             messages.add(
-                UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid",
-                    UtilMisc.toMap("cardType", (String) context.get("cardType"),
-                                   "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale));
+                    UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid",
+                            UtilMisc.toMap("cardType", (String) context.get("cardType"),
+                                    "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale));
         }
 
         if (!UtilValidate.isDateAfterToday((String) context.get("expireDate"))) {
             messages.add(
-                UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday",
-                    UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale));
+                    UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday",
+                            UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale));
         }
 
         if (messages.size() > 0) {
@@ -323,15 +323,15 @@ public class PaymentMethodServices {
 
         if (!UtilValidate.isCardMatch((String) context.get("cardType"), (String) context.get("cardNumber"))) {
             messages.add(
-                UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid",
-                    UtilMisc.toMap("cardType", (String) context.get("cardType"),
-                                   "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale));
+                    UtilProperties.getMessage(RESOURCE, "AccountingCreditCardNumberInvalid",
+                            UtilMisc.toMap("cardType", (String) context.get("cardType"),
+                                    "validCardType", UtilValidate.getCardType((String) context.get("cardNumber"))), locale));
         }
 
         if (!UtilValidate.isDateAfterToday((String) context.get("expireDate"))) {
             messages.add(
-                UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday",
-                    UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale));
+                    UtilProperties.getMessage(RESOURCE, "AccountingCreditCardExpireDateBeforeToday",
+                            UtilMisc.toMap("expireDate", (String) context.get("expireDate")), locale));
         }
 
         if (messages.size() > 0) {
@@ -921,12 +921,13 @@ public class PaymentMethodServices {
         result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
         return result;
     }
+
     public static Map<String, Object> createCheckAccount(DispatchContext ctx, Map<String, ? extends Object> context) {
         Map<String, Object> result = new HashMap<>();
         Delegator delegator = ctx.getDelegator();
         Security security = ctx.getSecurity();
-                GenericValue userLogin = (GenericValue) context.get("userLogin");
-                Locale locale = (Locale) context.get("locale");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
+        Locale locale = (Locale) context.get("locale");
         Timestamp now = UtilDateTime.nowTimestamp();
 
         String partyId = ServiceUtil.getPartyIdCheckSecurity(userLogin, security, context, result, "PAY_INFO", "_CREATE", "ACCOUNTING", "_CREATE");
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java
index ac88d28..b4eeb49 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/tax/TaxAuthorityServices.java
@@ -280,11 +280,11 @@ public class TaxAuthorityServices {
         }
 
         if (orderShippingAmount != null && orderShippingAmount.compareTo(BigDecimal.ZERO) > 0) {
-           for (GenericValue prod : productWeight.keySet()) {
-               List<GenericValue> taxList = getTaxAdjustments(delegator, prod, productStore, payToPartyId, billToPartyId,
-                       taxAuthoritySet, ZERO_BASE, ZERO_BASE, ZERO_BASE, orderShippingAmount, null, productWeight.get(prod));
-               orderAdjustments.addAll(taxList);
-           }
+            for (GenericValue prod : productWeight.keySet()) {
+                List<GenericValue> taxList = getTaxAdjustments(delegator, prod, productStore, payToPartyId, billToPartyId,
+                        taxAuthoritySet, ZERO_BASE, ZERO_BASE, ZERO_BASE, orderShippingAmount, null, productWeight.get(prod));
+                orderAdjustments.addAll(taxList);
+            }
         }
         if (orderPromotionsAmount != null && orderPromotionsAmount.compareTo(BigDecimal.ZERO) != 0) {
             List<GenericValue> taxList = getTaxAdjustments(delegator, null, productStore, payToPartyId, billToPartyId,
@@ -300,7 +300,7 @@ public class TaxAuthorityServices {
     }
 
     private static void getTaxAuthorities(Delegator delegator, GenericValue shippingAddress,
-            Set<GenericValue> taxAuthoritySet) throws GenericEntityException {
+                                          Set<GenericValue> taxAuthoritySet) throws GenericEntityException {
         Map<String, String> geoIdByTypeMap = new HashMap<>();
         if (shippingAddress != null) {
             if (UtilValidate.isNotEmpty(shippingAddress.getString("countryGeoId"))) {
@@ -332,13 +332,13 @@ public class TaxAuthorityServices {
     }
 
     private static List<GenericValue> getTaxAdjustments(Delegator delegator, GenericValue product,
-            GenericValue productStore,
-            String payToPartyId, String billToPartyId, Set<GenericValue> taxAuthoritySet,
-            BigDecimal itemPrice, BigDecimal itemQuantity, BigDecimal itemAmount,
-            BigDecimal shippingAmount, BigDecimal orderPromotionsAmount) {
-            return getTaxAdjustments(delegator, product, productStore, payToPartyId, billToPartyId,
-                    taxAuthoritySet, itemPrice, itemQuantity, itemAmount, shippingAmount,
-                    orderPromotionsAmount, null);
+                                                        GenericValue productStore,
+                                                        String payToPartyId, String billToPartyId, Set<GenericValue> taxAuthoritySet,
+                                                        BigDecimal itemPrice, BigDecimal itemQuantity, BigDecimal itemAmount,
+                                                        BigDecimal shippingAmount, BigDecimal orderPromotionsAmount) {
+        return getTaxAdjustments(delegator, product, productStore, payToPartyId, billToPartyId,
+                taxAuthoritySet, itemPrice, itemQuantity, itemAmount, shippingAmount,
+                orderPromotionsAmount, null);
     }
 
     private static List<GenericValue> getTaxAdjustments(Delegator delegator, GenericValue product,
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java
index 80eec2a..c54429d 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AIMPaymentServices.java
@@ -754,29 +754,29 @@ public class AIMPaymentServices {
     private static void processAuthCaptureTransResult(Map<String, Object> request, Map<String, Object> reply, Map<String, Object> results) {
         AuthorizeResponse ar = (AuthorizeResponse) reply.get("authorizeResponse");
         try {
-        Boolean authResult = (Boolean) reply.get("authResult");
-        results.put("authResult", authResult);
-        results.put("authFlag", ar.getReasonCode());
-        results.put("authMessage", ar.getReasonText());
-        results.put("captureResult", authResult);
-        results.put("captureFlag", ar.getReasonCode());
-        results.put("captureMessage", ar.getReasonText());
-        results.put("captureRefNum", ar.getTransactionId());
-        if (authResult) { //passed
-            results.put("authCode", ar.getAuthorizationCode());
-            results.put("authRefNum", ar.getTransactionId());
-            results.put("cvCode", ar.getCvResult());
-            results.put("avsCode", ar.getAvsResult());
-            if (BigDecimal.ZERO.compareTo(ar.getAmount()) == 0) {
-                results.put("processAmount", getXAmount(request));
+            Boolean authResult = (Boolean) reply.get("authResult");
+            results.put("authResult", authResult);
+            results.put("authFlag", ar.getReasonCode());
+            results.put("authMessage", ar.getReasonText());
+            results.put("captureResult", authResult);
+            results.put("captureFlag", ar.getReasonCode());
+            results.put("captureMessage", ar.getReasonText());
+            results.put("captureRefNum", ar.getTransactionId());
+            if (authResult) { //passed
+                results.put("authCode", ar.getAuthorizationCode());
+                results.put("authRefNum", ar.getTransactionId());
+                results.put("cvCode", ar.getCvResult());
+                results.put("avsCode", ar.getAvsResult());
+                if (BigDecimal.ZERO.compareTo(ar.getAmount()) == 0) {
+                    results.put("processAmount", getXAmount(request));
+                } else {
+                    results.put("processAmount", ar.getAmount());
+                }
             } else {
-                results.put("processAmount", ar.getAmount());
+                results.put("authCode", ar.getResponseCode());
+                results.put("processAmount", BigDecimal.ZERO);
+                results.put("authRefNum", AuthorizeResponse.ERROR);
             }
-        } else {
-            results.put("authCode", ar.getResponseCode());
-            results.put("processAmount", BigDecimal.ZERO);
-            results.put("authRefNum", AuthorizeResponse.ERROR);
-        }
         } catch (Exception ex) {
             Debug.logError(ex, MODULE);
             results.put("authCode", ar.getResponseCode());
@@ -791,7 +791,8 @@ public class AIMPaymentServices {
         String returnValue = "";
         if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) {
             try {
-                GenericValue payflowPro = EntityQuery.use(delegator).from("PaymentGatewayAuthorizeNet").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne();
+                GenericValue payflowPro = EntityQuery.use(delegator).from("PaymentGatewayAuthorizeNet").where("paymentGatewayConfigId",
+                        paymentGatewayConfigId).queryOne();
                 if (payflowPro != null) {
                     Object payflowProField = payflowPro.get(paymentGatewayConfigParameterName);
                     if (payflowProField != null) {
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java
index 59da857..7feff8e 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/orbital/OrbitalPaymentServices.java
@@ -598,17 +598,17 @@ public class OrbitalPaymentServices {
 
     private static void printTransResult(ResponseIF response) {
         Map<String, Object> generatedResponse = new HashMap<>();
-        generatedResponse.put("isGood",  response.isGood());
+        generatedResponse.put("isGood", response.isGood());
         generatedResponse.put("isError", response.isError());
-        generatedResponse.put("isQuickResponse",  response.isQuickResponse());
+        generatedResponse.put("isQuickResponse", response.isQuickResponse());
         generatedResponse.put("isApproved", response.isApproved());
-        generatedResponse.put("isDeclined",  response.isDeclined());
-        generatedResponse.put("AuthCode",  response.getAuthCode());
-        generatedResponse.put("TxRefNum",  response.getTxRefNum());
-        generatedResponse.put("ResponseCode",  response.getResponseCode());
-        generatedResponse.put("Status",  response.getStatus());
-        generatedResponse.put("Message",  response.getMessage());
-        generatedResponse.put("AVSCode",  response.getAVSResponseCode());
+        generatedResponse.put("isDeclined", response.isDeclined());
+        generatedResponse.put("AuthCode", response.getAuthCode());
+        generatedResponse.put("TxRefNum", response.getTxRefNum());
+        generatedResponse.put("ResponseCode", response.getResponseCode());
+        generatedResponse.put("Status", response.getStatus());
+        generatedResponse.put("Message", response.getMessage());
+        generatedResponse.put("AVSCode", response.getAVSResponseCode());
         generatedResponse.put("CVV2ResponseCode", response.getCVV2RespCode());
 
         Debug.logInfo("printTransResult === " + generatedResponse.toString(), MODULE);
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java
index 33e3bc2..607cd3a 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalEvents.java
@@ -135,15 +135,17 @@ public class PayPalEvents {
         String imageUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "imageUrl", configString, "payment.paypal.image");
 
         // get the paypal account
-        String payPalAccount = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "businessEmail", configString, "payment.paypal.business");
+        String payPalAccount = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "businessEmail", configString, "payment.paypal" +
+                ".business");
 
         if (UtilValidate.isEmpty(redirectUrl)
-            || UtilValidate.isEmpty(notifyUrl)
-            || UtilValidate.isEmpty(returnUrl)
-            || UtilValidate.isEmpty(imageUrl)
-            || UtilValidate.isEmpty(payPalAccount)) {
+                || UtilValidate.isEmpty(notifyUrl)
+                || UtilValidate.isEmpty(returnUrl)
+                || UtilValidate.isEmpty(imageUrl)
+                || UtilValidate.isEmpty(payPalAccount)) {
             Debug.logError("Payment properties is not configured properly, some notify URL from PayPal is not correctly defined!", MODULE);
-            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "payPalEvents.problemsGettingMerchantConfiguration", locale));
+            request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "payPalEvents.problemsGettingMerchantConfiguration",
+                    locale));
             return "error";
         }
 
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java
index 31759a1..bab1e67 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/paypal/PayPalServices.java
@@ -714,7 +714,7 @@ public class PayPalServices {
         Map<String, String> errorMessages = getErrorMessageMap(decoder);
         if (UtilValidate.isNotEmpty(errorMessages)) {
             if (errorMessages.containsKey("10417")) {
-                // "The transaction cannot complete successfully,  Instruct the customer to use an alternative payment method"
+                // "The transaction cannot complete successfully, Instruct the customer to use an alternative payment method"
                 // I've only encountered this once and there's no indication of the cause so the temporary solution is to try again
                 boolean retry = context.get("_RETRY_") == null || (Boolean) context.get("_RETRY_");
                 if (retry) {
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java
index 56d9ebb..2e7a8b9 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayPaymentServices.java
@@ -138,7 +138,7 @@ public class SagePayPaymentServices {
         billingInfo.put("currency", currency);
         billingInfo.put("description", orderId);
         billingInfo.put("cardNumber", cardNumber);
-        billingInfo.put("cardHolder",  nameOnCard);
+        billingInfo.put("cardHolder", nameOnCard);
         billingInfo.put("expiryDate", expireDate);
         billingInfo.put("cardType", cardType);
         billingInfo.put("cv2", securityCode);
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java
index 4f57a94..9dfde0b 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayServices.java
@@ -42,8 +42,7 @@ import org.apache.ofbiz.service.DispatchContext;
 import org.apache.ofbiz.service.ModelService;
 import org.apache.ofbiz.service.ServiceUtil;
 
-public class SagePayServices
-{
+public class SagePayServices {
     private static final String MODULE = SagePayServices.class.getName();
     private static final String RESOURCE = "AccountingUiLabels";
 
@@ -147,58 +146,138 @@ public class SagePayServices
         parameters.put("TxType", txType);
         parameters.put("Vendor", vendor);
 
-        if (vendorTxCode != null) {parameters.put("VendorTxCode", vendorTxCode); }
-        if (amount != null) {parameters.put("Amount", amount); }
-        if (currency != null) {parameters.put("Currency", currency); } //GBP/USD
-        if (description != null) {parameters.put("Description", description); }
-        if (cardHolder != null) {parameters.put("CardHolder", cardHolder); }
-        if (cardNumber != null) {parameters.put("CardNumber", cardNumber); }
-        if (expiryDate != null) {parameters.put("ExpiryDate", expiryDate); }
-        if (cardType != null) {parameters.put("CardType", cardType); }
+        if (vendorTxCode != null) {
+            parameters.put("VendorTxCode", vendorTxCode);
+        }
+        if (amount != null) {
+            parameters.put("Amount", amount);
+        }
+        if (currency != null) {
+            parameters.put("Currency", currency);
+        } //GBP/USD
+        if (description != null) {
+            parameters.put("Description", description);
+        }
+        if (cardHolder != null) {
+            parameters.put("CardHolder", cardHolder);
+        }
+        if (cardNumber != null) {
+            parameters.put("CardNumber", cardNumber);
+        }
+        if (cardType != null) {
+            parameters.put("CardType", cardType);
+        }
+        if (expiryDate != null) {
+            parameters.put("ExpiryDate", expiryDate);
+        }
 
         //start - billing details
-        if (billingSurname != null) {parameters.put("BillingSurname", billingSurname); }
-        if (billingFirstnames != null) {parameters.put("BillingFirstnames", billingFirstnames); }
-        if (billingAddress != null) {parameters.put("BillingAddress", billingAddress); }
-        if (billingAddress2 != null) {parameters.put("BillingAddress2", billingAddress2); }
-        if (billingCity != null) {parameters.put("BillingCity", billingCity); }
-        if (billingPostCode != null) {parameters.put("BillingPostCode", billingPostCode); }
-        if (billingCountry != null) {parameters.put("BillingCountry", billingCountry); }
-        if (billingState != null) {parameters.put("BillingState", billingState); }
-        if (billingPhone != null) {parameters.put("BillingPhone", billingPhone); }
+        if (billingSurname != null) {
+            parameters.put("BillingSurname", billingSurname);
+        }
+        if (billingFirstnames != null) {
+            parameters.put("BillingFirstnames", billingFirstnames);
+        }
+        if (billingAddress != null) {
+            parameters.put("BillingAddress", billingAddress);
+        }
+        if (billingAddress2 != null) {
+            parameters.put("BillingAddress2", billingAddress2);
+        }
+        if (billingCity != null) {
+            parameters.put("BillingCity", billingCity);
+        }
+        if (billingPostCode != null) {
+            parameters.put("BillingPostCode", billingPostCode);
+        }
+        if (billingCountry != null) {
+            parameters.put("BillingCountry", billingCountry);
+        }
+        if (billingState != null) {
+            parameters.put("BillingState", billingState);
+        }
+        if (billingPhone != null) {
+            parameters.put("BillingPhone", billingPhone);
+        }
         //end - billing details
 
         //start - delivery details
         if (isBillingSameAsDelivery != null && isBillingSameAsDelivery) {
-            if (billingSurname != null) {parameters.put("DeliverySurname", billingSurname); }
-            if (billingFirstnames != null) {parameters.put("DeliveryFirstnames", billingFirstnames); }
-            if (billingAddress != null) {parameters.put("DeliveryAddress", billingAddress); }
-            if (billingAddress2 != null) {parameters.put("DeliveryAddress2", billingAddress2); }
-            if (billingCity != null) {parameters.put("DeliveryCity", billingCity); }
-            if (billingPostCode != null) {parameters.put("DeliveryPostCode", billingPostCode); }
-            if (billingCountry != null) {parameters.put("DeliveryCountry", billingCountry); }
-            if (billingState != null) {parameters.put("DeliveryState", billingState); }
-            if (billingPhone != null) {parameters.put("DeliveryPhone", billingPhone); }
+            if (billingSurname != null) {
+                parameters.put("DeliverySurname", billingSurname);
+            }
+            if (billingFirstnames != null) {
+                parameters.put("DeliveryFirstnames", billingFirstnames);
+            }
+            if (billingAddress != null) {
+                parameters.put("DeliveryAddress", billingAddress);
+            }
+            if (billingAddress2 != null) {
+                parameters.put("DeliveryAddress2", billingAddress2);
+            }
+            if (billingCity != null) {
+                parameters.put("DeliveryCity", billingCity);
+            }
+            if (billingPostCode != null) {
+                parameters.put("DeliveryPostCode", billingPostCode);
+            }
+            if (billingCountry != null) {
+                parameters.put("DeliveryCountry", billingCountry);
+            }
+            if (billingState != null) {
+                parameters.put("DeliveryState", billingState);
+            }
+            if (billingPhone != null) {
+                parameters.put("DeliveryPhone", billingPhone);
+            }
         } else {
-            if (deliverySurname != null) {parameters.put("DeliverySurname", deliverySurname); }
-            if (deliveryFirstnames != null) {parameters.put("DeliveryFirstnames", deliveryFirstnames); }
-            if (deliveryAddress != null) {parameters.put("DeliveryAddress", deliveryAddress); }
-            if (deliveryAddress2 != null) {parameters.put("DeliveryAddress2", deliveryAddress2); }
-            if (deliveryCity != null) {parameters.put("DeliveryCity", deliveryCity); }
-            if (deliveryPostCode != null) {parameters.put("DeliveryPostCode", deliveryPostCode); }
-            if (deliveryCountry != null) {parameters.put("DeliveryCountry", deliveryCountry); }
-            if (deliveryState != null) {parameters.put("DeliveryState", deliveryState); }
-            if (deliveryPhone != null) {parameters.put("DeliveryPhone", deliveryPhone); }
+            if (deliverySurname != null) {
+                parameters.put("DeliverySurname", deliverySurname);
+            }
+            if (deliveryFirstnames != null) {
+                parameters.put("DeliveryFirstnames", deliveryFirstnames);
+            }
+            if (deliveryAddress != null) {
+                parameters.put("DeliveryAddress", deliveryAddress);
+            }
+            if (deliveryAddress2 != null) {
+                parameters.put("DeliveryAddress2", deliveryAddress2);
+            }
+            if (deliveryCity != null) {
+                parameters.put("DeliveryCity", deliveryCity);
+            }
+            if (deliveryPostCode != null) {
+                parameters.put("DeliveryPostCode", deliveryPostCode);
+            }
+            if (deliveryCountry != null) {
+                parameters.put("DeliveryCountry", deliveryCountry);
+            }
+            if (deliveryState != null) {
+                parameters.put("DeliveryState", deliveryState);
+            }
+            if (deliveryPhone != null) {
+                parameters.put("DeliveryPhone", deliveryPhone);
+            }
         }
         //end - delivery details
         //end - required parameters
 
         //start - optional parameters
-        if (cv2 != null) {parameters.put("CV2", cv2); }
-        if (startDate != null) {parameters.put("StartDate", startDate); }
-        if (issueNumber != null) {parameters.put("IssueNumber", issueNumber); }
-        if (basket != null) {parameters.put("Basket", basket); }
-        if (clientIPAddress != null) {parameters.put("ClientIPAddress", clientIPAddress); }
+        if (cv2 != null) {
+            parameters.put("CV2", cv2);
+        }
+        if (startDate != null) {
+            parameters.put("StartDate", startDate);
+        }
+        if (issueNumber != null) {
+            parameters.put("IssueNumber", issueNumber);
+        }
+        if (basket != null) {
+            parameters.put("Basket", basket);
+        }
+        if (clientIPAddress != null) {
+            parameters.put("ClientIPAddress", clientIPAddress);
+        }
         //end - optional parameters
         //end - authentication parameters
 
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java
index 57a247b..c351f70 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/sagepay/SagePayUtil.java
@@ -31,6 +31,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+
 import org.apache.http.HttpEntity;
 import org.apache.http.HttpHost;
 import org.apache.http.HttpResponse;
@@ -46,79 +47,144 @@ import org.apache.ofbiz.base.util.Debug;
 public final class SagePayUtil {
 
     private static final String MODULE = SagePayUtil.class.getName();
-    private SagePayUtil() { }
 
-    public static Map<String, Object> buildCardAuthorisationPaymentResponse
-    (Boolean authResult, String authCode, String authFlag, BigDecimal processAmount, String authRefNum, String authAltRefNum, String authMessage) {
+    private SagePayUtil() {
+    }
+
+    public static Map<String, Object> buildCardAuthorisationPaymentResponse(Boolean authResult,
+            String authCode, String authFlag, BigDecimal processAmount, String authRefNum, String authAltRefNum, String authMessage) {
 
         Map<String, Object> result = new HashMap<>();
-        if (authResult != null) {result.put("authResult", authResult); }
-        if (authCode != null) {result.put("authCode", authCode); }
-        if (authFlag != null) {result.put("authFlag", authFlag); }
-        if (processAmount != null) {result.put("processAmount", processAmount); }
-        if (authRefNum != null) {result.put("authRefNum", authRefNum); }
-        if (authAltRefNum != null) {result.put("authAltRefNum", authAltRefNum); }
-        if (authMessage != null) {result.put("authMessage", authMessage); }
+        if (authResult != null) {
+            result.put("authResult", authResult);
+        }
+        if (authCode != null) {
+            result.put("authCode", authCode);
+        }
+        if (authFlag != null) {
+            result.put("authFlag", authFlag);
+        }
+        if (processAmount != null) {
+            result.put("processAmount", processAmount);
+        }
+        if (authRefNum != null) {
+            result.put("authRefNum", authRefNum);
+        }
+        if (authAltRefNum != null) {
+            result.put("authAltRefNum", authAltRefNum);
+        }
+        if (authMessage != null) {
+            result.put("authMessage", authMessage);
+        }
         return result;
     }
 
-    public static Map<String, Object> buildCardCapturePaymentResponse
-    (Boolean captureResult, String captureCode, String captureFlag, BigDecimal captureAmount, String captureRefNum, String captureAltRefNum, String captureMessage) {
+    public static Map<String, Object> buildCardCapturePaymentResponse(Boolean captureResult,
+            String captureCode, String captureFlag, BigDecimal captureAmount, String captureRefNum, String captureAltRefNum, String captureMessage) {
 
         Map<String, Object> result = new HashMap<>();
-        if (captureResult != null) {result.put("captureResult", captureResult); }
-        if (captureCode != null) {result.put("captureCode", captureCode); }
-        if (captureFlag != null) {result.put("captureFlag", captureFlag); }
-        if (captureAmount != null) {result.put("captureAmount", captureAmount); }
-        if (captureRefNum != null) {result.put("captureRefNum", captureRefNum); }
-        if (captureAltRefNum != null) {result.put("captureAltRefNum", captureAltRefNum); }
-        if (captureMessage != null) {result.put("captureMessage", captureMessage); }
+        if (captureResult != null) {
+            result.put("captureResult", captureResult);
+        }
+        if (captureCode != null) {
+            result.put("captureCode", captureCode);
+        }
+        if (captureFlag != null) {
+            result.put("captureFlag", captureFlag);
+        }
+        if (captureAmount != null) {
+            result.put("captureAmount", captureAmount);
+        }
+        if (captureRefNum != null) {
+            result.put("captureRefNum", captureRefNum);
+        }
+        if (captureAltRefNum != null) {
+            result.put("captureAltRefNum", captureAltRefNum);
+        }
+        if (captureMessage != null) {
+            result.put("captureMessage", captureMessage);
+        }
         return result;
     }
 
-    public static Map<String, Object> buildCardReleasePaymentResponse
-    (Boolean releaseResult, String releaseCode, BigDecimal releaseAmount, String releaseRefNum, String releaseAltRefNum, String releaseMessage) {
+    public static Map<String, Object> buildCardReleasePaymentResponse(Boolean releaseResult,
+            String releaseCode, BigDecimal releaseAmount, String releaseRefNum, String releaseAltRefNum, String releaseMessage) {
 
         Map<String, Object> result = new HashMap<>();
-        if (releaseResult != null) {result.put("releaseResult", releaseResult); }
-        if (releaseCode != null) {result.put("releaseCode", releaseCode); }
-        if (releaseAmount != null) {result.put("releaseAmount", releaseAmount); }
-        if (releaseRefNum != null) {result.put("releaseRefNum", releaseRefNum); }
-        if (releaseAltRefNum != null) {result.put("releaseAltRefNum", releaseAltRefNum); }
-        if (releaseMessage != null) {result.put("releaseMessage", releaseMessage); }
+        if (releaseResult != null) {
+            result.put("releaseResult", releaseResult);
+        }
+        if (releaseCode != null) {
+            result.put("releaseCode", releaseCode);
+        }
+        if (releaseAmount != null) {
+            result.put("releaseAmount", releaseAmount);
+        }
+        if (releaseRefNum != null) {
+            result.put("releaseRefNum", releaseRefNum);
+        }
+        if (releaseAltRefNum != null) {
+            result.put("releaseAltRefNum", releaseAltRefNum);
+        }
+        if (releaseMessage != null) {
+            result.put("releaseMessage", releaseMessage);
+        }
         return result;
     }
 
-    public static Map<String, Object> buildCardVoidPaymentResponse
-    (Boolean refundResult, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) {
+    public static Map<String, Object> buildCardVoidPaymentResponse(Boolean refundResult,
+            BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) {
 
         Map<String, Object> result = new HashMap<>();
-        if (refundResult != null) {result.put("refundResult", refundResult); }
-        if (refundAmount != null) {result.put("refundAmount", refundAmount); }
-        if (refundRefNum != null) {result.put("refundRefNum", refundRefNum); }
-        if (refundAltRefNum != null) {result.put("refundAltRefNum", refundAltRefNum); }
-        if (refundMessage != null) {result.put("refundMessage", refundMessage); }
+        if (refundResult != null) {
+            result.put("refundResult", refundResult);
+        }
+        if (refundAmount != null) {
+            result.put("refundAmount", refundAmount);
+        }
+        if (refundRefNum != null) {
+            result.put("refundRefNum", refundRefNum);
+        }
+        if (refundAltRefNum != null) {
+            result.put("refundAltRefNum", refundAltRefNum);
+        }
+        if (refundMessage != null) {
+            result.put("refundMessage", refundMessage);
+        }
         return result;
     }
 
-    public static Map<String, Object> buildCardRefundPaymentResponse
-    (Boolean refundResult, String refundCode, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) {
+    public static Map<String, Object> buildCardRefundPaymentResponse(Boolean refundResult,
+            String refundCode, BigDecimal refundAmount, String refundRefNum, String refundAltRefNum, String refundMessage) {
 
         Map<String, Object> result = new HashMap<>();
-        if (refundResult != null) {result.put("refundResult", refundResult); }
-        if (refundCode != null) {result.put("refundCode", refundCode); }
-        if (refundAmount != null) {result.put("refundAmount", refundAmount); }
-        if (refundRefNum != null) {result.put("refundRefNum", refundRefNum); }
-        if (refundAltRefNum != null) {result.put("refundAltRefNum", refundAltRefNum); }
-        if (refundMessage != null) {result.put("refundMessage", refundMessage); }
+        if (refundResult != null) {
+            result.put("refundResult", refundResult);
+        }
+        if (refundCode != null) {
+            result.put("refundCode", refundCode);
+        }
+        if (refundAmount != null) {
+            result.put("refundAmount", refundAmount);
+        }
+        if (refundRefNum != null) {
+            result.put("refundRefNum", refundRefNum);
+        }
+        if (refundAltRefNum != null) {
+            result.put("refundAltRefNum", refundAltRefNum);
+        }
+        if (refundMessage != null) {
+            result.put("refundMessage", refundMessage);
+        }
         return result;
     }
 
     /**
      * Builds HttpHost with the given SagePayProperties.
+     *
      * @param props SagePay properties
-     * @throws IllegalArgumentException if neither productionHost nor testingHost found in properties.
      * @return
+     * @throws IllegalArgumentException if neither productionHost nor testingHost found in properties.
      */
     public static HttpHost getHost(Map<String, String> props) {
         String hostUrl = null;
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java
index 26e561c..5aedd27 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/securepay/SecurePayServiceTest.java
@@ -67,7 +67,7 @@ public class SecurePayServiceTest extends OFBizTestCase {
         orderId = "Demo1002";
         creditCard = delegator.makeValue("CreditCard", UtilMisc.toMap(
                 "cardType", "CCT_VISA",
-                "expireDate", "10/2011",  // mm/yyyy, gets converted to mm/yy
+                "expireDate", "10/2011", // mm/yyyy, gets converted to mm/yy
                 "cardNumber", "4444333322221111"));
         billingAddress = delegator.makeValue("PostalAddress", UtilMisc.toMap(
                 "toName", "The customer Name",
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java
index e1dd58d..f042f80 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/valuelink/ValueLinkApi.java
@@ -419,7 +419,7 @@ public class ValueLinkApi {
         byte[] secretKey = ka.generateSecret();
 
         if (debug) {
-            Debug.logInfo("Secret Key : " + StringUtil.toHexString(secretKey) + " / " + secretKey.length,  MODULE);
+            Debug.logInfo("Secret Key : " + StringUtil.toHexString(secretKey) + " / " + secretKey.length, MODULE);
         }
 
         // generate 3DES from secret key using VL algorithm (KEK)
diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java
index f6a5755..a4a74c8 100644
--- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java
+++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/verisign/PayflowPro.java
@@ -108,7 +108,7 @@ public class PayflowPro {
             data.put("CUSTCODE", party.getString("partyId"));
 
             // transaction type
-            if (comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "preAuth", configString, "payment.verisign.preAuth",  "Y")) {
+            if (comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "preAuth", configString, "payment.verisign.preAuth", "Y")) {
                 data.put("TRXTYPE", "A");
                 // only support re-auth for auth types; sale types don't do it
                 if (authTrans != null) {
@@ -147,7 +147,7 @@ public class PayflowPro {
             // gather the address info
             if (ps != null) {
                 String street = ps.getString("address1") + ((UtilValidate.isNotEmpty(ps.getString("address2"))) ? " " + ps.getString("address2") : "");
-                data.put("STREET"+"["+street.length()+"]", street);
+                data.put("STREET" + "[" + street.length() + "]", street);
                 data.put("ZIP", ps.getString("postalCode"));
             }
         }
@@ -168,7 +168,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
@@ -253,7 +253,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
@@ -335,7 +335,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
@@ -416,7 +416,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&AUTHCODE=T&PNREF=" + (new Date()).getTime() + "&RESPMSG=Testing";
@@ -480,7 +480,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&TOKEN=" + (new Date()).getTime() + "&RESPMSG=Testing";
@@ -583,7 +583,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&PAYERID=" + (new Date()).getTime() + "&RESPMSG=Testing";
@@ -664,7 +664,7 @@ public class PayflowPro {
             Debug.logVerbose("Sending to Verisign: " + params.toString(), MODULE);
         }
         String resp;
-        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit",  "false")) {
+        if (!comparePaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "enableTransmit", configString, "payment.verisign.enable_transmit", "false")) {
             resp = pfp.submitTransaction(params.toString(), pfp.generateRequestId());
         } else {
             resp = "RESULT=0&PAYERID=" + (new Date()).getTime() + "&RESPMSG=Testing";
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java
index 0a3151d..cf126b2 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementEvents.java
@@ -120,16 +120,16 @@ public class ContentManagementEvents {
                         }
                     } else if (UtilValidate.isNotEmpty(pubValue)) {
                         if ("Y".equalsIgnoreCase(pubValue)) {
-                                serviceIn.put("thruDate", UtilDateTime.nowTimestamp());
-                                Timestamp fromDate = (Timestamp) map.get(pubContentId + "FromDate");
-                                serviceIn.put("fromDate", fromDate);
-                                result = dispatcher.runSync("updateContentAssoc", serviceIn);
-                                if (ServiceUtil.isError(result)) {
-                                    String errorMessage = ServiceUtil.getErrorMessage(result);
-                                    request.setAttribute("_ERROR_MESSAGE_", errorMessage);
-                                    Debug.logError(errorMessage, MODULE);
-                                    return "error";
-                                }
+                            serviceIn.put("thruDate", UtilDateTime.nowTimestamp());
+                            Timestamp fromDate = (Timestamp) map.get(pubContentId + "FromDate");
+                            serviceIn.put("fromDate", fromDate);
+                            result = dispatcher.runSync("updateContentAssoc", serviceIn);
+                            if (ServiceUtil.isError(result)) {
+                                String errorMessage = ServiceUtil.getErrorMessage(result);
+                                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
+                                Debug.logError(errorMessage, MODULE);
+                                return "error";
+                            }
                         }
                     }
                 } catch (GenericServiceException e) {
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java
index 284c1e3..8d91954 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementServices.java
@@ -282,7 +282,7 @@ public class ContentManagementServices {
                 Map<String, Object> thisResult = dispatcher.runSync("updateContent", contentContext);
                 if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentContentUpdatingError", UtilMisc.toMap("serviceName",
-                        "persistContentAndAssoc"), locale), null, null, thisResult);
+                            "persistContentAndAssoc"), locale), null, null, thisResult);
                 }
             } else {
                 Map<String, Object> contentContext = new HashMap<>();
@@ -295,7 +295,7 @@ public class ContentManagementServices {
                 Map<String, Object> thisResult = dispatcher.runSync("createContent", contentContext);
                 if (ServiceUtil.isError(thisResult) || ServiceUtil.isFailure(thisResult)) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentContentCreatingError", UtilMisc.toMap("serviceName",
-                        "persistContentAndAssoc"), locale), null, null, thisResult);
+                            "persistContentAndAssoc"), locale), null, null, thisResult);
                 }
                 contentId = (String) thisResult.get("contentId");
             }
@@ -309,7 +309,7 @@ public class ContentManagementServices {
                     Set<String> contentPurposeSet = new LinkedHashSet<>(contentPurposeList);
                     for (String contentPurposeTypeId : contentPurposeSet) {
                         GenericValue contentPurpose = delegator.makeValue("ContentPurpose", UtilMisc.toMap("contentId", contentId,
-                            "contentPurposeTypeId", contentPurposeTypeId));
+                                "contentPurposeTypeId", contentPurposeTypeId));
                         contentPurpose.create();
                     }
                 } catch (GenericEntityException e) {
@@ -830,12 +830,12 @@ public class ContentManagementServices {
         }
         EntityCondition conditionType = EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList);
         EntityCondition conditionMain = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("contentIdTo",
-            EntityOperator.EQUALS, contentIdTo), conditionType), EntityOperator.AND);
+                EntityOperator.EQUALS, contentIdTo), conditionType), EntityOperator.AND);
         try {
             List<GenericValue> listAll = EntityQuery.use(delegator).from("ContentAssoc")
-                .where(conditionMain)
-                .orderBy("sequenceNum", "fromDate", "createdDate")
-                .filterByDate().queryList();
+                    .where(conditionMain)
+                    .orderBy("sequenceNum", "fromDate", "createdDate")
+                    .filterByDate().queryList();
             String contentId = (String) context.get("contentId");
             String dir = (String) context.get("dir");
             int seqNum = seqIncrement;
@@ -994,7 +994,7 @@ public class ContentManagementServices {
             thisContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
             if (thisContent == null) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId),
-                    locale));
+                        locale));
             }
             thisContent.set("contentTypeId", contentTypeId);
             thisContent.store();
@@ -1035,7 +1035,7 @@ public class ContentManagementServices {
             thisContent = EntityQuery.use(delegator).from("Content").where("contentId", contentId).queryOne();
             if (thisContent == null) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
-                    "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), locale));
+                        "ContentNoContentFound", UtilMisc.toMap("contentId", contentId), locale));
             }
             thisContent.set("contentTypeId", "OUTLINE_NODE");
             thisContent.store();
@@ -1047,7 +1047,7 @@ public class ContentManagementServices {
                     kidContent.put("contentTypeId", "PAGE_NODE");
                     kidContent.store();
                     List<GenericValue> kids2 = ContentWorker.getAssociatedContent(kidContent, "from", UtilMisc.toList("SUB_CONTENT"), null, null,
-                        null);
+                            null);
                     for (GenericValue kidContent2 : kids2) {
                         updatePageNodeChildren(kidContent2, context);
                     }
@@ -1162,11 +1162,11 @@ public class ContentManagementServices {
         String contentIdTo = (String) context.get("contentId");
         try {
             List<GenericValue> lst = EntityQuery.use(delegator).from("ContentAssocDataResourceViewFrom")
-                .where("caContentIdTo", contentIdTo,
-                    "caContentAssocTypeId", "SUB_CONTENT",
-                    "caThruDate", null)
-                .orderBy("caSequenceNum", "caFromDate", "createdDate")
-                .queryList();
+                    .where("caContentIdTo", contentIdTo,
+                            "caContentAssocTypeId", "SUB_CONTENT",
+                            "caThruDate", null)
+                    .orderBy("caSequenceNum", "caFromDate", "createdDate")
+                    .queryList();
             results.put("_LIST_", lst);
         } catch (GenericEntityException e) {
             Debug.logError(e, MODULE);
@@ -1221,7 +1221,7 @@ public class ContentManagementServices {
             GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
             if (content == null) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId),
-                    locale));
+                        locale));
             }
             Long leafCount = (Long) content.get("childLeafCount");
             if (leafCount == null) {
@@ -1231,7 +1231,7 @@ public class ContentManagementServices {
             int changeBranchCount = 1;
 
             ContentManagementWorker.updateStatsBottomUp(delegator, contentId, UtilMisc.toList(contentAssocTypeId), changeBranchCount,
-                changeLeafCount);
+                    changeLeafCount);
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError(e.toString());
         }
@@ -1249,7 +1249,7 @@ public class ContentManagementServices {
             GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
             if (content == null) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentNoContentFound", UtilMisc.toMap("contentId", contentId),
-                    locale));
+                        locale));
             }
             Long leafCount = (Long) content.get("childLeafCount");
             if (leafCount == null) {
@@ -1259,7 +1259,7 @@ public class ContentManagementServices {
             int changeBranchCount = -1;
 
             ContentManagementWorker.updateStatsBottomUp(delegator, contentId, UtilMisc.toList(contentAssocTypeId), changeBranchCount,
-                changeLeafCount);
+                    changeLeafCount);
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError(e.toString());
         }
@@ -1303,10 +1303,10 @@ public class ContentManagementServices {
         GenericValue contentRole = null;
         try {
             contentRole = EntityQuery.use(delegator).from("ContentRole")
-                .where("partyId", partyId, "contentId", webPubPt, "roleTypeId", roleTypeId)
-                .orderBy("fromDate DESC")
-                .cache().filterByDate()
-                .queryFirst();
+                    .where("partyId", partyId, "contentId", webPubPt, "roleTypeId", roleTypeId)
+                    .orderBy("fromDate DESC")
+                    .cache().filterByDate()
+                    .queryFirst();
             if (contentRole != null) {
                 hasExistingContentRole = true;
             }
@@ -1386,12 +1386,12 @@ public class ContentManagementServices {
         GenericValue productContent = null;
         try {
             List<GenericValue> lst = EntityQuery.use(delegator).from("ProductContent")
-                .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS")
-                .orderBy("purchaseFromDate", "purchaseThruDate")
-                .filterByDate("purchaseFromDate", "purchaseThruDate")
-                .cache().queryList();
+                    .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS")
+                    .orderBy("purchaseFromDate", "purchaseThruDate")
+                    .filterByDate("purchaseFromDate", "purchaseThruDate")
+                    .cache().queryList();
             List<GenericValue> listThrusOnly = EntityUtil.filterOutByCondition(lst, EntityCondition.makeCondition("purchaseThruDate",
-                EntityOperator.EQUALS, null));
+                    EntityOperator.EQUALS, null));
             if (listThrusOnly.size() > 0) {
                 productContent = listThrusOnly.get(0);
             } else if (lst.size() > 0) {
@@ -1437,8 +1437,8 @@ public class ContentManagementServices {
         GenericValue orderHeader = null;
         try {
             GenericValue orderRole = EntityQuery.use(delegator).from("OrderRole")
-                .where("orderId", orderId, "roleTypeId", "END_USER_CUSTOMER")
-                .queryFirst();
+                    .where("orderId", orderId, "roleTypeId", "END_USER_CUSTOMER")
+                    .queryFirst();
             if (orderRole != null) {
                 String partyId = (String) orderRole.get("partyId");
                 context.put("partyId", partyId);
@@ -1460,8 +1460,8 @@ public class ContentManagementServices {
                 BigDecimal qty = orderItem.getBigDecimal("quantity");
                 String productId = (String) orderItem.get("productId");
                 long productContentCount = EntityQuery.use(delegator).from("ProductContent")
-                    .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS")
-                    .filterByDate().queryCount();
+                        .where("productId", productId, "productContentTypeId", "ONLINE_ACCESS")
+                        .filterByDate().queryCount();
                 if (productContentCount > 0) {
                     context.put("productId", productId);
                     context.put("quantity", qty.intValue());
@@ -1514,7 +1514,7 @@ public class ContentManagementServices {
     }
 
     public static Map<String, Object> followNodeChildrenMethod(GenericValue content, LocalDispatcher dispatcher, String serviceName, Map<String,
-        Object> context) throws GenericEntityException, GenericServiceException {
+            Object> context) throws GenericEntityException, GenericServiceException {
         Map<String, Object> result = null;
         String contentId = content.getString("contentId");
         List<String> contentAssocTypeIdList = UtilGenerics.cast(context.get("contentAssocTypeIdList"));
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java
index 218dc35..3fd62b7 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/ContentManagementWorker.java
@@ -303,7 +303,7 @@ public final class ContentManagementWorker {
             }
             Map<String, Object> results = null;
             results = EntityPermissionChecker.checkPermission(content, statusId, userLogin, passedPurposes, targetOperationList, roles, delegator,
-                security, entityAction);
+                    security, entityAction);
             String permissionStatus = (String) results.get("permissionStatus");
             if (permissionStatus != null && "granted".equalsIgnoreCase(permissionStatus)) {
                 String[] arr = {contentId, templateTitle};
@@ -323,8 +323,8 @@ public final class ContentManagementWorker {
         List<GenericValue> relatedPubPts = null;
         try {
             relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc")
-                .where("contentIdTo", parentPubPt, "contentAssocTypeId", "SUBSITE")
-                .cache().queryList();
+                    .where("contentIdTo", parentPubPt, "contentAssocTypeId", "SUBSITE")
+                    .cache().queryList();
         } catch (GenericEntityException e) {
             throw new GeneralException(e.getMessage());
         }
@@ -451,8 +451,8 @@ public final class ContentManagementWorker {
     public static String getParentWebSitePublishPointId(Delegator delegator, String contentId) throws GenericEntityException {
         String contentIdTo = null;
         GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc")
-            .where("contentId", contentId, "contentAssocTypeId", "SUBSITE")
-            .filterByDate().cache().queryFirst();
+                .where("contentId", contentId, "contentAssocTypeId", "SUBSITE")
+                .filterByDate().cache().queryFirst();
         if (contentAssoc != null) {
             contentIdTo = contentAssoc.getString("contentIdTo");
         }
@@ -478,7 +478,7 @@ public final class ContentManagementWorker {
         // and another map (publishPointMapAll) that points to one of the top-level points.
         List<GenericValue> allPublishPointList = getAllPublishPoints(delegator, rootPubId);
         List<String[]> publishPointList = getPermittedPublishPoints(delegator, allPublishPointList, userLogin, security, permittedAction,
-            permittedOperations, passedRoles);
+                permittedOperations, passedRoles);
         Map<String, Object> publishPointMap = new HashMap<>();
         Map<String, Object> publishPointMapAll = new HashMap<>();
         for (String[] arr : publishPointList) {
@@ -500,8 +500,8 @@ public final class ContentManagementWorker {
         List<GenericValue> assocValueList = null;
         try {
             assocValueList = EntityQuery.use(delegator).from("ContentAssoc")
-                .where("contentId", targContentId, "contentAssocTypeId", "PUBLISH_LINK")
-                .filterByDate().cache().queryList();
+                    .where("contentId", targContentId, "contentAssocTypeId", "PUBLISH_LINK")
+                    .filterByDate().cache().queryList();
         } catch (GenericEntityException e) {
             throw new GeneralException(e.getMessage());
         }
@@ -544,7 +544,7 @@ public final class ContentManagementWorker {
             // TODO check if we want contentTypes to be filled/used, else this should be removed
             List<String> contentTypes = null;
             Map<String, Object> results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "To",
-                null, null, assocTypes, contentTypes, Boolean.TRUE, null, null);
+                    null, null, assocTypes, contentTypes, Boolean.TRUE, null, null);
             List<GenericValue> valueList = UtilGenerics.cast(results.get("entityList"));
             if (valueList.size() > 0) {
                 GenericValue value = valueList.get(0);
@@ -583,7 +583,7 @@ public final class ContentManagementWorker {
             }
             Map<String, Object> results = null;
             results = EntityPermissionChecker.checkPermission(content, statusId, userLogin, passedPurposes, targetOperationList, roles, delegator,
-                security, entityAction);
+                    security, entityAction);
             String permissionStatus = (String) results.get("permissionStatus");
             if (permissionStatus != null && "granted".equalsIgnoreCase(permissionStatus)) {
                 String[] arr = {contentId, contentName};
@@ -603,8 +603,8 @@ public final class ContentManagementWorker {
         List<GenericValue> relatedPubPts = null;
         try {
             relatedPubPts = EntityQuery.use(delegator).from("ContentAssoc")
-                .where("contentIdTo", parentPubPt, "contentAssocTypeId", "DEPARTMENT")
-                .cache().queryList();
+                    .where("contentIdTo", parentPubPt, "contentAssocTypeId", "DEPARTMENT")
+                    .cache().queryList();
 
         } catch (GenericEntityException e) {
             throw new GeneralException(e.getMessage());
@@ -640,7 +640,7 @@ public final class ContentManagementWorker {
             conditionMain.add(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList));
         }
         List<GenericValue> contentAssocs = EntityQuery.use(delegator).from("ContentAssoc").where(conditionMain)
-            .filterByDate().cache().queryList();
+                .filterByDate().cache().queryList();
         for (GenericValue contentAssoc : contentAssocs) {
             String subContentId = contentAssoc.getString("contentId");
             subLeafCount += updateStatsTopDown(delegator, subContentId, typeList);
@@ -663,9 +663,9 @@ public final class ContentManagementWorker {
             throw new RuntimeException("No entity found for id=" + contentId);
 
         List<GenericValue> contentAssocs = EntityQuery.use(delegator).from("ContentAssoc")
-            .where(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList),
-                EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId))
-            .cache().filterByDate().queryList();
+                .where(EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.IN, typeList),
+                        EntityCondition.makeCondition("contentId", EntityOperator.EQUALS, contentId))
+                .cache().filterByDate().queryList();
         for (GenericValue contentAssoc : contentAssocs) {
             String contentIdTo = contentAssoc.getString("contentIdTo");
             GenericValue contentTo = EntityQuery.use(delegator).from("Content").where("contentId", contentIdTo).queryOne();
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java
index 3249281..0483378 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/cms/CmsEvents.java
@@ -118,241 +118,240 @@ public class CmsEvents {
                 throw new GeneralRuntimeException("Error in the response writer/output stream while rendering content.", e);
             } catch (GeneralException e) {
                 throw new GeneralRuntimeException("Error rendering content", e);
-            }
-        } else {
-        // If an override view is present then use that in place of request.getPathInfo()
-        String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_");
-        if (UtilValidate.isNotEmpty(overrideViewUri)) {
-            pathInfo = overrideViewUri;
-        } else {
-            pathInfo = request.getPathInfo();
-            if (targetRequest.equals(actualRequest) && pathInfo != null) {
-                // was called directly -- path info is everything after the request
-                String[] pathParsed = pathInfo.split("/", 3);
-                if (pathParsed.length > 2) {
-                    pathInfo = pathParsed[2];
-                } else {
-                    pathInfo = null;
-                }
-            } // if called through the default request, there is no request in pathinfo
-        }
-
-        // if path info is null or path info is / (i.e application mounted on root); check for a default content
-        if (pathInfo == null || "/".equals(pathInfo)) {
-            GenericValue defaultContent = null;
-            try {
-                defaultContent = EntityQuery.use(delegator).from("WebSiteContent")
-                        .where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE")
-                        .orderBy("-fromDate").filterByDate().cache().queryFirst();
-            } catch (GenericEntityException e) {
-                Debug.logError(e, MODULE);
-            }
-            if (defaultContent != null) {
-                pathInfo = defaultContent.getString("contentId");
-            }
-        }
-
-        // check for path alias first
-        if (pathInfo != null) {
-            // clean up the pathinfo for parsing
-            pathInfo = pathInfo.trim();
-            if (pathInfo.startsWith("/")) {
-                pathInfo = pathInfo.substring(1);
-            }
-            if (pathInfo.endsWith("/")) {
-                pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
-            }
-
-            GenericValue pathAlias = null;
-            try {
-                pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryFirst();
-            } catch (GenericEntityException e) {
-                Debug.logError(e, MODULE);
             }
-            if (pathAlias != null) {
-                String alias = pathAlias.getString("aliasTo");
-                contentId = pathAlias.getString("contentId");
-                mapKey = pathAlias.getString("mapKey");
-                if (contentId == null && UtilValidate.isNotEmpty(alias)) {
-                    if (!alias.startsWith("/")) {
-                        alias = "/" + alias;
+        } else {
+            // If an override view is present then use that in place of request.getPathInfo()
+            String overrideViewUri = (String) request.getAttribute("_CURRENT_CHAIN_VIEW_");
+            if (UtilValidate.isNotEmpty(overrideViewUri)) {
+                pathInfo = overrideViewUri;
+            } else {
+                pathInfo = request.getPathInfo();
+                if (targetRequest.equals(actualRequest) && pathInfo != null) {
+                    // was called directly -- path info is everything after the request
+                    String[] pathParsed = pathInfo.split("/", 3);
+                    if (pathParsed.length > 2) {
+                        pathInfo = pathParsed[2];
+                    } else {
+                        pathInfo = null;
                     }
-
-                    String context = request.getContextPath();
-                    String location = context + request.getServletPath();
-                    GenericValue webSite = WebSiteWorker.getWebSite(request);
-                    if (webSite != null && webSite.getString("hostedPathAlias") != null && !"ROOT".equals(pathInfo))
-                        location += "/" + webSite.getString("hostedPathAlias");
-
-                    String uriWithContext = request.getRequestURI();
-                    String uri = uriWithContext.substring(context.length());
-                    uri = uri.substring(0, uri.lastIndexOf('/'));
-
-                    response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
-                    response.setHeader("Location", location + uri + alias);
-                    response.setHeader("Connection", "close");
-
-                    return null; // null to not process any views
-                }
+                } // if called through the default request, there is no request in pathinfo
             }
 
-            // get the contentId/mapKey from URL
-            if (contentId == null) {
-                if (Debug.verboseOn()) {
-                    Debug.logVerbose("Current PathInfo: " + pathInfo, MODULE);
-                }
-                String[] pathSplit = pathInfo.split("/");
-                if (Debug.verboseOn()) {
-                    Debug.logVerbose("Split pathinfo: " + pathSplit.length, MODULE);
+            // if path info is null or path info is / (i.e application mounted on root); check for a default content
+            if (pathInfo == null || "/".equals(pathInfo)) {
+                GenericValue defaultContent = null;
+                try {
+                    defaultContent = EntityQuery.use(delegator).from("WebSiteContent")
+                            .where("webSiteId", webSiteId, "webSiteContentTypeId", "DEFAULT_PAGE")
+                            .orderBy("-fromDate").filterByDate().cache().queryFirst();
+                } catch (GenericEntityException e) {
+                    Debug.logError(e, MODULE);
                 }
-                contentId = pathSplit[0];
-                if (pathSplit.length > 1) {
-                    mapKey = pathSplit[1];
+                if (defaultContent != null) {
+                    pathInfo = defaultContent.getString("contentId");
                 }
             }
 
-
-            // verify the request content is associated with the current website
-            int statusCode = -1;
-            boolean hasErrorPage = false;
-
-            if (contentId != null) {
-                try {
-                    statusCode = verifyContentToWebSite(delegator, webSiteId, contentId);
-                } catch (GeneralException e) {
-                    Debug.logError(e, MODULE);
-                    throw new GeneralRuntimeException(e.getMessage(), e);
+            // check for path alias first
+            if (pathInfo != null) {
+                // clean up the pathinfo for parsing
+                pathInfo = pathInfo.trim();
+                if (pathInfo.startsWith("/")) {
+                    pathInfo = pathInfo.substring(1);
+                }
+                if (pathInfo.endsWith("/")) {
+                    pathInfo = pathInfo.substring(0, pathInfo.length() - 1);
                 }
-            } else {
-                statusCode = HttpServletResponse.SC_NOT_FOUND;
-            }
 
-            // We try to find a specific Error page for this website concerning the status code
-            if (statusCode != HttpServletResponse.SC_OK) {
-                GenericValue errorContainer = null;
+                GenericValue pathAlias = null;
                 try {
-                    errorContainer = EntityQuery.use(delegator).from("WebSiteContent")
-                            .where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT")
-                            .orderBy("fromDate").filterByDate().cache().queryFirst();
+                    pathAlias = EntityQuery.use(delegator).from("WebSitePathAlias").where("webSiteId", webSiteId, "pathAlias", pathInfo).orderBy("-fromDate").cache().filterByDate().queryFirst();
                 } catch (GenericEntityException e) {
                     Debug.logError(e, MODULE);
                 }
+                if (pathAlias != null) {
+                    String alias = pathAlias.getString("aliasTo");
+                    contentId = pathAlias.getString("contentId");
+                    mapKey = pathAlias.getString("mapKey");
+                    if (contentId == null && UtilValidate.isNotEmpty(alias)) {
+                        if (!alias.startsWith("/")) {
+                            alias = "/" + alias;
+                        }
+
+                        String context = request.getContextPath();
+                        String location = context + request.getServletPath();
+                        GenericValue webSite = WebSiteWorker.getWebSite(request);
+                        if (webSite != null && webSite.getString("hostedPathAlias") != null && !"ROOT".equals(pathInfo))
+                            location += "/" + webSite.getString("hostedPathAlias");
+
+                        String uriWithContext = request.getRequestURI();
+                        String uri = uriWithContext.substring(context.length());
+                        uri = uri.substring(0, uri.lastIndexOf('/'));
+
+                        response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
+                        response.setHeader("Location", location + uri + alias);
+                        response.setHeader("Connection", "close");
 
-                if (errorContainer != null) {
+                        return null; // null to not process any views
+                    }
+                }
+
+                // get the contentId/mapKey from URL
+                if (contentId == null) {
+                    if (Debug.verboseOn()) {
+                        Debug.logVerbose("Current PathInfo: " + pathInfo, MODULE);
+                    }
+                    String[] pathSplit = pathInfo.split("/");
                     if (Debug.verboseOn()) {
-                        Debug.logVerbose("Found error containers: " + errorContainer, MODULE);
+                        Debug.logVerbose("Split pathinfo: " + pathSplit.length, MODULE);
                     }
+                    contentId = pathSplit[0];
+                    if (pathSplit.length > 1) {
+                        mapKey = pathSplit[1];
+                    }
+                }
+
+
+                // verify the request content is associated with the current website
+                int statusCode = -1;
+                boolean hasErrorPage = false;
+
+                if (contentId != null) {
+                    try {
+                        statusCode = verifyContentToWebSite(delegator, webSiteId, contentId);
+                    } catch (GeneralException e) {
+                        Debug.logError(e, MODULE);
+                        throw new GeneralRuntimeException(e.getMessage(), e);
+                    }
+                } else {
+                    statusCode = HttpServletResponse.SC_NOT_FOUND;
+                }
 
-                    GenericValue errorPage = null;
+                // We try to find a specific Error page for this website concerning the status code
+                if (statusCode != HttpServletResponse.SC_OK) {
+                    GenericValue errorContainer = null;
                     try {
-                        errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo")
-                                .where("contentIdStart", errorContainer.getString("contentId"),
-                                        "caContentAssocTypeId", "TREE_CHILD",
-                                        "contentTypeId", "DOCUMENT",
-                                        "caMapKey", String.valueOf(statusCode))
-                                .filterByDate().queryFirst();
+                        errorContainer = EntityQuery.use(delegator).from("WebSiteContent")
+                                .where("webSiteId", webSiteId, "webSiteContentTypeId", "ERROR_ROOT")
+                                .orderBy("fromDate").filterByDate().cache().queryFirst();
                     } catch (GenericEntityException e) {
                         Debug.logError(e, MODULE);
                     }
-                    if (errorPage != null) {
+
+                    if (errorContainer != null) {
                         if (Debug.verboseOn()) {
-                             Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, MODULE);
+                            Debug.logVerbose("Found error containers: " + errorContainer, MODULE);
                         }
-                        contentId = errorPage.getString("contentId");
-                    } else {
-                        if (Debug.verboseOn()) {
-                             Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, MODULE);
+
+                        GenericValue errorPage = null;
+                        try {
+                            errorPage = EntityQuery.use(delegator).from("ContentAssocViewTo")
+                                    .where("contentIdStart", errorContainer.getString("contentId"),
+                                            "caContentAssocTypeId", "TREE_CHILD",
+                                            "contentTypeId", "DOCUMENT",
+                                            "caMapKey", String.valueOf(statusCode))
+                                    .filterByDate().queryFirst();
+                        } catch (GenericEntityException e) {
+                            Debug.logError(e, MODULE);
                         }
-                        contentId = errorContainer.getString("contentId");
-                    }
-                    mapKey = null;
-                    hasErrorPage = true;
-                }
-                // We try to find a generic content Error page concerning the status code
-                if (!hasErrorPage) {
-                    try {
-                        GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne();
                         if (errorPage != null) {
                             if (Debug.verboseOn()) {
-                                Debug.logVerbose("Found generic page " + statusCode, MODULE);
+                                 Debug.logVerbose("Found error pages " + statusCode + " : " + errorPage, MODULE);
                             }
                             contentId = errorPage.getString("contentId");
-                            mapKey = null;
-                            hasErrorPage = true;
+                        } else {
+                            if (Debug.verboseOn()) {
+                                 Debug.logVerbose("No specific error page, falling back to the Error Container for " + statusCode, MODULE);
+                            }
+                            contentId = errorContainer.getString("contentId");
+                        }
+                        mapKey = null;
+                        hasErrorPage = true;
+                    }
+                    // We try to find a generic content Error page concerning the status code
+                    if (!hasErrorPage) {
+                        try {
+                            GenericValue errorPage = EntityQuery.use(delegator).from("Content").where("contentId", "CONTENT_ERROR_" + statusCode).cache().queryOne();
+                            if (errorPage != null) {
+                                if (Debug.verboseOn()) {
+                                    Debug.logVerbose("Found generic page " + statusCode, MODULE);
+                                }
+                                contentId = errorPage.getString("contentId");
+                                mapKey = null;
+                                hasErrorPage = true;
+                            }
+                        } catch (GenericEntityException e) {
+                            Debug.logError(e, MODULE);
                         }
-                    } catch (GenericEntityException e) {
-                        Debug.logError(e, MODULE);
                     }
                 }
 
-            }
+                if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) {
+                    // create the template map
+                    MapStack<String> templateMap = MapStack.create();
+                    ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext);
+                    templateMap.put("statusCode", statusCode);
 
-            if (statusCode == HttpServletResponse.SC_OK || hasErrorPage) {
-                // create the template map
-                MapStack<String> templateMap = MapStack.create();
-                ScreenRenderer.populateContextForRequest(templateMap, null, request, response, servletContext);
-                templateMap.put("statusCode", statusCode);
+                    // make the link prefix
+                    templateMap.put("_REQUEST_HANDLER_", RequestHandler.from(request));
 
-                // make the link prefix
-                templateMap.put("_REQUEST_HANDLER_", RequestHandler.from(request));
+                    //Cache Headers
+                    UtilHttp.setResponseBrowserProxyNoCache(response);
+                    //Security Headers
+                    UtilHttp.setResponseBrowserDefaultSecurityHeaders(response, null);
 
-                //Cache Headers
-                UtilHttp.setResponseBrowserProxyNoCache(response);
-                //Security Headers
-                UtilHttp.setResponseBrowserDefaultSecurityHeaders(response, null);
+                    response.setStatus(statusCode);
 
-                response.setStatus(statusCode);
+                    try {
+                        writer = response.getWriter();
+                        // TODO: replace "screen" to support dynamic rendering of different output
+                        if (visualTheme == null) {
+                            String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
+                            visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
+                        }
+                        FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response);
+                        templateMap.put("formStringRenderer", formStringRenderer);
+
+                        // if use web analytics
+                        List<GenericValue> webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList();
+                        // render
+                        if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) {
+                            ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics);
+                        } else if (UtilValidate.isEmpty(mapKey)) {
+                            ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true);
+                        } else {
+                            ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true);
+                        }
 
-                try {
-                    writer = response.getWriter();
-                    // TODO: replace "screen" to support dynamic rendering of different output
-                    if (visualTheme == null) {
-                        String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
-                        visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
-                    }
-                    FormStringRenderer formStringRenderer = new MacroFormRenderer(visualTheme.getModelTheme().getFormRendererLocation("screen"), request, response);
-                    templateMap.put("formStringRenderer", formStringRenderer);
-
-                    // if use web analytics
-                    List<GenericValue> webAnalytics = EntityQuery.use(delegator).from("WebAnalyticsConfig").where("webSiteId", webSiteId).queryList();
-                    // render
-                    if (UtilValidate.isNotEmpty(webAnalytics) && hasErrorPage) {
-                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true, webAnalytics);
-                    } else if (UtilValidate.isEmpty(mapKey)) {
-                        ContentWorker.renderContentAsText(dispatcher, contentId, writer, templateMap, locale, "text/html", null, null, true);
-                    } else {
-                        ContentWorker.renderSubContentAsText(dispatcher, contentId, writer, mapKey, templateMap, locale, "text/html", true);
+                    } catch (TemplateException e) {
+                        throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
+                    } catch (IOException e) {
+                        throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
+                    } catch (GeneralException e) {
+                        throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
                     }
 
-                } catch (TemplateException e) {
-                    throw new GeneralRuntimeException(String.format("Error creating form renderer while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
-                } catch (IOException e) {
-                    throw new GeneralRuntimeException(String.format("Error in the response writer/output stream while rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
-                } catch (GeneralException e) {
-                    throw new GeneralRuntimeException(String.format("Error rendering content [%s] with path alias [%s]", contentId, pathInfo), e);
-                }
-
-                return "success";
-            } else {
-                String contentName = null;
-                String siteName = null;
-                try {
-                    GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
-                    if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) {
-                        contentName = content.getString("contentName");
-                    } else {
-                        request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]");
-                        return "error";
+                    return "success";
+                } else {
+                    String contentName = null;
+                    String siteName = null;
+                    try {
+                        GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId).cache().queryOne();
+                        if (content != null && UtilValidate.isNotEmpty(content.getString("contentName"))) {
+                            contentName = content.getString("contentName");
+                        } else {
+                            request.setAttribute("_ERROR_MESSAGE_", "Content: [" + contentId + "] is not a publish point for the current website: [" + webSiteId + "]");
+                            return "error";
+                        }
+                        siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName");
+                    } catch (GenericEntityException e) {
+                        Debug.logError(e, MODULE);
                     }
-                    siteName = EntityQuery.use(delegator).from("WebSite").where("webSiteId", webSiteId).cache().queryOne().getString("siteName");
-                } catch (GenericEntityException e) {
-                    Debug.logError(e, MODULE);
+                    request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]");
+                    return "error";
                 }
-                request.setAttribute("_ERROR_MESSAGE_", "Content: " + contentName + " [" + contentId + "] is not a publish point for the current website: " + siteName + " [" + webSiteId + "]");
-                return "error";
             }
         }
-        }
         String siteName = null;
         GenericValue webSite = null;
         try {
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java
index fa1235e..229fcf3 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/cms/ContentJsonEvents.java
@@ -56,8 +56,8 @@ public class ContentJsonEvents {
         String contentId = request.getParameter("contentId");
 
         EntityCondition condition = EntityCondition.makeCondition(
-            EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)),
-            EntityUtil.getFilterByDateExpr());
+                EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)),
+                EntityUtil.getFilterByDateExpr());
         List<GenericValue> assocs = delegator.findList("ContentAssoc", condition, null, null, null, false);
 
         List<Map<String, Object>> nodes = new LinkedList<>();
@@ -133,8 +133,8 @@ public class ContentJsonEvents {
     public static void deleteContent(Delegator delegator, String contentId) throws GenericEntityException {
         Timestamp now = UtilDateTime.nowTimestamp();
         EntityCondition condition = EntityCondition.makeCondition(
-            EntityCondition.makeCondition(UtilMisc.toMap("contentIdTo", contentId)),
-            EntityUtil.getFilterByDateExpr());
+                EntityCondition.makeCondition(UtilMisc.toMap("contentIdTo", contentId)),
+                EntityUtil.getFilterByDateExpr());
         List<GenericValue> assocs = delegator.findList("ContentAssoc", condition, null, null, null, true);
         for (GenericValue assoc : assocs) {
             assoc.set("thruDate", now);
@@ -146,8 +146,8 @@ public class ContentJsonEvents {
     private static void deleteWebPathAliases(Delegator delegator, String contentId) throws GenericEntityException {
         Timestamp now = UtilDateTime.nowTimestamp();
         EntityCondition condition = EntityCondition.makeCondition(
-            EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)),
-            EntityUtil.getFilterByDateExpr());
+                EntityCondition.makeCondition(UtilMisc.toMap("contentId", contentId)),
+                EntityUtil.getFilterByDateExpr());
         List<GenericValue> pathAliases = delegator.findList("WebSitePathAlias", condition, null, null, null, true);
         for (GenericValue alias : pathAliases) {
             alias.set("thruDate", now);
@@ -172,14 +172,14 @@ public class ContentJsonEvents {
         Map<String, Object> data = UtilMisc.toMap("title", (Object) contentName);
 
         Map<String, Object> attr = UtilMisc.toMap(
-            "id", assoc.get("contentIdTo"),
-            "contentId", assoc.get("contentId"),
-            "fromDate", assoc.getTimestamp("fromDate").toString(),
-            "contentAssocTypeId", assoc.get("contentAssocTypeId"));
+                "id", assoc.get("contentIdTo"),
+                "contentId", assoc.get("contentId"),
+                "fromDate", assoc.getTimestamp("fromDate").toString(),
+                "contentAssocTypeId", assoc.get("contentAssocTypeId"));
 
         Map<String, Object> node = UtilMisc.toMap("data", (Object) data, "attr", (Object) attr);
 
-        List<GenericValue> assocChildren  = content != null ? content.getRelated("FromContentAssoc", null, null, true) : null;
+        List<GenericValue> assocChildren = content != null ? content.getRelated("FromContentAssoc", null, null, true) : null;
         assocChildren = EntityUtil.filterByDate(assocChildren);
         if (!CollectionUtils.isEmpty(assocChildren)) {
             node.put("state", "closed");
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java
index 455c355..fa7d648 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/compdoc/CompDocEvents.java
@@ -102,7 +102,7 @@ public class CompDocEvents {
             Map<String, Object> persistResult = dispatcher.runSync("persistContentAndAssoc", persistMap);
             if (ServiceUtil.isError(persistResult)) {
                 String errMsg = "Error running serviceName, 'persistContentAndAssoc'. " + ServiceUtil.getErrorMessage(persistResult);
-                request.setAttribute("_ERROR_MESSAGE_",  "<li>" + errMsg + "</li>");
+                request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
                 Debug.logError(errMsg, MODULE);
                 return "error";
             }
@@ -121,7 +121,7 @@ public class CompDocEvents {
             Map<String, Object> result = dispatcher.runSync("persistContentRevisionAndItem", contentRevisionMap);
             if (ServiceUtil.isError(result)) {
                 String errMsg = "Error running serviceName, 'persistContentRevisionAndItem'. " + ServiceUtil.getErrorMessage(result);
-                request.setAttribute("_ERROR_MESSAGE_",  "<li>" + errMsg + "</li>");
+                request.setAttribute("_ERROR_MESSAGE_", "<li>" + errMsg + "</li>");
                 Debug.logError(errMsg, MODULE);
                 return "error";
             }
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java
index fa5464b..e7274a4 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentPermissionServices.java
@@ -105,13 +105,13 @@ public class ContentPermissionServices {
         Boolean bDisplayFailCond = (Boolean) context.get("displayFailCond");
         boolean displayFailCond = false;
         if (bDisplayFailCond != null && bDisplayFailCond) {
-             displayFailCond = true;
+            displayFailCond = true;
         }
-                Debug.logInfo("displayFailCond(0):" + displayFailCond, "");
+        Debug.logInfo("displayFailCond(0):" + displayFailCond, "");
         Boolean bDisplayPassCond = (Boolean) context.get("displayPassCond");
         boolean displayPassCond = false;
         if (bDisplayPassCond != null && bDisplayPassCond) {
-             displayPassCond = true;
+            displayPassCond = true;
         }
         Debug.logInfo("displayPassCond(0):" + displayPassCond, "");
         Map<String, Object> results = new HashMap<>();
@@ -150,7 +150,7 @@ public class ContentPermissionServices {
             passedPurposes.addAll(purposesFromString);
         }
 
-        EntityPermissionChecker.StdAuxiliaryValueGetter auxGetter = new EntityPermissionChecker.StdAuxiliaryValueGetter("ContentPurpose",  "contentPurposeTypeId", "contentId");
+        EntityPermissionChecker.StdAuxiliaryValueGetter auxGetter = new EntityPermissionChecker.StdAuxiliaryValueGetter("ContentPurpose", "contentPurposeTypeId", "contentId");
         // Sometimes permissions need to be checked before an entity is created, so
         // there needs to be a method for setting a purpose list
         auxGetter.setList(passedPurposes);
@@ -163,10 +163,10 @@ public class ContentPermissionServices {
             }
             targetOperations.addAll(operationsFromString);
         }
-        EntityPermissionChecker.StdPermissionConditionGetter permCondGetter = new EntityPermissionChecker.StdPermissionConditionGetter("ContentPurposeOperation",  "contentOperationId", "roleTypeId", "statusId", "contentPurposeTypeId", "privilegeEnumId");
+        EntityPermissionChecker.StdPermissionConditionGetter permCondGetter = new EntityPermissionChecker.StdPermissionConditionGetter("ContentPurposeOperation", "contentOperationId", "roleTypeId", "statusId", "contentPurposeTypeId", "privilegeEnumId");
         permCondGetter.setOperationList(targetOperations);
 
-        EntityPermissionChecker.StdRelatedRoleGetter roleGetter = new EntityPermissionChecker.StdRelatedRoleGetter("Content",  "roleTypeId", "contentId", "partyId", "ownerContentId", "ContentRole");
+        EntityPermissionChecker.StdRelatedRoleGetter roleGetter = new EntityPermissionChecker.StdRelatedRoleGetter("Content", "roleTypeId", "contentId", "partyId", "ownerContentId", "ContentRole");
         List<String> passedRoles = UtilGenerics.cast(context.get("roleTypeList"));
         if (passedRoles == null) passedRoles = new LinkedList<>();
         String roleTypeString = (String) context.get("roleTypeString");
@@ -189,23 +189,26 @@ public class ContentPermissionServices {
             results.put("permissionStatus", "granted");
             permissionStatus = "granted";
             if (displayPassCond) {
-                 errBuf.append("\n    hasEntityPermission(" + entityAction + "): PASSED");
+                errBuf.append("\n    hasEntityPermission(" + entityAction + "): PASSED");
             }
 
         } else {
             if (displayFailCond) {
-                 errBuf.append("\n    hasEntityPermission(" + entityAction + "): FAILED");
+                errBuf.append("\n    hasEntityPermission(" + entityAction + "): FAILED");
             }
 
-            if (content != null)
+            if (content != null) {
                 entityIds.add(content);
+            }
             String quickCheckContentId = (String) context.get("quickCheckContentId");
             if (UtilValidate.isNotEmpty(quickCheckContentId)) {
-               List<String> quickList = StringUtil.split(quickCheckContentId, "|");
-               if (UtilValidate.isNotEmpty(quickList)) entityIds.addAll(quickList);
+                List<String> quickList = StringUtil.split(quickCheckContentId, "|");
+                if (UtilValidate.isNotEmpty(quickList)) {
+                    entityIds.addAll(quickList);
+                }
             }
             try {
-                boolean check = EntityPermissionChecker.checkPermissionMethod(delegator, partyId,  "Content", entityIds, auxGetter, roleGetter, permCondGetter);
+                boolean check = EntityPermissionChecker.checkPermissionMethod(delegator, partyId, "Content", entityIds, auxGetter, roleGetter, permCondGetter);
                 if (check) {
                     results.put("permissionStatus", "granted");
                 } else {
@@ -220,27 +223,27 @@ public class ContentPermissionServices {
         }
 
         if (("granted".equals(permissionStatus) && displayPassCond)
-            || ("rejected".equals(permissionStatus) && displayFailCond)) {
+                || ("rejected".equals(permissionStatus) && displayFailCond)) {
             // Don't show this if passed on 'hasEntityPermission'
             if (displayFailCond || displayPassCond) {
-              if (!passed) {
-                 errBuf.append("\n    targetOperations:");
-                 errBuf.append(targetOperations);
+                if (!passed) {
+                    errBuf.append("\n    targetOperations:");
+                    errBuf.append(targetOperations);
 
-                 String errMsg = permCondGetter.dumpAsText();
-                 errBuf.append("\n");
-                 errBuf.append(errMsg);
-                 errBuf.append("\n    partyId:");
-                 errBuf.append(partyId);
-                 errBuf.append("\n    entityIds:");
-                 errBuf.append(entityIds);
+                    String errMsg = permCondGetter.dumpAsText();
+                    errBuf.append("\n");
+                    errBuf.append(errMsg);
+                    errBuf.append("\n    partyId:");
+                    errBuf.append(partyId);
+                    errBuf.append("\n    entityIds:");
+                    errBuf.append(entityIds);
 
-                 errBuf.append("\n    auxList:");
-                 errBuf.append(auxGetter.getList());
+                    errBuf.append("\n    auxList:");
+                    errBuf.append(auxGetter.getList());
 
-                 errBuf.append("\n    roleList:");
-                 errBuf.append(roleGetter.getList());
-              }
+                    errBuf.append("\n    roleList:");
+                    errBuf.append(roleGetter.getList());
+                }
 
             }
         }
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java
index 8cd4a5e..0a79c42 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentServicesComplex.java
@@ -243,30 +243,34 @@ public class ContentServicesComplex {
         List<GenericValue> contentAssocDataResourceList = new LinkedList<>();
         Locale locale = Locale.getDefault(); // TODO: this needs to be passed in
         try {
-        for (GenericValue contentAssocView : contentAssocsTypeFiltered) {
-            GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc").where(UtilMisc.toMap("contentId", contentAssocView.getString("contentId"),
-                    "contentIdTo", contentAssocView.getString(contentFieldName), "contentAssocTypeId", contentAssocView.getString("caContentAssocTypeId"),
-                    "fromDate", contentAssocView.getTimestamp("caFromDate"))).queryOne();
-            content = contentAssoc.getRelatedOne(assocRelationName, true);
-            if (UtilValidate.isNotEmpty(contentTypes)) {
-                String contentTypeId = (String) content.get("contentTypeId");
-                if (contentTypes.contains(contentTypeId)) {
+            for (GenericValue contentAssocView : contentAssocsTypeFiltered) {
+                GenericValue contentAssoc = EntityQuery.use(delegator).from("ContentAssoc").where(UtilMisc.toMap("contentId",
+                        contentAssocView.getString("contentId"),
+                        "contentIdTo", contentAssocView.getString(contentFieldName), "contentAssocTypeId", contentAssocView.getString(
+                                "caContentAssocTypeId"),
+                        "fromDate", contentAssocView.getTimestamp("caFromDate"))).queryOne();
+                content = contentAssoc.getRelatedOne(assocRelationName, true);
+                if (UtilValidate.isNotEmpty(contentTypes)) {
+                    String contentTypeId = (String) content.get("contentTypeId");
+                    if (contentTypes.contains(contentTypeId)) {
+                        contentAssocDataResourceView = delegator.makeValue(viewName);
+                        contentAssocDataResourceView.setAllFields(content, true, null, null);
+                    }
+                } else {
                     contentAssocDataResourceView = delegator.makeValue(viewName);
                     contentAssocDataResourceView.setAllFields(content, true, null, null);
                 }
-            } else {
-                contentAssocDataResourceView = delegator.makeValue(viewName);
-                contentAssocDataResourceView.setAllFields(content, true, null, null);
-            }
-            SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut", contentAssoc, contentAssocDataResourceView, new LinkedList<>(), locale);
-            String dataResourceId = content.getString("dataResourceId");
-            if (UtilValidate.isNotEmpty(dataResourceId))
-                dataResource = content.getRelatedOne("DataResource", true);
-            if (dataResource != null) {
-                SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut", dataResource, contentAssocDataResourceView, new LinkedList<>(), locale);
+                SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "contentAssocOut",
+                        contentAssoc, contentAssocDataResourceView, new LinkedList<>(), locale);
+                String dataResourceId = content.getString("dataResourceId");
+                if (UtilValidate.isNotEmpty(dataResourceId))
+                    dataResource = content.getRelatedOne("DataResource", true);
+                if (dataResource != null) {
+                    SimpleMapProcessor.runSimpleMapProcessor("component://content/minilang/ContentManagementMapProcessors.xml", "dataResourceOut",
+                            dataResource, contentAssocDataResourceView, new LinkedList<>(), locale);
+                }
+                contentAssocDataResourceList.add(contentAssocDataResourceView);
             }
-            contentAssocDataResourceList.add(contentAssocDataResourceView);
-        }
         } catch (GenericEntityException e) {
             Debug.logError(e, MODULE);
             return ServiceUtil.returnError(e.getMessage());
@@ -274,7 +278,7 @@ public class ContentServicesComplex {
 
         if (UtilValidate.isNotEmpty(orderBy)) {
             List<String> orderByList = StringUtil.split(orderBy, "|");
-           contentAssocDataResourceList = EntityUtil.orderBy(contentAssocDataResourceList, orderByList);
+            contentAssocDataResourceList = EntityUtil.orderBy(contentAssocDataResourceList, orderByList);
         }
         Map<String, Object> results = new HashMap<>();
         results.put("entityList", contentAssocDataResourceList);
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java
index 3cef6e8..f06a36c 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWorker.java
@@ -719,13 +719,13 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor
             boolean isPick = booleanDataType(thisNode.get("isPick"));
             kids.add(thisNode);
             if (isPick) {
-                    Integer count = (Integer) currentNode.get("count");
-                    if (count == null) {
-                        count = 1;
-                    } else {
-                        count = count + 1;
-                    }
-                    currentNode.put("count", count);
+                Integer count = (Integer) currentNode.get("count");
+                if (count == null) {
+                    count = 1;
+                } else {
+                    count = count + 1;
+                }
+                currentNode.put("count", count);
             }
         }
     }
@@ -971,22 +971,23 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor
         }
     }
 
-    public static List<Map<String, Object>> getContentAncestryNodeTrail(Delegator delegator, String contentId, String contentAssocTypeId, String direction) throws GenericEntityException {
-         List<GenericValue> contentAncestorList = new LinkedList<>();
-         List<Map<String, Object>> nodeTrail = new LinkedList<>();
-         getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList);
-         for (GenericValue value : contentAncestorList) {
-             Map<String, Object> thisNode = ContentWorker.makeNode(value);
-             nodeTrail.add(thisNode);
-         }
-         return nodeTrail;
+    public static List<Map<String, Object>> getContentAncestryNodeTrail(Delegator delegator, String contentId, String contentAssocTypeId,
+                                                                        String direction) throws GenericEntityException {
+        List<GenericValue> contentAncestorList = new LinkedList<>();
+        List<Map<String, Object>> nodeTrail = new LinkedList<>();
+        getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList);
+        for (GenericValue value : contentAncestorList) {
+            Map<String, Object> thisNode = ContentWorker.makeNode(value);
+            nodeTrail.add(thisNode);
+        }
+        return nodeTrail;
     }
 
     public static String getContentAncestryNodeTrailCsv(Delegator delegator, String contentId, String contentAssocTypeId, String direction) throws GenericEntityException {
-         List<GenericValue> contentAncestorList = new LinkedList<>();
-         getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList);
-         String csv = StringUtil.join(contentAncestorList, ",");
-         return csv;
+        List<GenericValue> contentAncestorList = new LinkedList<>();
+        getContentAncestry(delegator, contentId, contentAssocTypeId, direction, contentAncestorList);
+        String csv = StringUtil.join(contentAncestorList, ",");
+        return csv;
     }
 
     public static void getContentAncestryValues(Delegator delegator, String contentId, String contentAssocTypeId, String direction, List<GenericValue> contentAncestorList) throws GenericEntityException {
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java
index 3c01d41..15115c9 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentWrapper.java
@@ -26,6 +26,6 @@ import org.apache.ofbiz.base.util.StringUtil;
 
 public interface ContentWrapper {
 
-    public StringUtil.StringWrapper get(String contentTypeId, String encoderType);
+    StringUtil.StringWrapper get(String contentTypeId, String encoderType);
 
 }
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java
index 9d6b80c..2abf58d 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataEvents.java
@@ -359,10 +359,10 @@ public class DataEvents {
             request.setAttribute("dataResourceId", result.get("dataResourceId"));
             String dataResourceTypeId = (String) serviceInMap.get("dataResourceTypeId");
             if (dataResourceTypeId != null) {
-                 if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)
-                     || "IMAGE_OBJECT".equals(dataResourceTypeId)) {
+                if ("ELECTRONIC_TEXT".equals(dataResourceTypeId)
+                        || "IMAGE_OBJECT".equals(dataResourceTypeId)) {
                     returnStr = dataResourceTypeId;
-                 }
+                }
             }
         }
 
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java
index f14142b..a166c4b 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataResourceWorker.java
@@ -153,9 +153,9 @@ public class DataResourceWorker  implements org.apache.ofbiz.widget.content.Data
         // The other test is to only get all the children if the "leaf" node where all the
         // children of the leaf are wanted for expansion.
         if (parentCategoryId == null
-            || "ROOT".equals(parentCategoryId)
-            || (currentDataCategoryId != null && currentDataCategoryId.equals(parentCategoryId))
-            || getAll) {
+                || "ROOT".equals(parentCategoryId)
+                || (currentDataCategoryId != null && currentDataCategoryId.equals(parentCategoryId))
+                || getAll) {
             categoryNode.put("kids", subCategoryIds);
         }
         return errorMsg;
@@ -482,8 +482,8 @@ public class DataResourceWorker  implements org.apache.ofbiz.widget.content.Data
             mimeType = view.getString("drMimeTypeId");
         }
         if (UtilValidate.isEmpty(mimeType) && UtilValidate.isNotEmpty(dataResourceId)) {
-                GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
-                mimeType = dataResource.getString("mimeTypeId");
+            GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
+            mimeType = dataResource.getString("mimeTypeId");
 
         }
         return mimeType;
@@ -623,19 +623,20 @@ public class DataResourceWorker  implements org.apache.ofbiz.widget.content.Data
         }
     }
 
-    public static String renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId, Map<String, Object> templateContext,
-             Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException {
+    public static String renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId,
+                                                  Map<String, Object> templateContext,
+                                                  Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException {
         try (Writer writer = new StringWriter()) {
-        renderDataResourceAsText(dispatcher, delegator, dataResourceId, writer, templateContext, locale, targetMimeTypeId, cache, null);
-        return writer.toString();
+            renderDataResourceAsText(dispatcher, delegator, dataResourceId, writer, templateContext, locale, targetMimeTypeId, cache, null);
+            return writer.toString();
         }
     }
 
     public static String renderDataResourceAsText(LocalDispatcher dispatcher, String dataResourceId, Appendable out,
-            Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException {
-       renderDataResourceAsText(dispatcher, null, dataResourceId, out, templateContext, locale, targetMimeTypeId, cache, null);
-       return out.toString();
-   }
+                                                  Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache) throws GeneralException, IOException {
+        renderDataResourceAsText(dispatcher, null, dataResourceId, out, templateContext, locale, targetMimeTypeId, cache, null);
+        return out.toString();
+    }
 
     public static void renderDataResourceAsText(LocalDispatcher dispatcher, Delegator delegator, String dataResourceId,
             Appendable out, Map<String, Object> templateContext, Locale locale, String targetMimeTypeId, boolean cache, List<GenericValue> webAnalytics) throws GeneralException, IOException {
@@ -720,7 +721,7 @@ public class DataResourceWorker  implements org.apache.ofbiz.widget.content.Data
                 }
 
             } else if ("XSLT".equals(dataTemplateTypeId)) {
-                File targetFileLocation = new File(System.getProperty("ofbiz.home")+"/runtime/tempfiles/docbook.css");
+                File targetFileLocation = new File(System.getProperty("ofbiz.home") + "/runtime/tempfiles/docbook.css");
                 String defaultVisualThemeId = EntityUtilProperties.getPropertyValue("general", "VISUAL_THEME", delegator);
                 visualTheme = ThemeFactory.getVisualThemeFromId(defaultVisualThemeId);
                 modelTheme = visualTheme.getModelTheme();
@@ -885,10 +886,10 @@ public class DataResourceWorker  implements org.apache.ofbiz.widget.content.Data
             if (url.getHost() != null) { // is absolute
                 int c;
                 try (InputStream in = url.openStream(); StringWriter sw = new StringWriter()) {
-                while ((c = in.read()) != -1) {
-                    sw.write(c);
-                }
-                text = sw.toString();
+                    while ((c = in.read()) != -1) {
+                        sw.write(c);
+                    }
+                    text = sw.toString();
                 }
             } else {
                 String prefix = DataResourceWorker.buildRequestPrefix(delegator, locale, webSiteId, https);
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java
index de484f5..0476440 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/data/DataServices.java
@@ -140,7 +140,7 @@ public class DataServices {
             try {
                 GenericValue statusItem = EntityQuery.use(delegator).from("StatusItem").where("statusTypeId", "CONTENT_STATUS").orderBy("sequenceId").queryFirst();
                 if (statusItem != null) {
-                    dataResource.put("statusId",  statusItem.get("statusId"));
+                    dataResource.put("statusId", statusItem.get("statusId"));
                 }
             } catch (GenericEntityException e) {
                 return ServiceUtil.returnError(e.getMessage());
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java
index 63e6a76..74b8c0e 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/survey/PdfSurveyServices.java
@@ -304,9 +304,9 @@ public class PdfSurveyServices {
             return ServiceUtil.returnError(e.getMessage());
         }
 
-    Map<String, Object> results = ServiceUtil.returnSuccess();
-    results.put("acroFieldMap", acroFieldMap);
-    return results;
+        Map<String, Object> results = ServiceUtil.returnSuccess();
+        results.put("acroFieldMap", acroFieldMap);
+        return results;
     }
 
     /**
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java b/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java
index 33952a9..acc482c 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/survey/SurveyWrapper.java
@@ -83,9 +83,9 @@ public class SurveyWrapper {
         this.checkParameters();
     }
 
-     public SurveyWrapper(Delegator delegator, String responseId, String partyId, String surveyId, Map<String, Object> passThru) {
-         this(delegator, responseId, partyId, surveyId, passThru, null);
-     }
+    public SurveyWrapper(Delegator delegator, String responseId, String partyId, String surveyId, Map<String, Object> passThru) {
+        this(delegator, responseId, partyId, surveyId, passThru, null);
+    }
 
     public SurveyWrapper(Delegator delegator, String surveyId) {
         this(delegator, null, null, surveyId, null);
@@ -223,9 +223,8 @@ public class SurveyWrapper {
         Configuration config = FreeMarkerWorker.getDefaultOfbizConfig();
 
         Template template = null;
-        try (
-            InputStream templateStream = templateUrl.openStream();
-            InputStreamReader templateReader = new InputStreamReader(templateStream, StandardCharsets.UTF_8);) {
+        try (InputStream templateStream = templateUrl.openStream();
+                InputStreamReader templateReader = new InputStreamReader(templateStream, StandardCharsets.UTF_8);) {
             template = new Template(templateUrl.toExternalForm(), templateReader, config);
         } catch (IOException e) {
             Debug.logError(e, "Unable to get template from URL :" + templateUrl.toExternalForm(), MODULE);
@@ -460,27 +459,27 @@ public class SurveyWrapper {
         // note this will need to be updated as new types are added
         if ("OPTION".equals(questionType)) {
             Map<String, Object> thisResult = getOptionResult(question);
-                Long questionTotal = (Long) thisResult.remove("_total");
-                if (questionTotal == null) {
-                    questionTotal = 0L;
-                }
-                // set the total responses
-                resultMap.put("_total", questionTotal);
+            Long questionTotal = (Long) thisResult.remove("_total");
+            if (questionTotal == null) {
+                questionTotal = 0L;
+            }
+            // set the total responses
+            resultMap.put("_total", questionTotal);
 
-                // create the map of option info ("_total", "_percent")
+            // create the map of option info ("_total", "_percent")
             for (Entry<String, Object> entry : thisResult.entrySet()) {
-                    Map<String, Object> optMap = new HashMap<>();
-                    Long optTotal = (Long) entry.getValue();
-                    String optId = entry.getKey();
-                    if (optTotal == null) {
-                        optTotal = 0L;
-                    }
-                    Long percent = (long) (((double) optTotal / (double) questionTotal) * 100);
-                    optMap.put("_total", optTotal);
-                    optMap.put("_percent", percent);
-                    resultMap.put(optId, optMap);
+                Map<String, Object> optMap = new HashMap<>();
+                Long optTotal = (Long) entry.getValue();
+                String optId = entry.getKey();
+                if (optTotal == null) {
+                    optTotal = 0L;
                 }
-                resultMap.put("_a_type", "option");
+                Long percent = (long) (((double) optTotal / (double) questionTotal) * 100);
+                optMap.put("_total", optTotal);
+                optMap.put("_percent", percent);
+                resultMap.put(optId, optMap);
+            }
+            resultMap.put("_a_type", "option");
         } else if ("BOOLEAN".equals(questionType)) {
             long[] thisResult = getBooleanResult(question);
             long yesPercent = thisResult[1] > 0 ? (long) (((double) thisResult[1] / (double) thisResult[0]) * 100) : 0;
@@ -527,7 +526,7 @@ public class SurveyWrapper {
         try {
             beganTransaction = TransactionUtil.begin();
 
-            long[] result = { 0, 0, 0 };
+            long[] result = {0, 0, 0 };
             // index 0 = total responses
             // index 1 = total yes
             // index 2 = total no
@@ -566,7 +565,7 @@ public class SurveyWrapper {
     }
 
     private double[] getNumberResult(GenericValue question, int type) throws SurveyWrapperException {
-        double[] result = { 0, 0, 0 };
+        double[] result = {0, 0, 0 };
         // index 0 = total responses
         // index 1 = tally
         // index 2 = average
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java b/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java
index 6a9f380..b8a7227 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/view/SimpleContentViewHandler.java
@@ -155,7 +155,7 @@ public class SimpleContentViewHandler extends AbstractViewHandler {
                     }
                 }
                 // setup content type
-                String contentType2 = UtilValidate.isNotEmpty(mimeTypeId) ? mimeTypeId + "; charset=" +charset : contentType;
+                String contentType2 = UtilValidate.isNotEmpty(mimeTypeId) ? mimeTypeId + "; charset=" + charset : contentType;
                 String fileName = null;
                 if (UtilValidate.isNotEmpty(dataResource.getString("dataResourceName"))) {
                     fileName = dataResource.getString("dataResourceName").replace(" ", "_"); // spaces in filenames can be a problem
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java
index 83695d0..d5ee911 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/EditRenderSubContentCacheTransform.java
@@ -50,7 +50,7 @@ import freemarker.template.TemplateTransformModel;
 public class EditRenderSubContentCacheTransform implements TemplateTransformModel {
 
     private static final String MODULE = EditRenderSubContentCacheTransform.class.getName();
-    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale",  "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"};
+    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"};
 
     /**
      * @deprecated use FreeMarkerWorker.getWrappedObject()
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java
index c813ef7..4f7f632 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/InjectNodeTrailCsvTransform.java
@@ -107,7 +107,7 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel {
                 List<Map<String, ? extends Object>> trail = UtilGenerics.cast(templateCtx.get("globalNodeTrail"));
 
                 if (Debug.infoOn()) {
-                    Debug.logInfo("in InjectNodeTrailCsv(0), trail:"+trail, MODULE);
+                    Debug.logInfo("in InjectNodeTrailCsv(0), trail:" + trail, MODULE);
                 }
                 // This will build a nodeTrail if none exists
                 // Maybe only contentId or subContentId are passed in
@@ -116,15 +116,15 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel {
                 if (UtilValidate.isEmpty(trail) || (redo != null && "true".equalsIgnoreCase(redo))) {
                     String subContentId = (String) templateCtx.get("subContentId");
                     if (Debug.infoOn()) {
-                        Debug.logInfo("in InjectNodeTrailCsv(0), subContentId:"+subContentId, MODULE);
+                        Debug.logInfo("in InjectNodeTrailCsv(0), subContentId:" + subContentId, MODULE);
                     }
                     String contentId = (String) templateCtx.get("contentId");
                     if (Debug.infoOn()) {
-                        Debug.logInfo("in InjectNodeTrailCsv(0), contentId:"+contentId, MODULE);
+                        Debug.logInfo("in InjectNodeTrailCsv(0), contentId:" + contentId, MODULE);
                     }
                     String contentAssocTypeId = (String) templateCtx.get("contentAssocTypeId");
                     if (Debug.infoOn()) {
-                        Debug.logInfo("in InjectNodeTrailCsv(0), contentAssocTypeId:"+contentAssocTypeId, MODULE);
+                        Debug.logInfo("in InjectNodeTrailCsv(0), contentAssocTypeId:" + contentAssocTypeId, MODULE);
                     }
                     try {
                         if (UtilValidate.isNotEmpty(subContentId)) {
@@ -144,7 +144,7 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel {
                         throw new RuntimeException("Error getting current content. " + e.toString());
                     }
                     if (Debug.infoOn()) {
-                        Debug.logInfo("in InjectNodeTrailCsv(0), csvTrail:"+csvTrail, MODULE);
+                        Debug.logInfo("in InjectNodeTrailCsv(0), csvTrail:" + csvTrail, MODULE);
                     }
                 } else {
                     // Build nodeTrail if one does not exist
@@ -163,8 +163,8 @@ public class InjectNodeTrailCsvTransform implements TemplateTransformModel {
                                 Map<String, ? extends Object> nd = trail.get(0);
                                 String firstTrailContentId = (String) nd.get("contentId");
                                 if (UtilValidate.isNotEmpty(firstTrailContentId)
-                                    && UtilValidate.isNotEmpty(lastPassedContentId)
-                                    && firstTrailContentId.equals(lastPassedContentId)) {
+                                        && UtilValidate.isNotEmpty(lastPassedContentId)
+                                        && firstTrailContentId.equals(lastPassedContentId)) {
                                     csvTrail += "," + ContentWorker.nodeTrailToCsv(trail.subList(1, trail.size()));
                                 } else {
                                     csvTrail += "," + ContentWorker.nodeTrailToCsv(trail);
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java
index f672f28..70c1eb8 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderContentAsText.java
@@ -53,7 +53,7 @@ public class RenderContentAsText implements TemplateTransformModel {
 
     private static final String MODULE = RenderContentAsText.class.getName();
     static final String[] upSaveKeyNames = {"globalNodeTrail"};
-    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale",  "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
+    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
 
     @Override
     @SuppressWarnings("unchecked")
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java
index 29342e1..ceb02b2 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentAsText.java
@@ -49,7 +49,7 @@ public class RenderSubContentAsText implements TemplateTransformModel {
 
     private static final String MODULE = RenderSubContentAsText.class.getName();
     public static final String[] upSaveKeyNames = {"globalNodeTrail"};
-    public static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale",  "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
+    public static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
 
     @Override
     @SuppressWarnings("unchecked")
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java
index 7d673e8..47b8524 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/TraverseSubContentCacheTransform.java
@@ -50,7 +50,7 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel
 
     private static final String MODULE = TraverseSubContentCacheTransform.class.getName();
     static final String[] upSaveKeyNames = {"globalNodeTrail"};
-    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale",  "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
+    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"};
 
     /**
      * @deprecated use FreeMarkerWorker.getWrappedObject()
diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java
index da68697..23b9e90 100644
--- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java
+++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/WrapSubContentCacheTransform.java
@@ -50,7 +50,7 @@ public class WrapSubContentCacheTransform implements TemplateTransformModel {
 
     private static final String MODULE = WrapSubContentCacheTransform.class.getName();
     static final String[] upSaveKeyNames = {"globalNodeTrail"};
-    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale",  "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"};
+    static final String[] saveKeyNames = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"};
 
     /**
      * @deprecated use FreeMarkerWorker.getWrappedObject()
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java
index fa41944..3ff500b 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMHelper.java
@@ -34,7 +34,8 @@ import org.apache.ofbiz.service.GenericServiceException;
 import org.apache.ofbiz.service.LocalDispatcher;
 import org.apache.ofbiz.service.ServiceUtil;
 
-/** Helper class containing static method useful when dealing
+/**
+ * Helper class containing static method useful when dealing
  * with product's bills of materials.
  * These methods are also available as services (see {@link BOMServices}).
  */
@@ -42,18 +43,21 @@ public final class BOMHelper {
 
     private static final String MODULE = BOMHelper.class.getName();
 
-    /** Creates a new instance of BOMHelper */
-    private BOMHelper() {
-    }
+    /**
+     * Creates a new instance of BOMHelper
+     */
+    private BOMHelper() { }
 
-    /** Returns the product's low level code (llc) i.e. the maximum depth
+    /**
+     * Returns the product's low level code (llc) i.e. the maximum depth
      * in which the productId can be found in any of the
      * bills of materials of bomType type.
-     * @return The low level code for the productId. (0 = root, 1 = first level, etc...)
+     *
      * @param productId The product id
-     * @param bomType The bill of materials type (e.g. manufacturing, engineering,...)
+     * @param bomType   The bill of materials type (e.g. manufacturing, engineering,...)
      * @param delegator Validity date (if null, today is used).
-     * @param inDate The delegator
+     * @param inDate    The delegator
+     * @return The low level code for the productId. (0 = root, 1 = first level, etc...)
      * @throws GenericEntityException If a db problem occurs.
      */
     /*
@@ -84,26 +88,29 @@ public final class BOMHelper {
         return maxDepth;
     }
 
-    /** Returns the ProductAssoc generic value for a duplicate productIdKey
+    /**
+     * Returns the ProductAssoc generic value for a duplicate productIdKey
      * ancestor if present, null otherwise.
      * Useful to avoid loops when adding new assocs (components)
      * to a bill of materials.
-     * @param productId The product to which we want to add a new child.
-     * @param productIdKey The new component we want to add to the existing bom.
-     * @param bomType The bill of materials type (e.g. manufacturing, engineering).
-     * @param inDate Validity date (if null, today is used).
      *
-     * @param delegator The delegator used
-     * @throws GenericEntityException If a db problem occurs
+     * @param productId    The product to which we want to add a new child.
+     * @param productIdKey The new component we want to add to the existing bom.
+     * @param bomType      The bill of materials type (e.g. manufacturing, engineering).
+     * @param inDate       Validity date (if null, today is used).
+     * @param delegator    The delegator used
      * @return the ProductAssoc generic value for a duplicate productIdKey
      * ancestor if present, null otherwise.
+     * @throws GenericEntityException If a db problem occurs
      */
-    public static GenericValue searchDuplicatedAncestor(String productId, String productIdKey, String bomType, Date inDate, Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin) throws GenericEntityException {
+    public static GenericValue searchDuplicatedAncestor(String productId, String productIdKey, String bomType, Date inDate, Delegator delegator,
+                                                        LocalDispatcher dispatcher, GenericValue userLogin) throws GenericEntityException {
         return searchDuplicatedAncestor(productId, productIdKey, null, bomType, inDate, delegator, dispatcher, userLogin);
     }
 
     private static GenericValue searchDuplicatedAncestor(String productId, String productIdKey, List<String> productIdKeys,
-            String bomType, Date inDate, Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin) throws GenericEntityException {
+                                                         String bomType, Date inDate, Delegator delegator, LocalDispatcher dispatcher,
+                                                         GenericValue userLogin) throws GenericEntityException {
         // If the date is null, set it to today.
         if (inDate == null) inDate = new Date();
         if (productIdKeys == null) {
@@ -122,7 +129,8 @@ public final class BOMHelper {
                     return oneNode;
                 }
             }
-            duplicatedNode = searchDuplicatedAncestor(oneNode.getString("productId"), productIdKey, productIdKeys, bomType, inDate, delegator, dispatcher, userLogin);
+            duplicatedNode = searchDuplicatedAncestor(oneNode.getString("productId"), productIdKey, productIdKeys, bomType, inDate, delegator,
+                    dispatcher, userLogin);
             if (duplicatedNode != null) {
                 break;
             }
@@ -130,7 +138,8 @@ public final class BOMHelper {
         return duplicatedNode;
     }
 
-    public static String createProductionRunsForShipment(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) {
+    public static String createProductionRunsForShipment(javax.servlet.http.HttpServletRequest request,
+                                                         javax.servlet.http.HttpServletResponse response) {
         Delegator delegator = (Delegator) request.getAttribute("delegator");
         LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher");
         GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin");
@@ -138,30 +147,32 @@ public final class BOMHelper {
         String shipmentId = request.getParameter("shipmentId");
 
         try {
-        List<GenericValue> shipmentPlans = EntityQuery.use(delegator).from("OrderShipment")
-                .where("shipmentId", shipmentId).queryList();
-        for (GenericValue shipmentPlan : shipmentPlans) {
-            GenericValue orderItem = shipmentPlan.getRelatedOne("OrderItem", false);
-
-            List<GenericValue> productionRuns = EntityQuery.use(delegator).from("WorkOrderItemFulfillment")
-                    .where("orderId", shipmentPlan.get("orderId"),
-                            "orderItemSeqId", shipmentPlan.get("orderItemSeqId"),
-                            "shipGroupSeqId", shipmentPlan.get("shipGroupSeqId"))
-                    .cache().queryList();
-            if (UtilValidate.isNotEmpty(productionRuns)) {
-                Debug.logError("Production Run for order item (" + orderItem.getString("orderId") + "/" + orderItem.getString("orderItemSeqId") + ") not created.", MODULE);
-                continue;
-            }
-            Map<String, Object> result = dispatcher.runSync("createProductionRunsForOrder", UtilMisc.<String, Object>toMap("quantity", shipmentPlan.getBigDecimal("quantity"), "orderId",
-                    shipmentPlan.getString("orderId"), "orderItemSeqId", shipmentPlan.getString("orderItemSeqId"), "shipGroupSeqId", shipmentPlan.getString("shipGroupSeqId"), "shipmentId",
-                    shipmentId, "userLogin", userLogin));
-            if (ServiceUtil.isError(result)) {
-                String errorMessage = ServiceUtil.getErrorMessage(result);
-                request.setAttribute("_ERROR_MESSAGE_", errorMessage);
-                Debug.logError(errorMessage, MODULE);
-                return "error";
+            List<GenericValue> shipmentPlans = EntityQuery.use(delegator).from("OrderShipment")
+                    .where("shipmentId", shipmentId).queryList();
+            for (GenericValue shipmentPlan : shipmentPlans) {
+                GenericValue orderItem = shipmentPlan.getRelatedOne("OrderItem", false);
+
+                List<GenericValue> productionRuns = EntityQuery.use(delegator).from("WorkOrderItemFulfillment")
+                        .where("orderId", shipmentPlan.get("orderId"),
+                                "orderItemSeqId", shipmentPlan.get("orderItemSeqId"),
+                                "shipGroupSeqId", shipmentPlan.get("shipGroupSeqId"))
+                        .cache().queryList();
+                if (UtilValidate.isNotEmpty(productionRuns)) {
+                    Debug.logError("Production Run for order item (" + orderItem.getString("orderId") + "/" + orderItem.getString("orderItemSeqId") + ") not created.", MODULE);
+                    continue;
+                }
+                Map<String, Object> result = dispatcher.runSync("createProductionRunsForOrder", UtilMisc.<String, Object>toMap("quantity",
+                        shipmentPlan.getBigDecimal("quantity"), "orderId",
+                        shipmentPlan.getString("orderId"), "orderItemSeqId", shipmentPlan.getString("orderItemSeqId"), "shipGroupSeqId",
+                        shipmentPlan.getString("shipGroupSeqId"), "shipmentId",
+                        shipmentId, "userLogin", userLogin));
+                if (ServiceUtil.isError(result)) {
+                    String errorMessage = ServiceUtil.getErrorMessage(result);
+                    request.setAttribute("_ERROR_MESSAGE_", errorMessage);
+                    Debug.logError(errorMessage, MODULE);
+                    return "error";
+                }
             }
-        }
         } catch (GenericEntityException | GenericServiceException ge) {
             Debug.logWarning(ge, MODULE);
         }
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java
index 7afd6b2..3448182 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMNode.java
@@ -367,7 +367,7 @@ public class BOMNode {
     }
 
     public BOMNode getRootNode() {
-        return (parentNode != null? getParentNode(): this);
+        return (parentNode != null ? getParentNode() : this);
     }
     /** Setter for property parentNode.
      * @param parentNode New value of property parentNode.
@@ -675,7 +675,7 @@ public class BOMNode {
     }
 
     public boolean isVirtual() {
-        return (product.get("isVirtual") != null? "Y".equals(product.get("isVirtual")): false);
+        return (product.get("isVirtual") != null ? "Y".equals(product.get("isVirtual")) : false);
     }
 
     public void isConfigured(List<BOMNode> arr) {
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java
index fcef0b3..9a2ef39 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMServices.java
@@ -524,7 +524,7 @@ public class BOMServices {
             OrderReadHelper orderReadHelper = (OrderReadHelper) orderReadHelpers.get(orderShipment.getString("orderId"));
             if (orderReadHelper != null) {
                 Map<String, Object> orderShipmentReadMap = UtilMisc.toMap("orderShipment", orderShipment, "orderReadHelper", orderReadHelper);
-                String partyId = (orderReadHelper.getPlacingParty() != null? orderReadHelper.getPlacingParty().getString("partyId"): null); // FIXME: is it the customer?
+                String partyId = (orderReadHelper.getPlacingParty() != null ? orderReadHelper.getPlacingParty().getString("partyId") : null); // FIXME: is it the customer?
                 if (partyId != null) {
                     if (!partyOrderShipments.containsKey(partyId)) {
                         List<Map<String, Object>> orderShipmentReadMapList = new LinkedList<>();
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java
index 1a5a78f..bbe2a57 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/bom/BOMTree.java
@@ -117,7 +117,7 @@ public class BOMTree {
         // We load the information about the product that needs to be manufactured
         // from Product entity
         GenericValue product = EntityQuery.use(delegator).from("Product")
-                .where("productId", (manufacturedAsProduct != null? manufacturedAsProduct.getString("productIdTo"): productId))
+                .where("productId", (manufacturedAsProduct != null ? manufacturedAsProduct.getString("productIdTo") : productId))
                 .queryOne();
         if (product == null) return;
         BOMNode originalNode = new BOMNode(product, dispatcher, userLogin);
@@ -135,7 +135,7 @@ public class BOMTree {
                 productIdForRules = virtualProduct.getString("productId");
                 manufacturedAsProduct = manufacturedAsProduct(virtualProduct.getString("productId"), inDate);
                 product = EntityQuery.use(delegator).from("Product")
-                        .where("productId", (manufacturedAsProduct != null? manufacturedAsProduct.getString("productIdTo"): virtualProduct.get("productId")))
+                        .where("productId", (manufacturedAsProduct != null ? manufacturedAsProduct.getString("productIdTo") : virtualProduct.get("productId")))
                         .queryOne();
             }
         }
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java
index 4f056fc..46d244a 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRun.java
@@ -376,7 +376,7 @@ public class ProductionRun {
                     Debug.logWarning(e.getMessage(), MODULE);
                 }
             }
-            return (UtilValidate.isNotEmpty(productionRunRoutingTasks) ? productionRunRoutingTasks.get(productionRunRoutingTasks.size() - 1): null);
+            return (UtilValidate.isNotEmpty(productionRunRoutingTasks) ? productionRunRoutingTasks.get(productionRunRoutingTasks.size() - 1) : null);
         }
         return null;
     }
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java
index a8f6da2..2439158 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/jobshopmgt/ProductionRunServices.java
@@ -59,9 +59,9 @@ import org.apache.ofbiz.service.GenericServiceException;
 import org.apache.ofbiz.service.LocalDispatcher;
 import org.apache.ofbiz.service.ModelService;
 import org.apache.ofbiz.service.ServiceUtil;
+
 /**
  * Services for Production Run maintenance
- *
  */
 public class ProductionRunServices {
 
@@ -76,7 +76,8 @@ public class ProductionRunServices {
 
     /**
      * Cancels a ProductionRun.
-     * @param ctx The DispatchContext that this service is operating in.
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters.
      * @return Map with the result of the service, the output parameters.
      */
@@ -104,7 +105,8 @@ public class ProductionRunServices {
                 for (int i = 1; i < mandatoryWorkEfforts.size(); i++) {
                     GenericValue mandatoryWorkEffort = (mandatoryWorkEfforts.get(i)).getGenericValue();
                     if (!("PRUN_CANCELLED".equals(mandatoryWorkEffort.getString("currentStatusId")))) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunFound", locale));
+                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
+                                "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunFound", locale));
                     }
                 }
                 Map<String, Object> serviceContext = new HashMap<>();
@@ -159,7 +161,8 @@ public class ProductionRunServices {
                 Debug.logError(e, "Problem accessing WorkEffortGoodStandard entity", MODULE);
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChanged", locale));
             }
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_DOC_PRINTED"), locale));
             return result;
         }
         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotBeCancelled", locale));
@@ -168,16 +171,17 @@ public class ProductionRunServices {
     /**
      * Creates a Production Run.
      * <ul>
-     *  <li> check if routing - product link exist</li>
-     *  <li> check if product have a Bill Of Material</li>
-     *  <li> check if routing have routingTask</li>
-     *  <li> create the workEffort for ProductionRun</li>
-     *  <li> create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce</li>
-     *  <li> for each valid routingTask of the routing create a workeffort-task</li>
-     *  <li> for the first routingTask, create for all the valid productIdTo with no associateRoutingTask  a WorkEffortGoodStandard</li>
-     *  <li> for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard</li>
+     * <li> check if routing - product link exist</li>
+     * <li> check if product have a Bill Of Material</li>
+     * <li> check if routing have routingTask</li>
+     * <li> create the workEffort for ProductionRun</li>
+     * <li> create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce</li>
+     * <li> for each valid routingTask of the routing create a workeffort-task</li>
+     * <li> for the first routingTask, create for all the valid productIdTo with no associateRoutingTask  a WorkEffortGoodStandard</li>
+     * <li> for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard</li>
      * </ul>
-     * @param ctx The DispatchContext that this service is operating in.
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters, productId, routingId, pRQuantity, startDate, workEffortName, description
      * @return Map with the result of the service, the output parameters.
      */
@@ -190,7 +194,7 @@ public class ProductionRunServices {
         // TODO: security management  and finishing cleaning (ex copy from PartyServices.java)
         // Mandatory input fields
         String productId = (String) context.get("productId");
-        Timestamp  startDate = (Timestamp) context.get("startDate");
+        Timestamp startDate = (Timestamp) context.get("startDate");
         BigDecimal pRQuantity = (BigDecimal) context.get("pRQuantity");
         String facilityId = (String) context.get("facilityId");
         // Optional input fields
@@ -261,8 +265,10 @@ public class ProductionRunServices {
 
         // ProductionRun header creation,
         if (workEffortName == null) {
-            String prdName = UtilValidate.isNotEmpty(product.getString("productName"))? product.getString("productName"): product.getString("productId");
-            String wefName = UtilValidate.isNotEmpty(routing.getString("workEffortName"))? routing.getString("workEffortName"): routing.getString("workEffortId");
+            String prdName = UtilValidate.isNotEmpty(product.getString("productName")) ? product.getString("productName") : product.getString(
+                    "productId");
+            String wefName = UtilValidate.isNotEmpty(routing.getString("workEffortName")) ? routing.getString("workEffortName") :
+                    routing.getString("workEffortId");
             workEffortName = prdName + "-" + wefName;
         }
 
@@ -290,7 +296,7 @@ public class ProductionRunServices {
             Debug.logInfo("ProductionRun created: " + productionRunId, MODULE);
         }
 
-        // ProductionRun,  product will be produce creation = WorkEffortGoodStandard for the productId
+        // ProductionRun, product will be produce creation = WorkEffortGoodStandard for the productId
         serviceContext.clear();
         serviceContext.put("workEffortId", productionRunId);
         serviceContext.put("productId", productId);
@@ -317,7 +323,7 @@ public class ProductionRunServices {
                 try {
                     routingTask = routingTaskAssoc.getRelatedOne("ToWorkEffort", false);
                 } catch (GenericEntityException e) {
-                    Debug.logError(e.getMessage(),  MODULE);
+                    Debug.logError(e.getMessage(), MODULE);
                 }
                 // Calculate the estimatedCompletionDate
                 long totalTime = ProductionRun.getEstimatedTaskTime(routingTask, pRQuantity, dispatcher);
@@ -372,8 +378,8 @@ public class ProductionRunServices {
                 // clone associated objects from the routing task to the run task
                 String routingTaskId = routingTaskAssoc.getString("workEffortIdTo");
                 try {
-                cloneWorkEffortPartyAssignments(ctx, userLogin, routingTaskId, productionRunTaskId);
-                cloneWorkEffortCostCalcs(ctx, userLogin, routingTaskId, productionRunTaskId);
+                    cloneWorkEffortPartyAssignments(ctx, userLogin, routingTaskId, productionRunTaskId);
+                    cloneWorkEffortCostCalcs(ctx, userLogin, routingTaskId, productionRunTaskId);
                 } catch (GeneralException e) {
                     return ServiceUtil.returnError(e.getMessage());
                 }
@@ -433,7 +439,8 @@ public class ProductionRunServices {
         }
         result.put("productionRunId", productionRunId);
         result.put("estimatedCompletionDate", startDate);
-        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale));
+        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap(
+                "productionRunId", productionRunId), locale));
         return result;
     }
 
@@ -441,23 +448,23 @@ public class ProductionRunServices {
      * Make a copy of the party assignments that were defined on the template routing task to the new production run task.
      */
     private static void cloneWorkEffortPartyAssignments(DispatchContext dctx, GenericValue userLogin,
-            String routingTaskId, String productionRunTaskId) throws GeneralException {
+                                                        String routingTaskId, String productionRunTaskId) throws GeneralException {
         List<GenericValue> workEffortPartyAssignments = null;
         try {
             workEffortPartyAssignments = EntityUtil.filterByDate(
                     dctx.getDelegator().findByAnd("WorkEffortPartyAssignment", UtilMisc.toMap("workEffortId", routingTaskId), null, false));
         } catch (GenericEntityException e) {
-            Debug.logError(e.getMessage(),  MODULE);
+            Debug.logError(e.getMessage(), MODULE);
         }
 
         if (workEffortPartyAssignments != null) {
             for (GenericValue workEffortPartyAssignment : workEffortPartyAssignments) {
                 Map<String, Object> partyToWorkEffort = UtilMisc.<String, Object>toMap(
-                        "workEffortId",  productionRunTaskId,
-                        "partyId",  workEffortPartyAssignment.getString("partyId"),
-                        "roleTypeId",  workEffortPartyAssignment.getString("roleTypeId"),
-                        "fromDate",  workEffortPartyAssignment.getTimestamp("fromDate"),
-                        "statusId",  workEffortPartyAssignment.getString("statusId"),
+                        "workEffortId", productionRunTaskId,
+                        "partyId", workEffortPartyAssignment.getString("partyId"),
+                        "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"),
+                        "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"),
+                        "statusId", workEffortPartyAssignment.getString("statusId"),
                         "userLogin", userLogin);
                 try {
                     Map<String, Object> result = dctx.getDispatcher().runSync("assignPartyToWorkEffort", partyToWorkEffort);
@@ -485,7 +492,7 @@ public class ProductionRunServices {
             workEffortCostCalcs = EntityUtil.filterByDate(
                     dctx.getDelegator().findByAnd("WorkEffortCostCalc", UtilMisc.toMap("workEffortId", routingTaskId), null, false));
         } catch (GenericEntityException e) {
-            Debug.logError(e.getMessage(),  MODULE);
+            Debug.logError(e.getMessage(), MODULE);
         }
 
         if (workEffortCostCalcs != null) {
@@ -518,13 +525,14 @@ public class ProductionRunServices {
     /**
      * Update a Production Run.
      * <ul>
-     *  <li> update field and after recalculate the entire ProductionRun data (routingTask and productComponent)</li>
-     *  <li> create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce</li>
-     *  <li> for each valid routingTask of the routing create a workeffort-task</li>
-     *  <li> for the first routingTask, create for all the valid productIdTo with no associateRoutingTask  a WorkEffortGoodStandard</li>
-     *  <li> for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard</li>
-     * </ul>
-     * @param ctx The DispatchContext that this service is operating in.
+     * <li> update field and after recalculate the entire ProductionRun data (routingTask and productComponent)</li>
+     * <li> create the WorkEffortGoodStandard for link between ProductionRun and the product it will produce</li>
+     * <li> for each valid routingTask of the routing create a workeffort-task</li>
+     * <li> for the first routingTask, create for all the valid productIdTo with no associateRoutingTask  a WorkEffortGoodStandard</li>
+     * <li> for each valid routingTask of the routing and valid productIdTo associate with this RoutingTask create a WorkEffortGoodStandard</li>
+     * </ul>
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters, productId, routingId, quantity, estimatedStartDate, workEffortName, description
      * @return Map with the result of the service, the output parameters.
      */
@@ -540,31 +548,31 @@ public class ProductionRunServices {
             if (productionRun.exist()) {
 
                 if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId")) &&
-                      !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
+                        !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale));
                 }
 
                 BigDecimal quantity = (BigDecimal) context.get("quantity");
-                if (quantity != null &&  quantity.compareTo(productionRun.getQuantity()) != 0) {
+                if (quantity != null && quantity.compareTo(productionRun.getQuantity()) != 0) {
                     productionRun.setQuantity(quantity);
                 }
 
-                Timestamp  estimatedStartDate = (Timestamp) context.get("estimatedStartDate");
+                Timestamp estimatedStartDate = (Timestamp) context.get("estimatedStartDate");
                 if (estimatedStartDate != null && !estimatedStartDate.equals(productionRun.getEstimatedStartDate())) {
                     productionRun.setEstimatedStartDate(estimatedStartDate);
                 }
 
-                String  workEffortName = (String) context.get("workEffortName");
+                String workEffortName = (String) context.get("workEffortName");
                 if (workEffortName != null) {
                     productionRun.setProductionRunName(workEffortName);
                 }
 
-                String  description = (String) context.get("description");
+                String description = (String) context.get("description");
                 if (description != null) {
                     productionRun.setDescription(description);
                 }
 
-                String  facilityId = (String) context.get("facilityId");
+                String facilityId = (String) context.get("facilityId");
                 if (facilityId != null) {
                     productionRun.getGenericValue().set("facilityId", facilityId);
                 }
@@ -585,11 +593,11 @@ public class ProductionRunServices {
                     }
                     return ServiceUtil.returnSuccess();
                 } else {
-                    Debug.logError("productionRun.store() fail for productionRunId ="+productionRunId, MODULE);
+                    Debug.logError("productionRun.store() fail for productionRunId =" + productionRunId, MODULE);
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale));
                 }
             }
-            Debug.logError("no productionRun for productionRunId ="+productionRunId, MODULE);
+            Debug.logError("no productionRun for productionRunId =" + productionRunId, MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale));
         }
         Debug.logError("service updateProductionRun call with productionRunId empty", MODULE);
@@ -614,7 +622,8 @@ public class ProductionRunServices {
 
         if (currentStatusId.equals(statusId)) {
             result.put("newStatusId", currentStatusId);
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", currentStatusId), locale));
             return result;
         }
 
@@ -652,7 +661,8 @@ public class ProductionRunServices {
                 }
             }
             result.put("newStatusId", statusId);
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_CLOSED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_CLOSED"), locale));
             return result;
         }
 
@@ -690,7 +700,8 @@ public class ProductionRunServices {
                 }
             }
             result.put("newStatusId", "PRUN_DOC_PRINTED");
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_DOC_PRINTED"), locale));
             return result;
         }
 
@@ -709,7 +720,8 @@ public class ProductionRunServices {
                     if (!("PRUN_COMPLETED".equals(mandatoryWorkEffort.getString("currentStatusId"))
                             || "PRUN_RUNNING".equals(mandatoryWorkEffort.getString("currentStatusId"))
                             || "PRUN_CLOSED".equals(mandatoryWorkEffort.getString("currentStatusId")))) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunNotCompleted", locale));
+                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
+                                "ManufacturingProductionRunStatusNotChangedMandatoryProductionRunNotCompleted", locale));
                     }
                 }
             } catch (GenericEntityException gee) {
@@ -732,7 +744,8 @@ public class ProductionRunServices {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChanged", locale));
             }
             result.put("newStatusId", "PRUN_RUNNING");
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_DOC_PRINTED"), locale));
             return result;
         }
 
@@ -756,7 +769,8 @@ public class ProductionRunServices {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusNotChanged", locale));
             }
             result.put("newStatusId", "PRUN_COMPLETED");
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_DOC_PRINTED"), locale));
             return result;
         }
 
@@ -794,11 +808,13 @@ public class ProductionRunServices {
                 }
             }
             result.put("newStatusId", "PRUN_CLOSED");
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_CLOSED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_CLOSED"), locale));
             return result;
         }
         result.put("newStatusId", currentStatusId);
-        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale));
+        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                "newStatusId", currentStatusId), locale));
         return result;
     }
 
@@ -831,7 +847,8 @@ public class ProductionRunServices {
             if (oneTask.getString("workEffortId").equals(taskId)) {
                 theTask = oneTask;
             } else {
-                if (theTask == null && allPrecTaskCompletedOrRunning && (!"PRUN_COMPLETED".equals(oneTask.getString("currentStatusId")) && !"PRUN_RUNNING".equals(oneTask.getString("currentStatusId")))) {
+                if (theTask == null && allPrecTaskCompletedOrRunning && (!"PRUN_COMPLETED".equals(oneTask.getString("currentStatusId")) && !
+                        "PRUN_RUNNING".equals(oneTask.getString("currentStatusId")))) {
                     allPrecTaskCompletedOrRunning = false;
                 }
                 if (allTaskCompleted && !"PRUN_COMPLETED".equals(oneTask.getString("currentStatusId"))) {
@@ -849,7 +866,8 @@ public class ProductionRunServices {
         if (statusId != null && currentStatusId.equals(statusId)) {
             result.put("oldStatusId", oldStatusId);
             result.put("newStatusId", currentStatusId);
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged",
+                    UtilMisc.toMap("newStatusId", currentStatusId), locale));
             return result;
         }
 
@@ -859,10 +877,12 @@ public class ProductionRunServices {
             // change the production run task status to PRUN_RUNNING
             // if necessary change the production run (header) status to PRUN_RUNNING
             if (!allPrecTaskCompletedOrRunning) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartPrevTasksNotCompleted", locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartPrevTasksNotCompleted"
+                        , locale));
             }
             if ("PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartDocsNotPrinted", locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotStartDocsNotPrinted",
+                        locale));
             }
             Map<String, Object> serviceContext = new HashMap<>();
             serviceContext.clear();
@@ -896,7 +916,8 @@ public class ProductionRunServices {
             }
             result.put("oldStatusId", oldStatusId);
             result.put("newStatusId", "PRUN_RUNNING");
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_DOC_PRINTED"), locale));
             return result;
         }
 
@@ -1008,7 +1029,8 @@ public class ProductionRunServices {
                     if (partyAccountingPreference == null) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCosts", locale));
                     }
-                    outputMap = dispatcher.runSync("getProductionRunCost", UtilMisc.<String, Object>toMap("userLogin", userLogin, "workEffortId", productionRunId));
+                    outputMap = dispatcher.runSync("getProductionRunCost", UtilMisc.<String, Object>toMap("userLogin", userLogin, "workEffortId",
+                            productionRunId));
                     if (ServiceUtil.isError(outputMap)) {
                         return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap));
                     }
@@ -1025,7 +1047,8 @@ public class ProductionRunServices {
                         GenericValue customMethod = costComponentCalc.getRelatedOne("CustomMethod", false);
                         if (customMethod == null) {
                             // TODO: not supported for CostComponentCalc entries directly associated to a product
-                            Debug.logWarning("Unable to create cost component for cost component calc with id [" + costComponentCalc.getString("costComponentCalcId") + "] because customMethod is not set", MODULE);
+                            Debug.logWarning("Unable to create cost component for cost component calc with id [" + costComponentCalc.getString(
+                                    "costComponentCalcId") + "] because customMethod is not set", MODULE);
                         } else {
                             Map<String, Object> costMethodResult = dispatcher.runSync(customMethod.getString("customMethodName"),
                                     UtilMisc.toMap("productCostComponentCalc", productCostComponentCalc,
@@ -1058,12 +1081,14 @@ public class ProductionRunServices {
 
             result.put("oldStatusId", oldStatusId);
             result.put("newStatusId", "PRUN_COMPLETED");
-            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap("newStatusId", "PRUN_DOC_PRINTED"), locale));
+            result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunStatusChanged", UtilMisc.toMap(
+                    "newStatusId", "PRUN_DOC_PRINTED"), locale));
             return result;
         }
         result.put("oldStatusId", oldStatusId);
         result.put("newStatusId", currentStatusId);
-        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", UtilMisc.toMap("newStatusId", currentStatusId), locale));
+        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskStatusChanged", UtilMisc.toMap(
+                "newStatusId", currentStatusId), locale));
         return result;
     }
 
@@ -1096,7 +1121,8 @@ public class ProductionRunServices {
             result.put("totalCost", totalCost);
             result.put("totalCostNoMaterials", totalCostNoMaterials);
         } catch (GenericEntityException gee) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCostsForWorkEffort", UtilMisc.toMap("workEffortId", workEffortId, "errorString", gee.getMessage()), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCostsForWorkEffort",
+                    UtilMisc.toMap("workEffortId", workEffortId, "errorString", gee.getMessage()), locale));
         }
         return result;
     }
@@ -1148,7 +1174,8 @@ public class ProductionRunServices {
         try {
             GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", productionRunTaskId).queryOne();
             if (UtilValidate.isEmpty(workEffort)) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskNotFound", UtilMisc.toMap("productionRunTaskId", productionRunTaskId), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskNotFound", UtilMisc.toMap(
+                        "productionRunTaskId", productionRunTaskId), locale));
             }
             double actualTotalMilliSeconds = 0.0;
             Double actualSetupMillis = workEffort.getDouble("actualSetupMillis");
@@ -1165,7 +1192,7 @@ public class ProductionRunServices {
             GenericValue routingTaskAssoc = EntityQuery.use(delegator).from("WorkEffortAssoc")
                     .where("workEffortIdTo", productionRunTaskId,
                             "workEffortAssocTypeId", "WORK_EFF_TEMPLATE")
-                            .filterByDate().queryFirst();
+                    .filterByDate().queryFirst();
             GenericValue routingTask = null;
             if (routingTaskAssoc != null) {
                 routingTask = routingTaskAssoc.getRelatedOne("FromWorkEffort", false);
@@ -1229,10 +1256,11 @@ public class ProductionRunServices {
                 List<GenericValue> setupCosts = fixedAsset.getRelated("FixedAssetStdCost",
                         UtilMisc.toMap("fixedAssetStdCostTypeId", "SETUP_COST"), null, false);
                 GenericValue setupCost = EntityUtil.getFirst(EntityUtil.filterByDate(setupCosts));
-                List<GenericValue> usageCosts = fixedAsset.getRelated("FixedAssetStdCost", UtilMisc.toMap("fixedAssetStdCostTypeId", "USAGE_COST"), null, false);
+                List<GenericValue> usageCosts = fixedAsset.getRelated("FixedAssetStdCost", UtilMisc.toMap("fixedAssetStdCostTypeId", "USAGE_COST"),
+                        null, false);
                 GenericValue usageCost = EntityUtil.getFirst(EntityUtil.filterByDate(usageCosts));
                 if (setupCost != null || usageCost != null) {
-                    String currencyUomId = (setupCost != null? setupCost.getString("amountUomId"): usageCost.getString("amountUomId"));
+                    String currencyUomId = (setupCost != null ? setupCost.getString("amountUomId") : usageCost.getString("amountUomId"));
                     BigDecimal setupCostAmount = ZERO;
                     if (setupCost != null) {
                         setupCostAmount = setupCost.getBigDecimal("amount").multiply(BigDecimal.valueOf(actualSetupMillis));
@@ -1264,7 +1292,7 @@ public class ProductionRunServices {
         try {
             Map<String, BigDecimal> materialsCostByCurrency = new HashMap<>();
             for (GenericValue inventoryConsumed : EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign")
-                                .where("workEffortId", productionRunTaskId).queryList()) {
+                    .where("workEffortId", productionRunTaskId).queryList()) {
                 BigDecimal quantity = inventoryConsumed.getBigDecimal("quantity");
                 BigDecimal unitCost = inventoryConsumed.getBigDecimal("unitCost");
                 if (UtilValidate.isEmpty(unitCost) || UtilValidate.isEmpty(quantity)) {
@@ -1301,13 +1329,15 @@ public class ProductionRunServices {
      * Check if field for routingTask update are correct and if need recalculated data in Production Run.
      * Check
      * <ul>
-     *  <li> if estimatedStartDate is not before Production Run estimatedStartDate.</li>
-     *  <li> if there is not a another routingTask with the same priority</li>
-     *  <li>If priority or estimatedStartDate has changed recalculated data for routingTask after that one.</li>
+     * <li> if estimatedStartDate is not before Production Run estimatedStartDate.</li>
+     * <li> if there is not a another routingTask with the same priority</li>
+     * <li>If priority or estimatedStartDate has changed recalculated data for routingTask after that one.</li>
      * </ul>
      * Update the productionRun
-     * @param ctx The DispatchContext that this service is operating in.
-     * @param context Map containing the input parameters, productId, routingId, priority, estimatedStartDate, estimatedSetupMillis, estimatedMilliSeconds
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
+     * @param context Map containing the input parameters, productId, routingId, priority, estimatedStartDate, estimatedSetupMillis,
+     *                estimatedMilliSeconds
      * @return Map with the result of the service, the output parameters, estimatedCompletionDate.
      */
     public static Map<String, Object> checkUpdatePrunRoutingTask(DispatchContext ctx, Map<String, ? extends Object> context) {
@@ -1323,7 +1353,7 @@ public class ProductionRunServices {
             if (productionRun.exist()) {
 
                 if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId")) &&
-                      !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
+                        !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale));
                 }
 
@@ -1331,7 +1361,8 @@ public class ProductionRunServices {
                 Timestamp pRestimatedStartDate = productionRun.getEstimatedStartDate();
                 if (pRestimatedStartDate.after(estimatedStartDate)) {
                     try {
-                        serviceResult = dispatcher.runSync("updateProductionRun", UtilMisc.toMap("productionRunId", productionRunId, "estimatedStartDate", estimatedStartDate, "userLogin", userLogin));
+                        serviceResult = dispatcher.runSync("updateProductionRun", UtilMisc.toMap("productionRunId", productionRunId,
+                                "estimatedStartDate", estimatedStartDate, "userLogin", userLogin));
                         if (ServiceUtil.isError(serviceResult)) {
                             return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                         }
@@ -1373,11 +1404,11 @@ public class ProductionRunServices {
                 if (productionRun.store()) {
                     return ServiceUtil.returnSuccess();
                 } else {
-                    Debug.logError("productionRun.store() fail for productionRunId ="+productionRunId, MODULE);
+                    Debug.logError("productionRun.store() fail for productionRunId =" + productionRunId, MODULE);
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale));
                 }
             }
-            Debug.logError("no productionRun for productionRunId ="+productionRunId, MODULE);
+            Debug.logError("no productionRun for productionRunId =" + productionRunId, MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotUpdated", locale));
         }
         Debug.logError("service updateProductionRun call with productionRunId empty", MODULE);
@@ -1478,7 +1509,7 @@ public class ProductionRunServices {
         }
 
         if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId"))
-            && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
+                && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale));
         }
 
@@ -1531,7 +1562,8 @@ public class ProductionRunServices {
             Debug.logError(e, "Problem calling the updateWorkEffortGoodStandard service", MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunComponentNotAdded", locale));
         }
-        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunComponentUpdated", UtilMisc.toMap("productionRunId", productionRunId), locale));
+        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunComponentUpdated", UtilMisc.toMap(
+                "productionRunId", productionRunId), locale));
         return result;
     }
 
@@ -1553,12 +1585,12 @@ public class ProductionRunServices {
         Timestamp estimatedCompletionDate = (Timestamp) context.get("estimatedCompletionDate");
 
         Double estimatedSetupMillis = null;
-        if (context.get("estimatedSetupMillis") != null)
-        estimatedSetupMillis = ((BigDecimal) context.get("estimatedSetupMillis")).doubleValue();
+        if (context.get("estimatedSetupMillis") != null)
+            estimatedSetupMillis = ((BigDecimal) context.get("estimatedSetupMillis")).doubleValue();
 
         Double estimatedMilliSeconds = null;
-        if (context.get("estimatedMilliSeconds") != null)
-        estimatedMilliSeconds = ((BigDecimal) context.get("estimatedMilliSeconds")).doubleValue();
+        if (context.get("estimatedMilliSeconds") != null)
+            estimatedMilliSeconds = ((BigDecimal) context.get("estimatedMilliSeconds")).doubleValue();
 
         // The production run is loaded
         ProductionRun productionRun = new ProductionRun(productionRunId, delegator, dispatcher);
@@ -1568,7 +1600,7 @@ public class ProductionRunServices {
         }
 
         if (!"PRUN_CREATED".equals(productionRun.getGenericValue().getString("currentStatusId"))
-            && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
+                && !"PRUN_SCHEDULED".equals(productionRun.getGenericValue().getString("currentStatusId"))) {
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunPrinted", locale));
         }
 
@@ -1584,11 +1616,11 @@ public class ProductionRunServices {
         try {
             routingTask = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", routingTaskId).queryOne();
         } catch (GenericEntityException e) {
-            Debug.logError(e.getMessage(),  MODULE);
+            Debug.logError(e.getMessage(), MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingRoutingTaskNotExists", locale));
         }
         if (routingTask == null) {
-            Debug.logError("Routing task: " + routingTaskId + " is null.",  MODULE);
+            Debug.logError("Routing task: " + routingTaskId + " is null.", MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingRoutingTaskNotExists", locale));
         }
 
@@ -1657,16 +1689,16 @@ public class ProductionRunServices {
                     .where("workEffortId", routingTaskId)
                     .filterByDate().queryList();
         } catch (GenericEntityException e) {
-            Debug.logError(e.getMessage(),  MODULE);
+            Debug.logError(e.getMessage(), MODULE);
         }
         if (workEffortPartyAssignments != null) {
             for (GenericValue workEffortPartyAssignment : workEffortPartyAssignments) {
                 Map<String, Object> partyToWorkEffort = UtilMisc.<String, Object>toMap(
-                        "workEffortId",  productionRunTaskId,
-                        "partyId",  workEffortPartyAssignment.getString("partyId"),
-                        "roleTypeId",  workEffortPartyAssignment.getString("roleTypeId"),
-                        "fromDate",  workEffortPartyAssignment.getTimestamp("fromDate"),
-                        "statusId",  workEffortPartyAssignment.getString("statusId"),
+                        "workEffortId", productionRunTaskId,
+                        "partyId", workEffortPartyAssignment.getString("partyId"),
+                        "roleTypeId", workEffortPartyAssignment.getString("roleTypeId"),
+                        "fromDate", workEffortPartyAssignment.getTimestamp("fromDate"),
+                        "statusId", workEffortPartyAssignment.getString("statusId"),
                         "userLogin", userLogin);
                 try {
                     serviceResult = dispatcher.runSync("assignPartyToWorkEffort", partyToWorkEffort);
@@ -1759,27 +1791,27 @@ public class ProductionRunServices {
         if (lotId == null && autoCreateLot) {
             createLotIfNeeded = Boolean.TRUE;
         }
-            try {
-                // Find the lot
-                GenericValue lot = EntityQuery.use(delegator).from("Lot").where("lotId", lotId).queryOne();
-                if (lot == null) {
-                    if (createLotIfNeeded) {
-                        Map<String, Object> createLotCtx = ctx.makeValidContext("createLot", ModelService.IN_PARAM, context);
-                        createLotCtx.put("creationDate", UtilDateTime.nowTimestamp());
-                        Map<String, Object> serviceResults = dispatcher.runSync("createLot", createLotCtx);
-                        if (ServiceUtil.isError(serviceResults)) {
-                            Debug.logError(ServiceUtil.getErrorMessage(serviceResults), MODULE);
-                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
-                        }
-                        lotId = (String) serviceResults.get("lotId");
-                    } else if (UtilValidate.isNotEmpty(lotId)) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingLotNotExists", locale));
+        try {
+            // Find the lot
+            GenericValue lot = EntityQuery.use(delegator).from("Lot").where("lotId", lotId).queryOne();
+            if (lot == null) {
+                if (createLotIfNeeded) {
+                    Map<String, Object> createLotCtx = ctx.makeValidContext("createLot", ModelService.IN_PARAM, context);
+                    createLotCtx.put("creationDate", UtilDateTime.nowTimestamp());
+                    Map<String, Object> serviceResults = dispatcher.runSync("createLot", createLotCtx);
+                    if (ServiceUtil.isError(serviceResults)) {
+                        Debug.logError(ServiceUtil.getErrorMessage(serviceResults), MODULE);
+                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResults));
                     }
+                    lotId = (String) serviceResults.get("lotId");
+                } else if (UtilValidate.isNotEmpty(lotId)) {
+                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingLotNotExists", locale));
                 }
-            } catch (GenericEntityException | GenericServiceException e) {
-                Debug.logWarning(e.getMessage(), MODULE);
-                return ServiceUtil.returnError(e.getMessage());
             }
+        } catch (GenericEntityException | GenericServiceException e) {
+            Debug.logWarning(e.getMessage(), MODULE);
+            return ServiceUtil.returnError(e.getMessage());
+        }
 
         GenericValue orderItem = null;
         try {
@@ -1796,7 +1828,8 @@ public class ProductionRunServices {
         try {
             // get the currency
             facility = productionRun.getGenericValue().getRelatedOne("Facility", false);
-            Map<String, Object> outputMap = dispatcher.runSync("getPartyAccountingPreferences", UtilMisc.<String, Object>toMap("userLogin", userLogin, "organizationPartyId", facility.getString("ownerPartyId")));
+            Map<String, Object> outputMap = dispatcher.runSync("getPartyAccountingPreferences", UtilMisc.<String, Object>toMap("userLogin",
+                    userLogin, "organizationPartyId", facility.getString("ownerPartyId")));
             if (ServiceUtil.isError(outputMap)) {
                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap));
             }
@@ -1804,7 +1837,9 @@ public class ProductionRunServices {
             if (partyAccountingPreference == null) {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToFindCosts", locale));
             }
-            outputMap = dispatcher.runSync("getProductCost", UtilMisc.<String, Object>toMap("userLogin", userLogin, "productId", productionRun.getProductProduced().getString("productId"), "currencyUomId", (String) partyAccountingPreference.get("baseCurrencyUomId"), "costComponentTypePrefix", "EST_STD"));
+            outputMap = dispatcher.runSync("getProductCost", UtilMisc.<String, Object>toMap("userLogin", userLogin, "productId",
+                    productionRun.getProductProduced().getString("productId"), "currencyUomId",
+                    (String) partyAccountingPreference.get("baseCurrencyUomId"), "costComponentTypePrefix", "EST_STD"));
             if (ServiceUtil.isError(outputMap)) {
                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(outputMap));
             }
@@ -1816,7 +1851,7 @@ public class ProductionRunServices {
                 List<GenericValue> actualGenCosts = EntityQuery.use(delegator)
                         .from("CostComponent")
                         .where("workEffortId", productionRunId,
-                               "costUomId", partyAccountingPreference.get("baseCurrencyUomId"))
+                                "costUomId", partyAccountingPreference.get("baseCurrencyUomId"))
                         .queryList();
                 for (GenericValue actualGenCost : actualGenCosts) {
                     totalCost = totalCost.add((BigDecimal) actualGenCost.get("cost"));
@@ -1825,7 +1860,7 @@ public class ProductionRunServices {
                     List<GenericValue> otherCosts = EntityQuery.use(delegator)
                             .from("CostComponent")
                             .where("workEffortId", task.get("workEffortId"),
-                                   "costUomId", partyAccountingPreference.get("baseCurrencyUomId"))
+                                    "costUomId", partyAccountingPreference.get("baseCurrencyUomId"))
                             .queryList();
                     for (GenericValue otherCost : otherCosts) {
                         totalCost = totalCost.add((BigDecimal) otherCost.get("cost"));
@@ -1837,8 +1872,9 @@ public class ProductionRunServices {
                     unitCost = BigDecimal.ZERO;
                 }
             }
-         // Before creating InvntoryItem and InventoryItemDetails, check weather the record of ProductFacility exist in the system or not
-            GenericValue productFacility = EntityQuery.use(delegator). from("ProductFacility").where("productId", productionRun.getProductProduced().getString("productId"),
+            // Before creating InvntoryItem and InventoryItemDetails, check weather the record of ProductFacility exist in the system or not
+            GenericValue productFacility = EntityQuery.use(delegator).from("ProductFacility").where("productId",
+                    productionRun.getProductProduced().getString("productId"),
                     "facilityId", facility.get("facilityId")).queryOne();
             if (productFacility == null) {
                 Map<String, Object> createProductFacilityCtx = new HashMap<>();
@@ -1860,7 +1896,8 @@ public class ProductionRunServices {
             try {
                 int numOfItems = quantity.intValue();
                 for (int i = 0; i < numOfItems; i++) {
-                    Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("productId", productionRun.getProductProduced().getString("productId"),
+                    Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("productId", productionRun.getProductProduced().getString(
+                            "productId"),
                             "inventoryItemTypeId", "SERIALIZED_INV_ITEM",
                             "statusId", "INV_AVAILABLE");
                     serviceContext.put("facilityId", productionRun.getGenericValue().getString("facilityId"));
@@ -1912,7 +1949,8 @@ public class ProductionRunServices {
             }
         } else {
             try {
-                Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("productId", productionRun.getProductProduced().getString("productId"),
+                Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("productId", productionRun.getProductProduced().getString(
+                        "productId"),
                         "inventoryItemTypeId", "NON_SERIAL_INV_ITEM");
                 serviceContext.put("facilityId", productionRun.getGenericValue().getString("facilityId"));
                 serviceContext.put("datetimeReceived", UtilDateTime.nowTimestamp());
@@ -2220,7 +2258,7 @@ public class ProductionRunServices {
         try {
             BigDecimal totalIssued = BigDecimal.ZERO;
             for (GenericValue issuance : EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign")
-                            .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) {
+                    .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) {
                 BigDecimal issued = issuance.getBigDecimal("quantity");
                 if (issued != null) {
                     totalIssued = totalIssued.add(issued);
@@ -2228,7 +2266,7 @@ public class ProductionRunServices {
             }
             BigDecimal totalReturned = BigDecimal.ZERO;
             for (GenericValue returned : EntityQuery.use(delegator).from("WorkEffortAndInventoryProduced")
-                            .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) {
+                    .where("workEffortId", productionRunTaskId, "productId", productId).queryList()) {
                 GenericValue returnDetail = EntityQuery.use(delegator).from("InventoryItemDetail")
                         .where("inventoryItemId", returned.get("inventoryItemId"))
                         .orderBy("inventoryItemDetailSeqId")
@@ -2241,7 +2279,9 @@ public class ProductionRunServices {
                 }
             }
             if (quantity.compareTo(totalIssued.subtract(totalReturned)) > 0) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotReturnMoreItems", UtilMisc.toMap("productionRunTaskId", productionRunTaskId, "quantity", quantity, "quantityAllocated", totalIssued.subtract(totalReturned)), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskCannotReturnMoreItems",
+                        UtilMisc.toMap("productionRunTaskId", productionRunTaskId, "quantity", quantity, "quantityAllocated",
+                                totalIssued.subtract(totalReturned)), locale));
             }
         } catch (GenericEntityException gee) {
             return ServiceUtil.returnError(gee.getMessage());
@@ -2256,7 +2296,8 @@ public class ProductionRunServices {
                             "productId", productId, "quantity", quantity, "lotId", lotId, "currencyUomId", uomId, "isReturned", "Y",
                             "inventoryItemTypeId", inventoryItemTypeId, "userLogin", userLogin));
             if (ServiceUtil.isError(inventoryResult)) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTaskProduceError" + ServiceUtil.getErrorMessage(inventoryResult), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
+                        "ManufacturingProductionRunTaskProduceError" + ServiceUtil.getErrorMessage(inventoryResult), locale));
             }
         } catch (GenericServiceException exc) {
             return ServiceUtil.returnError(exc.getMessage());
@@ -2352,7 +2393,8 @@ public class ProductionRunServices {
                 try {
                     List<GenericValue> components = theTask.getRelated("WorkEffortGoodStandard", null, null, false);
                     for (GenericValue component : components) {
-                        BigDecimal totalRequiredMaterialQuantity = component.getBigDecimal("estimatedQuantity").multiply(totalQuantityProduced).divide(quantityToProduce, ROUNDING);
+                        BigDecimal totalRequiredMaterialQuantity =
+                                component.getBigDecimal("estimatedQuantity").multiply(totalQuantityProduced).divide(quantityToProduce, ROUNDING);
                         // now get the units that have been already issued and subtract them
                         List<GenericValue> issuances = EntityQuery.use(delegator).from("WorkEffortAndInventoryAssign")
                                 .where("workEffortId", workEffortId,
@@ -2387,7 +2429,7 @@ public class ProductionRunServices {
                             if (ServiceUtil.isError(serviceResult)) {
                                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
                             }
-                       }
+                        }
                     }
                 } catch (GenericEntityException | GenericServiceException e) {
                     String errMsg = "Problem calling the updateProductionRunTaskStatus service";
@@ -2525,7 +2567,8 @@ public class ProductionRunServices {
         String productionRunId = (String) serviceResult.get("productionRunId");
         result.put("productionRunId", productionRunId);
 
-        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale));
+        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap(
+                "productionRunId", productionRunId), locale));
         return result;
     }
 
@@ -2549,7 +2592,8 @@ public class ProductionRunServices {
         }
         if (config == null && configId != null) {
             // TODO: load the configuration
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunFromConfigurationNotYetImplemented", locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunFromConfigurationNotYetImplemented",
+                    locale));
         }
         if (!config.isCompleted()) {
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunFromConfigurationNotValid", locale));
@@ -2637,7 +2681,8 @@ public class ProductionRunServices {
                     } catch (GenericServiceException e) {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotCreated", locale));
                     } catch (GenericEntityException e) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTryToCreateWorkEffortAssoc", locale));
+                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunTryToCreateWorkEffortAssoc",
+                                locale));
                     }
 
                 } else {
@@ -2691,13 +2736,15 @@ public class ProductionRunServices {
         }
         try {
             if (productionRunId != null && orderId != null && orderItemSeqId != null) {
-                delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId", orderItemSeqId));
+                delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId",
+                        orderItemSeqId));
             }
         } catch (GenericEntityException e) {
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingRequirementNotDeleted", locale));
         }
 
-        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale));
+        result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap(
+                "productionRunId", productionRunId), locale));
         return result;
     }
 
@@ -2720,20 +2767,23 @@ public class ProductionRunServices {
             GenericValue productStore = delegator.getRelatedOne("ProductStore", order, false);
             isImmediatelyFulfilled = "Y".equals(productStore.getString("isImmediatelyFulfilled"));
         } catch (GenericEntityException e) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError",
+                    UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale));
         }
 
         GenericValue orderItem = null;
         try {
             orderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryOne();
         } catch (GenericEntityException e) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError",
+                    UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale));
         }
         if (orderItem == null) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesOrderItemNotFound", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesOrderItemNotFound",
+                    UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId), locale));
         }
         if (orderItem.get("quantity") == null) {
-            Debug.logWarning("No quantity found for orderItem [" + orderItem +"], skipping production run of this marketing package", MODULE);
+            Debug.logWarning("No quantity found for orderItem [" + orderItem + "], skipping production run of this marketing package", MODULE);
             return ServiceUtil.returnSuccess();
         }
 
@@ -2754,7 +2804,9 @@ public class ProductionRunServices {
                 existingAtp = existingAtp.subtract(orderItem.getBigDecimal("quantity"));
             }
 
-            if (Debug.verboseOn()) { Debug.logVerbose("Order item [" + orderItem + "] Existing ATP = [" + existingAtp + "]", MODULE); }
+            if (Debug.verboseOn()) {
+                Debug.logVerbose("Order item [" + orderItem + "] Existing ATP = [" + existingAtp + "]", MODULE);
+            }
             // we only need to produce more marketing packages if there isn't enough in stock.
             if (existingAtp.compareTo(ZERO) < 0) {
                 // how many should we produce?  If there already is some inventory, then just produce enough to bring ATP back up to zero.
@@ -2802,7 +2854,10 @@ public class ProductionRunServices {
                 }
 
                 if (qtyToProduce.compareTo(ZERO) > 0) {
-                    if (Debug.verboseOn()) { Debug.logVerbose("Required quantity (all orders) = [" + qtyRequired + "] quantity to produce = [" + qtyToProduce + "]", MODULE); }
+                    if (Debug.verboseOn()) {
+                        Debug.logVerbose("Required quantity (all orders) = [" + qtyRequired + "] quantity to produce = [" + qtyToProduce + "]",
+                                MODULE);
+                    }
 
                     serviceContext.put("pRQuantity", qtyToProduce);
                     serviceContext.put("startDate", UtilDateTime.nowTimestamp());
@@ -2814,10 +2869,13 @@ public class ProductionRunServices {
                     result.put("productionRunId", productionRunId);
 
                     try {
-                        delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId, "orderItemSeqId", orderItemSeqId));
+                        delegator.create("WorkOrderItemFulfillment", UtilMisc.toMap("workEffortId", productionRunId, "orderId", orderId,
+                                "orderItemSeqId", orderItemSeqId));
                     } catch (GenericEntityException e) {
-                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "errorString", e.getMessage()), locale));
-                   }
+                        return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
+                                "ManufacturingProductionRunForMarketingPackagesCreationError", UtilMisc.toMap("orderId", orderId, "orderItemSeqId",
+                                        orderItemSeqId, "errorString", e.getMessage()), locale));
+                    }
 
                     try {
                         serviceContext.clear();
@@ -2839,14 +2897,20 @@ public class ProductionRunServices {
                         return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunNotCreated", locale));
                     }
 
-                    result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated", UtilMisc.toMap("productionRunId", productionRunId), locale));
+                    result.put(ModelService.SUCCESS_MESSAGE, UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCreated",
+                            UtilMisc.toMap("productionRunId", productionRunId), locale));
                     return result;
                 } else {
-                    if (Debug.verboseOn()) { Debug.logVerbose("There are not enough components available to produce any marketing packages [" + orderItem.getString("productId") + "]", MODULE); }
+                    if (Debug.verboseOn()) {
+                        Debug.logVerbose("There are not enough components available to produce any marketing packages [" + orderItem.getString(
+                                "productId") + "]", MODULE);
+                    }
                     return ServiceUtil.returnSuccess();
                 }
             } else {
-                if (Debug.verboseOn()) { Debug.logVerbose("No marketing packages need to be produced - ATP is [" + existingAtp + "]", MODULE); }
+                if (Debug.verboseOn()) {
+                    Debug.logVerbose("No marketing packages need to be produced - ATP is [" + existingAtp + "]", MODULE);
+                }
                 return ServiceUtil.returnSuccess();
             }
         } catch (GenericServiceException e) {
@@ -2884,28 +2948,33 @@ public class ProductionRunServices {
             try {
                 GenericValue orderItem = null;
                 if (UtilValidate.isNotEmpty(shipGroupSeqId)) {
-                    orderItem = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId).queryOne();
+                    orderItem = EntityQuery.use(delegator).from("OrderItemShipGroupAssoc").where("orderId", orderId, "orderItemSeqId",
+                            orderItemSeqId, "shipGroupSeqId", shipGroupSeqId).queryOne();
                 } else {
                     orderItem = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId, "orderItemSeqId", orderItemSeqId).queryOne();
                 }
                 if (orderItem == null) {
-                    return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", ""), locale));
+                    return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId",
+                            orderId, "orderItemSeqId", ""), locale));
                 }
                 if (quantity != null) {
                     orderItem.set("quantity", quantity);
                 }
                 orderItems = UtilMisc.toList(orderItem);
             } catch (GenericEntityException gee) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap("errorString", gee.getMessage()), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap(
+                        "errorString", gee.getMessage()), locale));
             }
         } else {
             try {
                 orderItems = EntityQuery.use(delegator).from("OrderItem").where("orderId", orderId).queryList();
                 if (orderItems == null) {
-                    return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", ""), locale));
+                    return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderErrorOrderItemNotFound", UtilMisc.toMap("orderId",
+                            orderId, "orderItemSeqId", ""), locale));
                 }
             } catch (GenericEntityException gee) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap("errorString", gee.getMessage()), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RES_ORDER, "OrderProblemsReadingOrderItemInformation", UtilMisc.toMap(
+                        "errorString", gee.getMessage()), locale));
             }
         }
         List<String> productionRuns = new LinkedList<>();
@@ -2945,24 +3014,28 @@ public class ProductionRunServices {
                     existingProductionRuns = EntityQuery.use(delegator).from("WorkAndOrderItemFulfillment")
                             .where(
                                     EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderId")),
-                                    EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderItemSeqId")),
-                                    EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("shipGroupSeqId")),
+                                    EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get(
+                                            "orderItemSeqId")),
+                                    EntityCondition.makeCondition("shipGroupSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get(
+                                            "shipGroupSeqId")),
                                     EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED"))
-                                    .cache().queryList();
+                            .cache().queryList();
                 } else {
                     existingProductionRuns = EntityQuery.use(delegator).from("WorkAndOrderItemFulfillment")
                             .where(
                                     EntityCondition.makeCondition("orderId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderId")),
-                                    EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get("orderItemSeqId")),
+                                    EntityCondition.makeCondition("orderItemSeqId", EntityOperator.EQUALS, orderItemOrShipGroupAssoc.get(
+                                            "orderItemSeqId")),
                                     EntityCondition.makeCondition("currentStatusId", EntityOperator.NOT_EQUAL, "PRUN_CANCELLED"))
-                                    .cache().queryList();
+                            .cache().queryList();
                 }
                 if (UtilValidate.isNotEmpty(existingProductionRuns)) {
                     Debug.logWarning("Production Run for order item [" + orderItemOrShipGroupAssoc.getString("orderId") + "/" + orderItemOrShipGroupAssoc.getString("orderItemSeqId") + "] and ship group [" + shipGroupSeqId + "] already exists.", MODULE);
                     continue;
                 }
             } catch (GenericEntityException gee) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturinWorkOrderItemFulfillmentError", UtilMisc.toMap("errorString", gee.getMessage()), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturinWorkOrderItemFulfillmentError", UtilMisc.toMap(
+                        "errorString", gee.getMessage()), locale));
             }
             try {
                 List<BOMNode> components = new LinkedList<>();
@@ -2970,9 +3043,11 @@ public class ProductionRunServices {
                 tree.setRootQuantity(quantity);
                 tree.setRootAmount(amount);
                 tree.print(components);
-                productionRuns.add(tree.createManufacturingOrders(null, fromDate, null, null, null, orderId, orderItem.getString("orderItemSeqId"), shipGroupSeqId, shipmentId, userLogin));
+                productionRuns.add(tree.createManufacturingOrders(null, fromDate, null, null, null, orderId, orderItem.getString("orderItemSeqId"),
+                        shipGroupSeqId, shipmentId, userLogin));
             } catch (GenericEntityException gee) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", UtilMisc.toMap("errorString", gee.getMessage()), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree",
+                        UtilMisc.toMap("errorString", gee.getMessage()), locale));
             }
         }
         result.put("productionRuns", productionRuns);
@@ -2983,7 +3058,7 @@ public class ProductionRunServices {
         Map<String, Object> result = new HashMap<>();
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin =(GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
         String productId = (String) context.get("productId");
         Timestamp startDate = (Timestamp) context.get("startDate");
@@ -3002,12 +3077,15 @@ public class ProductionRunServices {
             tree.setRootQuantity(quantity);
             tree.setRootAmount(BigDecimal.ZERO);
             tree.print(components);
-            workEffortId = tree.createManufacturingOrders(facilityId, startDate, workEffortName, description, routingId, null, null, null, null, userLogin);
+            workEffortId = tree.createManufacturingOrders(facilityId, startDate, workEffortName, description, routingId, null, null, null, null,
+                    userLogin);
         } catch (GenericEntityException gee) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", UtilMisc.toMap("errorString", gee.getMessage()), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingBomErrorCreatingBillOfMaterialsTree", UtilMisc.toMap(
+                    "errorString", gee.getMessage()), locale));
         }
         if (workEffortId == null) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunIsNotRequiredForProductId", UtilMisc.toMap("productId", productId, "startDate", startDate), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunIsNotRequiredForProductId",
+                    UtilMisc.toMap("productId", productId, "startDate", startDate), locale));
         }
         List<String> productionRuns = new LinkedList<>();
         result.put("productionRuns", productionRuns);
@@ -3018,7 +3096,8 @@ public class ProductionRunServices {
     /**
      * Quick runs a ProductionRun task to the completed status, also issuing components
      * if necessary.
-     * @param ctx The DispatchContext that this service is operating in.
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters.
      * @return Map with the result of the service, the output parameters.
      */
@@ -3049,7 +3128,8 @@ public class ProductionRunServices {
                 }
                 currentStatusId = (String) serviceResult.get("newStatusId");
                 if (currentStatusId.equals(prevStatusId)) {
-                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToProgressTaskStatus", UtilMisc.toMap("prevStatusId", prevStatusId, "taskId", taskId), locale));
+                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunUnableToProgressTaskStatus",
+                            UtilMisc.toMap("prevStatusId", prevStatusId, "taskId", taskId), locale));
                 } else {
                     prevStatusId = currentStatusId;
                 }
@@ -3068,7 +3148,8 @@ public class ProductionRunServices {
     /**
      * Quick runs all the tasks of a ProductionRun to the completed status,
      * also issuing components if necessary.
-     * @param ctx The DispatchContext that this service is operating in.
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters.
      * @return Map with the result of the service, the output parameters.
      */
@@ -3152,7 +3233,8 @@ public class ProductionRunServices {
     /**
      * Quick moves a ProductionRun to the passed in status, performing all
      * the needed tasks in the way.
-     * @param ctx The DispatchContext that this service is operating in.
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters.
      * @return Map with the result of the service, the output parameters.
      */
@@ -3235,7 +3317,8 @@ public class ProductionRunServices {
     /**
      * Given a productId and an optional date, returns the total qty
      * of productId reserved by production runs.
-     * @param ctx The DispatchContext that this service is operating in.
+     *
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters.
      * @return Map with the result of the service, the output parameters.
      */
@@ -3294,18 +3377,21 @@ public class ProductionRunServices {
         try {
             GenericValue inventoryItem = EntityQuery.use(delegator).from("InventoryItem").where("inventoryItemId", inventoryItemId).queryOne();
             if (inventoryItem == null) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductInventoryItemNotFound", UtilMisc.toMap("inventoryItemId", inventoryItemId), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductInventoryItemNotFound", UtilMisc.toMap(
+                        "inventoryItemId", inventoryItemId), locale));
             }
             if (inventoryItem.get("availableToPromiseTotal") != null && inventoryItem.getBigDecimal("availableToPromiseTotal").compareTo(ZERO) <= 0) {
                 return ServiceUtil.returnSuccess();
             }
             GenericValue product = inventoryItem.getRelatedOne("Product", false);
             if (product == null) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductProductNotFound", locale) + " " + inventoryItem.get("productId"));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RES_PRODUCT, "ProductProductNotFound", locale) + " " + inventoryItem.get(
+                        "productId"));
             }
-            if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG_AUTO")) {
+            if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId",
+                    "MARKETING_PKG_AUTO")) {
                 Map<String, Object> serviceContext = UtilMisc.toMap("inventoryItemId", inventoryItemId,
-                                                    "userLogin", userLogin);
+                        "userLogin", userLogin);
                 serviceResult = dispatcher.runSync("decomposeInventoryItem", serviceContext);
                 if (ServiceUtil.isError(serviceResult)) {
                     return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
@@ -3336,13 +3422,16 @@ public class ProductionRunServices {
             GenericValue inventoryItem = EntityQuery.use(delegator).from("InventoryItem")
                     .where("inventoryItemId", inventoryItemId).queryOne();
             if (inventoryItem == null) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItem", UtilMisc.toMap("inventoryItemId", inventoryItemId), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItem",
+                        UtilMisc.toMap("inventoryItemId", inventoryItemId), locale));
             }
             // the work effort (disassemble order) is created
             Map<String, Object> serviceContext = UtilMisc.<String, Object>toMap("workEffortTypeId", "TASK",
                     "workEffortPurposeTypeId", "WEPT_PRODUCTION_RUN",
                     "currentStatusId", "CAL_COMPLETED");
-            serviceContext.put("workEffortName", "Decomposing product [" + inventoryItem.getString("productId") + "] inventory item [" + inventoryItem.getString("inventoryItemId") + "]");
+            serviceContext.put("workEffortName",
+                    "Decomposing product [" + inventoryItem.getString("productId") + "] inventory item [" + inventoryItem.getString("inventoryItemId") +
+                            "]");
             serviceContext.put("facilityId", inventoryItem.getString("facilityId"));
             serviceContext.put("estimatedStartDate", now);
             serviceContext.put("userLogin", userLogin);
@@ -3364,15 +3453,18 @@ public class ProductionRunServices {
             }
             BigDecimal issuedQuantity = (BigDecimal) serviceResult.get("quantityIssued");
             if (issuedQuantity.compareTo(ZERO) == 0) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItemNoMarketingPackagesFound", UtilMisc.toMap("inventoryItemId", inventoryItem.getString("inventoryItemId")), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
+                        "ManufacturingProductionRunCannotDecomposingInventoryItemNoMarketingPackagesFound", UtilMisc.toMap("inventoryItemId",
+                                inventoryItem.getString("inventoryItemId")), locale));
             }
-            // get the package's unit cost to compute a cost coefficient ratio which is the marketing package's actual unit cost divided by its standard cost
+            // get the package's unit cost to compute a cost coefficient ratio which is the marketing package's actual unit cost divided by its
+            // standard cost
             // this ratio will be used to determine the cost of the marketing package components when they are returned to inventory
             serviceContext.clear();
             serviceContext = UtilMisc.toMap("productId", inventoryItem.getString("productId"),
-                                 "currencyUomId", inventoryItem.getString("currencyUomId"),
-                                 "costComponentTypePrefix", "EST_STD",
-                                 "userLogin", userLogin);
+                    "currencyUomId", inventoryItem.getString("currencyUomId"),
+                    "costComponentTypePrefix", "EST_STD",
+                    "userLogin", userLogin);
             serviceResult = dispatcher.runSync("getProductCost", serviceContext);
             if (ServiceUtil.isError(serviceResult)) {
                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
@@ -3394,23 +3486,25 @@ public class ProductionRunServices {
             // the components are retrieved
             serviceContext.clear();
             serviceContext = UtilMisc.toMap("productId", inventoryItem.getString("productId"),
-                                 "quantity", issuedQuantity,
-                                 "userLogin", userLogin);
+                    "quantity", issuedQuantity,
+                    "userLogin", userLogin);
             serviceResult = dispatcher.runSync("getManufacturingComponents", serviceContext);
             if (ServiceUtil.isError(serviceResult)) {
                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
             }
             List<Map<String, Object>> components = UtilGenerics.cast(serviceResult.get("componentsMap"));
             if (UtilValidate.isEmpty(components)) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunCannotDecomposingInventoryItemNoComponentsFound", UtilMisc.toMap("productId", inventoryItem.getString("productId")), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
+                        "ManufacturingProductionRunCannotDecomposingInventoryItemNoComponentsFound", UtilMisc.toMap("productId", inventoryItem.getString(
+                        "productId")), locale));
             }
             for (Map<String, Object> component : components) {
                 // get the component's standard cost
                 serviceContext.clear();
                 serviceContext = UtilMisc.toMap("productId", ((GenericValue) component.get("product")).getString("productId"),
-                                     "currencyUomId", inventoryItem.getString("currencyUomId"),
-                                     "costComponentTypePrefix", "EST_STD",
-                                     "userLogin", userLogin);
+                        "currencyUomId", inventoryItem.getString("currencyUomId"),
+                        "costComponentTypePrefix", "EST_STD",
+                        "userLogin", userLogin);
                 serviceResult = dispatcher.runSync("getProductCost", serviceContext);
                 if (ServiceUtil.isError(serviceResult)) {
                     return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
@@ -3421,10 +3515,10 @@ public class ProductionRunServices {
                 BigDecimal componentInventoryItemCost = costCoefficient.multiply(componentCost);
                 serviceContext.clear();
                 serviceContext = UtilMisc.toMap("productId", ((GenericValue) component.get("product")).getString("productId"),
-                                     "quantity", component.get("quantity"),
-                                     "facilityId", inventoryItem.getString("facilityId"),
-                                     "unitCost", componentInventoryItemCost,
-                                     "userLogin", userLogin);
+                        "quantity", component.get("quantity"),
+                        "facilityId", inventoryItem.getString("facilityId"),
+                        "unitCost", componentInventoryItemCost,
+                        "userLogin", userLogin);
                 serviceContext.put("workEffortId", workEffortId);
                 serviceResult = dispatcher.runSync("productionRunTaskProduce", serviceContext);
                 if (ServiceUtil.isError(serviceResult)) {
@@ -3456,7 +3550,7 @@ public class ProductionRunServices {
                     .queryList();
             for (GenericValue genericResult : resultList) {
                 if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId"))
-                    || "PRUN_CREATED".equals(genericResult.getString("currentStatusId"))) {
+                        || "PRUN_CREATED".equals(genericResult.getString("currentStatusId"))) {
                     continue;
                 }
                 BigDecimal qtyToProduce = genericResult.getBigDecimal("quantityToProduce");
@@ -3502,12 +3596,14 @@ public class ProductionRunServices {
                 if (!newOrderId.equals(orderId)) {
                     orderDeliverySchedule = null;
                     orderId = newOrderId;
-                    orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne();
+                    orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId",
+                            "_NA_").queryOne();
                 }
                 String productId = genericResult.getString("productId");
                 BigDecimal orderQuantity = genericResult.getBigDecimal("quantity");
                 GenericValue orderItemDeliverySchedule = null;
-                orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryOne();
+                orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId",
+                        genericResult.getString("orderItemSeqId")).queryOne();
                 Timestamp estimatedShipDate = null;
                 if (orderItemDeliverySchedule != null && orderItemDeliverySchedule.get("estimatedReadyDate") != null) {
                     estimatedShipDate = orderItemDeliverySchedule.getTimestamp("estimatedReadyDate");
@@ -3590,7 +3686,8 @@ public class ProductionRunServices {
             }
         } catch (GenericEntityException e) {
             Debug.logError(e, "Error", MODULE);
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunErrorRunningSetEstimatedDeliveryDates", locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingProductionRunErrorRunningSetEstimatedDeliveryDates",
+                    locale));
         }
         return ServiceUtil.returnSuccess();
     }
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java
index 5cf831f..9c0415e 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/InventoryEventPlannedServices.java
@@ -41,7 +41,7 @@ public class InventoryEventPlannedServices {
     /**
      *
      *  Create an MrpEvent.
-     *  Make an update if a record exist with same key,  (adding the event quantity to the exiting record)
+     *  Make an update if a record exist with same key, (adding the event quantity to the exiting record)
      *
      * @param ctx the dispatch context
      * @param context a map containing the parameters used to create an MrpEvent
@@ -58,7 +58,7 @@ public class InventoryEventPlannedServices {
         try {
             createOrUpdateMrpEvent(parameters, quantity, (String) context.get("facilityId"), (String) context.get("eventName"), false, delegator);
         } catch (GenericEntityException e) {
-            Debug.logError(e, "Error : findOne(\"MrpEvent\", parameters =)"+parameters, MODULE);
+            Debug.logError(e, "Error : findOne(\"MrpEvent\", parameters =)" + parameters, MODULE);
             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", UtilMisc.toMap("parameters", parameters), locale));
         }
         return ServiceUtil.returnSuccess();
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java
index 9ebe99f..92807a6 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/MrpServices.java
@@ -53,7 +53,6 @@ import com.ibm.icu.util.Calendar;
 
 /**
  * Services for running MRP
- *
  */
 public class MrpServices {
 
@@ -83,7 +82,7 @@ public class MrpServices {
             try {
                 delegator.removeAll(listResult);
             } catch (GenericEntityException e) {
-                Debug.logError(e, "Error : removeAll(listResult), listResult ="+listResult, MODULE);
+                Debug.logError(e, "Error : removeAll(listResult), listResult =" + listResult, MODULE);
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventRemoveError", locale));
             }
         }
@@ -122,7 +121,7 @@ public class MrpServices {
         }
         if (listResult != null) {
             try {
-                for (GenericValue tempRequirement: listResult) {
+                for (GenericValue tempRequirement : listResult) {
                     requirementStatus.addAll(tempRequirement.getRelated("RequirementStatus", null, null, false));
                 }
                 delegator.removeAll(requirementStatus);
@@ -199,9 +198,11 @@ public class MrpServices {
             }
             parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", requiredByDate, "mrpEventTypeId", "SALES_ORDER_SHIP");
             try {
-                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
+                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null,
+                        genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
             } catch (GenericEntityException e) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "SALES_ORDER_SHIP"), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap(
+                        "mrpEventTypeId", "SALES_ORDER_SHIP"), locale));
             }
         }
         // ----------------------------------------
@@ -229,9 +230,11 @@ public class MrpServices {
 
             parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "PROD_REQ_RECP");
             try {
-                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("requirementId"), false, delegator);
+                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("requirementId"),
+                        false, delegator);
             } catch (GenericEntityException e) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "PROD_REQ_RECP"), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap(
+                        "mrpEventTypeId", "PROD_REQ_RECP"), locale));
             }
         }
 
@@ -264,7 +267,8 @@ public class MrpServices {
                 if (!newOrderId.equals(orderId)) {
                     orderDeliverySchedule = null;
                     orderId = newOrderId;
-                    orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", "_NA_").queryOne();
+                    orderDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId",
+                            "_NA_").queryOne();
                 }
                 String productId = genericResult.getString("productId");
                 BigDecimal shipGroupQuantity = genericResult.getBigDecimal("quantity");
@@ -277,7 +281,9 @@ public class MrpServices {
                 }
 
                 try {
-                    List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from("ShipmentReceipt").where("orderId", genericResult.getString("orderId"), "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryList();
+                    List<GenericValue> shipmentReceipts = EntityQuery.use(delegator).select("quantityAccepted", "quantityRejected").from(
+                            "ShipmentReceipt").where("orderId", genericResult.getString("orderId"), "orderItemSeqId", genericResult.getString(
+                                    "orderItemSeqId")).queryList();
                     for (GenericValue shipmentReceipt : shipmentReceipts) {
                         shipGroupQuantity = shipGroupQuantity.subtract(shipmentReceipt.getBigDecimal("quantityAccepted"));
                         shipGroupQuantity = shipGroupQuantity.subtract(shipmentReceipt.getBigDecimal("quantityRejected"));
@@ -286,7 +292,8 @@ public class MrpServices {
                     Debug.logWarning(e, MODULE);
                 }
                 GenericValue orderItemDeliverySchedule = null;
-                orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId", genericResult.getString("orderItemSeqId")).queryOne();
+                orderItemDeliverySchedule = EntityQuery.use(delegator).from("OrderDeliverySchedule").where("orderId", orderId, "orderItemSeqId",
+                        genericResult.getString("orderItemSeqId")).queryOne();
                 Timestamp estimatedShipDate = null;
                 if (orderItemDeliverySchedule != null && orderItemDeliverySchedule.get("estimatedReadyDate") != null) {
                     estimatedShipDate = orderItemDeliverySchedule.getTimestamp("estimatedReadyDate");
@@ -299,10 +306,13 @@ public class MrpServices {
                     estimatedShipDate = now;
                 }
 
-                parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "PUR_ORDER_RECP");
-                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, shipGroupQuantity, null, genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
+                parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId",
+                        "PUR_ORDER_RECP");
+                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, shipGroupQuantity, null,
+                        genericResult.getString("orderId") + "-" + genericResult.getString("orderItemSeqId"), false, delegator);
             } catch (GenericEntityException e) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "PUR_ORDER_RECP"), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap(
+                        "mrpEventTypeId", "PUR_ORDER_RECP"), locale));
             }
         }
 
@@ -317,8 +327,8 @@ public class MrpServices {
                     .queryList();
             for (GenericValue genericResult : resultList) {
                 if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId"))
-                    || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId"))
-                    || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) {
+                        || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId"))
+                        || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) {
                     continue;
                 }
                 String productId = genericResult.getString("productId");
@@ -336,12 +346,15 @@ public class MrpServices {
                     estimatedShipDate = now;
                 }
 
-                parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_REQ");
-                String eventName = (UtilValidate.isEmpty(genericResult.getString("workEffortParentId"))? genericResult.getString("workEffortId"): genericResult.getString("workEffortParentId") + "-" + genericResult.getString("workEffortId"));
+                parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId",
+                        "MANUF_ORDER_REQ");
+                String eventName = (UtilValidate.isEmpty(genericResult.getString("workEffortParentId")) ? genericResult.getString("workEffortId")
+                        : genericResult.getString("workEffortParentId") + "-" + genericResult.getString("workEffortId"));
                 InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, eventName, false, delegator);
             }
         } catch (GenericEntityException e) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "MANUF_ORDER_REQ"), locale) + " " + e.getMessage());
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap(
+                    "mrpEventTypeId", "MANUF_ORDER_REQ"), locale) + " " + e.getMessage());
         }
 
         // ----------------------------------------
@@ -356,8 +369,8 @@ public class MrpServices {
                     .queryList();
             for (GenericValue genericResult : resultList) {
                 if ("PRUN_CLOSED".equals(genericResult.getString("currentStatusId"))
-                    || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId"))
-                    || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) {
+                        || "PRUN_COMPLETED".equals(genericResult.getString("currentStatusId"))
+                        || "PRUN_CANCELLED".equals(genericResult.getString("currentStatusId"))) {
                     continue;
                 }
                 BigDecimal qtyToProduce = genericResult.getBigDecimal("quantityToProduce");
@@ -379,11 +392,14 @@ public class MrpServices {
                     estimatedShipDate = now;
                 }
 
-                parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId", "MANUF_ORDER_RECP");
-                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("workEffortId"), false, delegator);
+                parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", estimatedShipDate, "mrpEventTypeId",
+                        "MANUF_ORDER_RECP");
+                InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, genericResult.getString("workEffortId"),
+                        false, delegator);
             }
         } catch (GenericEntityException e) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "MANUF_ORDER_RECP"), locale) + " " + e.getMessage());
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap(
+                    "mrpEventTypeId", "MANUF_ORDER_RECP"), locale) + " " + e.getMessage());
         }
 
         // ----------------------------------------
@@ -422,7 +438,8 @@ public class MrpServices {
             try {
                 InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, BigDecimal.ZERO, null, null, false, delegator);
             } catch (GenericEntityException e) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "REQUIRED_MRP"), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap(
+                        "mrpEventTypeId", "REQUIRED_MRP"), locale));
             }
         }
 
@@ -452,7 +469,8 @@ public class MrpServices {
                 return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindCustomTimePeriod", locale));
             }
             if (customTimePeriod != null) {
-                if (UtilValidate.isNotEmpty(customTimePeriod.getTimestamp("thruDate")) && customTimePeriod.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp())) {
+                if (UtilValidate.isNotEmpty(customTimePeriod.getTimestamp("thruDate"))
+                        && customTimePeriod.getTimestamp("thruDate").before(UtilDateTime.nowTimestamp())) {
                     continue;
                 } else {
                     List<GenericValue> salesForecastDetails = null;
@@ -470,11 +488,14 @@ public class MrpServices {
                             continue;
                         }
                         eventQuantityTmp = eventQuantityTmp.negate();
-                        parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", customTimePeriod.getDate("fromDate"), "mrpEventTypeId", "SALES_FORECAST");
+                        parameters = UtilMisc.toMap("mrpId", mrpId, "productId", productId, "eventDate", customTimePeriod.getDate("fromDate"),
+                                "mrpEventTypeId", "SALES_FORECAST");
                         try {
-                            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, sfd.getString("salesForecastDetailId"), false, delegator);
+                            InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, eventQuantityTmp, null, sfd.getString(
+                                    "salesForecastDetailId"), false, delegator);
                         } catch (GenericEntityException e) {
-                            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing", UtilMisc.toMap("mrpEventTypeId", "SALES_FORECAST"), locale));
+                            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpEventProblemInitializing",
+                                    UtilMisc.toMap("mrpEventTypeId", "SALES_FORECAST"), locale));
                         }
                     }
                 }
@@ -494,11 +515,14 @@ public class MrpServices {
      * </ul>
      *
      * @param product the product for which the Quantity Available is required
-     * @return the sum of all the totalAvailableToPromise of the inventoryItem related to the product, if the related facility is Mrp available (not yet implemented!!)
+     * @return the sum of all the totalAvailableToPromise of the inventoryItem related to the product, if the related facility is Mrp available
+     * (not yet implemented!!)
      */
-    public static BigDecimal findProductMrpQoh(String mrpId, GenericValue product, String facilityId, LocalDispatcher dispatcher, Delegator delegator) {
+    public static BigDecimal findProductMrpQoh(String mrpId, GenericValue product, String facilityId, LocalDispatcher dispatcher,
+                                               Delegator delegator) {
         return findProductMrpQoh(mrpId, product.getString("productId"), facilityId, dispatcher, delegator);
     }
+
     public static BigDecimal findProductMrpQoh(String mrpId, String productId, String facilityId, LocalDispatcher dispatcher, Delegator delegator) {
         Map<String, Object> resultMap = null;
         try {
@@ -522,14 +546,15 @@ public class MrpServices {
     public static void logMrpError(String mrpId, String productId, String errorMessage, Delegator delegator) {
         logMrpError(mrpId, productId, UtilDateTime.nowTimestamp(), errorMessage, delegator);
     }
+
     public static void logMrpError(String mrpId, String productId, Timestamp eventDate, String errorMessage, Delegator delegator) {
         try {
             if (UtilValidate.isNotEmpty(productId) && UtilValidate.isNotEmpty(errorMessage)) {
                 GenericValue inventoryEventError = delegator.makeValue("MrpEvent", UtilMisc.toMap("productId", productId,
-                                                                                                  "mrpId", mrpId,
-                                                                                                  "eventDate", eventDate,
-                                                                                                  "mrpEventTypeId", "ERROR",
-                                                                                                  "eventName", errorMessage));
+                        "mrpId", mrpId,
+                        "eventDate", eventDate,
+                        "mrpEventTypeId", "ERROR",
+                        "eventName", errorMessage));
                 delegator.createOrStore(inventoryEventError);
             }
         } catch (GenericEntityException e) {
@@ -540,15 +565,17 @@ public class MrpServices {
     /**
      * Process the bill of material (bom) of the product  to insert components in the MrpEvent table.
      * Before inserting in the entity, test if there is the record already existing to add quantity rather to create a new one.
-     * @param mrpId the mrp id
-     * @param product GenericValue oject of the product
-     * @param eventQuantity the product quantity needed
-     * @param startDate the startDate of the productionRun which will used to produce the product
+     *
+     * @param mrpId                the mrp id
+     * @param product              GenericValue oject of the product
+     * @param eventQuantity        the product quantity needed
+     * @param startDate            the startDate of the productionRun which will used to produce the product
      * @param routingTaskStartDate Map with all the routingTask as keys and startDate of each of them
-     * @param listComponent a List with all the components
+     * @param listComponent        a List with all the components
      */
 
-    public static void processBomComponent(String mrpId, GenericValue product, BigDecimal eventQuantity, Timestamp startDate, Map<String, Object> routingTaskStartDate, List<BOMNode> listComponent) {
+    public static void processBomComponent(String mrpId, GenericValue product, BigDecimal eventQuantity, Timestamp startDate,
+                                           Map<String, Object> routingTaskStartDate, List<BOMNode> listComponent) {
         // TODO : change the return type to boolean to be able to test if all is ok or if it have had a exception
         Delegator delegator = product.getDelegator();
 
@@ -557,7 +584,8 @@ public class MrpServices {
                 GenericValue productComponent = node.getProductAssoc();
                 // read the startDate for the component
                 String routingTask = node.getProductAssoc().getString("routingWorkEffortId");
-                Timestamp eventDate = (routingTask == null || !routingTaskStartDate.containsKey(routingTask)) ? startDate : (Timestamp) routingTaskStartDate.get(routingTask);
+                Timestamp eventDate = (routingTask == null || !routingTaskStartDate.containsKey(routingTask)) ? startDate
+                        : (Timestamp) routingTaskStartDate.get(routingTask);
                 // if the components is valid at the event Date create the Mrp requirement in the M entity
                 if (EntityUtil.isValueActive(productComponent, eventDate)) {
                     Map<String, Object> parameters = UtilMisc.<String, Object>toMap("productId", node.getProduct().getString("productId"));
@@ -566,7 +594,8 @@ public class MrpServices {
                     parameters.put("mrpEventTypeId", "MRP_REQUIREMENT");
                     BigDecimal componentEventQuantity = node.getQuantity();
                     try {
-                        InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, componentEventQuantity.negate(), null, product.get("productId") + ": " + eventDate, false, delegator);
+                        InventoryEventPlannedServices.createOrUpdateMrpEvent(parameters, componentEventQuantity.negate(), null, product.get(
+                                "productId") + ": " + eventDate, false, delegator);
                     } catch (GenericEntityException e) {
                         Debug.logError("Error : findOne(\"MrpEvent\", parameters) =" + parameters + "--" + e.getMessage(), MODULE);
                         logMrpError(mrpId, node.getProduct().getString("productId"), "Unable to create event (processBomComponent)", delegator);
@@ -585,7 +614,7 @@ public class MrpServices {
      * <li>OUTPUT : Result to put in the map : <ul><li>none</li></ul></li>
      * </ul>
      *
-     * @param ctx The DispatchContext that this service is operating in.
+     * @param ctx     The DispatchContext that this service is operating in.
      * @param context Map containing the input parameters, productId routingId, quantity, startDate.
      * @return Map with the result of the service, the output parameters.
      */
@@ -608,11 +637,13 @@ public class MrpServices {
             try {
                 GenericValue facilityGroup = EntityQuery.use(delegator).from("FacilityGroup").where("facilityGroupId", facilityGroupId).queryOne();
                 if (UtilValidate.isEmpty(facilityGroup)) {
-                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotValid", UtilMisc.toMap("facilityGroupId", facilityGroupId), locale));
+                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotValid", UtilMisc.toMap(
+                            "facilityGroupId", facilityGroupId), locale));
                 }
                 List<GenericValue> facilities = facilityGroup.getRelated("FacilityGroupMember", null, UtilMisc.toList("sequenceNum"), false);
                 if (UtilValidate.isEmpty(facilities)) {
-                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotAssociatedToFacility", UtilMisc.toMap("facilityGroupId", facilityGroupId), locale));
+                    return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupIsNotAssociatedToFacility",
+                            UtilMisc.toMap("facilityGroupId", facilityGroupId), locale));
                 }
                 for (GenericValue facilityMember : facilities) {
                     GenericValue facility = facilityMember.getRelatedOne("Facility", false);
@@ -624,14 +655,16 @@ public class MrpServices {
                     }
                 }
             } catch (GenericEntityException e) {
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupCannotBeLoad", UtilMisc.toMap("errorString", e.getMessage()), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityGroupCannotBeLoad", UtilMisc.toMap(
+                        "errorString", e.getMessage()), locale));
             }
         } else {
             manufacturingFacilityId = facilityId;
         }
 
         if (UtilValidate.isEmpty(facilityId) || UtilValidate.isEmpty(manufacturingFacilityId)) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityOrManufacturingFacilityNotAvailable", locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpFacilityOrManufacturingFacilityNotAvailable",
+                    locale));
         }
 
         int bomLevelWithNoEvent = 0;
@@ -657,7 +690,8 @@ public class MrpServices {
         ListIterator<GenericValue> iteratorListInventoryEventForMRP = null;
 
         // Initialization of the MrpEvent table, This table will contain the products we want to buy or build.
-        parameters = UtilMisc.<String, Object>toMap("mrpId", mrpId, "reInitialize", Boolean.TRUE, "defaultYearsOffset", defaultYearsOffset, "userLogin", userLogin);
+        parameters = UtilMisc.<String, Object>toMap("mrpId", mrpId, "reInitialize", Boolean.TRUE, "defaultYearsOffset", defaultYearsOffset,
+                "userLogin", userLogin);
         parameters.put("facilityId", facilityId);
         parameters.put("manufacturingFacilityId", manufacturingFacilityId);
         try {
@@ -666,7 +700,8 @@ public class MrpServices {
                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
             }
         } catch (GenericServiceException e) {
-            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorRunningInitMrpEvents", UtilMisc.toMap("errorString", e.getMessage()), locale));
+            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorRunningInitMrpEvents", UtilMisc.toMap(
+                    "errorString", e.getMessage()), locale));
         }
         long bomLevel = 0;
         do {
@@ -674,8 +709,8 @@ public class MrpServices {
             EntityCondition filterByConditions = null;
             if (bomLevel == 0) {
                 filterByConditions = EntityCondition.makeCondition(EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, null),
-                                            EntityOperator.OR,
-                                            EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, bomLevel));
+                        EntityOperator.OR,
+                        EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, bomLevel));
             } else {
                 filterByConditions = EntityCondition.makeCondition("billOfMaterialLevel", EntityOperator.EQUALS, bomLevel);
             }
@@ -686,7 +721,8 @@ public class MrpServices {
                         .queryList();
             } catch (GenericEntityException e) {
                 Long bomLevelToString = bomLevel;
-                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorForBomLevel", UtilMisc.toMap("bomLevel", bomLevelToString.toString(), "errorString", e.getMessage()), locale));
+                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpErrorForBomLevel", UtilMisc.toMap("bomLevel",
+                        bomLevelToString.toString(), "errorString", e.getMessage()), locale));
             }
 
             if (UtilValidate.isNotEmpty(listInventoryEventForMRP)) {
@@ -698,15 +734,17 @@ public class MrpServices {
                     eventCount++;
 
                     productId = inventoryEventForMRP.getString("productId");
-                    boolean isLastEvent = (eventCount == listInventoryEventForMRP.size() || !productId.equals(listInventoryEventForMRP.get(eventCount).getString("productId")));
+                    boolean isLastEvent = (eventCount == listInventoryEventForMRP.size()
+                            || !productId.equals(listInventoryEventForMRP.get(eventCount).getString("productId")));
                     eventQuantity = inventoryEventForMRP.getBigDecimal("quantity");
 
                     if (!productId.equals(oldProductId)) {
-                        BigDecimal positiveEventQuantity = eventQuantity.compareTo(BigDecimal.ZERO) > 0 ? eventQuantity: eventQuantity.negate();
+                        BigDecimal positiveEventQuantity = eventQuantity.compareTo(BigDecimal.ZERO) > 0 ? eventQuantity : eventQuantity.negate();
                         // It's a new product, so it's necessary to  read the MrpQoh
                         try {
                             product = inventoryEventForMRP.getRelatedOne("Product", true);
-                            productFacility = EntityUtil.getFirst(product.getRelated("ProductFacility", UtilMisc.toMap("facilityId", facilityId), null, true));
+                            productFacility = EntityUtil.getFirst(product.getRelated("ProductFacility", UtilMisc.toMap("facilityId", facilityId),
+                                    null, true));
                         } catch (GenericEntityException e) {
                             return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindProductForEvent", locale));
                         }
@@ -717,16 +755,20 @@ public class MrpServices {
                                     "mrpEventTypeId", "INITIAL_QOH", "eventDate", now),
                                     stockTmp, facilityId, null, false, delegator);
                         } catch (GenericEntityException e) {
-                            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", UtilMisc.toMap("parameters", parameters), locale));
+                            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent",
+                                    UtilMisc.toMap("parameters", parameters), locale));
                         }
-                        // days to ship is only relevant for sales order to plan for preparatory days to ship.  Otherwise MRP will push event dates for manufacturing parts
+                        // days to ship is only relevant for sales order to plan for preparatory days to ship.  Otherwise MRP will push event dates
+                        // for manufacturing parts
                         // as well and cause problems
                         daysToShip = 0;
                         if (productFacility != null) {
-                            reorderQuantity = (productFacility.getBigDecimal("reorderQuantity") != null ? productFacility.getBigDecimal("reorderQuantity"): BigDecimal.ONE.negate());
-                            minimumStock = (productFacility.getBigDecimal("minimumStock") != null ? productFacility.getBigDecimal("minimumStock"): BigDecimal.ZERO);
+                            reorderQuantity = (productFacility.getBigDecimal("reorderQuantity") != null ? productFacility.getBigDecimal(
+                                    "reorderQuantity") : BigDecimal.ONE.negate());
+                            minimumStock = (productFacility.getBigDecimal("minimumStock") != null ? productFacility.getBigDecimal("minimumStock")
+                                    : BigDecimal.ZERO);
                             if ("SALES_ORDER_SHIP".equals(inventoryEventForMRP.getString("mrpEventTypeId"))) {
-                                daysToShip = (productFacility.getLong("daysToShip") != null? productFacility.getLong("daysToShip").intValue(): 0);
+                                daysToShip = (productFacility.getLong("daysToShip") != null ? productFacility.getLong("daysToShip").intValue() : 0);
                             }
                         } else {
                             minimumStock = BigDecimal.ZERO;
@@ -736,7 +778,9 @@ public class MrpServices {
                         // The components are also loaded thru the configurator
                         Map<String, Object> serviceResponse = null;
                         try {
-                            serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.<String, Object>toMap("productId", product.getString("productId"), "quantity", positiveEventQuantity, "excludeWIPs", Boolean.FALSE, "userLogin", userLogin));
+                            serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.<String, Object>toMap("productId",
+                                    product.getString("productId"), "quantity", positiveEventQuantity, "excludeWIPs", Boolean.FALSE, "userLogin",
+                                    userLogin));
                             if (ServiceUtil.isError(serviceResponse)) {
                                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResponse));
                             }
@@ -757,12 +801,13 @@ public class MrpServices {
                     }
 
                     stockTmp = stockTmp.add(eventQuantity);
-                    if (stockTmp.compareTo(minimumStock) < 0 && (eventQuantity.compareTo(BigDecimal.ZERO) < 0 || isLastEvent)) { // No need to create a supply event/requirement if the current event is not a demand and there are other events to process
+                    if (stockTmp.compareTo(minimumStock) < 0 && (eventQuantity.compareTo(BigDecimal.ZERO) < 0 || isLastEvent)) { // No need to
+                        // create a supply event/requirement if the current event is not a demand and there are other events to process
                         BigDecimal qtyToStock = minimumStock.subtract(stockTmp);
                         //need to buy or build the product as we have not enough stock
                         eventDate = inventoryEventForMRP.getTimestamp("eventDate");
                         // to be just before the requirement
-                        eventDate.setTime(eventDate.getTime()-1);
+                        eventDate.setTime(eventDate.getTime() - 1);
                         ProposedOrder proposedOrder = new ProposedOrder(product, facilityId, manufacturingFacilityId, isBuilt, eventDate, qtyToStock);
                         proposedOrder.setMrpName(mrpName);
                         // calculate the ProposedOrder quantity and update the quantity object property.
@@ -772,7 +817,9 @@ public class MrpServices {
                         // The components are also loaded thru the configurator
                         Map<String, Object> serviceResponse = null;
                         try {
-                            serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.<String, Object>toMap("productId", product.getString("productId"), "quantity", proposedOrder.getQuantity(), "excludeWIPs", Boolean.FALSE, "userLogin", userLogin));
+                            serviceResponse = dispatcher.runSync("getManufacturingComponents", UtilMisc.<String, Object>toMap("productId",
+                                    product.getString("productId"), "quantity", proposedOrder.getQuantity(), "excludeWIPs", Boolean.FALSE,
+                                    "userLogin", userLogin));
                             if (ServiceUtil.isError(serviceResponse)) {
                                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResponse));
                             }
@@ -786,7 +833,8 @@ public class MrpServices {
                             try {
                                 routing = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", routingId).queryOne();
                             } catch (GenericEntityException e) {
-                                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindProductForEvent", locale));
+                                return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCannotFindProductForEvent",
+                                        locale));
                             }
                         } else {
                             routing = null;
@@ -800,10 +848,12 @@ public class MrpServices {
                         // #####################################################
 
                         // calculate the ProposedOrder requirementStartDate and update the requirementStartDate object property.
-                        Map<String, Object> routingTaskStartDate = proposedOrder.calculateStartDate(daysToShip, routing, delegator, dispatcher, userLogin);
+                        Map<String, Object> routingTaskStartDate = proposedOrder.calculateStartDate(daysToShip, routing, delegator, dispatcher,
+                                userLogin);
                         if (isBuilt) {
                             // process the product components
-                            processBomComponent(mrpId, product, proposedOrder.getQuantity(), proposedOrder.getRequirementStartDate(), routingTaskStartDate, components);
+                            processBomComponent(mrpId, product, proposedOrder.getQuantity(), proposedOrder.getRequirementStartDate(),
+                                    routingTaskStartDate, components);
                         }
                         // create the  ProposedOrder (only if the product is warehouse managed), and the MrpEvent associated
                         String requirementId = null;
@@ -811,20 +861,23 @@ public class MrpServices {
                             requirementId = proposedOrder.create(ctx, userLogin);
                         }
                         if (UtilValidate.isEmpty(productFacility) && !isBuilt) {
-                            logMrpError(mrpId, productId, now, "No ProductFacility record for [" + facilityId + "]; no requirement created.", delegator);
+                            logMrpError(mrpId, productId, now, "No ProductFacility record for [" + facilityId + "]; no requirement created.",
+                                    delegator);
                         }
                         String eventName = null;
                         if (UtilValidate.isNotEmpty(requirementId)) {
                             eventName = "*" + requirementId + " (" + proposedOrder.getRequirementStartDate() + ")*";
                         }
                         Map<String, Object> eventMap = UtilMisc.<String, Object>toMap("productId", product.getString("productId"),
-                                                      "mrpId", mrpId,
-                                                      "eventDate", eventDate,
-                                                      "mrpEventTypeId", (isBuilt? "PROP_MANUF_O_RECP" : "PROP_PUR_O_RECP"));
+                                "mrpId", mrpId,
+                                "eventDate", eventDate,
+                                "mrpEventTypeId", (isBuilt ? "PROP_MANUF_O_RECP" : "PROP_PUR_O_RECP"));
                         try {
-                            InventoryEventPlannedServices.createOrUpdateMrpEvent(eventMap, proposedOrder.getQuantity(), null, eventName, (proposedOrder.getRequirementStartDate().compareTo(now) < 0), delegator);
+                            InventoryEventPlannedServices.createOrUpdateMrpEvent(eventMap, proposedOrder.getQuantity(), null,
+                                    eventName, (proposedOrder.getRequirementStartDate().compareTo(now) < 0), delegator);
                         } catch (GenericEntityException e) {
-                            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent", UtilMisc.toMap("parameters", parameters), locale));
+                            return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ManufacturingMrpCreateOrUpdateEvent",
+                                    UtilMisc.toMap("parameters", parameters), locale));
                         }
                         //
                         stockTmp = stockTmp.add(proposedOrder.getQuantity());
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java
index 6593056..7c77cf1 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/mrp/ProposedOrder.java
@@ -176,7 +176,7 @@ public class ProposedOrder {
                         try {
                             routingTask = routingTaskAssoc.getRelatedOne("ToWorkEffort", true);
                         } catch (GenericEntityException e) {
-                            Debug.logError(e.getMessage(),  MODULE);
+                            Debug.logError(e.getMessage(), MODULE);
                         }
                         // Calculate the estimatedStartDate
                         long totalTime = ProductionRun.getEstimatedTaskTime(routingTask, quantity, dispatcher);
@@ -267,7 +267,7 @@ public class ProposedOrder {
             }
             return (String) result.get("requirementId");
         } catch (GenericServiceException e) {
-            Debug.logError(e, "Error : createRequirement with parameters = "+parameters+"--" + e.getMessage(), MODULE);
+            Debug.logError(e, "Error : createRequirement with parameters = " + parameters + "--" + e.getMessage(), MODULE);
             return null;
         }
     }
diff --git a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java
index 7ae4f24..bfbe79a 100644
--- a/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java
+++ b/applications/manufacturing/src/main/java/org/apache/ofbiz/manufacturing/techdata/TechDataServices.java
@@ -137,10 +137,11 @@ public class TechDataServices {
         if (listRoutingTaskAssoc != null) {
             for (GenericValue routingTaskAssoc : listRoutingTaskAssoc) {
                 if (!workEffortIdFrom.equals(routingTaskAssoc.getString("workEffortIdFrom"))
-                || !workEffortIdTo.equals(routingTaskAssoc.getString("workEffortIdTo"))
-                || !workEffortAssocTypeId.equals(routingTaskAssoc.getString("workEffortAssocTypeId"))
-                || !sequenceNum.equals(routingTaskAssoc.getLong("sequenceNum"))) {
-                    if (routingTaskAssoc.getTimestamp("thruDate") == null && routingTaskAssoc.getTimestamp("fromDate") == null) sequenceNumNotOk = "Y";
+                        || !workEffortIdTo.equals(routingTaskAssoc.getString("workEffortIdTo"))
+                        || !workEffortAssocTypeId.equals(routingTaskAssoc.getString("workEffortAssocTypeId"))
+                        || !sequenceNum.equals(routingTaskAssoc.getLong("sequenceNum"))) {
+                    if (routingTaskAssoc.getTimestamp("thruDate") == null && routingTaskAssoc.getTimestamp("fromDate") == null)
+                        sequenceNumNotOk = "Y";
                     else if (routingTaskAssoc.getTimestamp("thruDate") == null) {
                         if (thruDate == null) sequenceNumNotOk = "Y";
                         else if (thruDate.after(routingTaskAssoc.getTimestamp("fromDate"))) sequenceNumNotOk = "Y";
@@ -152,7 +153,9 @@ public class TechDataServices {
                         if (fromDate.before(routingTaskAssoc.getTimestamp("thruDate"))) sequenceNumNotOk = "Y";
                     } else if (fromDate == null) {
                         if (thruDate.after(routingTaskAssoc.getTimestamp("fromDate"))) sequenceNumNotOk = "Y";
-                    } else if (routingTaskAssoc.getTimestamp("fromDate").before(thruDate) && fromDate.before(routingTaskAssoc.getTimestamp("thruDate"))) sequenceNumNotOk = "Y";
+                    } else if (routingTaskAssoc.getTimestamp("fromDate").before(thruDate) && fromDate.before(routingTaskAssoc.getTimestamp(
+                            "thruDate")))
+                        sequenceNumNotOk = "Y";
                 } else if (createProcess) sequenceNumNotOk = "Y";
             }
         }
@@ -436,7 +439,7 @@ public class TechDataServices {
         Double capacity = (Double) position.get("capacity");
         Timestamp startAvailablePeriod = new Timestamp(UtilDateTime.getDayStart(dateFrom).getTime() + startTime.getTime() + cDateTrav.get(Calendar.ZONE_OFFSET) + cDateTrav.get(Calendar.DST_OFFSET));
         if (dateFrom.before(startAvailablePeriod)) return 0;
-        Timestamp endAvailablePeriod = new Timestamp(startAvailablePeriod.getTime()+capacity.longValue());
+        Timestamp endAvailablePeriod = new Timestamp(startAvailablePeriod.getTime() + capacity.longValue());
         if (dateFrom.after(endAvailablePeriod)) return 0;
         return dateFrom.getTime() - startAvailablePeriod.getTime();
     }
diff --git a/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java b/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java
index a92d95b..e8fbabe 100644
--- a/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java
+++ b/applications/marketing/src/main/java/org/apache/ofbiz/marketing/tracking/TrackingCodeEvents.java
@@ -277,8 +277,7 @@ public class TrackingCodeEvents {
                 String siteIdEnc;
                 try {
                     siteIdEnc = URLEncoder.encode(siteId, "UTF-8");
-                }
-                catch (UnsupportedEncodingException e) {
+                } catch (UnsupportedEncodingException e) {
                     Debug.logWarning("There went something wrong while encoding for the cookie creation in TrackingCodeEvents.processTrackingCode", MODULE);
                     return "error";
                 }
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java
index 307258d..a6757b7 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/finaccount/FinAccountHelper.java
@@ -40,22 +40,19 @@ import org.apache.ofbiz.entity.util.EntityQuery;
 
 /**
  * A package of methods for improving efficiency of financial accounts services
- *
  */
 public final class FinAccountHelper {
     private static final String MODULE = FinAccountHelper.class.getName();
     /**
-    * Precision: since we're just adding and subtracting, the interim figures should have one more decimal place of precision than the final numbers
-    */
+     * Precision: since we're just adding and subtracting, the interim figures should have one more decimal place of precision than the final numbers
+     */
     private static final int DECIMALS = UtilNumber.getBigDecimalScale("finaccount.decimals");
     private static final RoundingMode ROUNDING = UtilNumber.getRoundingMode("finaccount.rounding");
     private static final BigDecimal ZERO = BigDecimal.ZERO.setScale(DECIMALS, ROUNDING);
     private static final String GC_FIN_ACCOUNT_TYPE = "GIFTCERT_ACCOUNT";
-
-    protected FinAccountHelper() { }
-
     // pool of available characters for account codes, here numbers plus uppercase characters
     private static char[] charPool = new char[10 + 26];
+
     static {
         int j = 0;
         for (int i = "0".charAt(0); i <= "9".charAt(0); i++) {
@@ -65,118 +62,131 @@ public final class FinAccountHelper {
             charPool[j++] = (char) i;
         }
     }
+
+    protected FinAccountHelper() {
+    }
+
     public static int getDecimals() {
         return DECIMALS;
     }
+
     public static RoundingMode getRounding() {
         return ROUNDING;
     }
+
     public static BigDecimal getZero() {
         return ZERO;
     }
+
     public static String getGiftCertFinAccountTypeId() {
         return GC_FIN_ACCOUNT_TYPE;
     }
-     /**
-      * A convenience method which adds transactions.get(0).get(fieldName) to initialValue, all done in BigDecimal to decimals and rounding
-      * @param initialValue the initial value
-      * @param transactions a List of GenericValue objects of transactions
-      * @param fieldName the field name to get the value from the transaction
-      * @param decimals number of decimals
-      * @param rounding how to rounding
-      * @return the new value in a BigDecimal field
-      * @throws GenericEntityException
-      */
-     public static BigDecimal addFirstEntryAmount(BigDecimal initialValue, List<GenericValue> transactions, String fieldName, int decimals, RoundingMode rounding) throws GenericEntityException {
-          if ((transactions != null) && (transactions.size() == 1)) {
-              GenericValue firstEntry = transactions.get(0);
-              if (firstEntry.get(fieldName) != null) {
-                  BigDecimal valueToAdd = firstEntry.getBigDecimal(fieldName);
-                  return initialValue.add(valueToAdd).setScale(decimals, rounding);
-              } else {
-                  return initialValue;
-              }
-          } else {
-              return initialValue;
-          }
-     }
-
-     /**
-      * Returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers
-      * @param codeLength length of code in number of characters
-      * @param delegator the delegator
-      * @return returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers
-      * @throws GenericEntityException
-      */
-     public static String getNewFinAccountCode(int codeLength, Delegator delegator) throws GenericEntityException {
-
-         // keep generating new account codes until a unique one is found
-         Random r = new Random();
-         boolean foundUniqueNewCode = false;
-         StringBuilder newAccountCode = null;
-         long count = 0;
-
-         while (!foundUniqueNewCode) {
-             newAccountCode = new StringBuilder(codeLength);
-             for (int i = 0; i < codeLength; i++) {
-                 newAccountCode.append(charPool[r.nextInt(charPool.length)]);
-             }
-
-             GenericValue existingAccountWithCode = EntityQuery.use(delegator).from("FinAccount")
-                     .where("finAccountCode", newAccountCode.toString()).queryFirst();
-             if (existingAccountWithCode == null) {
-                 foundUniqueNewCode = true;
-             }
-
-             count++;
-             if (count > 999999) {
-                 throw new GenericEntityException("Unable to locate unique FinAccountCode! Length [" + codeLength + "]");
-             }
-         }
-
-         return newAccountCode.toString();
-     }
-
-     /**
-      * Gets the first (and should be only) FinAccount based on finAccountCode, which will be cleaned up to be only uppercase and alphanumeric
-      * @param finAccountCode the financial account code
-      * @param delegator the delegator
-      * @return gets the first financial account by code
-      * @throws GenericEntityException
-      */
-     public static GenericValue getFinAccountFromCode(String finAccountCode, Delegator delegator) throws GenericEntityException {
-         if (finAccountCode == null) {
-             return null;
-         }
+
+    /**
+     * A convenience method which adds transactions.get(0).get(fieldName) to initialValue, all done in BigDecimal to decimals and rounding
+     *
+     * @param initialValue the initial value
+     * @param transactions a List of GenericValue objects of transactions
+     * @param fieldName    the field name to get the value from the transaction
+     * @param decimals     number of decimals
+     * @param rounding     how to rounding
+     * @return the new value in a BigDecimal field
+     * @throws GenericEntityException
+     */
+    public static BigDecimal addFirstEntryAmount(BigDecimal initialValue, List<GenericValue> transactions, String fieldName, int decimals,
+                                                 RoundingMode rounding) throws GenericEntityException {
+        if ((transactions != null) && (transactions.size() == 1)) {
+            GenericValue firstEntry = transactions.get(0);
+            if (firstEntry.get(fieldName) != null) {
+                BigDecimal valueToAdd = firstEntry.getBigDecimal(fieldName);
+                return initialValue.add(valueToAdd).setScale(decimals, rounding);
+            } else {
+                return initialValue;
+            }
+        } else {
+            return initialValue;
+        }
+    }
+
+    /**
+     * Returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers
+     *
+     * @param codeLength length of code in number of characters
+     * @param delegator  the delegator
+     * @return returns a unique randomly generated account code for FinAccount.finAccountCode composed of uppercase letters and numbers
+     * @throws GenericEntityException
+     */
+    public static String getNewFinAccountCode(int codeLength, Delegator delegator) throws GenericEntityException {
+
+        // keep generating new account codes until a unique one is found
+        Random r = new Random();
+        boolean foundUniqueNewCode = false;
+        StringBuilder newAccountCode = null;
+        long count = 0;
+
+        while (!foundUniqueNewCode) {
+            newAccountCode = new StringBuilder(codeLength);
+            for (int i = 0; i < codeLength; i++) {
+                newAccountCode.append(charPool[r.nextInt(charPool.length)]);
+            }
+
+            GenericValue existingAccountWithCode = EntityQuery.use(delegator).from("FinAccount")
+                    .where("finAccountCode", newAccountCode.toString()).queryFirst();
+            if (existingAccountWithCode == null) {
+                foundUniqueNewCode = true;
+            }
+
+            count++;
+            if (count > 999999) {
+                throw new GenericEntityException("Unable to locate unique FinAccountCode! Length [" + codeLength + "]");
+            }
+        }
+
+        return newAccountCode.toString();
+    }
+
+    /**
+     * Gets the first (and should be only) FinAccount based on finAccountCode, which will be cleaned up to be only uppercase and alphanumeric
+     *
+     * @param finAccountCode the financial account code
+     * @param delegator      the delegator
+     * @return gets the first financial account by code
+     * @throws GenericEntityException
+     */
+    public static GenericValue getFinAccountFromCode(String finAccountCode, Delegator delegator) throws GenericEntityException {
+        if (finAccountCode == null) {
+            return null;
+        }
         finAccountCode = finAccountCode.toUpperCase(Locale.getDefault()).replaceAll("[^0-9A-Z]", "");
 
-         // now look for the account
-         List<GenericValue> accounts = EntityQuery.use(delegator).from("FinAccount")
-                 .where("finAccountCode", finAccountCode)
-                 .filterByDate().queryList();
-         if (UtilValidate.isEmpty(accounts)) {
-             // OK to display - not a code anyway
-             Debug.logWarning("No fin account found for account code ["  + finAccountCode + "]", MODULE);
-             return null;
-         } else if (accounts.size() > 1) {
-             // This should never happen, but don't display the code if it does -- it is supposed to be encrypted!
-             Debug.logError("Multiple fin accounts found", MODULE);
-             return null;
-         } else {
-             return accounts.get(0);
-         }
-     }
-
-
-     /**
-      * Sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions whose transactionDate is before asOfDateTime
-      * @param finAccountId the financial account id
-      * @param asOfDateTime the validity date
-      * @param delegator the delegator
-      * @return returns the sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions
-      * @throws GenericEntityException
-      */
-     public static BigDecimal getBalance(String finAccountId, Timestamp asOfDateTime, Delegator delegator) throws GenericEntityException {
+        // now look for the account
+        List<GenericValue> accounts = EntityQuery.use(delegator).from("FinAccount")
+                .where("finAccountCode", finAccountCode)
+                .filterByDate().queryList();
+        if (UtilValidate.isEmpty(accounts)) {
+            // OK to display - not a code anyway
+            Debug.logWarning("No fin account found for account code [" + finAccountCode + "]", MODULE);
+            return null;
+        } else if (accounts.size() > 1) {
+            // This should never happen, but don't display the code if it does -- it is supposed to be encrypted!
+            Debug.logError("Multiple fin accounts found", MODULE);
+            return null;
+        } else {
+            return accounts.get(0);
+        }
+    }
+
+
+    /**
+     * Sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions whose transactionDate is before asOfDateTime
+     *
+     * @param finAccountId the financial account id
+     * @param asOfDateTime the validity date
+     * @param delegator    the delegator
+     * @return returns the sum of all DEPOSIT and ADJUSTMENT transactions minus all WITHDRAWAL transactions
+     * @throws GenericEntityException
+     */
+    public static BigDecimal getBalance(String finAccountId, Timestamp asOfDateTime, Delegator delegator) throws GenericEntityException {
         if (asOfDateTime == null) asOfDateTime = UtilDateTime.nowTimestamp();
 
         BigDecimal incrementTotal = ZERO;  // total amount of transactions which increase balance
@@ -191,7 +201,7 @@ public final class FinAccountHelper {
                         EntityCondition.makeCondition(UtilMisc.toList(
                                 EntityCondition.makeCondition("finAccountTransTypeId", EntityOperator.EQUALS, "DEPOSIT"),
                                 EntityCondition.makeCondition("finAccountTransTypeId", EntityOperator.EQUALS, "ADJUSTMENT")),
-                            EntityOperator.OR))
+                                EntityOperator.OR))
                 .queryList();
         incrementTotal = addFirstEntryAmount(incrementTotal, transSums, "amount", (DECIMALS + 1), ROUNDING);
 
@@ -209,14 +219,15 @@ public final class FinAccountHelper {
         return incrementTotal.subtract(decrementTotal).setScale(DECIMALS, ROUNDING);
     }
 
-     /**
-      * Returns the net balance (see above) minus the sum of all authorization amounts which are not expired and were authorized by the as of date
-      * @param finAccountId the financial account id
-      * @param asOfDateTime the validity date
-      * @param delegator the delegator
-      * @return returns the net balance (see above) minus the sum of all authorization amounts which are not expired
-      * @throws GenericEntityException
-      */
+    /**
+     * Returns the net balance (see above) minus the sum of all authorization amounts which are not expired and were authorized by the as of date
+     *
+     * @param finAccountId the financial account id
+     * @param asOfDateTime the validity date
+     * @param delegator    the delegator
+     * @return returns the net balance (see above) minus the sum of all authorization amounts which are not expired
+     * @throws GenericEntityException
+     */
     public static BigDecimal getAvailableBalance(String finAccountId, Timestamp asOfDateTime, Delegator delegator) throws GenericEntityException {
         if (asOfDateTime == null) asOfDateTime = UtilDateTime.nowTimestamp();
 
@@ -242,9 +253,10 @@ public final class FinAccountHelper {
 
     /**
      * Validates a FinAccount's PIN number
-     * @param delegator the delegator
+     *
+     * @param delegator    the delegator
      * @param finAccountId the financial account id
-     * @param pinNumber a pin number
+     * @param pinNumber    a pin number
      * @return true if the bin is valid
      */
     public static boolean validatePin(Delegator delegator, String finAccountId, String pinNumber) {
@@ -269,9 +281,10 @@ public final class FinAccountHelper {
 
     /**
      * Generate a random financial number
+     *
      * @param delegator the delegator
-     * @param length length of the number to generate (up to 19 digits)
-     * @param isId to be used as an ID (will check the DB to make sure it doesn't already exist)
+     * @param length    length of the number to generate (up to 19 digits)
+     * @param isId      to be used as an ID (will check the DB to make sure it doesn't already exist)
      * @return Generated number
      * @throws GenericEntityException
      */
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java
index 4e908bb..74846ce 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderChangeHelper.java
@@ -53,24 +53,24 @@ public final class OrderChangeHelper {
         }
 
         // interal status for held orders
-        String HEADER_STATUS = "ORDER_PROCESSING";
-        String ITEM_STATUS = "ITEM_CREATED";
-        String DIGITAL_ITEM_STATUS = "ITEM_APPROVED";
+        String headerStatus = "ORDER_PROCESSING";
+        String itemStatus = "ITEM_CREATED";
+        String digitalItemStatus = "ITEM_APPROVED";
 
         if (!holdOrder) {
             if (productStore.get("headerApprovedStatus") != null) {
-                HEADER_STATUS = productStore.getString("headerApprovedStatus");
+                headerStatus = productStore.getString("headerApprovedStatus");
             }
             if (productStore.get("itemApprovedStatus") != null) {
-                ITEM_STATUS = productStore.getString("itemApprovedStatus");
+                itemStatus = productStore.getString("itemApprovedStatus");
             }
             if (productStore.get("digitalItemApprovedStatus") != null) {
-                DIGITAL_ITEM_STATUS = productStore.getString("digitalItemApprovedStatus");
+                digitalItemStatus = productStore.getString("digitalItemApprovedStatus");
             }
         }
 
         try {
-            OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, "ITEM_CREATED", ITEM_STATUS, DIGITAL_ITEM_STATUS);
+            OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, headerStatus, "ITEM_CREATED", itemStatus, digitalItemStatus);
         } catch (GenericServiceException e) {
             Debug.logError(e, "Service invocation error, status changes were not updated for order #" + orderId, MODULE);
             return false;
@@ -81,17 +81,17 @@ public final class OrderChangeHelper {
 
     public static boolean rejectOrder(LocalDispatcher dispatcher, GenericValue userLogin, String orderId) {
         GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId);
-        String HEADER_STATUS = "ORDER_REJECTED";
-        String ITEM_STATUS = "ITEM_REJECTED";
+        String headerStatus = "ORDER_REJECTED";
+        String itemStatus = "ITEM_REJECTED";
         if (productStore.get("headerDeclinedStatus") != null) {
-              HEADER_STATUS = productStore.getString("headerDeclinedStatus");
-          }
-          if (productStore.get("itemDeclinedStatus") != null) {
-              ITEM_STATUS = productStore.getString("itemDeclinedStatus");
-          }
+            headerStatus = productStore.getString("headerDeclinedStatus");
+        }
+        if (productStore.get("itemDeclinedStatus") != null) {
+            itemStatus = productStore.getString("itemDeclinedStatus");
+        }
 
         try {
-            OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, null, ITEM_STATUS, null);
+            OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, headerStatus, null, itemStatus, null);
             OrderChangeHelper.cancelInventoryReservations(dispatcher, userLogin, orderId);
             OrderChangeHelper.releasePaymentAuthorizations(dispatcher, userLogin, orderId);
         } catch (GenericServiceException e) {
@@ -115,17 +115,17 @@ public final class OrderChangeHelper {
 
     public static boolean cancelOrder(LocalDispatcher dispatcher, GenericValue userLogin, String orderId) {
         GenericValue productStore = OrderReadHelper.getProductStoreFromOrder(dispatcher.getDelegator(), orderId);
-        String HEADER_STATUS = "ORDER_CANCELLED";
-        String ITEM_STATUS = "ITEM_CANCELLED";
+        String headerStatus = "ORDER_CANCELLED";
+        String itemStatus = "ITEM_CANCELLED";
         if (productStore.get("headerCancelStatus") != null) {
-              HEADER_STATUS = productStore.getString("headerCancelStatus");
-          }
-          if (productStore.get("itemCancelStatus") != null) {
-              ITEM_STATUS = productStore.getString("itemCancelStatus");
-          }
+            headerStatus = productStore.getString("headerCancelStatus");
+        }
+        if (productStore.get("itemCancelStatus") != null) {
+            itemStatus = productStore.getString("itemCancelStatus");
+        }
 
         try {
-            OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, HEADER_STATUS, null, ITEM_STATUS, null);
+            OrderChangeHelper.orderStatusChanges(dispatcher, userLogin, orderId, headerStatus, null, itemStatus, null);
             OrderChangeHelper.cancelInventoryReservations(dispatcher, userLogin, orderId);
             OrderChangeHelper.releasePaymentAuthorizations(dispatcher, userLogin, orderId);
         } catch (GenericServiceException e) {
@@ -266,7 +266,7 @@ public final class OrderChangeHelper {
                         // only do this one time; if we have payment already for this pref ignore.
                         Map<String, Object> results = dispatcher.runSync("createPaymentFromPreference",
                                 UtilMisc.<String, Object>toMap("userLogin", userLogin, "orderPaymentPreferenceId", opp.getString("orderPaymentPreferenceId"),
-                                "paymentRefNum",  UtilDateTime.nowTimestamp().toString(), "paymentFromId", partyId));
+                                "paymentRefNum", UtilDateTime.nowTimestamp().toString(), "paymentFromId", partyId));
                         if (ServiceUtil.isError(results)) {
                             String errorMessage = ServiceUtil.getErrorMessage(results);
                             Debug.logError(errorMessage, MODULE);
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java
index 830d944..202f293 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderEvents.java
@@ -107,7 +107,7 @@ public class OrderEvents {
                 String[] orderItemSeqIdAndOrderItemShipGrpId = selectedItem.split(":");
                 String orderItemSeqId = orderItemSeqIdAndOrderItemShipGrpId[0];
                 String shipGroupSeqId = orderItemSeqIdAndOrderItemShipGrpId[1];
-                BigDecimal cancelQuantity = new BigDecimal(request.getParameter("iqm_"+orderItemSeqId+":"+shipGroupSeqId));
+                BigDecimal cancelQuantity = new BigDecimal(request.getParameter("iqm_" + orderItemSeqId + ":" + shipGroupSeqId));
                 Map<String, Object> contextMap = new HashMap<>();
                 contextMap.put("orderId", orderId);
                 contextMap.put("orderItemSeqId", orderItemSeqId);
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java
index 0b7d7f2..71991e0 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderListState.java
@@ -254,7 +254,7 @@ public class OrderListState implements Serializable {
             typeConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, parameterToOrderTypeId.get(type)));
         }
 
-        EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions,  EntityOperator.OR);
+        EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions, EntityOperator.OR);
         EntityCondition typeConditionsList = EntityCondition.makeCondition(typeConditions, EntityOperator.OR);
         if (statusConditions.size() > 0) {
             allConditions.add(statusConditionsList);
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java
index a7793b1..2bec373 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderLookupServices.java
@@ -632,7 +632,7 @@ public class OrderLookupServices {
         result.put("viewSize", viewSize);
         result.put("showAll", showAll);
 
-        result.put("paramList", (paramString != null? paramString: ""));
+        result.put("paramList", (paramString != null ? paramString : ""));
         result.put("orderList", orderList);
         result.put("orderListSize", orderCount);
 
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java
index fddaf60..3d32603 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReadHelper.java
@@ -1220,7 +1220,7 @@ public class OrderReadHelper {
         itemInfo.put("productId", item.getString("productId"));
         itemInfo.put("quantity", getOrderItemQuantity(item));
         itemInfo.put("weight", this.getItemWeight(item));
-        itemInfo.put("size",  this.getItemSize(item));
+        itemInfo.put("size", this.getItemSize(item));
         itemInfo.put("piecesIncluded", this.getItemPiecesIncluded(item));
         itemInfo.put("featureSet", this.getItemFeatureSet(item));
         return itemInfo;
@@ -1540,7 +1540,7 @@ public class OrderReadHelper {
         return getOrderItemAdjustmentList(orderItem, getAdjustments());
     }
 
-    public String getCurrentOrderItemWorkEffort(GenericValue orderItem)    {
+    public String getCurrentOrderItemWorkEffort(GenericValue orderItem) {
         String orderItemSeqId = orderItem.getString("orderItemSeqId");
         String orderId = orderItem.getString("orderId");
         Delegator delegator = orderItem.getDelegator();
@@ -2422,7 +2422,7 @@ public class OrderReadHelper {
                 Iterator<GenericValue> weIter = UtilMisc.toIterator(workEfforts);
                 while (weIter != null && weIter.hasNext()) {
                     GenericValue workEffort = weIter.next();
-                    if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0)    {
+                    if (workEffort.getString("workEffortId").compareTo(orderItem.getString("orderItemSeqId")) == 0) {
                         itemTotal = itemTotal.multiply(getWorkEffortRentalQuantity(workEffort)).setScale(DECIMALS, ROUNDING);
                         break;
                     }
@@ -2490,7 +2490,7 @@ public class OrderReadHelper {
         while (itemIter != null && itemIter.hasNext()) {
             result = result.add(getOrderItemTotal(itemIter.next(), adjustments));
         }
-        return result.setScale(DECIMALS,  ROUNDING);
+        return result.setScale(DECIMALS, ROUNDING);
     }
 
     public static BigDecimal getOrderItemTotal(GenericValue orderItem, List<GenericValue> adjustments) {
@@ -2543,7 +2543,7 @@ public class OrderReadHelper {
         }
 
         BigDecimal rentalAdjustment = ZERO;
-        if (persons.compareTo(BigDecimal.ONE) == 1)    {
+        if (persons.compareTo(BigDecimal.ONE) == 1) {
             if (persons.compareTo(new BigDecimal(2)) == 1) {
                 persons = persons.subtract(new BigDecimal(2));
                 if (nthPersonPerc.signum() == 1) {
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java
index bd6d293..714217b 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderReturnServices.java
@@ -836,7 +836,7 @@ public class OrderReturnServices {
                             createAccountCtx.put("finAccountTypeId", "STORE_CREDIT_ACCT");
                             createAccountCtx.put("productStoreId", productStore.getString("productStoreId"));
                             createAccountCtx.put("currencyUomId", returnHeader.getString("currencyUomId"));
-                            createAccountCtx.put("finAccountName", "Store Credit Account for party ["+fromPartyId+"]");
+                            createAccountCtx.put("finAccountName", "Store Credit Account for party [" + fromPartyId + "]");
                             createAccountCtx.put("userLogin", userLogin);
                             Map<String, Object> createAccountResult = null;
                             try {
@@ -1751,7 +1751,7 @@ public class OrderReturnServices {
                 orderMap.put("webSiteId", orderHeader.get("webSiteId"));
                 orderMap.put("visitId", orderHeader.get("visitId"));
                 orderMap.put("currencyUom", orderHeader.get("currencyUom"));
-                orderMap.put("grandTotal",  BigDecimal.ZERO);
+                orderMap.put("grandTotal", BigDecimal.ZERO);
 
                 // make the contact mechs
                 List<GenericValue> contactMechs = new LinkedList<>();
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java
index 7c24190..21cbe66 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/order/OrderServices.java
@@ -307,14 +307,14 @@ public class OrderServices {
             try {
                 product = EntityQuery.use(delegator).from("Product").where("productId", currentProductId).cache().queryOne();
             } catch (GenericEntityException e) {
-                String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] { currentProductId }, locale);
+                String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] {currentProductId }, locale);
                 Debug.logError(e, errMsg, MODULE);
                 errorMessages.add(errMsg);
                 continue;
             }
 
             if (product == null) {
-                String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] { currentProductId }, locale);
+                String errMsg = UtilProperties.getMessage(RES_ERROR, "product.not_found", new Object[] {currentProductId }, locale);
                 Debug.logError(errMsg, MODULE);
                 errorMessages.add(errMsg);
                 continue;
@@ -359,7 +359,7 @@ public class OrderServices {
                         errorMessages.addAll(errMsgList);
                     } else if (!"Y".equals(invReqResult.get("availableOrNotRequired"))) {
                         String invErrMsg = UtilProperties.getMessage(RES_ERROR, "product.out_of_stock",
-                                new Object[] { getProductName(product, itemName), currentProductId }, locale);
+                                new Object[] {getProductName(product, itemName), currentProductId }, locale);
                         Debug.logWarning(invErrMsg, MODULE);
                         errorMessages.add(invErrMsg);
                         continue;
@@ -377,8 +377,8 @@ public class OrderServices {
         for (GenericValue orderItem : orderItems) {
             if ("RENTAL_ORDER_ITEM".equals(orderItem.getString("orderItemTypeId"))) {
                 // check to see if workefforts are available for this order type.
-                if (UtilValidate.isEmpty(workEfforts))    {
-                    String errMsg = "Work Efforts missing for ordertype RENTAL_ORDER_ITEM " + "Product: "  + orderItem.getString("productId");
+                if (UtilValidate.isEmpty(workEfforts)) {
+                    String errMsg = "Work Efforts missing for ordertype RENTAL_ORDER_ITEM " + "Product: " + orderItem.getString("productId");
                     Debug.logError(errMsg, MODULE);
                     errorMessages.add(errMsg);
                     return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR,
@@ -387,7 +387,7 @@ public class OrderServices {
                 for (GenericValue workEffort : workEfforts) {
                     // find the related workEffortItem (workEffortId = orderSeqId)
                     // create the entity maps required.
-                    if (workEffort.getString("workEffortId").equals(orderItem.getString("orderItemSeqId")))    {
+                    if (workEffort.getString("workEffortId").equals(orderItem.getString("orderItemSeqId"))) {
                         List<GenericValue> selFixedAssetProduct = null;
                         try {
                             selFixedAssetProduct = EntityQuery.use(delegator).from("FixedAssetProduct").where("productId", orderItem.getString("productId"), "fixedAssetProductTypeId", "FAPT_USE").filterByDate(nowTimestamp, "fromDate", "thruDate").queryList();
@@ -676,8 +676,7 @@ public class OrderServices {
                 Debug.logInfo("find the fixedAsset", MODULE);
                 try {
                     fixedAsset = EntityQuery.use(delegator).from("FixedAsset").where("fixedAssetId", workEffort.get("fixedAssetId")).queryOne();
-                }
-                catch (GenericEntityException e) {
+                } catch (GenericEntityException e) {
                     return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR,
                             "OrderFixedAssetNotFoundFixedAssetId",
                             UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId")), locale));
@@ -690,9 +689,9 @@ public class OrderServices {
                 // see if this fixed asset has a calendar, when no create one and attach to fixed asset
                 Debug.logInfo("find the techdatacalendar", MODULE);
                 GenericValue techDataCalendar = null;
-                try { techDataCalendar = fixedAsset.getRelatedOne("TechDataCalendar", false);
-                }
-                catch (GenericEntityException e) {
+                try {
+                    techDataCalendar = fixedAsset.getRelatedOne("TechDataCalendar", false);
+                } catch (GenericEntityException e) {
                     Debug.logInfo("TechData calendar does not exist yet so create for fixedAsset: " + fixedAsset.get("fixedAssetId"), MODULE);
                 }
                 if (techDataCalendar == null) {
@@ -736,15 +735,14 @@ public class OrderServices {
                 // please note that calendarId is the same for (TechData)Calendar, CalendarExcDay and CalendarExWeek
                 Timestamp estimatedStartDate = workEffort.getTimestamp("estimatedStartDate");
                 Timestamp estimatedCompletionDate = workEffort.getTimestamp("estimatedCompletionDate");
-                long dayCount = (estimatedCompletionDate.getTime() - estimatedStartDate.getTime())/86400000;
-                while (--dayCount >= 0)    {
+                long dayCount = (estimatedCompletionDate.getTime() - estimatedStartDate.getTime()) / 86400000;
+                while (--dayCount >= 0) {
                     GenericValue techDataCalendarExcDay = null;
                     // find an existing Day exception record
                     Timestamp exceptionDateStartTime = UtilDateTime.getDayStart(new Timestamp(estimatedStartDate.getTime()), (int) dayCount);
                     try {
                         techDataCalendarExcDay = EntityQuery.use(delegator).from("TechDataCalendarExcDay").where("calendarId", fixedAsset.get("calendarId"), "exceptionDateStartTime", exceptionDateStartTime).queryOne();
-                    }
-                    catch (GenericEntityException e) {
+                    } catch (GenericEntityException e) {
                         Debug.logInfo(" techData excday record not found so creating........", MODULE);
                     }
                     if (techDataCalendarExcDay == null) {
@@ -756,7 +754,7 @@ public class OrderServices {
                             }
                         }
                     }
-                    if (techDataCalendarExcDay == null)    {
+                    if (techDataCalendarExcDay == null) {
                         techDataCalendarExcDay = delegator.makeValue("TechDataCalendarExcDay");
                         techDataCalendarExcDay.set("calendarId", fixedAsset.get("calendarId"));
                         techDataCalendarExcDay.set("exceptionDateStartTime", exceptionDateStartTime);
@@ -766,8 +764,8 @@ public class OrderServices {
                     // add the quantity to the quantity on the date record
                     BigDecimal newUsedCapacity = techDataCalendarExcDay.getBigDecimal("usedCapacity").add(workEffort.getBigDecimal("quantityToProduce"));
                     // check to see if the requested quantity is available on the requested day but only when the maximum capacity is set on the fixed asset
-                    if (fixedAsset.get("productionCapacity") != null)    {
-                       if (newUsedCapacity.compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0)    {
+                    if (fixedAsset.get("productionCapacity") != null) {
+                       if (newUsedCapacity.compareTo(techDataCalendarExcDay.getBigDecimal("exceptionCapacity")) > 0) {
                             String errMsg = UtilProperties.getMessage(RES_ERROR, "OrderFixedAssetSoldOut", UtilMisc.toMap("fixedAssetId", workEffort.get("fixedAssetId"), "exceptionDateStartTime", techDataCalendarExcDay.getString("exceptionDateStartTime")), locale);
                             Debug.logError(errMsg, MODULE);
                             errorMessages.add(errMsg);
@@ -1015,25 +1013,25 @@ public class OrderServices {
 
        // store the OrderTerm entities
 
-       List<GenericValue> orderTerms = UtilGenerics.cast(context.get("orderTerms"));
-       if (UtilValidate.isNotEmpty(orderTerms)) {
-           for (GenericValue orderTerm : orderTerms) {
-               orderTerm.set("orderId", orderId);
-               if (orderTerm.get("orderItemSeqId") == null) {
-                   orderTerm.set("orderItemSeqId", "_NA_");
-               }
-               toBeStored.add(orderTerm);
-           }
-       }
-
-       // if a workEffortId is passed, then prepare a OrderHeaderWorkEffort value
-       String workEffortId = (String) context.get("workEffortId");
-       if (UtilValidate.isNotEmpty(workEffortId)) {
-           GenericValue orderHeaderWorkEffort = delegator.makeValue("OrderHeaderWorkEffort");
-           orderHeaderWorkEffort.set("orderId", orderId);
-           orderHeaderWorkEffort.set("workEffortId", workEffortId);
-           toBeStored.add(orderHeaderWorkEffort);
-       }
+        List<GenericValue> orderTerms = UtilGenerics.cast(context.get("orderTerms"));
+        if (UtilValidate.isNotEmpty(orderTerms)) {
+            for (GenericValue orderTerm : orderTerms) {
+                orderTerm.set("orderId", orderId);
+                if (orderTerm.get("orderItemSeqId") == null) {
+                    orderTerm.set("orderItemSeqId", "_NA_");
+                }
+                toBeStored.add(orderTerm);
+            }
+        }
+
+        // if a workEffortId is passed, then prepare a OrderHeaderWorkEffort value
+        String workEffortId = (String) context.get("workEffortId");
+        if (UtilValidate.isNotEmpty(workEffortId)) {
+            GenericValue orderHeaderWorkEffort = delegator.makeValue("OrderHeaderWorkEffort");
+            orderHeaderWorkEffort.set("orderId", orderId);
+            orderHeaderWorkEffort.set("workEffortId", workEffortId);
+            toBeStored.add(orderHeaderWorkEffort);
+        }
 
         try {
             // store line items, etc so that they will be there for the foreign key checks
@@ -1467,7 +1465,7 @@ public class OrderServices {
                     Debug.logError(e, errorMessage, MODULE);
                     return ServiceUtil.returnError(errorMessage + e.getMessage() + ").");
                 }
-                showPricesWithVatTax  = productStore.getString("showPricesWithVatTax");
+                showPricesWithVatTax = productStore.getString("showPricesWithVatTax");
             }
             BigDecimal remainingSubTotal = ZERO;
             if (UtilValidate.isNotEmpty(productStoreId) && "Y".equalsIgnoreCase(showPricesWithVatTax)) {
@@ -1958,7 +1956,7 @@ public class OrderServices {
                             }
                         }
                     } catch (GenericEntityException e) {
-                         String errMsg = UtilProperties.getMessage(RES_ERROR, "OrderDatabaseErrorCheckingIfWeShouldChangeOrderHeaderStatusToApproved", UtilMisc.toMap("errorString", e.toString()), locale);
+                        String errMsg = UtilProperties.getMessage(RES_ERROR, "OrderDatabaseErrorCheckingIfWeShouldChangeOrderHeaderStatusToApproved", UtilMisc.toMap("errorString", e.toString()), locale);
                         Debug.logError(e, errMsg, MODULE);
                         return ServiceUtil.returnError(errMsg);
                     }
@@ -2021,7 +2019,7 @@ public class OrderServices {
         Map<String, String> itemCommentMap = UtilGenerics.cast(context.get("itemCommentMap"));
         Map<String, String> itemQuantityMap = UtilGenerics.cast(context.get("itemQtyMap"));
         if ((cancelQuantity == null) && UtilValidate.isNotEmpty(itemQuantityMap)) {
-            String key = orderItemSeqId+":"+shipGroupSeqId;
+            String key = orderItemSeqId + ":" + shipGroupSeqId;
             if (UtilValidate.isNotEmpty(itemQuantityMap.get(key))) {
                 cancelQuantity = new BigDecimal(itemQuantityMap.get(key));
             }
@@ -2098,7 +2096,7 @@ public class OrderServices {
                     itemQuantity = itemQuantity.subtract(receivedQty);
                 } else {
                     BigDecimal shippedQty = orh.getItemShippedQuantity(orderItem);
-                    if (shippedQty.compareTo(BigDecimal.ZERO) > 0 ) {
+                    if (shippedQty.compareTo(BigDecimal.ZERO) > 0) {
                         itemStatus = "ITEM_COMPLETED";
                     }
                     itemQuantity = itemQuantity.subtract(shippedQty);
@@ -2178,8 +2176,8 @@ public class OrderServices {
                     try {
                         BigDecimal quantity = thisCancelQty.setScale(1, ROUNDING);
                         String cancelledItemToOrder = UtilProperties.getMessage(RESOURCE, "OrderCancelledItemToOrder", locale);
-                        resp = dispatcher.runSync("createOrderNote", UtilMisc.<String, Object>toMap("orderId", orderId, "note", cancelledItemToOrder +
-                                orderItem.getString("productId") + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin));
+                        resp = dispatcher.runSync("createOrderNote", UtilMisc.<String, Object>toMap("orderId", orderId, "note", cancelledItemToOrder
+                                + orderItem.getString("productId") + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin));
                         if (ServiceUtil.isError(resp)) {
                             return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resp));
                         }
@@ -3620,7 +3618,7 @@ public class OrderServices {
             if (itemAttributesMap != null) {
                 // go through the item attributes map once to get a list of key names
                 Set<String> attributeNames = new HashSet<>();
-                Set<String> keys  = itemAttributesMap.keySet();
+                Set<String> keys = itemAttributesMap.keySet();
                 for (String key : keys) {
                     attributeNames.add(key);
                 }
@@ -3650,8 +3648,8 @@ public class OrderServices {
         // log an order note
         try {
             String addedItemToOrder = UtilProperties.getMessage(RESOURCE, "OrderAddedItemToOrder", locale);
-            Map<String, Object> result = dispatcher.runSync("createOrderNote", UtilMisc.<String, Object>toMap("orderId", orderId, "note", addedItemToOrder +
-                    productId + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin));
+            Map<String, Object> result = dispatcher.runSync("createOrderNote", UtilMisc.<String, Object>toMap("orderId", orderId, "note", addedItemToOrder
+                    + productId + " (" + quantity + ")", "internalNote", "Y", "userLogin", userLogin));
             if (ServiceUtil.isError(result)) {
                 return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
             }
@@ -3801,7 +3799,7 @@ public class OrderServices {
                 if (itemAttributesMap != null) {
                     // go through the item attributes map once to get a list of key names
                     Set<String> attributeNames = new HashSet<>();
-                    Set<String> keys  = itemAttributesMap.keySet();
+                    Set<String> keys = itemAttributesMap.keySet();
                     for (String key : keys) {
                         String[] attributeInfo = key.split(":");
                         attributeNames.add(attributeInfo[0]);
@@ -4665,15 +4663,15 @@ public class OrderServices {
             // create the payment
             Map<String, Object> paymentParams = new HashMap<>();
             BigDecimal maxAmount = orderPaymentPreference.getBigDecimal("maxAmount");
-                paymentParams.put("paymentTypeId", "CUSTOMER_PAYMENT");
-                paymentParams.put("paymentMethodTypeId", orderPaymentPreference.getString("paymentMethodTypeId"));
-                paymentParams.put("paymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"));
-                paymentParams.put("amount", maxAmount);
-                paymentParams.put("statusId", "PMNT_RECEIVED");
-                paymentParams.put("effectiveDate", eventDate);
-                paymentParams.put("partyIdFrom", paymentFromId);
-                paymentParams.put("currencyUomId", productStore.getString("defaultCurrencyUomId"));
-                paymentParams.put("partyIdTo", payToPartyId);
+            paymentParams.put("paymentTypeId", "CUSTOMER_PAYMENT");
+            paymentParams.put("paymentMethodTypeId", orderPaymentPreference.getString("paymentMethodTypeId"));
+            paymentParams.put("paymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"));
+            paymentParams.put("amount", maxAmount);
+            paymentParams.put("statusId", "PMNT_RECEIVED");
+            paymentParams.put("effectiveDate", eventDate);
+            paymentParams.put("partyIdFrom", paymentFromId);
+            paymentParams.put("currencyUomId", productStore.getString("defaultCurrencyUomId"));
+            paymentParams.put("partyIdTo", payToPartyId);
             if (paymentRefNum != null) {
                 paymentParams.put("paymentRefNum", paymentRefNum);
             }
@@ -6036,8 +6034,7 @@ public class OrderServices {
                     if (rowCountInt == rowNumberInt - 1) {
                         try {
                             message = validateOrderItemShipGroupAssoc(delegator, dispatcher, orderItem, totalQuantity, oisga, userLogin, locale);
-                        }
-                        catch (GeneralException e) {
+                        } catch (GeneralException e) {
                             String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsLessThanOrderItemQuantity", locale);
                             Debug.logError(errMsg, MODULE);
                             return ServiceUtil.returnError(errMsg);
@@ -6049,20 +6046,21 @@ public class OrderServices {
                     result.put(ModelService.SUCCESS_MESSAGE, message);
                 }
                 return result;
-           }
-
-           BigDecimal actualQuantity = totalQuantity.add(quantity);
-           BigDecimal qty = (BigDecimal) orderItem.get("quantity");
-           if (UtilValidate.isEmpty(qty)) {
-               qty = BigDecimal.ZERO;
-           }
-           BigDecimal cancelQty = (BigDecimal) orderItem.get("cancelQuantity");
-           if (UtilValidate.isEmpty(cancelQty)) {
-               cancelQty = BigDecimal.ZERO;
-           }
-           BigDecimal orderItemQuantity = qty.subtract(cancelQty);
+            }
+
+            BigDecimal actualQuantity = totalQuantity.add(quantity);
+            BigDecimal qty = (BigDecimal) orderItem.get("quantity");
+            if (UtilValidate.isEmpty(qty)) {
+                qty = BigDecimal.ZERO;
+            }
+            BigDecimal cancelQty = (BigDecimal) orderItem.get("cancelQuantity");
+            if (UtilValidate.isEmpty(cancelQty)) {
+                cancelQty = BigDecimal.ZERO;
+            }
+            BigDecimal orderItemQuantity = qty.subtract(cancelQty);
             if (actualQuantity.compareTo(orderItemQuantity) > 0) {
-                String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsBiggerThanOrderItemQuantity", locale);
+                String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsBiggerThanOrderItemQuantity",
+                        locale);
                 Debug.logError(errMsg, MODULE);
                 return ServiceUtil.returnError(errMsg);
             }
@@ -6102,9 +6100,8 @@ public class OrderServices {
                 int rowNumberInt = rowNumber;
                 if (rowCountInt == rowNumberInt - 1) {
                     try {
-                        message = validateOrderItemShipGroupAssoc(delegator, dispatcher, orderItem, totalQuantity,  oisga, userLogin, locale);
-                    }
-                    catch (GeneralException e) {
+                        message = validateOrderItemShipGroupAssoc(delegator, dispatcher, orderItem, totalQuantity, oisga, userLogin, locale);
+                    } catch (GeneralException e) {
                         String errMsg = mainErrorMessage + UtilProperties.getMessage(RES_ERROR, "OrderQuantityAssociatedIsLessThanOrderItemQuantity", locale);
                         Debug.logError(errMsg, MODULE);
                         return ServiceUtil.returnError(errMsg);
@@ -6380,7 +6377,7 @@ public class OrderServices {
         LocalDispatcher dispatcher = dctx.getDispatcher();
         Delegator delegator = dctx.getDelegator();
         Locale locale = (Locale) context.get("locale");
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String orderId = (String) context.get("orderId");
         String shipGroupSeqId = (String) context.get("shipGroupSeqId");
         String contactMechId = (String) context.get("contactMechId");
@@ -6446,8 +6443,8 @@ public class OrderServices {
                     shoppingCart.setShipmentMethodTypeId(groupIdx - 1, shippingMethods.get(0).getString("shipmentMethodTypeId"));
                     shoppingCart.setCarrierPartyId(groupIdx - 1, shippingMethods.get(0).getString("carrierPartyId"));
 
-                    String newShipMethTypeDesc =null;
-                    String shipMethTypeDesc=null;
+                    String newShipMethTypeDesc = null;
+                    String shipMethTypeDesc = null;
                     try {
                         shipMethTypeDesc = EntityQuery.use(delegator).from("ShipmentMethodType").where("shipmentMethodTypeId", shipmentMethodTypeId).queryOne().getString("description");
                         newShipMethTypeDesc = EntityQuery.use(delegator).from("ShipmentMethodType").where("shipmentMethodTypeId", shippingMethods.get(0).getString("shipmentMethodTypeId")).queryOne().getString("description");
@@ -6455,7 +6452,7 @@ public class OrderServices {
                         Debug.logError(e, MODULE);
                     }
                     // message to notify user for not applicability of shipping method
-                    message= "Shipping Method "+carrierPartyId+" "+shipMethTypeDesc+" is not applicable to shipping address. "+shippingMethods.get(0).getString("carrierPartyId")+" "+newShipMethTypeDesc+" has been set for shipping address.";
+                    message = "Shipping Method " + carrierPartyId + " " + shipMethTypeDesc + " is not applicable to shipping address. " + shippingMethods.get(0).getString("carrierPartyId") + " " + newShipMethTypeDesc + " has been set for shipping address.";
                 }
                 shoppingCart.setShippingContactMechId(groupIdx-1, contactMechId);
             }
@@ -6478,7 +6475,7 @@ public class OrderServices {
     public static Map<String, Object> associateOrderWithAllocationPlans(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String orderId = (String) context.get("orderId");
         Map<String, String> productPlanMap = new HashMap<>();
         Map<String, Object> serviceResult = new HashMap<>();
@@ -6513,7 +6510,7 @@ public class OrderServices {
                     serviceCtx.put("planId", planId);
                     serviceCtx.put("productId", productId);
                     serviceCtx.put("planTypeId", "SALES_ORD_ALLOCATION");
-                    serviceCtx.put("planName", "Allocation Plan For Product #"+productId);
+                    serviceCtx.put("planName", "Allocation Plan For Product #" + productId);
                     serviceCtx.put("statusId", "ALLOC_PLAN_CREATED");
                     serviceCtx.put("createdByUserLogin", userLoginId);
                     serviceCtx.put("userLogin", userLogin);
@@ -6597,7 +6594,7 @@ public class OrderServices {
     public static Map<String, Object> approveAllocationPlanItems(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String planId = (String) context.get("planId");
         Map<String, Object> serviceCtx = new HashMap<>();
         Map<String, Object> serviceResult = new HashMap<>();
@@ -6661,7 +6658,7 @@ public class OrderServices {
     public static Map<String, Object> cancelAllocationPlanItems(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String planId = (String) context.get("planId");
         Map<String, Object> serviceCtx = new HashMap<>();
         Map<String, Object> serviceResult = new HashMap<>();
@@ -6698,7 +6695,7 @@ public class OrderServices {
     public static Map<String, Object> changeAllocationPlanStatus(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
         String planId = (String) context.get("planId");
         String statusId = (String) context.get("statusId");
@@ -6749,7 +6746,7 @@ public class OrderServices {
     public static Map<String, Object> changeAllocationPlanItemStatus(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
         String planId = (String) context.get("planId");
         String planItemSeqId = (String) context.get("planItemSeqId");
@@ -6799,7 +6796,7 @@ public class OrderServices {
     public static Map<String, Object> completeAllocationPlanItemByOrderItem(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String orderId = (String) context.get("orderId");
         String orderItemSeqId = (String) context.get("orderItemSeqId");
         try {
@@ -6865,7 +6862,7 @@ public class OrderServices {
     public static Map<String, Object> cancelAllocationPlanItemByOrderItem(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String orderId = (String) context.get("orderId");
         String orderItemSeqId = (String) context.get("orderItemSeqId");
         try {
@@ -6930,7 +6927,7 @@ public class OrderServices {
     public static Map<String, Object> updateAllocatedQuantityOnOrderItemChange(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         String orderId = (String) context.get("orderId");
         try {
             OrderReadHelper orderReadHelper = new OrderReadHelper(delegator, orderId);
@@ -6977,7 +6974,7 @@ public class OrderServices {
     public static Map<String, Object> createAllocationPlanAndItems(DispatchContext dctx, Map<String, ? extends Object> context) {
         Delegator delegator = dctx.getDelegator();
         LocalDispatcher dispatcher = dctx.getDispatcher();
-        GenericValue userLogin  = (GenericValue) context.get("userLogin");
+        GenericValue userLogin = (GenericValue) context.get("userLogin");
         Locale locale = (Locale) context.get("locale");
         String productId = (String) context.get("productId");
         Integer itemListSize = (Integer) context.get("itemListSize");
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java
index d5184b0..47fba12 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutEvents.java
@@ -891,7 +891,7 @@ public class CheckOutEvents {
             //See whether we need to return an error or not
             callResult = ServiceUtil.returnSuccess();
             if (errorMessages.size() > 0) {
-                callResult.put(ModelService.ERROR_MESSAGE_LIST,  errorMessages);
+                callResult.put(ModelService.ERROR_MESSAGE_LIST, errorMessages);
                 callResult.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
             }
             if (errorMaps.size() > 0) {
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java
index e03a6f7..2811553 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/CheckOutHelper.java
@@ -366,27 +366,27 @@ public class CheckOutHelper {
     }
 
     public Map<String, Object> setCheckOutDates(Timestamp shipBefore, Timestamp shipAfter) {
-          List<String> errorMessages = new ArrayList<>();
-          Map<String, Object> result = null;
-          String errMsg = null;
-
-          if (UtilValidate.isNotEmpty(this.cart)) {
-              this.cart.setShipBeforeDate(shipBefore);
-              this.cart.setShipAfterDate(shipAfter);
-          } else {
-              errMsg = UtilProperties.getMessage(RES_ERROR, "checkhelper.no_items_in_cart",
-                                                     (cart != null ? cart.getLocale() : Locale.getDefault()));
-              errorMessages.add(errMsg);
-          }
-
-          if (errorMessages.size() == 1) {
-              result = ServiceUtil.returnError(errorMessages.get(0));
-          } else if (errorMessages.size() > 0) {
-              result = ServiceUtil.returnError(errorMessages);
-          } else {
-              result = ServiceUtil.returnSuccess();
-          }
-          return result;
+        List<String> errorMessages = new ArrayList<>();
+        Map<String, Object> result = null;
+        String errMsg = null;
+
+        if (UtilValidate.isNotEmpty(this.cart)) {
+            this.cart.setShipBeforeDate(shipBefore);
+            this.cart.setShipAfterDate(shipAfter);
+        } else {
+            errMsg = UtilProperties.getMessage(RES_ERROR, "checkhelper.no_items_in_cart",
+                    (cart != null ? cart.getLocale() : Locale.getDefault()));
+            errorMessages.add(errMsg);
+        }
+
+        if (errorMessages.size() == 1) {
+            result = ServiceUtil.returnError(errorMessages.get(0));
+        } else if (errorMessages.size() > 0) {
+            result = ServiceUtil.returnError(errorMessages);
+        } else {
+            result = ServiceUtil.returnSuccess();
+        }
+        return result;
     }
 
 
@@ -950,11 +950,11 @@ public class CheckOutHelper {
 
     public static Map<String, Object> processPayment(String orderId, BigDecimal orderTotal, String currencyUomId, GenericValue productStore, GenericValue userLogin, boolean faceToFace, boolean manualHold, LocalDispatcher dispatcher, Delegator delegator) throws GeneralException {
         // Get some payment related strings
-        String DECLINE_MESSAGE = productStore.getString("authDeclinedMessage");
-        String ERROR_MESSAGE = productStore.getString("authErrorMessage");
-        String RETRY_ON_ERROR = productStore.getString("retryFailedAuths");
-        if (RETRY_ON_ERROR == null) {
-            RETRY_ON_ERROR = "Y";
+        String declineMessage = productStore.getString("authDeclinedMessage");
+        String errMessage = productStore.getString("authErrorMessage");
+        String retryOnError = productStore.getString("retryFailedAuths");
+        if (retryOnError == null) {
+            retryOnError = "Y";
         }
 
         List<GenericValue> allPaymentPreferences = null;
@@ -1033,6 +1033,8 @@ public class CheckOutHelper {
 
         // Check the payment preferences; if we have ANY w/ status PAYMENT_NOT_AUTH invoke payment service.
         // Invoke payment processing.
+        Debug.log("==========allPaymentPreferences=======" + allPaymentPreferences);
+        Debug.log("==========onlinePaymentPrefs=======" + onlinePaymentPrefs);
         if (UtilValidate.isNotEmpty(onlinePaymentPrefs)) {
             boolean autoApproveOrder = UtilValidate.isEmpty(productStore.get("autoApproveOrder")) || "Y".equalsIgnoreCase(productStore.getString("autoApproveOrder"));
             if (orderTotal.compareTo(BigDecimal.ZERO) == 0 && autoApproveOrder) {
@@ -1078,7 +1080,7 @@ public class CheckOutHelper {
                         throw new GeneralException("Problem with order change; see above error");
                     }
                     if (UtilValidate.isEmpty(messages)) {
-                        return ServiceUtil.returnError(DECLINE_MESSAGE);
+                        return ServiceUtil.returnError(declineMessage);
                     }
                     return ServiceUtil.returnError(messages);
                 } else if ("APPROVED".equals(authResp)) {
@@ -1119,16 +1121,16 @@ public class CheckOutHelper {
                     if (Debug.verboseOn()) {
                         Debug.logVerbose("Payment auth failed due to processor trouble.", MODULE);
                     }
-                    if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) {
+                    if (!faceToFace && "Y".equalsIgnoreCase(retryOnError)) {
                         // never do this for a face to face purchase regardless of store setting
-                        return ServiceUtil.returnSuccess(ERROR_MESSAGE);
+                        return ServiceUtil.returnSuccess(errMessage);
                     }
                     boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                     if (!ok) {
                         throw new GeneralException("Problem with order change; see above error");
                     }
                     if (UtilValidate.isEmpty(messages)) {
-                        return ServiceUtil.returnError(ERROR_MESSAGE);
+                        return ServiceUtil.returnError(errMessage);
                     }
                     return ServiceUtil.returnError(messages);
                 } else {
@@ -1140,15 +1142,15 @@ public class CheckOutHelper {
                 if (Debug.verboseOn()) {
                     Debug.logVerbose("Payment auth failed due to processor trouble.", MODULE);
                 }
-                if (!faceToFace && "Y".equalsIgnoreCase(RETRY_ON_ERROR)) {
+                if (!faceToFace && "Y".equalsIgnoreCase(retryOnError)) {
                     // never do this for a face to face purchase regardless of store setting
-                    return ServiceUtil.returnSuccess(ERROR_MESSAGE);
+                    return ServiceUtil.returnSuccess(errMessage);
                 }
                 boolean ok = OrderChangeHelper.cancelOrder(dispatcher, userLogin, orderId);
                 if (!ok) {
                     throw new GeneralException("Problem with order change; see above error");
                 }
-                return ServiceUtil.returnError(ERROR_MESSAGE);
+                return ServiceUtil.returnError(errMessage);
             }
         } else {
             // Get the paymentMethodTypeIds - this will need to change when ecom supports multiple payments
@@ -1158,6 +1160,7 @@ public class CheckOutHelper {
                                            EntityCondition.makeCondition("paymentMethodTypeId", EntityOperator.EQUALS, "EXT_BILLACT"));
             List<GenericValue> cashCodPcBaPaymentPreferences = EntityUtil.filterByOr(allPaymentPreferences, cashCodPcBaExpr);
 
+            Debug.log("==========cashCodPcBaPaymentPreferences=======" + cashCodPcBaPaymentPreferences);
             if (UtilValidate.isNotEmpty(cashCodPcBaPaymentPreferences)
                     && UtilValidate.isNotEmpty(allPaymentPreferences)
                     && cashCodPcBaPaymentPreferences.size() == allPaymentPreferences.size()) {
@@ -1472,31 +1475,32 @@ public class CheckOutHelper {
 
         // set ship before date
         if ((shipBeforeDate != null) && (shipBeforeDate.length() > 8)) {
-           shipBeforeDate = shipBeforeDate.trim();
-           if (shipBeforeDate.length() < 14) {
-               shipBeforeDate = shipBeforeDate + " " + "00:00:00.000";
-           }
+            shipBeforeDate = shipBeforeDate.trim();
+            if (shipBeforeDate.length() < 14) {
+                shipBeforeDate = shipBeforeDate + " " + "00:00:00.000";
+            }
 
-           try {
-               this.cart.setShipBeforeDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipBeforeDate, "Timestamp", null, null));
-           } catch (Exception e) {
-               errMsg = "Ship Before Date must be a valid date formed ";
-               result = ServiceUtil.returnError(errMsg);
-           }
+            try {
+                this.cart.setShipBeforeDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipBeforeDate, "Timestamp", null,
+                        null));
+            } catch (Exception e) {
+                errMsg = "Ship Before Date must be a valid date formed ";
+                result = ServiceUtil.returnError(errMsg);
+            }
         }
 
         // set ship after date
         if ((shipAfterDate != null) && (shipAfterDate.length() > 8)) {
-           shipAfterDate = shipAfterDate.trim();
-           if (shipAfterDate.length() < 14) {
-               shipAfterDate = shipAfterDate + " " + "00:00:00.000";
-           }
+            shipAfterDate = shipAfterDate.trim();
+            if (shipAfterDate.length() < 14) {
+                shipAfterDate = shipAfterDate + " " + "00:00:00.000";
+            }
 
-           try {
-               this.cart.setShipAfterDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipAfterDate, "Timestamp", null, null));
+            try {
+                this.cart.setShipAfterDate(shipGroupIndex, (Timestamp) ObjectType.simpleTypeOrObjectConvert(shipAfterDate, "Timestamp", null, null));
             } catch (Exception e) {
-              errMsg = "Ship After Date must be a valid date formed ";
-              result = ServiceUtil.returnError(errMsg);
+                errMsg = "Ship After Date must be a valid date formed ";
+                result = ServiceUtil.returnError(errMsg);
             }
         }
 
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java
index f03cdba..5ad2ca2 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCart.java
@@ -587,11 +587,12 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
                     if (supplierProduct != null && supplierProduct.getBigDecimal("lastPrice") != null) {
                         sci.setSupplierProductId(supplierProduct.getString("supplierProductId"));
                         sci.setBasePrice(supplierProduct.getBigDecimal("lastPrice"));
-                        sci.setName(ShoppingCartItem.getPurchaseOrderItemDescription(sci.getProduct(), supplierProduct, this.getLocale(), dispatcher));
+                        sci.setName(ShoppingCartItem.getPurchaseOrderItemDescription(sci.getProduct(), supplierProduct, this.getLocale(),
+                                dispatcher));
                     } else {
-                       throw new CartItemModifyException("SupplierProduct not found");
+                        throw new CartItemModifyException("SupplierProduct not found");
                     }
-                 }
+                }
                 return i;
             }
         }
@@ -600,7 +601,8 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
         if ("PURCHASE_ORDER".equals(getOrderType())) {
             supplierProduct = getSupplierProduct(productId, quantity, dispatcher);
             if (supplierProduct != null || "_NA_".equals(this.getPartyId())) {
-                 item = ShoppingCartItem.makePurchaseOrderItem(0, productId, selectedAmount, quantity, features, attributes, prodCatalogId, configWrapper, itemType, itemGroup, dispatcher, this, supplierProduct, shipBeforeDate, shipAfterDate, cancelBackOrderDate);
+                item = ShoppingCartItem.makePurchaseOrderItem(0, productId, selectedAmount, quantity, features, attributes, prodCatalogId,
+                        configWrapper, itemType, itemGroup, dispatcher, this, supplierProduct, shipBeforeDate, shipAfterDate, cancelBackOrderDate);
             } else {
                 throw new CartItemModifyException("SupplierProduct not found");
             }
@@ -664,55 +666,105 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
 
     /** Add an item to the shopping cart. */
     public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap<String, GenericValue> features,
-        HashMap<String, Object> attributes, String prodCatalogId, String itemType, ProductConfigWrapper configWrapper, LocalDispatcher dispatcher,
-        Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
+            HashMap<String, Object> attributes, String prodCatalogId, String itemType, ProductConfigWrapper configWrapper, LocalDispatcher dispatcher,
+            Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
         return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, null, null, null, null, null, features,
                 attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null,
                 Boolean.FALSE, Boolean.FALSE));
     }
 
-    /** Add an item to the shopping cart. */
+    /**
+     * Add an item to the shopping cart.
+     */
     public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap<String, GenericValue> features,
-        HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps,
-        Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
-        return addItemToEnd(productId, amount, quantity, unitPrice, features, attributes, prodCatalogId, itemType, dispatcher, triggerExternalOps, triggerPriceRules, Boolean.FALSE, Boolean.FALSE);
+                            HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher,
+                            Boolean triggerExternalOps,
+                            Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(productId, amount, quantity, unitPrice, features, attributes, prodCatalogId, itemType, dispatcher, triggerExternalOps,
+                triggerPriceRules, Boolean.FALSE, Boolean.FALSE);
     }
 
-    /** Add an (rental)item to the shopping cart. */
-    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE));
+    /**
+     * Add an (rental)item to the shopping cart.
+     */
+    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart,
+                            BigDecimal reservLength, BigDecimal reservPersons, HashMap<String, GenericValue> features, HashMap<String, Object> attributes,
+                            String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null,
+                null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null,
+                Boolean.FALSE, Boolean.FALSE));
     }
 
-    /** Add an (rental)item to the shopping cart. */
-    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
+    /**
+     * Add an (rental)item to the shopping cart.
+     */
+    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart,
+                            BigDecimal reservLength, BigDecimal reservPersons, HashMap<String, GenericValue> features, HashMap<String, Object> attributes,
+                            String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules,
+                            Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null,
+                null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null,
+                skipInventoryChecks, skipProductChecks));
     }
 
-    /** Add an (rental/aggregated)item to the shopping cart. */
-    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModif [...]
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
+    /**
+     * Add an (rental/aggregated)item to the shopping cart.
+     */
+    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart,
+                            BigDecimal reservLength, BigDecimal reservPersons, HashMap<String, GenericValue> features, HashMap<String, Object> attributes,
+                            String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps,
+                            Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, null,
+                null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null,
+                skipInventoryChecks, skipProductChecks));
     }
 
-    /** Add an accommodation(rental)item to the shopping cart. */
-    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE));
+    /**
+     * Add an accommodation(rental)item to the shopping cart.
+     */
+    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart,
+                            BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId,
+                            HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher
+            , Boolean triggerExternalOps, Boolean triggerPriceRules) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons,
+                accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this,
+                triggerExternalOps, triggerPriceRules, null, Boolean.FALSE, Boolean.FALSE));
     }
 
-    /** Add an accommodation(rental)item to the shopping cart. */
-    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart, BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) t [...]
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons, accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
+    /**
+     * Add an accommodation(rental)item to the shopping cart.
+     */
+    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart,
+                            BigDecimal reservLength, BigDecimal reservPersons, String accommodationMapId, String accommodationSpotId,
+                            HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher
+            , Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersons,
+                accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this,
+                triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
     }
 
-    /** Add an accommodation(rental/aggregated)item to the shopping cart. */
+    /**
+     * Add an accommodation(rental/aggregated)item to the shopping cart.
+     */
     public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, Timestamp reservStart,
-        BigDecimal reservLength, BigDecimal reservPersonsDbl, String accommodationMapId, String accommodationSpotId, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps,
-                            Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersonsDbl, accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
+                            BigDecimal reservLength, BigDecimal reservPersonsDbl, String accommodationMapId, String accommodationSpotId,
+                            HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId,
+                            ProductConfigWrapper configWrapper, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps,
+                            Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException,
+            ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, reservStart, reservLength, reservPersonsDbl,
+                accommodationMapId, accommodationSpotId, null, null, features, attributes, prodCatalogId, configWrapper, itemType, null, dispatcher, this,
+                triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
     }
 
-    /** Add an item to the shopping cart. */
-    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap<String, GenericValue> features, HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps, Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
-        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, null, null, null, null, null, features, attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
+    /**
+     * Add an item to the shopping cart.
+     */
+    public int addItemToEnd(String productId, BigDecimal amount, BigDecimal quantity, BigDecimal unitPrice, HashMap<String, GenericValue> features,
+                            HashMap<String, Object> attributes, String prodCatalogId, String itemType, LocalDispatcher dispatcher, Boolean triggerExternalOps,
+                            Boolean triggerPriceRules, Boolean skipInventoryChecks, Boolean skipProductChecks) throws CartItemModifyException, ItemNotFoundException {
+        return addItemToEnd(ShoppingCartItem.makeItem(null, productId, amount, quantity, unitPrice, null, null, null, null, null, features,
+                attributes, prodCatalogId, null, itemType, null, dispatcher, this, triggerExternalOps, triggerPriceRules, null, skipInventoryChecks, skipProductChecks));
     }
 
     /** Add an item to the shopping cart. */
@@ -1183,69 +1235,74 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
      */
     public void setShipBeforeDate(int idx, Timestamp shipBeforeDate) {
         CartShipInfo csi = this.getShipInfo(idx);
-        csi.shipBeforeDate  = shipBeforeDate;
+        csi.shipBeforeDate = shipBeforeDate;
     }
 
     /**
     * Set ship before date for ship group 0
     * @param shipBeforeDate
-    */
+     */
     public void setShipBeforeDate(Timestamp shipBeforeDate) {
-       this.setShipBeforeDate(0, shipBeforeDate);
+        this.setShipBeforeDate(0, shipBeforeDate);
     }
+
     /**
     * Get ship before date for a particular ship group
     * @param idx the ship group number
     * @return ship before date for a given ship group
     */
     public Timestamp getShipBeforeDate(int idx) {
-       CartShipInfo csi = this.getShipInfo(idx);
-       return csi.shipBeforeDate;
+        CartShipInfo csi = this.getShipInfo(idx);
+        return csi.shipBeforeDate;
     }
 
     /**
-    * Get ship before date for ship group 0
-    * @return ship before date for the first ship group
-    */
+     * Get ship before date for ship group 0
+     *
+     * @return ship before date for the first ship group
+     */
     public Timestamp getShipBeforeDate() {
-       return this.getShipBeforeDate(0);
-   }
+        return this.getShipBeforeDate(0);
+    }
 
-   /**
-    * Set ship after date for a particular ship group
-    * @param idx the ship group number
-    * @param shipAfterDate the ship after date to be set for the given ship group
-    */
+    /**
+     * Set ship after date for a particular ship group
+     *
+     * @param idx           the ship group number
+     * @param shipAfterDate the ship after date to be set for the given ship group
+     */
     public void setShipAfterDate(int idx, Timestamp shipAfterDate) {
         CartShipInfo csi = this.getShipInfo(idx);
         csi.shipAfterDate = shipAfterDate;
     }
 
-   /**
-    * Set ship after date for a particular ship group
-    * @param shipAfterDate the ship after date to be set for the first ship group
-    */
-    public void setShipAfterDate(Timestamp shipAfterDate) {
-       this.setShipAfterDate(0, shipAfterDate);
-   }
-
-   /**
-    * Get ship after date for a particular ship group
-    * @param idx the ship group number
-    * @return return the ship after date for the given ship group
-    */
+    /**
+     * Get ship after date for a particular ship group
+     *
+     * @param idx the ship group number
+     * @return return the ship after date for the given ship group
+     */
     public Timestamp getShipAfterDate(int idx) {
         CartShipInfo csi = this.getShipInfo(idx);
         return csi.shipAfterDate;
     }
 
-   /**
+    /**
     * Get ship after date for ship group 0
     * @return return the ship after date for the first ship group
     */
     public Timestamp getShipAfterDate() {
-       return this.getShipAfterDate(0);
-   }
+        return this.getShipAfterDate(0);
+    }
+
+    /**
+     * Set ship after date for a particular ship group
+     *
+     * @param shipAfterDate the ship after date to be set for the first ship group
+     */
+    public void setShipAfterDate(Timestamp shipAfterDate) {
+        this.setShipAfterDate(0, shipAfterDate);
+    }
 
     public void setDefaultShipBeforeDate(Timestamp defaultShipBeforeDate) {
         this.defaultShipBeforeDate = defaultShipBeforeDate != null ? (Timestamp) defaultShipBeforeDate.clone() : null;
@@ -2264,20 +2321,20 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
     * @return
     */
     public int getItemShipGroupIndex(int itemId) {
-    int shipGroupIndex = this.getShipGroupSize() - 1;
-    ShoppingCartItem item = this.findCartItem(itemId);
-    int result = 0;
-    for (int i = 0; i < (shipGroupIndex + 1); i++) {
-        CartShipInfo csi = this.getShipInfo(i);
-        Iterator<ShoppingCartItem> it = csi.shipItemInfo.keySet().iterator();
-        while (it.hasNext()) {
-            ShoppingCartItem item2 = it.next();
-            if (item.equals(item2)) {
-                result = i;
+        int shipGroupIndex = this.getShipGroupSize() - 1;
+        ShoppingCartItem item = this.findCartItem(itemId);
+        int result = 0;
+        for (int i = 0; i < (shipGroupIndex + 1); i++) {
+            CartShipInfo csi = this.getShipInfo(i);
+            Iterator<ShoppingCartItem> it = csi.shipItemInfo.keySet().iterator();
+            while (it.hasNext()) {
+                ShoppingCartItem item2 = it.next();
+                if (item.equals(item2)) {
+                    result = i;
+                }
             }
         }
-    }
-    return result;
+        return result;
     }
 
     /** Sets the shipping contact mech id. */
@@ -2776,7 +2833,7 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
         return OrderReadHelper.calcOrderAdjustments(tempAdjustmentsList, this.getSubTotal(), false, true, true);
     }
     public BigDecimal getDisplayTaxIncluded() {
-        BigDecimal taxIncluded  = getDisplaySubTotal().subtract(getSubTotal());
+        BigDecimal taxIncluded = getDisplaySubTotal().subtract(getSubTotal());
         return taxIncluded.setScale(TAX_FINAL_SCALE, TAX_ROUNDING);
     }
 
@@ -4203,8 +4260,8 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
         for (int i = 0; i < this.shipInfo.size(); i++) {
             CartShipInfo csi = shipInfo.get(i);
             if ((csi.supplierPartyId == null && supplierPartyId == null)
-                || (UtilValidate.isNotEmpty(csi.supplierPartyId) && csi.supplierPartyId.equals(supplierPartyId))) {
-                    shipGroups.put(i, csi);
+                    || (UtilValidate.isNotEmpty(csi.supplierPartyId) && csi.supplierPartyId.equals(supplierPartyId))) {
+                shipGroups.put(i, csi);
             }
         }
         return shipGroups;
@@ -4786,7 +4843,7 @@ public class ShoppingCart implements Iterable<ShoppingCartItem>, Serializable {
             Timestamp estimatedShipDate = null;
             if (estimatedShipDates.size() > 0) {
                 estimatedShipDates.sort(null);
-                estimatedShipDate  = estimatedShipDates.getLast();
+                estimatedShipDate = estimatedShipDates.getLast();
                 shipGroup.set("estimatedShipDate", estimatedShipDate);
             }
 
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java
index 0ce2085..634870f 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartHelper.java
@@ -890,13 +890,13 @@ public class ShoppingCartHelper {
                     }
 
                     if (parameterName.toUpperCase(Locale.getDefault()).startsWith("COMMENT")) {
-                      if (!oldItemComment.equals(itemComment)) {
-                          if (security.hasEntityPermission("ORDERMGR", "_CREATE", userLogin)) {
-                              if (item != null) {
-                                  item.setItemComment(itemComment);
-                              }
-                          }
-                      }
+                        if (!oldItemComment.equals(itemComment)) {
+                            if (security.hasEntityPermission("ORDERMGR", "_CREATE", userLogin)) {
+                                if (item != null) {
+                                    item.setItemComment(itemComment);
+                                }
+                            }
+                        }
                     }
 
                     if (parameterName.toUpperCase(Locale.getDefault()).startsWith("PRICE")) {
@@ -1091,24 +1091,26 @@ public class ShoppingCartHelper {
             }
 
             try {
-                 // clear the existing order terms
-                 cart.removeOrderTerms();
-                 // set order terms based on agreement terms
-                 List<GenericValue> agreementTerms = EntityUtil.filterByDate(agreement.getRelated("AgreementTerm", null, null, false));
-                 if (agreementTerms.size() > 0) {
-                      for (int i = 0; agreementTerms.size() > i;i++) {
-                           GenericValue agreementTerm = agreementTerms.get(i);
-                           String termTypeId = (String) agreementTerm.get("termTypeId");
-                           BigDecimal termValue = agreementTerm.getBigDecimal("termValue");
-                           Long termDays = (Long) agreementTerm.get("termDays");
-                           String textValue = agreementTerm.getString("textValue");
-                           cart.addOrderTerm(termTypeId, termValue, termDays, textValue);
-                      }
-                  }
+                // clear the existing order terms
+                cart.removeOrderTerms();
+                // set order terms based on agreement terms
+                List<GenericValue> agreementTerms = EntityUtil.filterByDate(agreement.getRelated("AgreementTerm", null, null, false));
+                if (agreementTerms.size() > 0) {
+                    for (int i = 0; agreementTerms.size() > i; i++) {
+                        GenericValue agreementTerm = agreementTerms.get(i);
+                        String termTypeId = (String) agreementTerm.get("termTypeId");
+                        BigDecimal termValue = agreementTerm.getBigDecimal("termValue");
+                        Long termDays = (Long) agreementTerm.get("termDays");
+                        String textValue = agreementTerm.getString("textValue");
+                        cart.addOrderTerm(termTypeId, termValue, termDays, textValue);
+                    }
+                }
             } catch (GenericEntityException e) {
-                  Debug.logWarning(e.toString(), MODULE);
-                  result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderCouldNotGetAgreementTermsThrough", UtilMisc.toMap("agreementId", agreementId), this.cart.getLocale())  + UtilProperties.getMessage(RES_ERROR, "OrderError", this.cart.getLocale()) + e.getMessage());
-                  return result;
+                Debug.logWarning(e.toString(), MODULE);
+                result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderCouldNotGetAgreementTermsThrough", UtilMisc.toMap(
+                        "agreementId", agreementId), this.cart.getLocale()) + UtilProperties.getMessage(RES_ERROR, "OrderError",
+                        this.cart.getLocale()) + e.getMessage());
+                return result;
             }
         }
         return result;
@@ -1120,10 +1122,10 @@ public class ShoppingCartHelper {
         try {
             this.cart.setCurrency(this.dispatcher, currencyUomId);
             result = ServiceUtil.returnSuccess();
-         } catch (CartItemModifyException ex) {
-             result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderSetCurrencyError", this.cart.getLocale()) + ex.getMessage());
-             return result;
-         }
+        } catch (CartItemModifyException ex) {
+            result = ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "OrderSetCurrencyError", this.cart.getLocale()) + ex.getMessage());
+            return result;
+        }
         return result;
     }
 
@@ -1144,5 +1146,4 @@ public class ShoppingCartHelper {
         result = ServiceUtil.returnSuccess();
         return result;
     }
-
 }
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java
index 26c16ad..dc63e7d 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/ShoppingCartItem.java
@@ -429,18 +429,18 @@ public class ShoppingCartItem implements java.io.Serializable {
 
         // check to see if the product is a rental item
         if ("ASSET_USAGE".equals(product.getString("productTypeId")) || "ASSET_USAGE_OUT_IN".equals(product.getString("productTypeId"))) {
-            if (reservStart == null)    {
+            if (reservStart == null) {
                 String excMsg = UtilProperties.getMessage(RES_ERROR, "item.missing_reservation_starting_date", cart.getLocale());
                 throw new CartItemModifyException(excMsg);
             }
 
-            if (reservStart.before(UtilDateTime.nowTimestamp()))    {
+            if (reservStart.before(UtilDateTime.nowTimestamp())) {
                 String excMsg = UtilProperties.getMessage(RES_ERROR, "item.reservation_from_tomorrow", cart.getLocale());
                 throw new CartItemModifyException(excMsg);
             }
             newItem.setReservStart(reservStart);
 
-            if (reservLength.compareTo(BigDecimal.ONE) < 0)    {
+            if (reservLength.compareTo(BigDecimal.ONE) < 0) {
                 String excMsg = UtilProperties.getMessage(RES_ERROR, "item.number_of_days", cart.getLocale());
                 throw new CartItemModifyException(excMsg);
             }
@@ -448,32 +448,34 @@ public class ShoppingCartItem implements java.io.Serializable {
 
             if (product.get("reservMaxPersons") != null) {
                 BigDecimal reservMaxPersons = product.getBigDecimal("reservMaxPersons");
-                 if (reservMaxPersons.compareTo(reservPersons) < 0)    {
-                     Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("reservMaxPersons", product.getString("reservMaxPersons"), "reservPersons", reservPersons);
-                     String excMsg = UtilProperties.getMessage(RES_ERROR, "item.maximum_number_of_person_renting", messageMap, cart.getLocale());
+                if (reservMaxPersons.compareTo(reservPersons) < 0) {
+                    Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("reservMaxPersons", product.getString("reservMaxPersons"),
+                            "reservPersons", reservPersons);
+                    String excMsg = UtilProperties.getMessage(RES_ERROR, "item.maximum_number_of_person_renting", messageMap, cart.getLocale());
 
-                     Debug.logInfo(excMsg, MODULE);
-                     throw new CartItemModifyException(excMsg);
-                 }
-             }
-             newItem.setReservPersons(reservPersons);
+                    Debug.logInfo(excMsg, MODULE);
+                    throw new CartItemModifyException(excMsg);
+                }
+            }
+            newItem.setReservPersons(reservPersons);
 
-             if (product.get("reserv2ndPPPerc") != null) {
+            if (product.get("reserv2ndPPPerc") != null) {
                 newItem.setReserv2ndPPPerc(product.getBigDecimal("reserv2ndPPPerc"));
             }
 
-             if (product.get("reservNthPPPerc") != null) {
+            if (product.get("reservNthPPPerc") != null) {
                 newItem.setReservNthPPPerc(product.getBigDecimal("reservNthPPPerc"));
             }
 
-             if ((accommodationMapId != null) && (accommodationSpotId != null)) {
+            if ((accommodationMapId != null) && (accommodationSpotId != null)) {
                 newItem.setAccommodationId(accommodationMapId, accommodationSpotId);
-             }
+            }
 
             // check to see if the related fixed asset is available for rent
             String isAvailable = checkAvailability(product.getString("productId"), quantity, reservStart, reservLength, cart);
             if (isAvailable.compareTo("OK") != 0) {
-                Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", product.getString("productId"), "availableMessage", isAvailable);
+                Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productId", product.getString("productId"), "availableMessage",
+                        isAvailable);
                 String excMsg = UtilProperties.getMessage(RES_ERROR, "item.product_not_available", messageMap, cart.getLocale());
                 Debug.logInfo(excMsg, MODULE);
                 throw new CartItemModifyException(isAvailable);
@@ -548,41 +550,41 @@ public class ShoppingCartItem implements java.io.Serializable {
     }
 
     public static void isValidCartProduct(ProductConfigWrapper configWrapper, GenericValue product, Timestamp nowTimestamp, Locale locale) throws CartItemModifyException {
-            // check to see if introductionDate hasn't passed yet
-            if (product.get("introductionDate") != null && nowTimestamp.before(product.getTimestamp("introductionDate"))) {
-                Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productName", product.getString("productName"),
-                                                "productId", product.getString("productId"));
+        // check to see if introductionDate hasn't passed yet
+        if (product.get("introductionDate") != null && nowTimestamp.before(product.getTimestamp("introductionDate"))) {
+            Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productName", product.getString("productName"),
+                    "productId", product.getString("productId"));
 
-                String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_yet_available",
-                                              messageMap, locale);
+            String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_yet_available",
+                    messageMap, locale);
 
-                Debug.logWarning(excMsg, MODULE);
-                throw new CartItemModifyException(excMsg);
-            }
+            Debug.logWarning(excMsg, MODULE);
+            throw new CartItemModifyException(excMsg);
+        }
 
-            // check to see if salesDiscontinuationDate has passed
-            if (product.get("salesDiscontinuationDate") != null && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"))) {
-                Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productName", product.getString("productName"),
-                                                "productId", product.getString("productId"));
+        // check to see if salesDiscontinuationDate has passed
+        if (product.get("salesDiscontinuationDate") != null && nowTimestamp.after(product.getTimestamp("salesDiscontinuationDate"))) {
+            Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productName", product.getString("productName"),
+                    "productId", product.getString("productId"));
+
+            String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_no_longer_available",
+                    messageMap, locale);
 
-                String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_no_longer_available",
-                                              messageMap, locale);
+            Debug.logWarning(excMsg, MODULE);
+            throw new CartItemModifyException(excMsg);
+        }
 
+        // check to see if the product is fully configured
+        if ("AGGREGATED".equals(product.getString("productTypeId")) || "AGGREGATED_SERVICE".equals(product.getString("productTypeId"))) {
+            if (configWrapper == null || !configWrapper.isCompleted()) {
+                Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productName", product.getString("productName"),
+                        "productId", product.getString("productId"));
+                String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_configured_correctly",
+                        messageMap, locale);
                 Debug.logWarning(excMsg, MODULE);
                 throw new CartItemModifyException(excMsg);
             }
-
-            // check to see if the product is fully configured
-            if ("AGGREGATED".equals(product.getString("productTypeId")) || "AGGREGATED_SERVICE".equals(product.getString("productTypeId"))) {
-                if (configWrapper == null || !configWrapper.isCompleted()) {
-                    Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("productName", product.getString("productName"),
-                                                    "productId", product.getString("productId"));
-                    String excMsg = UtilProperties.getMessage(RES_ERROR, "item.cannot_add_product_not_configured_correctly",
-                                                  messageMap, locale);
-                    Debug.logWarning(excMsg, MODULE);
-                    throw new CartItemModifyException(excMsg);
-                }
-            }
+        }
     }
 
     /**
@@ -850,19 +852,19 @@ public class ShoppingCartItem implements java.io.Serializable {
         this.reservNthPPPerc = reservNthPPPerc;
     }
     /** Sets the reservation start date */
-    public void setReservStart(Timestamp reservStart)    {
+    public void setReservStart(Timestamp reservStart) {
         this.reservStart = reservStart != null ? (Timestamp) reservStart.clone() : null;
     }
     /** Sets the reservation length */
-    public void setReservLength(BigDecimal reservLength)    {
+    public void setReservLength(BigDecimal reservLength) {
         this.reservLength = reservLength;
     }
     /** Sets number of persons using the reservation */
-    public void setReservPersons(BigDecimal reservPersons)    {
+    public void setReservPersons(BigDecimal reservPersons) {
         this.reservPersons = reservPersons;
     }
     /** Sets accommodationId using the reservation */
-    public void setAccommodationId(String accommodationMapId, String accommodationSpotId)    {
+    public void setAccommodationId(String accommodationMapId, String accommodationSpotId) {
         this.accommodationMapId = accommodationMapId;
         this.accommodationSpotId = accommodationSpotId;
     }
@@ -1321,11 +1323,11 @@ public class ShoppingCartItem implements java.io.Serializable {
     }
 
     /** Returns accommodationMapId */
-    public String getAccommodationMapId()    {
+    public String getAccommodationMapId() {
         return this.accommodationMapId;
     }
     /** Returns accommodationSpotId  */
-    public String getAccommodationSpotId()    {
+    public String getAccommodationSpotId() {
         return this.accommodationSpotId;
     }
 
@@ -2070,7 +2072,7 @@ public class ShoppingCartItem implements java.io.Serializable {
         }
         BigDecimal persons = this.getReservPersons();
         BigDecimal rentalValue = BigDecimal.ZERO;
-        if (persons.compareTo(BigDecimal.ONE) > 0)    {
+        if (persons.compareTo(BigDecimal.ONE) > 0) {
             if (persons.compareTo(new BigDecimal("2")) > 0) {
                 persons = persons.subtract(new BigDecimal("2"));
                 if (getReservNthPPPerc().compareTo(BigDecimal.ZERO) > 0) {
diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java
index d34f421..e1c7a3d 100644
--- a/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java
+++ b/applications/order/src/main/java/org/apache/ofbiz/order/shoppingcart/product/ProductDisplayWorker.java
@@ -246,18 +246,18 @@ public final class ProductDisplayWorker {
             }
 
             // if desired check view allow category
-                String currentCatalogId = CatalogWorker.getCurrentCatalogId(request);
-                String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId);
-                if (viewProductCategoryId != null) {
-                    for (Map.Entry<String, GenericValue> entry : products.entrySet()) {
-                        String productId = entry.getKey();
-                        if (!CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) {
-                            products.remove(productId);
-                            productQuantities.remove(productId);
-                            productOccurances.remove(productId);
-                        }
+            String currentCatalogId = CatalogWorker.getCurrentCatalogId(request);
+            String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, currentCatalogId);
+            if (viewProductCategoryId != null) {
+                for (Map.Entry<String, GenericValue> entry : products.entrySet()) {
+                    String productId = entry.getKey();
+                    if (!CategoryWorker.isProductInCategory(delegator, productId, viewProductCategoryId)) {
+                        products.remove(productId);
+                        productQuantities.remove(productId);
+                        productOccurances.remove(productId);
                     }
                 }
+            }
 
             List<GenericValue> reorderProds = new LinkedList<>();
             reorderProds.addAll(products.values());
diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java b/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java
index 4ce9478..f43741b 100644
--- a/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java
+++ b/applications/party/src/main/java/org/apache/ofbiz/party/communication/CommunicationEventServices.java
@@ -1187,10 +1187,10 @@ public class CommunicationEventServices {
 
     private static List<String> getCommEventAttachmentNames(final Delegator delegator, final String communicationEventId) throws GenericEntityException {
         List<GenericValue> commEventContentAssocList = EntityQuery.use(delegator)
-            .from("CommEventContentDataResource")
-            .where(EntityCondition.makeCondition("communicationEventId", communicationEventId))
-            .filterByDate()
-            .queryList();
+                .from("CommEventContentDataResource")
+                .where(EntityCondition.makeCondition("communicationEventId", communicationEventId))
+                .filterByDate()
+                .queryList();
 
         List<String> attachmentNames = new ArrayList<>();
         for (GenericValue commEventContentAssoc : commEventContentAssocList) {
@@ -1431,7 +1431,7 @@ public class CommunicationEventServices {
                     part2Text = "";
                 }
                 if (Debug.verboseOn()) {
-                     Debug.logVerbose("Part 2 Text :\n\n" + part2Text, MODULE);
+                    Debug.logVerbose("Part 2 Text :\n\n" + part2Text, MODULE);
                 }
 
                 // find the "Action" element and obtain its value (looking for "failed")
@@ -1449,7 +1449,7 @@ public class CommunicationEventServices {
                         part3Text = "";
                     }
                     if (Debug.verboseOn()) {
-                         Debug.logVerbose("Part 3 Text :\n\n" + part3Text, MODULE);
+                        Debug.logVerbose("Part 3 Text :\n\n" + part3Text, MODULE);
                     }
 
                     // find the "Message-Id" element and obtain its value (looking for "failed")
@@ -1609,7 +1609,7 @@ public class CommunicationEventServices {
         try {
             imageUrl = FlexibleLocation.resolveLocation("component://common-theme/webapp/images/spacer.gif");
             try (InputStream imageStream = imageUrl.openStream()) {
-            UtilHttp.streamContentToBrowser(response, imageStream, 43, "image/gif", null);
+                UtilHttp.streamContentToBrowser(response, imageStream, 43, "image/gif", null);
             }
         } catch (IOException e) {
             Debug.logError(e, MODULE);
diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java b/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java
index 58eb9a5..04c4026 100644
--- a/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java
+++ b/applications/party/src/main/java/org/apache/ofbiz/party/content/PartyContentWrapper.java
@@ -161,7 +161,7 @@ public class PartyContentWrapper implements ContentWrapper {
             String outString = outWriter.toString();
             if (UtilValidate.isEmpty(outString)) {
                 outString = party.getModelEntity().isField(candidateFieldName) ? party.getString(candidateFieldName): "";
-                outString = outString == null? "" : outString;
+                outString = outString == null ? "" : outString;
             }
             outString = encoder.sanitize(outString, null);
             if (partyContentCache != null) {
@@ -171,7 +171,7 @@ public class PartyContentWrapper implements ContentWrapper {
         } catch (GeneralException | IOException e) {
             Debug.logError(e, "Error rendering PartyContent, inserting empty String", MODULE);
             String candidateOut = party.getModelEntity().isField(candidateFieldName) ? party.getString(candidateFieldName): "";
-            return candidateOut == null? "" : encoder.sanitize(candidateOut, null);
+            return candidateOut == null ? "" : encoder.sanitize(candidateOut, null);
         }
     }
 
diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java
index 2ce8d70..a1ffe1a 100644
--- a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java
+++ b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyServices.java
@@ -1810,7 +1810,7 @@ public class PartyServices {
             // filter on infoString
             String infoString = (String) context.get("infoString");
             if (UtilValidate.isNotEmpty(infoString)) {
-                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityOperator.LIKE, EntityFunction.UPPER("%"+infoString+"%")));
+                andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("infoString"), EntityOperator.LIKE, EntityFunction.UPPER("%"+ infoString +"%")));
                 fieldsToSelect.add("infoString");
             }
         }
diff --git a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java
index 13c86e6..cbaab5a 100644
--- a/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java
+++ b/applications/party/src/main/java/org/apache/ofbiz/party/party/PartyWorker.java
@@ -219,7 +219,7 @@ public class PartyWorker {
             String firstName, String middleName, String lastName) throws GeneralException {
 
         List<GenericValue> matching = findMatchingPersonPostalAddresses(delegator, address1, address2, city, stateProvinceGeoId, postalCode,
-            postalCodeExt, countryGeoId, firstName, middleName, lastName);
+                postalCodeExt, countryGeoId, firstName, middleName, lastName);
         GenericValue v = EntityUtil.getFirst(matching);
         if (v != null) {
             return new String[] {v.getString("partyId"), v.getString("contactMechId") };
@@ -462,7 +462,7 @@ public class PartyWorker {
                     }
                     partyList.add(associatedParty);
                 }
-                associatedParties  = currentAssociatedParties;
+                associatedParties = currentAssociatedParties;
             }
             partyIds = EntityUtil.getFieldListFromEntityList(partyList, "partyIdTo", true);
         } catch (GenericEntityException e) {
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java
index 8657289..2ac3b82 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlServlet.java
@@ -79,70 +79,72 @@ public class CatalogUrlServlet extends HttpServlet {
             RequestDispatcher rd = request.getRequestDispatcher("/" + WebAppUtil.CONTROL_MOUNT_POINT + "/main");
             rd.forward(request, response);
         } else {
-        try {
-            String lastPathElement = pathElements.get(pathElements.size() - 1);
-            if (lastPathElement.startsWith("p_")) {
-                productId = lastPathElement.substring(2);
-            } else {
-                GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", lastPathElement).cache(true).queryOne();
-                if (productCategory != null) {
-                    categoryId = lastPathElement;
+            try {
+                String lastPathElement = pathElements.get(pathElements.size() - 1);
+                if (lastPathElement.startsWith("p_")) {
+                    productId = lastPathElement.substring(2);
                 } else {
-                    productId = lastPathElement;
+                    GenericValue productCategory =
+                            EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", lastPathElement).cache(true).queryOne();
+                    if (productCategory != null) {
+                        categoryId = lastPathElement;
+                    } else {
+                        productId = lastPathElement;
+                    }
                 }
+                pathElements.remove(pathElements.size() - 1);
+            } catch (GenericEntityException e) {
+                Debug.logError(e, "Error in looking up ProductUrl or CategoryUrl with path info [" + pathInfo + "]: " + e.toString(), MODULE);
             }
-            pathElements.remove(pathElements.size() - 1);
-        } catch (GenericEntityException e) {
-            Debug.logError(e, "Error in looking up ProductUrl or CategoryUrl with path info [" + pathInfo + "]: " + e.toString(), MODULE);
-        }
 
-        // get category info going with the IDs that remain
-        if (pathElements.size() == 1) {
-            CategoryWorker.setTrail(request, pathElements.get(0), null);
-            categoryId = pathElements.get(0);
-        } else if (pathElements.size() == 2) {
-            CategoryWorker.setTrail(request, pathElements.get(1), pathElements.get(0));
-            categoryId = pathElements.get(1);
-        } else if (pathElements.size() > 2) {
-            List<String> trail = CategoryWorker.getTrail(request);
-            if (trail == null) {
-                trail = new LinkedList<>();
-            }
+            // get category info going with the IDs that remain
+            if (pathElements.size() == 1) {
+                CategoryWorker.setTrail(request, pathElements.get(0), null);
+                categoryId = pathElements.get(0);
+            } else if (pathElements.size() == 2) {
+                CategoryWorker.setTrail(request, pathElements.get(1), pathElements.get(0));
+                categoryId = pathElements.get(1);
+            } else if (pathElements.size() > 2) {
+                List<String> trail = CategoryWorker.getTrail(request);
+                if (trail == null) {
+                    trail = new LinkedList<>();
+                }
 
-            if (trail.contains(pathElements.get(0))) {
-                // first category is in the trail, so remove it everything after that and fill it in with the list from the pathInfo
-                int firstElementIndex = trail.indexOf(pathElements.get(0));
-                while (trail.size() > firstElementIndex) {
-                    trail.remove(firstElementIndex);
+                if (trail.contains(pathElements.get(0))) {
+                    // first category is in the trail, so remove it everything after that and fill it in with the list from the pathInfo
+                    int firstElementIndex = trail.indexOf(pathElements.get(0));
+                    while (trail.size() > firstElementIndex) {
+                        trail.remove(firstElementIndex);
+                    }
+                    trail.addAll(pathElements);
+                } else {
+                    // first category is NOT in the trail, so clear out the trail and use the pathElements list
+                    trail.clear();
+                    trail.addAll(pathElements);
                 }
-                trail.addAll(pathElements);
-            } else {
-                // first category is NOT in the trail, so clear out the trail and use the pathElements list
-                trail.clear();
-                trail.addAll(pathElements);
+                CategoryWorker.setTrail(request, trail);
+                categoryId = pathElements.get(pathElements.size() - 1);
+            }
+            if (categoryId != null) {
+                request.setAttribute("productCategoryId", categoryId);
             }
-            CategoryWorker.setTrail(request, trail);
-            categoryId = pathElements.get(pathElements.size() - 1);
-        }
-        if (categoryId != null) {
-            request.setAttribute("productCategoryId", categoryId);
-        }
 
-        String rootCategoryId = null;
-        if (pathElements.size() >= 1) {
-            rootCategoryId = pathElements.get(0);
-        }
-        if (rootCategoryId != null) {
-            request.setAttribute("rootCategoryId", rootCategoryId);
-        }
+            String rootCategoryId = null;
+            if (pathElements.size() >= 1) {
+                rootCategoryId = pathElements.get(0);
+            }
+            if (rootCategoryId != null) {
+                request.setAttribute("rootCategoryId", rootCategoryId);
+            }
 
-        if (productId != null) {
-            request.setAttribute("product_id", productId);
-            request.setAttribute("productId", productId);
-        }
+            if (productId != null) {
+                request.setAttribute("product_id", productId);
+                request.setAttribute("productId", productId);
+            }
 
-        RequestDispatcher rd = request.getRequestDispatcher("/" + WebAppUtil.CONTROL_MOUNT_POINT + "/" + (productId != null ? PRODUCT_REQUEST : CATEGORY_REQUEST));
-        rd.forward(request, response);
+            RequestDispatcher rd = request.getRequestDispatcher("/" + WebAppUtil.CONTROL_MOUNT_POINT + "/" + (productId != null ? PRODUCT_REQUEST
+                    : CATEGORY_REQUEST));
+            rd.forward(request, response);
         }
     }
 
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java
index 7b3dcb6..5fd01af 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryContentWrapper.java
@@ -108,7 +108,7 @@ public class CategoryContentWrapper implements ContentWrapper {
             String outString = outWriter.toString();
             if (UtilValidate.isEmpty(outString)) {
                 outString = productCategory.getModelEntity().isField(candidateFieldName) ? productCategory.getString(candidateFieldName): "";
-                outString = outString == null? "" : outString;
+                outString = outString == null ? "" : outString;
             }
             outString = encoder.sanitize(outString, null);
             categoryContentCache.put(cacheKey, outString);
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java
index 984f356..c864e66 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CategoryWorker.java
@@ -398,7 +398,7 @@ public final class CategoryWorker {
     }
     /**
      * Returns a complete category trail - can be used for exporting proper category trees.
-     * This is mostly useful when used in combination with bread-crumbs,  for building a
+     * This is mostly useful when used in combination with bread-crumbs, for building a
      * faceted index tree, or to export a category tree for migration to another system.
      * Will create the tree from root point to categoryId.
      * This method is not meant to be run on every request.
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java
index 4c40679..de30f57 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigItemContentWrapper.java
@@ -132,7 +132,7 @@ public class ProductConfigItemContentWrapper implements ContentWrapper {
             String outString = outWriter.toString();
             if (UtilValidate.isEmpty(outString)) {
                 outString = productConfigItem.getModelEntity().isField(candidateFieldName) ? productConfigItem.getString(candidateFieldName): "";
-                outString = outString == null? "" : outString;
+                outString = outString == null ? "" : outString;
             }
             outString = encoder.sanitize(outString, null);
             configItemContentCache.put(cacheKey, outString);
@@ -140,7 +140,7 @@ public class ProductConfigItemContentWrapper implements ContentWrapper {
         } catch (GeneralException | IOException e) {
             Debug.logError(e, "Error rendering ProdConfItemContent, inserting empty String", MODULE);
             String candidateOut = productConfigItem.getModelEntity().isField(candidateFieldName) ? productConfigItem.getString(candidateFieldName): "";
-            return candidateOut == null? "" : encoder.sanitize(candidateOut, null);
+            return candidateOut == null ? "" : encoder.sanitize(candidateOut, null);
         }
     }
 
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java
index cdce5d9..2dba196 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWorker.java
@@ -296,14 +296,14 @@ public final class ProductConfigWorker {
 
                                 if (match && (UtilValidate.isEmpty(configOptionProductOptions))) {
                                     configWrapper.configId = tempConfigId;
-                                    Debug.logInfo("Existing configuration found with configId:"+ tempConfigId,  MODULE);
+                                    Debug.logInfo("Existing configuration found with configId:"+ tempConfigId, MODULE);
                                     return;
                                 }
                             }
 
                         } else {
                             configWrapper.configId = tempConfigId;
-                            Debug.logInfo("Existing configuration found with configId:"+ tempConfigId,  MODULE);
+                            Debug.logInfo("Existing configuration found with configId:"+ tempConfigId, MODULE);
                             return;
                         }
                     }
@@ -380,7 +380,7 @@ public final class ProductConfigWorker {
 
         //save  configId to configWrapper, so we can use it in shopping cart operations
         configWrapper.configId = configId;
-        Debug.logInfo("New configId created:"+ configId,  MODULE);
+        Debug.logInfo("New configId created:"+ configId, MODULE);
         return;
     }
 
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java
index 05fc4dc..8b3e353 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/config/ProductConfigWrapper.java
@@ -476,7 +476,7 @@ public class ProductConfigWrapper implements Serializable {
                 if (content != null) {
                     question = content.get("DESCRIPTION", "html").toString();
                 } else {
-                    question = (configItem.getString("description") != null? configItem.getString("description"): "");
+                    question = (configItem.getString("description") != null ? configItem.getString("description") : "");
                 }
             }
             return question;
@@ -490,7 +490,7 @@ public class ProductConfigWrapper implements Serializable {
                 if (content != null) {
                     description = content.get("LONG_DESCRIPTION", "html").toString();
                 } else {
-                    description = (configItem.getString("longDescription") != null? configItem.getString("longDescription"): "");
+                    description = (configItem.getString("longDescription") != null ? configItem.getString("longDescription") : "");
                 }
             }
             return description;
@@ -692,20 +692,20 @@ public class ProductConfigWrapper implements Serializable {
         }
 
         public String getOptionName() {
-            return (configOption.getString("configOptionName") != null? configOption.getString("configOptionName"): "no option name");
+            return (configOption.getString("configOptionName") != null ? configOption.getString("configOptionName") : "no option name");
         }
 
         public String getOptionName(Locale locale) {
 
-            return (configOption.getString("configOptionName") != null? (String) configOption.get("configOptionName", locale): "no option name");
+            return (configOption.getString("configOptionName") != null ? (String) configOption.get("configOptionName", locale) : "no option name");
         }
 
         public String getDescription() {
-            return (configOption.getString("description") != null? configOption.getString("description"): "no description");
+            return (configOption.getString("description") != null ? configOption.getString("description") : "no description");
         }
 
         public String getDescription(Locale locale) {
-            return (configOption.getString("description") != null? (String) configOption.get("description", locale): "no description");
+            return (configOption.getString("description") != null ? (String) configOption.get("description", locale) : "no description");
         }
 
         public String getId() {
@@ -751,20 +751,20 @@ public class ProductConfigWrapper implements Serializable {
             return this.equals(defaultConfigOption);
         }
 
-        public boolean hasVirtualComponent () {
-           List<GenericValue> components = getComponents();
-           if (UtilValidate.isNotEmpty(components)) {
-               for (GenericValue component : components) {
-                   if (isVirtualComponent(component)) {
-                       return true;
-                   }
-               }
-           }
+        public boolean hasVirtualComponent() {
+            List<GenericValue> components = getComponents();
+            if (UtilValidate.isNotEmpty(components)) {
+                for (GenericValue component : components) {
+                    if (isVirtualComponent(component)) {
+                        return true;
+                    }
+                }
+            }
 
-           return false;
-       }
+            return false;
+        }
 
-        public boolean isVirtualComponent (GenericValue component) {
+        public boolean isVirtualComponent(GenericValue component) {
             int index = getComponents().indexOf(component);
             if (index != -1) {
                 try {
@@ -806,10 +806,10 @@ public class ProductConfigWrapper implements Serializable {
             if (this == o) return true;
             if (o == null || getClass() != o.getClass()) return false;
             ConfigOption that = (ConfigOption) o;
-            return Objects.equals(availabilityDate, that.availabilityDate) &&
-                    Objects.equals(componentList, that.componentList) &&
-                    Objects.equals(getComponentOptions(), that.getComponentOptions()) &&
-                    Objects.equals(configOption, that.configOption);
+            return Objects.equals(availabilityDate, that.availabilityDate)
+                    && Objects.equals(componentList, that.componentList)
+                    && Objects.equals(getComponentOptions(), that.getComponentOptions())
+                    && Objects.equals(configOption, that.configOption);
         }
 
         @Override
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java
index 5d21ac3..ecc4753 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/FrameImage.java
@@ -110,7 +110,7 @@ public class FrameImage {
 
             // Image Frame
             BufferedImage bufImg1 = ImageIO.read(new File(imageServerPath + "/" + productId + "/" + imageName));
-            BufferedImage bufImg2 = ImageIO.read(new File(imageServerPath + "/frame/"+frameImageName));
+            BufferedImage bufImg2 = ImageIO.read(new File(imageServerPath + "/frame/" + frameImageName));
 
             int bufImgType;
             if (BufferedImage.TYPE_CUSTOM == bufImg1.getType()) {
@@ -224,10 +224,10 @@ public class FrameImage {
                 result.putAll(context);
             }
         } else {
-             String errMsg = UtilProperties.getMessage(RES_ERROR, "ProductPleaseSelectImage", locale);
-             Debug.logFatal(errMsg, MODULE);
-             result = ServiceUtil.returnError(errMsg);
-             result.putAll(context);
+            String errMsg = UtilProperties.getMessage(RES_ERROR, "ProductPleaseSelectImage", locale);
+            Debug.logFatal(errMsg, MODULE);
+            result = ServiceUtil.returnError(errMsg);
+            result.putAll(context);
         }
         String successMsg = UtilProperties.getMessage(RESOURCE, "ProductFrameImageSuccessfully", locale);
         result = ServiceUtil.returnSuccess(successMsg);
@@ -409,7 +409,7 @@ public class FrameImage {
             }
 
             int width = Integer.parseInt(request.getParameter("imageWidth"));
-            int height= Integer.parseInt(request.getParameter("imageHeight"));
+            int height = Integer.parseInt(request.getParameter("imageHeight"));
 
             Image newImg1 = bufImg1.getScaledInstance(width, height, Image.SCALE_SMOOTH);
             Image newImg2 = bufImg2.getScaledInstance(width, height, Image.SCALE_SMOOTH);
@@ -418,8 +418,8 @@ public class FrameImage {
             ImageIO.write(bufNewImg, mimeType, new File(imageServerPath + "/preview/" + "/previewImage.jpg"));
 
         } else {
-             String errMsg = "Please select Image.";
-             request.setAttribute("_EVENT_MESSAGE_", errMsg);
+            String errMsg = "Please select Image.";
+            request.setAttribute("_EVENT_MESSAGE_", errMsg);
             return "error";
         }
         return "success";
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java
index c1762ae..b8d4194 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/imagemanagement/ImageManagementServices.java
@@ -303,7 +303,7 @@ public class ImageManagementServices {
         Locale locale = (Locale) context.get("locale");
         List<String> sizeTypeList = null;
         if (UtilValidate.isNotEmpty(resizeType)) {
-            sizeTypeList  = UtilMisc.toList(resizeType);
+            sizeTypeList = UtilMisc.toList(resizeType);
         } else {
             sizeTypeList = UtilMisc.toList("small","100x75", "150x112", "320x240", "640x480", "800x600", "1024x768", "1280x1024", "1600x1200");
         }
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java
index eda6459..45be196 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/inventory/InventoryServices.java
@@ -689,56 +689,56 @@ public class InventoryServices {
             BigDecimal minQuantityOnHandTotal = null;
             BigDecimal minAvailableToPromiseTotal = null;
 
-           // loop through each associated product.
-           for (GenericValue productAssoc: productAssocList) {
-               String productIdTo = productAssoc.getString("productIdTo");
-               BigDecimal assocQuantity = productAssoc.getBigDecimal("quantity");
-
-               // if there is no quantity for the associated product in ProductAssoc entity, default it to 1.0
-               if (assocQuantity == null) {
-                   Debug.logWarning("ProductAssoc from [" + productAssoc.getString("productId") + "] to [" + productAssoc.getString("productIdTo")
-                           + "] has no quantity, assuming 1.0", MODULE);
-                   assocQuantity = BigDecimal.ONE;
-               }
-
-               // figure out the inventory available for this associated product
-               Map<String, Object> resultOutput = null;
-               try {
-                   Map<String, String> inputMap = UtilMisc.toMap("productId", productIdTo, "statusId", statusId);
-                   if (facilityId != null) {
-                       inputMap.put("facilityId", facilityId);
-                       resultOutput = dispatcher.runSync("getInventoryAvailableByFacility", inputMap);
-                   } else {
-                       resultOutput = dispatcher.runSync("getProductInventoryAvailable", inputMap);
-                   }
-               } catch (GenericServiceException e) {
-                  Debug.logError(e, "Problems getting inventory available by facility", MODULE);
-                  return ServiceUtil.returnError(e.getMessage());
-               }
-
-               // Figure out what the QOH and ATP inventory would be with this associated product
-               BigDecimal currentQuantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal");
-               BigDecimal currentAvailableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal");
-               BigDecimal tmpQuantityOnHandTotal = currentQuantityOnHandTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING);
-               BigDecimal tmpAvailableToPromiseTotal = currentAvailableToPromiseTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING);
-
-               // reset the minimum QOH and ATP quantities if those quantities for this product are less
-               if (minQuantityOnHandTotal == null || tmpQuantityOnHandTotal.compareTo(minQuantityOnHandTotal) < 0) {
-                   minQuantityOnHandTotal = tmpQuantityOnHandTotal;
-               }
-               if (minAvailableToPromiseTotal == null || tmpAvailableToPromiseTotal.compareTo(minAvailableToPromiseTotal) < 0) {
-                   minAvailableToPromiseTotal = tmpAvailableToPromiseTotal;
-               }
-
-               if (Debug.verboseOn()) {
-                   Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal
-                   + "currentATP = " + currentAvailableToPromiseTotal + " minQOH = " + minQuantityOnHandTotal + " minATP = "
-                   + minAvailableToPromiseTotal, MODULE);
-               }
-           }
-          // the final QOH and ATP quantities are the minimum of all the products
-          quantityOnHandTotal = minQuantityOnHandTotal;
-          availableToPromiseTotal = minAvailableToPromiseTotal;
+            // loop through each associated product.
+            for (GenericValue productAssoc : productAssocList) {
+                String productIdTo = productAssoc.getString("productIdTo");
+                BigDecimal assocQuantity = productAssoc.getBigDecimal("quantity");
+
+                // if there is no quantity for the associated product in ProductAssoc entity, default it to 1.0
+                if (assocQuantity == null) {
+                    Debug.logWarning("ProductAssoc from [" + productAssoc.getString("productId") + "] to [" + productAssoc.getString("productIdTo")
+                            + "] has no quantity, assuming 1.0", MODULE);
+                    assocQuantity = BigDecimal.ONE;
+                }
+
+                // figure out the inventory available for this associated product
+                Map<String, Object> resultOutput = null;
+                try {
+                    Map<String, String> inputMap = UtilMisc.toMap("productId", productIdTo, "statusId", statusId);
+                    if (facilityId != null) {
+                        inputMap.put("facilityId", facilityId);
+                        resultOutput = dispatcher.runSync("getInventoryAvailableByFacility", inputMap);
+                    } else {
+                        resultOutput = dispatcher.runSync("getProductInventoryAvailable", inputMap);
+                    }
+                } catch (GenericServiceException e) {
+                    Debug.logError(e, "Problems getting inventory available by facility", MODULE);
+                    return ServiceUtil.returnError(e.getMessage());
+                }
+
+                // Figure out what the QOH and ATP inventory would be with this associated product
+                BigDecimal currentQuantityOnHandTotal = (BigDecimal) resultOutput.get("quantityOnHandTotal");
+                BigDecimal currentAvailableToPromiseTotal = (BigDecimal) resultOutput.get("availableToPromiseTotal");
+                BigDecimal tmpQuantityOnHandTotal = currentQuantityOnHandTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING);
+                BigDecimal tmpAvailableToPromiseTotal = currentAvailableToPromiseTotal.divideToIntegralValue(assocQuantity, GEN_ROUNDING);
+
+                // reset the minimum QOH and ATP quantities if those quantities for this product are less
+                if (minQuantityOnHandTotal == null || tmpQuantityOnHandTotal.compareTo(minQuantityOnHandTotal) < 0) {
+                    minQuantityOnHandTotal = tmpQuantityOnHandTotal;
+                }
+                if (minAvailableToPromiseTotal == null || tmpAvailableToPromiseTotal.compareTo(minAvailableToPromiseTotal) < 0) {
+                    minAvailableToPromiseTotal = tmpAvailableToPromiseTotal;
+                }
+
+                if (Debug.verboseOn()) {
+                    Debug.logVerbose("productIdTo = " + productIdTo + " assocQuantity = " + assocQuantity + "current QOH " + currentQuantityOnHandTotal
+                            + "currentATP = " + currentAvailableToPromiseTotal + " minQOH = " + minQuantityOnHandTotal + " minATP = "
+                            + minAvailableToPromiseTotal, MODULE);
+                }
+            }
+            // the final QOH and ATP quantities are the minimum of all the products
+            quantityOnHandTotal = minQuantityOnHandTotal;
+            availableToPromiseTotal = minAvailableToPromiseTotal;
         }
 
         Map<String, Object> result = ServiceUtil.returnSuccess();
@@ -802,10 +802,13 @@ public class InventoryServices {
 
                 // get both the real ATP/QOH available and the quantities available from marketing packages
                 try {
-                    if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG")) {
-                        mktgPkgInvResult = dispatcher.runSync("getMktgPackagesAvailable", UtilMisc.toMap("productId", productId, "facilityId", facility.getString("facilityId")));
+                    if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId",
+                            "MARKETING_PKG")) {
+                        mktgPkgInvResult = dispatcher.runSync("getMktgPackagesAvailable", UtilMisc.toMap("productId", productId, "facilityId",
+                                facility.getString("facilityId")));
                     }
-                    invResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId", facility.getString("facilityId")));
+                    invResult = dispatcher.runSync("getInventoryAvailableByFacility", UtilMisc.toMap("productId", productId, "facilityId",
+                            facility.getString("facilityId")));
                 } catch (GenericServiceException e) {
                     Debug.logError(e, "Could not find inventory for facility " + facility.getString("facilityId"), MODULE);
                     return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE,
@@ -824,7 +827,8 @@ public class InventoryServices {
                         qoh = qoh.add(fqoh);
                     }
                 }
-                if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG") && ServiceUtil.isSuccess(mktgPkgInvResult)) {
+                if (EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId",
+                        "MARKETING_PKG") && ServiceUtil.isSuccess(mktgPkgInvResult)) {
                     BigDecimal fatp = (BigDecimal) mktgPkgInvResult.get("availableToPromiseTotal");
                     BigDecimal fqoh = (BigDecimal) mktgPkgInvResult.get("quantityOnHandTotal");
                     if (fatp != null) {
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java
index f1b76ec..068144b 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/price/PriceServices.java
@@ -461,11 +461,12 @@ public class PriceServices {
                         ruleListToUse.addAll(nonQuantityProductPriceRules);
 
                         Map<String, Object> quantCalcResults = calcPriceResultFromRules(ruleListToUse, listPrice, defaultPrice, promoPrice,
-                            wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound,
-                            averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId,
-                            webSiteId, partyId, null, currencyDefaultUomId, delegator, nowTimestamp, locale);
-                        Map<String, Object> quantErrorResult = addGeneralResults(quantCalcResults, competitivePriceValue, specialPromoPriceValue, productStore,
-                            checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
+                                wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound,
+                                averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId,
+                                webSiteId, partyId, null, currencyDefaultUomId, delegator, nowTimestamp, locale);
+                        Map<String, Object> quantErrorResult = addGeneralResults(quantCalcResults, competitivePriceValue, specialPromoPriceValue,
+                                productStore,
+                                checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
                         if (quantErrorResult != null) return quantErrorResult;
 
                         // also add the quantityProductPriceRule to the Map so it can be used for quantity break information
@@ -477,9 +478,9 @@ public class PriceServices {
 
                     // use a quantity 1 to get the main price, then fill in the quantity break prices
                     Map<String, Object> calcResults = calcPriceResultFromRules(allProductPriceRules, listPrice, defaultPrice, promoPrice,
-                        wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound,
-                        averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId,
-                        webSiteId, partyId, BigDecimal.ONE, currencyDefaultUomId, delegator, nowTimestamp, locale);
+                            wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound,
+                            averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId,
+                            webSiteId, partyId, BigDecimal.ONE, currencyDefaultUomId, delegator, nowTimestamp, locale);
                     result.putAll(calcResults);
                     // The orderItemPriceInfos out parameter requires a special treatment:
                     // the list of OrderItemPriceInfos generated by the price rule is appended to
@@ -495,9 +496,9 @@ public class PriceServices {
                     if (errorResult != null) return errorResult;
                 } else {
                     Map<String, Object> calcResults = calcPriceResultFromRules(allProductPriceRules, listPrice, defaultPrice, promoPrice,
-                        wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound,
-                        averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId,
-                        webSiteId, partyId, quantity, currencyDefaultUomId, delegator, nowTimestamp, locale);
+                            wholesalePrice, maximumPriceValue, minimumPriceValue, validPriceFound,
+                            averageCostValue, productId, virtualProductId, prodCatalogId, productStoreGroupId,
+                            webSiteId, partyId, quantity, currencyDefaultUomId, delegator, nowTimestamp, locale);
                     result.putAll(calcResults);
                     // The orderItemPriceInfos out parameter requires a special treatment:
                     // the list of OrderItemPriceInfos generated by the price rule is appended to
@@ -509,7 +510,7 @@ public class PriceServices {
                     result.put("orderItemPriceInfos", orderItemPriceInfos);
 
                     Map<String, Object> errorResult = addGeneralResults(result, competitivePriceValue, specialPromoPriceValue, productStore,
-                        checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
+                            checkIncludeVat, currencyDefaultUomId, productId, quantity, partyId, dispatcher, locale);
                     if (errorResult != null) return errorResult;
                 }
             } catch (GenericEntityException e) {
@@ -544,7 +545,8 @@ public class PriceServices {
                         if (tempPrice != null && tempPrice != BigDecimal.ZERO) {
                             Map<String, Object> priceResults = new HashMap<>();
                             try {
-                                priceResults = dispatcher.runSync("convertUom", UtilMisc.<String, Object> toMap("uomId", currencyDefaultUomId, "uomIdTo", currencyUomIdTo,
+                                priceResults = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", currencyDefaultUomId,
+                                        "uomIdTo", currencyUomIdTo,
                                         "originalValue", tempPrice, "defaultDecimalScale", 2L, "defaultRoundingMode", "HalfUp"));
                                 if (ServiceUtil.isError(priceResults) || (priceResults.get("convertedValue") == null)) {
                                     Debug.logWarning("Unable to convert " + entry.getKey() + " for product  " + productId, MODULE);
@@ -573,8 +575,8 @@ public class PriceServices {
         if (filteredPrices != null && filteredPrices.size() > 1) {
             if (Debug.infoOn()) {
                 Debug.logInfo("There is more than one " + productPriceTypeId + " with the currencyUomId " + priceValue.getString("currencyUomId")
-                + " and productId " + priceValue.getString("productId") + ", using the latest found with price: "
-                + priceValue.getBigDecimal("price"), MODULE);
+                        + " and productId " + priceValue.getString("productId") + ", using the latest found with price: "
+                        + priceValue.getBigDecimal("price"), MODULE);
             }
         }
         if (priceValue == null && secondaryPriceList != null) {
@@ -584,8 +586,9 @@ public class PriceServices {
     }
 
     public static Map<String, Object> addGeneralResults(Map<String, Object> result, GenericValue competitivePriceValue,
-        GenericValue specialPromoPriceValue, GenericValue productStore, String checkIncludeVat, String currencyUomId, String productId,
-        BigDecimal quantity, String partyId, LocalDispatcher dispatcher, Locale locale) {
+                                                        GenericValue specialPromoPriceValue, GenericValue productStore, String checkIncludeVat,
+                                                        String currencyUomId, String productId,
+                                                        BigDecimal quantity, String partyId, LocalDispatcher dispatcher, Locale locale) {
         result.put("competitivePrice", competitivePriceValue != null ? competitivePriceValue.getBigDecimal("price") : null);
         result.put("specialPromoPrice", specialPromoPriceValue != null ? specialPromoPriceValue.getBigDecimal("price") : null);
         result.put("currencyUsed", currencyUomId);
@@ -790,11 +793,15 @@ public class PriceServices {
         return productPriceRules;
     }
 
-    public static Map<String, Object> calcPriceResultFromRules(List<GenericValue> productPriceRules, BigDecimal listPrice, BigDecimal defaultPrice, BigDecimal promoPrice,
-        BigDecimal wholesalePrice, GenericValue maximumPriceValue, GenericValue minimumPriceValue, boolean validPriceFound,
-        GenericValue averageCostValue, String productId, String virtualProductId, String prodCatalogId, String productStoreGroupId,
-        String webSiteId, String partyId, BigDecimal quantity, String currencyUomId, Delegator delegator, Timestamp nowTimestamp,
-        Locale locale) throws GenericEntityException {
+    public static Map<String, Object> calcPriceResultFromRules(List<GenericValue> productPriceRules, BigDecimal listPrice, BigDecimal defaultPrice,
+                                                               BigDecimal promoPrice,
+                                                               BigDecimal wholesalePrice, GenericValue maximumPriceValue,
+                                                               GenericValue minimumPriceValue, boolean validPriceFound,
+                                                               GenericValue averageCostValue, String productId, String virtualProductId,
+                                                               String prodCatalogId, String productStoreGroupId,
+                                                               String webSiteId, String partyId, BigDecimal quantity, String currencyUomId,
+                                                               Delegator delegator, Timestamp nowTimestamp,
+                                                               Locale locale) throws GenericEntityException {
 
         Map<String, Object> calcResults = new HashMap<>();
 
@@ -1057,7 +1064,7 @@ public class PriceServices {
         int compare = 0;
 
         if ("PRIP_PRODUCT_ID".equals(productPriceCond.getString("inputParamEnumId"))) {
-            compare = UtilMisc.toList(productId, virtualProductId).contains(productPriceCond.getString("condValue"))? 0: 1;
+            compare = UtilMisc.toList(productId, virtualProductId).contains(productPriceCond.getString("condValue")) ? 0 : 1;
         } else if ("PRIP_PROD_CAT_ID".equals(productPriceCond.getString("inputParamEnumId"))) {
             // if a ProductCategoryMember exists for this productId and the specified productCategoryId
             String productCategoryId = productPriceCond.getString("condValue");
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java
index 1e72b0f..b057270 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductContentWrapper.java
@@ -121,16 +121,16 @@ public class ProductContentWrapper implements ContentWrapper {
             getProductContentAsText(null, product, productContentTypeId, locale, mimeTypeId, partyId, roleTypeId, delegator, dispatcher, outWriter, false);
             String outString = outWriter.toString();
             if (UtilValidate.isEmpty(outString)) {
-                outString = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName): "";
-                outString = outString == null? "" : outString;
+                outString = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName) : "";
+                outString = outString == null ? "" : outString;
             }
             outString = encoder.sanitize(outString, null);
             productContentCache.put(cacheKey, outString);
             return outString;
         } catch (GeneralException | IOException e) {
             Debug.logError(e, "Error rendering ProductContent, inserting empty String", MODULE);
-            String candidateOut = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName): "";
-            return candidateOut == null? "" : encoder.sanitize(candidateOut, null);
+            String candidateOut = product.getModelEntity().isField(candidateFieldName) ? product.getString(candidateFieldName) : "";
+            return candidateOut == null ? "" : encoder.sanitize(candidateOut, null);
         }
     }
 
@@ -183,22 +183,21 @@ public class ProductContentWrapper implements ContentWrapper {
         }
 
         if (productModel.isField(candidateFieldName)) {
-                String candidateValue = product.getString(candidateFieldName);
-                if (UtilValidate.isNotEmpty(candidateValue)) {
-                    outWriter.write(candidateValue);
-                    return;
-                } else if ("Y".equals(product.getString("isVariant"))) {
-                    // look up the virtual product
-                    GenericValue parent = ProductWorker.getParentProduct(productId, delegator);
-                    if (parent != null) {
-                        candidateValue = parent.getString(candidateFieldName);
-                        if (UtilValidate.isNotEmpty(candidateValue)) {
-                            outWriter.write(candidateValue);
-                            return;
-                        }
+            String candidateValue = product.getString(candidateFieldName);
+            if (UtilValidate.isNotEmpty(candidateValue)) {
+                outWriter.write(candidateValue);
+                return;
+            } else if ("Y".equals(product.getString("isVariant"))) {
+                // look up the virtual product
+                GenericValue parent = ProductWorker.getParentProduct(productId, delegator);
+                if (parent != null) {
+                    candidateValue = parent.getString(candidateFieldName);
+                    if (UtilValidate.isNotEmpty(candidateValue)) {
+                        outWriter.write(candidateValue);
+                        return;
                     }
                 }
+            }
         }
-
     }
 }
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java
index d2fd50b..9ebaa07 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductPromoContentWrapper.java
@@ -127,7 +127,7 @@ public class ProductPromoContentWrapper implements ContentWrapper {
             String outString = outWriter.toString();
             if (UtilValidate.isEmpty(outString)) {
                 outString = productPromo.getModelEntity().isField(candidateFieldName) ? productPromo.getString(candidateFieldName): "";
-                outString = outString == null? "" : outString;
+                outString = outString == null ? "" : outString;
             }
             outString = encoder.sanitize(outString, null);
             productPromoContentCache.put(cacheKey, outString);
@@ -135,7 +135,7 @@ public class ProductPromoContentWrapper implements ContentWrapper {
         } catch (GeneralException | IOException e) {
             Debug.logError(e, "Error rendering ProductPromoContent, inserting empty String", MODULE);
             String candidateOut = productPromo.getModelEntity().isField(candidateFieldName) ? productPromo.getString(candidateFieldName): "";
-            return candidateOut == null? "" : encoder.sanitize(candidateOut, null);
+            return candidateOut == null ? "" : encoder.sanitize(candidateOut, null);
         }
     }
 
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java
index 16bb960..48f7dfd 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearch.java
@@ -357,11 +357,11 @@ public class ProductSearch {
 
         public void finishCategoryAndFeatureConstraints() {
             if (includeCategoryIds.size() == 0 && excludeCategoryIds.size() == 0 && alwaysIncludeCategoryIds.size() == 0
-                && includeCategoryIdOrSetAndList.size() == 0 && alwaysIncludeCategoryIdOrSetAndList.size() == 0
-                && includeFeatureIds.size() == 0 && excludeFeatureIds.size() == 0 && alwaysIncludeFeatureIds.size() == 0
-                && includeFeatureIdOrSetAndList.size() == 0 && alwaysIncludeFeatureIdOrSetAndList.size() == 0
-                && includeFeatureCategoryIds.size() == 0 && excludeFeatureCategoryIds.size() == 0 && alwaysIncludeFeatureCategoryIds.size() == 0
-                && includeFeatureGroupIds.size() == 0 && excludeFeatureGroupIds.size() == 0 && alwaysIncludeFeatureGroupIds.size() == 0) {
+                    && includeCategoryIdOrSetAndList.size() == 0 && alwaysIncludeCategoryIdOrSetAndList.size() == 0
+                    && includeFeatureIds.size() == 0 && excludeFeatureIds.size() == 0 && alwaysIncludeFeatureIds.size() == 0
+                    && includeFeatureIdOrSetAndList.size() == 0 && alwaysIncludeFeatureIdOrSetAndList.size() == 0
+                    && includeFeatureCategoryIds.size() == 0 && excludeFeatureCategoryIds.size() == 0 && alwaysIncludeFeatureCategoryIds.size() == 0
+                    && includeFeatureGroupIds.size() == 0 && excludeFeatureGroupIds.size() == 0 && alwaysIncludeFeatureGroupIds.size() == 0) {
                 return;
             }
 
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java
index 02aa096..94ab324 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductSearchEvents.java
@@ -51,25 +51,28 @@ import org.apache.ofbiz.webapp.stats.VisitHandler;
  */
 public class ProductSearchEvents {
 
+    public static final int DEFAULT_TX_TIMEOUT = 600;
     private static final String MODULE = ProductSearchEvents.class.getName();
     private static final String RESOURCE = "ProductErrorUiLabels";
-    public static final int DEFAULT_TX_TIMEOUT = 600;
 
-    /** Removes the results of a search from the specified category
-     *@param request The HTTPRequest object for the current request
-     *@param response The HTTPResponse object for the current request
-     *@return String specifying the exit status of this event
+    /**
+     * Removes the results of a search from the specified category
+     *
+     * @param request  The HTTPRequest object for the current request
+     * @param response The HTTPResponse object for the current request
+     * @return String specifying the exit status of this event
      */
     public static String searchRemoveFromCategory(HttpServletRequest request, HttpServletResponse response) {
         Delegator delegator = (Delegator) request.getAttribute("delegator");
         String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID");
-        String errMsg=null;
+        String errMsg = null;
 
         try {
             boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
             try (EntityListIterator eli = getProductSearchResults(request)) {
                 if (eli == null) {
-                    errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
+                    errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints",
+                            UtilHttp.getLocale(request));
                     request.setAttribute("_ERROR_MESSAGE_", errMsg);
                     return "error";
                 }
@@ -78,14 +81,92 @@ public class ProductSearchEvents {
                 GenericValue searchResultView = null;
                 while ((searchResultView = eli.next()) != null) {
                     String productId = searchResultView.getString("mainProductId");
-                    numRemoved += delegator.removeByAnd("ProductCategoryMember", UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId));
+                    numRemoved += delegator.removeByAnd("ProductCategoryMember", UtilMisc.toMap("productCategoryId", productCategoryId,
+                            "productId", productId));
                 }
                 Map<String, String> messageMap = UtilMisc.toMap("numRemoved", Integer.toString(numRemoved));
                 errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.removed_x_items", messageMap, UtilHttp.getLocale(request));
                 request.setAttribute("_EVENT_MESSAGE_", errMsg);
             } catch (GenericEntityException e) {
                 Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
-                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
+                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap,
+                        UtilHttp.getLocale(request));
+                Debug.logError(e, errMsg, MODULE);
+                request.setAttribute("_ERROR_MESSAGE_", errMsg);
+                TransactionUtil.rollback(beganTransaction, errMsg, e);
+                return "error";
+            } finally {
+                TransactionUtil.commit(beganTransaction);
+            }
+        } catch (GenericTransactionException e) {
+            Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
+            errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
+            Debug.logError(e, errMsg, MODULE);
+            request.setAttribute("_ERROR_MESSAGE_", errMsg);
+            return "error";
+        }
+        return "success";
+    }
+
+    /**
+     * Sets the thru date of the results of a search to the specified date for the specified catogory
+     *
+     * @param request  The HTTPRequest object for the current request
+     * @param response The HTTPResponse object for the current request
+     * @return String specifying the exit status of this event
+     */
+    public static String searchExpireFromCategory(HttpServletRequest request, HttpServletResponse response) {
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID");
+        String thruDateStr = request.getParameter("thruDate");
+        String errMsg = null;
+
+        Timestamp thruDate;
+        try {
+            thruDate = Timestamp.valueOf(thruDateStr);
+        } catch (RuntimeException e) {
+            Map<String, String> messageMap = UtilMisc.toMap("errDateFormat", e.toString());
+            errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.thruDate_not_formatted_properly", messageMap,
+                    UtilHttp.getLocale(request));
+            Debug.logError(e, errMsg, MODULE);
+            request.setAttribute("_ERROR_MESSAGE_", errMsg);
+            return "error";
+        }
+
+        try {
+            boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
+            try (EntityListIterator eli = getProductSearchResults(request)) {
+                if (eli == null) {
+                    errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints",
+                            UtilHttp.getLocale(request));
+                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
+                    return "error";
+                }
+
+                GenericValue searchResultView = null;
+                int numExpired = 0;
+                while ((searchResultView = eli.next()) != null) {
+                    String productId = searchResultView.getString("mainProductId");
+                    //get all tuples that match product and category
+                    List<GenericValue> pcmList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId",
+                            productCategoryId, "productId", productId).queryList();
+
+                    //set those thrudate to that specificed maybe remove then add new one
+                    for (GenericValue pcm : pcmList) {
+                        if (pcm.get("thruDate") == null) {
+                            pcm.set("thruDate", thruDate);
+                            pcm.store();
+                            numExpired++;
+                        }
+                    }
+                }
+                Map<String, String> messageMap = UtilMisc.toMap("numExpired", Integer.toString(numExpired));
+                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.expired_x_items", messageMap, UtilHttp.getLocale(request));
+                request.setAttribute("_EVENT_MESSAGE_", errMsg);
+            } catch (GenericEntityException e) {
+                Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
+                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap,
+                        UtilHttp.getLocale(request));
                 Debug.logError(e, errMsg, MODULE);
                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
                 TransactionUtil.rollback(beganTransaction, errMsg, e);
@@ -103,148 +184,85 @@ public class ProductSearchEvents {
         return "success";
     }
 
-   /** Sets the thru date of the results of a search to the specified date for the specified catogory
-    *@param request The HTTPRequest object for the current request
-    *@param response The HTTPResponse object for the current request
-    *@return String specifying the exit status of this event
-    */
-   public static String searchExpireFromCategory(HttpServletRequest request, HttpServletResponse response) {
-       Delegator delegator = (Delegator) request.getAttribute("delegator");
-       String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID");
-       String thruDateStr = request.getParameter("thruDate");
-       String errMsg=null;
-
-       Timestamp thruDate;
-       try {
-           thruDate = Timestamp.valueOf(thruDateStr);
-       } catch (RuntimeException e) {
-           Map<String, String> messageMap = UtilMisc.toMap("errDateFormat", e.toString());
-           errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.thruDate_not_formatted_properly", messageMap, UtilHttp.getLocale(request));
-           Debug.logError(e, errMsg, MODULE);
-           request.setAttribute("_ERROR_MESSAGE_", errMsg);
-           return "error";
-       }
-
-       try {
-           boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
-           try (EntityListIterator eli = getProductSearchResults(request)) {
-               if (eli == null) {
-                   errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
-                   request.setAttribute("_ERROR_MESSAGE_", errMsg);
-                   return "error";
-               }
-
-               GenericValue searchResultView = null;
-               int numExpired = 0;
-               while ((searchResultView = eli.next()) != null) {
-                   String productId = searchResultView.getString("mainProductId");
-                   //get all tuples that match product and category
-                   List<GenericValue> pcmList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", productCategoryId, "productId", productId).queryList();
-
-                   //set those thrudate to that specificed maybe remove then add new one
-                   for (GenericValue pcm: pcmList) {
-                       if (pcm.get("thruDate") == null) {
-                           pcm.set("thruDate", thruDate);
-                           pcm.store();
-                           numExpired++;
-                       }
-                   }
-               }
-               Map<String, String> messageMap = UtilMisc.toMap("numExpired", Integer.toString(numExpired));
-               errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.expired_x_items", messageMap, UtilHttp.getLocale(request));
-               request.setAttribute("_EVENT_MESSAGE_", errMsg);
-           } catch (GenericEntityException e) {
-               Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
-               errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
-               Debug.logError(e, errMsg, MODULE);
-               request.setAttribute("_ERROR_MESSAGE_", errMsg);
-               TransactionUtil.rollback(beganTransaction, errMsg, e);
-               return "error";
-           } finally {
-               TransactionUtil.commit(beganTransaction);
-           }
-       } catch (GenericTransactionException e) {
-           Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
-           errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
-           Debug.logError(e, errMsg, MODULE);
-           request.setAttribute("_ERROR_MESSAGE_", errMsg);
-           return "error";
-       }
-
-       return "success";
-   }
-
-   /**  Adds the results of a search to the specified catogory
-    *@param request The HTTPRequest object for the current request
-    *@param response The HTTPResponse object for the current request
-    *@return String specifying the exit status of this event
-    */
-   public static String searchAddToCategory(HttpServletRequest request, HttpServletResponse response) {
-       Delegator delegator = (Delegator) request.getAttribute("delegator");
-       String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID");
-       String fromDateStr = request.getParameter("fromDate");
-       Timestamp fromDate = null;
-       String errMsg = null;
-
-       try {
-           fromDate = Timestamp.valueOf(fromDateStr);
+    /**
+     * Adds the results of a search to the specified catogory
+     *
+     * @param request  The HTTPRequest object for the current request
+     * @param response The HTTPResponse object for the current request
+     * @return String specifying the exit status of this event
+     */
+    public static String searchAddToCategory(HttpServletRequest request, HttpServletResponse response) {
+        Delegator delegator = (Delegator) request.getAttribute("delegator");
+        String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID");
+        String fromDateStr = request.getParameter("fromDate");
+        Timestamp fromDate = null;
+        String errMsg = null;
+
+        try {
+            fromDate = Timestamp.valueOf(fromDateStr);
         } catch (RuntimeException e) {
-           Map<String, String> messageMap = UtilMisc.toMap("errDateFormat", e.toString());
-           errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.fromDate_not_formatted_properly", messageMap, UtilHttp.getLocale(request));
-           request.setAttribute("_ERROR_MESSAGE_", errMsg);
+            Map<String, String> messageMap = UtilMisc.toMap("errDateFormat", e.toString());
+            errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.fromDate_not_formatted_properly", messageMap,
+                    UtilHttp.getLocale(request));
+            request.setAttribute("_ERROR_MESSAGE_", errMsg);
             return "error";
         }
 
-       try {
-           boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
-           try (EntityListIterator eli = getProductSearchResults(request)) {
-               if (eli == null) {
-                   errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
-                   request.setAttribute("_ERROR_MESSAGE_", errMsg);
-                   return "error";
-               }
-
-               GenericValue searchResultView = null;
-               int numAdded = 0;
-               while ((searchResultView = eli.next()) != null) {
-                   String productId = searchResultView.getString("mainProductId");
-
-                   GenericValue pcm=delegator.makeValue("ProductCategoryMember");
-                   pcm.set("productCategoryId", productCategoryId);
-                   pcm.set("productId", productId);
-                   pcm.set("fromDate", fromDate);
-                   pcm.create();
-
-                   numAdded++;
-               }
-               Map<String, String> messageMap = UtilMisc.toMap("numAdded", Integer.toString(numAdded));
-               errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.added_x_product_category_members", messageMap, UtilHttp.getLocale(request));
-               request.setAttribute("_EVENT_MESSAGE_", errMsg);
-           } catch (GenericEntityException e) {
-               Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
-               errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
-               Debug.logError(e, errMsg, MODULE);
-               request.setAttribute("_ERROR_MESSAGE_", errMsg);
-               TransactionUtil.rollback(beganTransaction, errMsg, e);
-               return "error";
-           } finally {
-               TransactionUtil.commit(beganTransaction);
-           }
-       } catch (GenericTransactionException e) {
-           Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
-           errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
-           Debug.logError(e, errMsg, MODULE);
-           request.setAttribute("_ERROR_MESSAGE_", errMsg);
-           return "error";
-       }
-
-       return "success";
-   }
-
-    /** Adds a feature to search results
-     *@param request The HTTPRequest object for the current request
-     *@param response The HTTPResponse object for the current request
-     *@return String specifying the exit status of this event
+        try {
+            boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
+            try (EntityListIterator eli = getProductSearchResults(request)) {
+                if (eli == null) {
+                    errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints",
+                            UtilHttp.getLocale(request));
+                    request.setAttribute("_ERROR_MESSAGE_", errMsg);
+                    return "error";
+                }
+
+                GenericValue searchResultView = null;
+                int numAdded = 0;
+                while ((searchResultView = eli.next()) != null) {
+                    String productId = searchResultView.getString("mainProductId");
+
+                    GenericValue pcm = delegator.makeValue("ProductCategoryMember");
+                    pcm.set("productCategoryId", productCategoryId);
+                    pcm.set("productId", productId);
+                    pcm.set("fromDate", fromDate);
+                    pcm.create();
+
+                    numAdded++;
+                }
+                Map<String, String> messageMap = UtilMisc.toMap("numAdded", Integer.toString(numAdded));
+                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.added_x_product_category_members", messageMap,
+                        UtilHttp.getLocale(request));
+                request.setAttribute("_EVENT_MESSAGE_", errMsg);
+            } catch (GenericEntityException e) {
+                Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
+                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap,
+                        UtilHttp.getLocale(request));
+                Debug.logError(e, errMsg, MODULE);
+                request.setAttribute("_ERROR_MESSAGE_", errMsg);
+                TransactionUtil.rollback(beganTransaction, errMsg, e);
+                return "error";
+            } finally {
+                TransactionUtil.commit(beganTransaction);
+            }
+        } catch (GenericTransactionException e) {
+            Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
+            errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
+            Debug.logError(e, errMsg, MODULE);
+            request.setAttribute("_ERROR_MESSAGE_", errMsg);
+            return "error";
+        }
+
+        return "success";
+    }
+
+    /**
+     * Adds a feature to search results
+     *
+     * @param request  The HTTPRequest object for the current request
+     * @param response The HTTPResponse object for the current request
+     * @return String specifying the exit status of this event
      */
     public static String searchAddFeature(HttpServletRequest request, HttpServletResponse response) {
         Delegator delegator = (Delegator) request.getAttribute("delegator");
@@ -273,7 +291,7 @@ public class ProductSearchEvents {
                 amount = new BigDecimal(amountStr);
             }
             if (UtilValidate.isNotEmpty(sequenceNumStr)) {
-                sequenceNum= Long.valueOf(sequenceNumStr);
+                sequenceNum = Long.valueOf(sequenceNumStr);
             }
         } catch (RuntimeException e) {
             String errorMsg = UtilProperties.getMessage(RESOURCE, "productSearchEvents.error_casting_types", locale) + " : " + e.toString();
@@ -286,7 +304,8 @@ public class ProductSearchEvents {
             boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
             try (EntityListIterator eli = getProductSearchResults(request)) {
                 if (eli == null) {
-                    String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
+                    String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints",
+                            UtilHttp.getLocale(request));
                     request.setAttribute("_ERROR_MESSAGE_", errMsg);
                     return "error";
                 }
@@ -295,7 +314,7 @@ public class ProductSearchEvents {
                 int numAdded = 0;
                 while ((searchResultView = eli.next()) != null) {
                     String productId = searchResultView.getString("mainProductId");
-                    GenericValue pfa=delegator.makeValue("ProductFeatureAppl");
+                    GenericValue pfa = delegator.makeValue("ProductFeatureAppl");
                     pfa.set("productId", productId);
                     pfa.set("productFeatureId", productFeatureId);
                     pfa.set("fromDate", fromDate);
@@ -328,10 +347,12 @@ public class ProductSearchEvents {
         return "success";
     }
 
-    /** Removes a feature from search results
-     *@param request The HTTPRequest object for the current request
-     *@param response The HTTPResponse object for the current request
-     *@return String specifying the exit status of this event
+    /**
+     * Removes a feature from search results
+     *
+     * @param request  The HTTPRequest object for the current request
+     * @param response The HTTPResponse object for the current request
+     * @return String specifying the exit status of this event
      */
     public static String searchRemoveFeature(HttpServletRequest request, HttpServletResponse response) {
         Delegator delegator = (Delegator) request.getAttribute("delegator");
@@ -343,7 +364,8 @@ public class ProductSearchEvents {
             boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
             try (EntityListIterator eli = getProductSearchResults(request)) {
                 if (eli == null) {
-                    String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
+                    String errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints",
+                            UtilHttp.getLocale(request));
                     request.setAttribute("_ERROR_MESSAGE_", errMsg);
                     return "error";
                 }
@@ -352,7 +374,8 @@ public class ProductSearchEvents {
                 int numRemoved = 0;
                 while ((searchResultView = eli.next()) != null) {
                     String productId = searchResultView.getString("mainProductId");
-                    numRemoved += delegator.removeByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", productId, "productFeatureId", productFeatureId));
+                    numRemoved += delegator.removeByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", productId, "productFeatureId",
+                            productFeatureId));
                 }
                 Map<String, Object> messageMap = UtilMisc.toMap("numRemoved", numRemoved, "productFeatureId", productFeatureId);
                 String eventMsg = UtilProperties.getMessage(RESOURCE, "productSearchEvents.removed_param_features", messageMap, locale) + ".";
@@ -376,10 +399,12 @@ public class ProductSearchEvents {
         return "success";
     }
 
-    /**  Formats the results of a search to the screen as a tab-delimited output
-     *@param request The HTTPRequest object for the current request
-     *@param response The HTTPResponse object for the current request
-     *@return String specifying the exit status of this event
+    /**
+     * Formats the results of a search to the screen as a tab-delimited output
+     *
+     * @param request  The HTTPRequest object for the current request
+     * @param response The HTTPResponse object for the current request
+     * @return String specifying the exit status of this event
      */
     public static String searchExportProductList(HttpServletRequest request, HttpServletResponse response) {
         Delegator delegator = (Delegator) request.getAttribute("delegator");
@@ -390,7 +415,8 @@ public class ProductSearchEvents {
             boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
             try (EntityListIterator eli = getProductSearchResults(request)) {
                 if (eli == null) {
-                    errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
+                    errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.no_results_found_probably_error_constraints",
+                            UtilHttp.getLocale(request));
                     request.setAttribute("_ERROR_MESSAGE_", errMsg);
                     return "error";
                 }
@@ -401,17 +427,21 @@ public class ProductSearchEvents {
                     String productId = searchResultView.getString("mainProductId");
                     productMap.put("productId", productId);
 
-                    productMap.put("productFeatureCustom", EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureTypeId", "HAZMAT").filterByDate().queryFirst());
+                    productMap.put("productFeatureCustom", EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId,
+                            "productFeatureTypeId", "HAZMAT").filterByDate().queryFirst());
 
-                    List<GenericValue> productCategories = EntityQuery.use(delegator).from("ProductCategoryAndMember").where("productId", productId).filterByDate().queryList();
+                    List<GenericValue> productCategories = EntityQuery.use(delegator).from("ProductCategoryAndMember").where("productId",
+                            productId).filterByDate().queryList();
                     productMap.put("productCategories", productCategories);
-                    List<GenericValue> productFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId).filterByDate().queryList();
+                    List<GenericValue> productFeatures =
+                            EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId).filterByDate().queryList();
                     productMap.put("productFeatures", productFeatures);
                     productExportList.add(productMap);
                 }
             } catch (GenericEntityException e) {
                 Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
-                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
+                errMsg = UtilProperties.getMessage(RESOURCE, "productsearchevents.error_getting_search_results", messageMap,
+                        UtilHttp.getLocale(request));
                 Debug.logError(e, errMsg, MODULE);
                 request.setAttribute("_ERROR_MESSAGE_", errMsg);
                 TransactionUtil.rollback(beganTransaction, errMsg, e);
@@ -436,7 +466,8 @@ public class ProductSearchEvents {
         Delegator delegator = (Delegator) request.getAttribute("delegator");
         String visitId = VisitHandler.getVisitId(session);
 
-        List<ProductSearch.ProductSearchConstraint> productSearchConstraintList = ProductSearchSession.ProductSearchOptions.getConstraintList(session);
+        List<ProductSearch.ProductSearchConstraint> productSearchConstraintList =
+                ProductSearchSession.ProductSearchOptions.getConstraintList(session);
         // if no constraints, don't do a search...
         if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
             ResultSortOrder resultSortOrder = ProductSearchSession.ProductSearchOptions.getResultSortOrder(request);
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java
index ca3ee88..84321e7 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductServices.java
@@ -1336,7 +1336,7 @@ public class ProductServices {
                 filenameToUse += "." + extension.getString("fileExtensionId");
             }
 
-            File makeResourceDirectory  = new File(imageServerPath + "/" + filePathPrefix);
+            File makeResourceDirectory = new File(imageServerPath + "/" + filePathPrefix);
             if (!makeResourceDirectory.exists()) {
                 if (!makeResourceDirectory.mkdirs()) {
                     Debug.logError("Directory :" + makeResourceDirectory.getPath() + ", couldn't be created", MODULE);
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java
index 7b47f47..ba44d38 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/product/ProductWorker.java
@@ -100,11 +100,11 @@ public final class ProductWorker {
                 return true;
             }
             // exclusion
-            for (GenericValue productGeo: excludeGeos) {
+            for (GenericValue productGeo : excludeGeos) {
                 List<GenericValue> excludeGeoGroup = GeoWorker.expandGeoGroup(productGeo.getString("geoId"), delegator);
                 if (GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("countryGeoId"), delegator)
-                      || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("stateProvinceGeoId"), delegator)
-                      || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("postalCodeGeoId"), delegator)) {
+                        || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("stateProvinceGeoId"), delegator)
+                        || GeoWorker.containsGeo(excludeGeoGroup, postalAddress.getString("postalCodeGeoId"), delegator)) {
                     return false;
                 }
             }
@@ -750,7 +750,7 @@ public final class ProductWorker {
             } catch (GenericEntityException e) {
                 Debug.logWarning(e.getMessage(), MODULE);
             }
-            String isDigitalValue = (productType != null? productType.getString("isDigital"): null);
+            String isDigitalValue = (productType != null ? productType.getString("isDigital") : null);
             isDigital = isDigitalValue != null && "Y".equalsIgnoreCase(isDigitalValue);
         }
         return isDigital;
@@ -765,7 +765,7 @@ public final class ProductWorker {
             } catch (GenericEntityException e) {
                 Debug.logWarning(e.getMessage(), MODULE);
             }
-            String isPhysicalValue = (productType != null? productType.getString("isPhysical"): null);
+            String isPhysicalValue = (productType != null ? productType.getString("isPhysical") : null);
             isPhysical = isPhysicalValue != null && "Y".equalsIgnoreCase(isPhysicalValue);
         }
         return isPhysical;
@@ -909,7 +909,7 @@ public final class ProductWorker {
     }
 
     public static List<GenericValue> findProductsById(Delegator delegator, String idToFind, String goodIdentificationTypeId)
-    throws GenericEntityException {
+            throws GenericEntityException {
         return findProductsById(delegator, idToFind, goodIdentificationTypeId, true, false);
     }
 
@@ -1051,7 +1051,7 @@ public final class ProductWorker {
             // find variant
             List<GenericValue> productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList();
             boolean productFound = false;
-nextProd:
+            nextProd:
             for (GenericValue productAssoc: productAssocs) {
                 for (String featureId: selectedFeatures) {
                     List<GenericValue> pAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productId", productAssoc.getString("productIdTo"), "productFeatureId", featureId, "productFeatureApplTypeId", "STANDARD_FEATURE").cache(true).queryList();
@@ -1070,7 +1070,7 @@ nextProd:
              */
             if (!productFound) {
                 // copy product to be variant
-                GenericValue product = EntityQuery.use(delegator).from("Product").where("productId",  productId).queryOne();
+                GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
                 product.put("isVariant", "Y");
                 product.put("isVirtual", "N");
                 product.put("productId", delegator.getNextSeqId("Product"));
@@ -1081,13 +1081,13 @@ nextProd:
                         UtilMisc.toMap("productId", product.getString("productId"), "productFeatureApplTypeId", "STANDARD_FEATURE"));
                 productFeatureAppl.put("fromDate", UtilDateTime.nowTimestamp());
                 for (String productFeatureId: selectedFeatures) {
-                    productFeatureAppl.put("productFeatureId",  productFeatureId);
+                    productFeatureAppl.put("productFeatureId", productFeatureId);
                     productFeatureAppl.create();
                 }
                 //add standard features too
                 List<GenericValue> stdFeaturesAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE").filterByDate().queryList();
                 for (GenericValue stdFeaturesAppl: stdFeaturesAppls) {
-                    stdFeaturesAppl.put("productId",  product.getString("productId"));
+                    stdFeaturesAppl.put("productId", product.getString("productId"));
                     stdFeaturesAppl.create();
                 }
                 /* 3. use the price of the virtual product(Entity:ProductPrice) as a basis and adjust according the prices in the feature price table.
@@ -1110,7 +1110,7 @@ nextProd:
                     if (productPrice.get("price") == null) {
                         productPrice.put("price", productPrice.getBigDecimal("price"));
                     }
-                    productPrice.put("productId",  product.getString("productId"));
+                    productPrice.put("productId", product.getString("productId"));
                     productPrice.create();
                 }
                 // add the product association
@@ -1123,7 +1123,7 @@ nextProd:
                 List<GenericValue> supplierProducts = EntityQuery.use(delegator).from("SupplierProduct").where("productId", productId).cache(true).queryList();
                 for (GenericValue supplierProduct: supplierProducts) {
                     supplierProduct = (GenericValue) supplierProduct.clone();
-                    supplierProduct.set("productId",  product.getString("productId"));
+                    supplierProduct.set("productId", product.getString("productId"));
                     supplierProduct.create();
                 }
 
@@ -1131,7 +1131,7 @@ nextProd:
                 List<GenericValue> productContents = EntityQuery.use(delegator).from("ProductContent").where("productId", productId).cache(true).queryList();
                 for (GenericValue productContent: productContents) {
                     productContent = (GenericValue) productContent.clone();
-                    productContent.set("productId",  product.getString("productId"));
+                    productContent.set("productId", product.getString("productId"));
                     productContent.create();
                 }
 
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java
index 4e37388..16a5c8b 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/promo/PromoServices.java
@@ -94,8 +94,7 @@ public class PromoServices {
                 GenericValue existingPromoCode = null;
                 try {
                     existingPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", newPromoCodeId).cache().queryOne();
-                }
-                catch (GenericEntityException e) {
+                } catch (GenericEntityException e) {
                     Debug.logWarning("Could not find ProductPromoCode for just generated ID: " + newPromoCodeId, MODULE);
                 }
                 if (existingPromoCode == null) {
diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java b/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java
index 55a4eed..04d8afb 100644
--- a/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java
+++ b/applications/product/src/main/java/org/apache/ofbiz/product/subscription/SubscriptionServices.java
@@ -326,9 +326,9 @@ public class SubscriptionServices {
 
             if (subscriptionList != null) {
                 for (GenericValue subscription : subscriptionList) {
-                 expirationCompletedDate = subscription.getTimestamp("expirationCompletedDate");
-                 if (expirationCompletedDate == null) {
-                 Calendar currentDate = Calendar.getInstance();
+                    expirationCompletedDate = subscription.getTimestamp("expirationCompletedDate");
+                    if (expirationCompletedDate == null) {
+                        Calendar currentDate = Calendar.getInstance();
                         currentDate.setTime(UtilDateTime.nowTimestamp());
                         // check if the thruDate + grace period (if provided) is earlier than today's date
                         Calendar endDateSubscription = Calendar.getInstance();
@@ -377,10 +377,11 @@ public class SubscriptionServices {
                                 Debug.logInfo("Service mentioned in serviceNameOnExpiry called with result: " + ServiceUtil.makeSuccessMessage(result, "", "", "", ""), MODULE);
                             } else if (result == null && subscriptionId != null) {
                                 Debug.logError("Subscription couldn't be expired for subscriptionId: " + subscriptionId, MODULE);
-                                return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductSubscriptionCouldntBeExpired", UtilMisc.toMap("subscriptionId", subscriptionId), locale));
... 2188 lines suppressed ...