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 371aab1 Improved: Corrected class names, method names, data members of class and variables names in application components. (OFBIZ-11926) Also corrected some formatting and line length related checkstyle issues. new 2c79c43 Merge branch 'trunk' of https://gitbox.apache.org/repos/asf/ofbiz-framework into trunk 371aab1 is described below commit 371aab1e5b926ee03ea94b3050d059a518a96bb4 Author: Suraj Khurana <[hidden email]> AuthorDate: Wed Aug 26 21:37:41 2020 +0530 Improved: Corrected class names, method names, data members of class and variables names in application components. (OFBIZ-11926) Also corrected some formatting and line length related checkstyle issues. --- .../finaccount/FinAccountPaymentServices.java | 27 +-- .../ofbiz/accounting/invoice/InvoiceServices.java | 126 ++++++++------ .../ofbiz/accounting/test/FinAccountTests.java | 10 +- .../authorizedotnet/AuthorizeResponse.java | 62 ++++++- .../thirdparty/clearcommerce/CCServicesTest.java | 8 +- .../thirdparty/gosoftware/PcChargeApi.java | 56 ++++-- .../accounting/thirdparty/paypal/PayPalEvents.java | 52 ++++-- .../thirdparty/worldpay/WorldPayEvents.java | 78 ++++++--- .../java/org/apache/ofbiz/content/ConvertTree.java | 189 +++++++++++--------- .../apache/ofbiz/content/blog/BlogRssServices.java | 9 +- .../ofbiz/content/content/ContentMapFacade.java | 59 +++++-- .../ofbiz/content/content/ContentWorker.java | 7 +- .../ofbiz/content/content/PermissionRecorder.java | 34 +++- .../ofbiz/content/output/OutputServices.java | 15 +- .../ftl/EditRenderSubContentCacheTransform.java | 7 +- .../ftl/LimitedSubContentCacheTransform.java | 13 +- .../webapp/ftl/LoopSubContentTransform.java | 13 +- .../webapp/ftl/OfbizContentAltUrlTransforms.java | 14 +- .../content/webapp/ftl/RenderContentAsText.java | 9 +- .../content/webapp/ftl/RenderSubContentAsText.java | 9 +- .../webapp/ftl/RenderSubContentCacheTransform.java | 39 +++-- .../ftl/TraverseSubContentCacheTransform.java | 18 +- .../webapp/ftl/WrapSubContentCacheTransform.java | 11 +- .../marketing/marketing/MarketingServices.java | 15 +- .../apache/ofbiz/order/order/OrderListState.java | 34 ++-- .../ofbiz/order/order/OrderLookupServices.java | 29 ++-- .../order/shoppingcart/ShoppingCartHelper.java | 2 +- .../ofbiz/order/shoppingcart/ShoppingCartItem.java | 148 ++++++++++++---- .../apache/ofbiz/order/test/FinAccountTest.java | 4 + .../org/apache/ofbiz/order/test/OrderTest.java | 18 +- .../apache/ofbiz/order/test/PurchaseOrderTest.java | 22 ++- .../apache/ofbiz/order/test/SalesOrderTest.java | 6 +- .../ofbiz/product/category/CatalogUrlFilter.java | 89 ++++++---- .../product/category/CatalogUrlSeoFilter.java | 12 +- .../product/category/CategoryContentWrapper.java | 55 +++--- .../product/category/SeoContentUrlFilter.java | 10 +- .../category/ftl/CatalogUrlSeoTransform.java | 4 +- .../org/apache/ofbiz/product/image/ScaleImage.java | 78 ++++++--- .../ofbiz/product/product/ProductServices.java | 104 ++++++----- .../ofbiz/product/product/ProductWorker.java | 162 ++++++++++------- .../apache/ofbiz/product/promo/PromoServices.java | 12 +- .../product/test/InventoryItemTransferTest.java | 12 +- .../apache/ofbiz/product/test/StockMovesTest.java | 10 +- .../apache/ofbiz/shipment/test/IssuanceTest.java | 16 +- .../ofbiz/shipment/thirdparty/dhl/DhlServices.java | 135 ++++++++------ .../shipment/thirdparty/fedex/FedexServices.java | 15 +- .../thirdparty/usps/UspsServicesTests.java | 42 ++++- .../ofbiz/shipment/verify/VerifyPickSession.java | 193 ++++++++++++++++++--- .../ofbiz/securityext/login/LoginEvents.java | 28 +-- .../ofbiz/workeffort/workeffort/ICalConverter.java | 75 ++++---- 50 files changed, 1451 insertions(+), 744 deletions(-) diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/finaccount/FinAccountPaymentServices.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/finaccount/FinAccountPaymentServices.java index 36ff3c6..ca98db8 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/finaccount/FinAccountPaymentServices.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/finaccount/FinAccountPaymentServices.java @@ -249,7 +249,8 @@ public class FinAccountPaymentServices { // make sure to round and scale it to the same as availableBalance amount = amount.setScale(FinAccountHelper.getDecimals(), FinAccountHelper.getRounding()); - Debug.logInfo("Allow auth to negative: " + allowAuthToNegative + " :: available: " + availableBalance + " comp: " + minBalance + " = " + availableBalance.compareTo(minBalance) + " :: req: " + amount, MODULE); + Debug.logInfo("Allow auth to negative: " + allowAuthToNegative + " :: available: " + availableBalance + " comp: " + + minBalance + " = " + availableBalance.compareTo(minBalance) + " :: req: " + amount, MODULE); // check the available balance to see if we can auth this tx if (("Y".equals(allowAuthToNegative) && availableBalance.compareTo(minBalance) > -1) || (availableBalance.compareTo(amount) > -1)) { @@ -261,8 +262,8 @@ public class FinAccountPaymentServices { thruDate = UtilDateTime.getDayEnd(UtilDateTime.nowTimestamp(), 30L); // default 30 days for an auth } - Map<String, Object> tmpResult = dispatcher.runSync("createFinAccountAuth", UtilMisc.<String, Object>toMap("finAccountId", finAccountId, - "amount", amount, "thruDate", thruDate, "userLogin", userLogin)); + Map<String, Object> tmpResult = dispatcher.runSync("createFinAccountAuth", UtilMisc.<String, Object>toMap("finAccountId", + finAccountId, "amount", amount, "thruDate", thruDate, "userLogin", userLogin)); if (ServiceUtil.isError(tmpResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult)); @@ -283,7 +284,6 @@ public class FinAccountPaymentServices { result.put("processAmount", amount); result.put("authMessage", authMessage); result.put("authResult", processResult); - result.put("processAmount", amount); result.put("authFlag", "1"); result.put("authCode", "A"); result.put("authRefNum", refNum); @@ -410,10 +410,12 @@ public class FinAccountPaymentServices { // BIG NOTE: make sure the expireFinAccountAuth and finAccountWithdraw services are done in the SAME TRANSACTION //(i.e. no require-new-transaction in either of them AND no running async) - // cancel the authorization before doing the withdraw to avoid problems with way negative available amount on account; should happen in same transaction to avoid conflict problems + // cancel the authorization before doing the withdraw to avoid problems with way negative available amount on account; + // should happen in same transaction to avoid conflict problems Map<String, Object> releaseResult; try { - releaseResult = dispatcher.runSync("expireFinAccountAuth", UtilMisc.<String, Object>toMap("userLogin", userLogin, "finAccountAuthId", finAccountAuthId)); + releaseResult = dispatcher.runSync("expireFinAccountAuth", UtilMisc.<String, Object>toMap("userLogin", userLogin, "finAccountAuthId", + finAccountAuthId)); if (ServiceUtil.isError(releaseResult)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(releaseResult)); } @@ -551,7 +553,7 @@ public class FinAccountPaymentServices { requireBalance = Boolean.TRUE; } - final String WITHDRAWAL = "WITHDRAWAL"; + final String withdrawal = "WITHDRAWAL"; String partyId = (String) context.get("partyId"); if (UtilValidate.isEmpty(partyId)) { @@ -608,7 +610,7 @@ public class FinAccountPaymentServices { try { refNum = FinAccountPaymentServices.createFinAcctPaymentTransaction(delegator, dispatcher, userLogin, amount, - productStoreId, partyId, orderId, orderItemSeqId, currencyUom, WITHDRAWAL, finAccountId, + productStoreId, partyId, orderId, orderItemSeqId, currencyUom, withdrawal, finAccountId, reasonEnumId); finAccount.refresh(); balance = finAccount.getBigDecimal("actualBalance"); @@ -648,7 +650,7 @@ public class FinAccountPaymentServices { Boolean isRefund = (Boolean) context.get("isRefund"); BigDecimal amount = (BigDecimal) context.get("amount"); - final String DEPOSIT = isRefund == null || !isRefund ? "DEPOSIT" : "ADJUSTMENT"; + final String deposit = isRefund == null || !isRefund ? "DEPOSIT" : "ADJUSTMENT"; String partyId = (String) context.get("partyId"); if (UtilValidate.isEmpty(partyId)) { @@ -694,7 +696,7 @@ public class FinAccountPaymentServices { String refNum; try { refNum = FinAccountPaymentServices.createFinAcctPaymentTransaction(delegator, dispatcher, userLogin, amount, - productStoreId, partyId, orderId, orderItemSeqId, currencyUom, DEPOSIT, finAccountId, reasonEnumId); + productStoreId, partyId, orderId, orderItemSeqId, currencyUom, deposit, finAccountId, reasonEnumId); finAccount.refresh(); actualBalance = finAccount.getBigDecimal("actualBalance"); } catch (GeneralException e) { @@ -928,7 +930,8 @@ public class FinAccountPaymentServices { // say we are in good standing again if ("FNACT_NEGPENDREPL".equals(statusId)) { try { - Map<String, Object> ufaResp = dispatcher.runSync("updateFinAccount", UtilMisc.<String, Object>toMap("finAccountId", finAccountId, "statusId", "FNACT_ACTIVE", "userLogin", userLogin)); + Map<String, Object> ufaResp = dispatcher.runSync("updateFinAccount", + UtilMisc.<String, Object>toMap("finAccountId", finAccountId, "statusId", "FNACT_ACTIVE", "userLogin", userLogin)); if (ServiceUtil.isError(ufaResp)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(ufaResp)); } @@ -996,7 +999,7 @@ public class FinAccountPaymentServices { partyIdFrom = partyId; partyIdTo = coParty; paymentAmount = amount; - } else if ("WITHDRAWAL".equals(txType)) { + } else if ("withdrawal".equals(txType)) { paymentType = "DISBURSEMENT"; partyIdFrom = coParty; partyIdTo = partyId; 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 dcd7d42..ecb07f8 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 @@ -147,13 +147,12 @@ public class InvoiceServices { } } - /* Service to create an invoice for an order */ + /** Service to create an invoice for an order */ public static Map<String, Object> createInvoiceForOrder(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Locale locale = (Locale) context.get("locale"); - if (DECIMALS == -1 || ROUNDING == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AccountingAritmeticPropertiesNotConfigured", locale)); @@ -337,8 +336,8 @@ public class InvoiceServices { } } } 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); } } @@ -438,16 +437,19 @@ public class InvoiceServices { } BigDecimal billingAmount = BigDecimal.ZERO; - GenericValue OrderAdjustment = EntityUtil.getFirst(orderItem.getRelated("OrderAdjustment", UtilMisc.toMap("orderAdjustmentTypeId", + GenericValue orderAdj = 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)); + if (UtilValidate.isNotEmpty(orderAdj) && (orderAdj.getBigDecimal("amount").signum() == 0) + && UtilValidate.isNotEmpty(orderAdj.getBigDecimal("amountAlreadyIncluded")) + && orderAdj.getBigDecimal("amountAlreadyIncluded").signum() != 0) { + BigDecimal sourcePercentageTotal = orderAdj.getBigDecimal("sourcePercentage").add(new BigDecimal(100)); billingAmount = - orderItem.getBigDecimal("unitPrice").divide(sourcePercentageTotal, 100, ROUNDING).multiply(new BigDecimal(100)).setScale(invoiceTypeDecimals, ROUNDING); + orderItem.getBigDecimal("unitPrice").divide(sourcePercentageTotal, 100, ROUNDING) + .multiply(new BigDecimal(100)).setScale(invoiceTypeDecimals, ROUNDING); } else { billingAmount = orderItem.getBigDecimal("unitPrice").setScale(invoiceTypeDecimals, ROUNDING); } @@ -572,8 +574,9 @@ 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")); } @@ -1040,7 +1043,8 @@ public class InvoiceServices { for (Map<String, Object> commissionMap : itemCommissions) { commissionMap.put("invoice", invoice); commissionMap.put("appliedFraction", appliedFraction); - if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) { + if (!billFromVendorInvoiceRoles.contains(commissionMap.get("partyIdFrom")) + || !salesRepPartyIds.contains(commissionMap.get("partyIdTo"))) { continue; } String partyIdFromTo = (String) commissionMap.get("partyIdFrom") + (String) commissionMap.get("partyIdTo"); @@ -1816,7 +1820,8 @@ public class InvoiceServices { // all at once. BigDecimal totalNewAuthAmount = totalAdditionalShippingCharges.setScale(DECIMALS, ROUNDING); for (GenericValue orderPaymentPreference : orderPaymentPreferences) { - if (!("PAYMENT_SETTLED".equals(orderPaymentPreference.getString("statusId")) || "PAYMENT_CANCELLED".equals(orderPaymentPreference.getString("statusId")))) { + if (!("PAYMENT_SETTLED".equals(orderPaymentPreference.getString("statusId")) || "PAYMENT_CANCELLED" + .equals(orderPaymentPreference.getString("statusId")))) { GenericValue authTransaction = PaymentGatewayServices.getAuthTransaction(orderPaymentPreference); if (authTransaction != null && authTransaction.get("amount") != null) { @@ -1936,11 +1941,13 @@ public class InvoiceServices { try { if (UtilValidate.isNotEmpty(key1)) { itemMap = - EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key1, "invoiceTypeId", invoiceTypeId).cache().queryOne(); + 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(); + EntityQuery.use(delegator).from("InvoiceItemTypeMap").where("invoiceItemMapKey", key2, "invoiceTypeId", + invoiceTypeId).cache().queryOne(); } } catch (GenericEntityException e) { Debug.logError(e, "Trouble getting InvoiceItemTypeMap entity record", MODULE); @@ -2253,8 +2260,8 @@ public class InvoiceServices { for (GenericValue adjustment : adjustments) { if (adjustment.get("amount") == null) { - Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId") + "] has null amount and will be skipped" - , MODULE); + Debug.logWarning("Return adjustment [" + adjustment.get("returnAdjustmentId") + + "] has null amount and will be skipped", MODULE); continue; } @@ -2942,11 +2949,13 @@ public class InvoiceServices { } else { currencyUomId = payment.getString("actualCurrencyUomId"); if (!currencyUomId.equals(invoice.getString("currencyUomId"))) { - errorMessageList.add("actual currency on payment (" + currencyUomId + ") not the same as original invoice currency (" + invoice.getString("currencyUomId") + ")"); + 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); + payment.getBigDecimal("actualCurrencyAmount").subtract(PaymentWorker.getPaymentApplied(payment)) + .setScale(DECIMALS, ROUNDING); } // check if the invoice already covered by payments @@ -2961,10 +2970,9 @@ public class InvoiceServices { if (invoiceApplyAvailable.signum() == 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceCompletelyApplied", UtilMisc.toMap("invoiceId", invoiceId), locale)); - } - // check here for too much application if a new record(s) are - // added (paymentApplicationId == null) - else if (amountApplied.compareTo(invoiceApplyAvailable) > 0) { + // check here for too much application if a new record(s) are + // added (paymentApplicationId == null) + } else if (amountApplied.compareTo(invoiceApplyAvailable) > 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceLessRequested", UtilMisc.<String, Object>toMap("invoiceId", invoiceId, "invoiceApplyAvailable", invoiceApplyAvailable, @@ -3015,7 +3023,8 @@ public class InvoiceServices { quantity = invoiceItem.getBigDecimal("quantity").setScale(DECIMALS, ROUNDING); } invoiceItemApplyAvailable = - invoiceItem.getBigDecimal("amount").multiply(quantity).setScale(DECIMALS, ROUNDING).subtract(InvoiceWorker.getInvoiceItemApplied(invoiceItem)); + 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 @@ -3129,8 +3138,8 @@ public class InvoiceServices { // record for the whole invoice if (invoiceItemSeqId == null && paymentApplication.get("invoiceItemSeqId") == null) { newInvoiceApplyAvailable = - invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied).setScale(DECIMALS - , ROUNDING); + invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")).subtract(amountApplied) + .setScale(DECIMALS, ROUNDING); if (invoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceNotEnough", @@ -3140,8 +3149,8 @@ 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); + invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")) + .subtract(amountApplied).setScale(DECIMALS, ROUNDING); if (invoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceNotEnough", @@ -3163,7 +3172,8 @@ public class InvoiceServices { // 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); + invoiceItemApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied")) + .subtract(amountApplied).setScale(DECIMALS, ROUNDING); if (newInvoiceItemApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingItemInvoiceNotEnough", @@ -3197,8 +3207,8 @@ public class InvoiceServices { // check the invoice newInvoiceApplyAvailable = - invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied").subtract(amountApplied)).setScale(DECIMALS, - ROUNDING); + invoiceApplyAvailable.add(paymentApplication.getBigDecimal("amountApplied") + .subtract(amountApplied)).setScale(DECIMALS, ROUNDING); if (newInvoiceApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingInvoiceNotEnough", @@ -3213,8 +3223,8 @@ public class InvoiceServices { // changed, if (toPaymentId != null && toPaymentId.equals(paymentApplication.getString("toPaymentId"))) { newToPaymentApplyAvailable = - toPaymentApplyAvailable.subtract(paymentApplication.getBigDecimal("amountApplied")).add(amountApplied).setScale(DECIMALS, - ROUNDING); + toPaymentApplyAvailable.subtract(paymentApplication.getBigDecimal("amountApplied")) + .add(amountApplied).setScale(DECIMALS, ROUNDING); if (newToPaymentApplyAvailable.compareTo(BigDecimal.ZERO) < 0) { errorMessageList.add(UtilProperties.getMessage(RESOURCE, "AccountingPaymentNotEnough", @@ -3250,7 +3260,9 @@ 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); @@ -3268,7 +3280,8 @@ public class InvoiceServices { UtilMisc.toMap("paymentId", toPaymentId), locale); } if (taxAuthGeoId != null) { - Debug.logInfo(" taxAuthGeoId(" + taxAuthGeoId + ") Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + " Requested amount to apply:" + amountApplied, MODULE); + Debug.logInfo(" taxAuthGeoId(" + taxAuthGeoId + ") Payment(" + paymentId + ") amount not yet applied: " + newPaymentApplyAvailable + + " Requested amount to apply:" + amountApplied, MODULE); toMessage = UtilProperties.getMessage(RESOURCE, "AccountingApplicationToTax", UtilMisc.toMap("taxAuthGeoId", taxAuthGeoId), locale); @@ -3529,10 +3542,11 @@ public class InvoiceServices { // if new record add to the already existing one. if (paymentApplication.get("paymentApplicationId") == null) { // add 2 amounts together - checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied"). - add(checkAppl.getBigDecimal("amountApplied")).setScale(DECIMALS, ROUNDING)); + checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied") + .add(checkAppl.getBigDecimal("amountApplied")).setScale(DECIMALS, ROUNDING)); if (debug) { - Debug.logInfo("Update paymentApplication record: " + checkAppl.getString("paymentApplicationId") + " with appliedAmount:" + checkAppl.getBigDecimal("amountApplied"), MODULE); + Debug.logInfo("Update paymentApplication record: " + checkAppl.getString("paymentApplicationId") + " with appliedAmount:" + + checkAppl.getBigDecimal("amountApplied"), MODULE); } try { checkAppl.store(); @@ -3543,7 +3557,8 @@ public class InvoiceServices { // update existing record in-place checkAppl.set("amountApplied", paymentApplication.getBigDecimal("amountApplied")); if (debug) { - Debug.logInfo("Update paymentApplication record: " + checkAppl.getString("paymentApplicationId") + " with appliedAmount:" + checkAppl.getBigDecimal("amountApplied"), MODULE); + Debug.logInfo("Update paymentApplication record: " + checkAppl.getString("paymentApplicationId") + " with appliedAmount:" + + checkAppl.getBigDecimal("amountApplied"), MODULE); } try { checkAppl.store(); @@ -3552,8 +3567,8 @@ public class InvoiceServices { } } 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)); + 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 " @@ -3566,7 +3581,8 @@ public class InvoiceServices { } // update amount existing record if (debug) { - Debug.logInfo("Update paymentApplication record: " + checkAppl.getString("paymentApplicationId") + " with appliedAmount:" + checkAppl.getBigDecimal("amountApplied"), MODULE); + Debug.logInfo("Update paymentApplication record: " + checkAppl.getString("paymentApplicationId") + " with appliedAmount:" + + checkAppl.getBigDecimal("amountApplied"), MODULE); } try { checkAppl.store(); @@ -3699,29 +3715,34 @@ public class InvoiceServices { + "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); + 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); } 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() + ": 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); } - Boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get( + boolean isPurchaseInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get( "invoiceTypeId"), "parentTypeId", "PURCHASE_INVOICE"); - Boolean isSalesInvoice = EntityTypeUtil.hasParentType(delegator, "InvoiceType", "invoiceTypeId", (String) invoice.get( + 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); + + "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); + + "the organizationPartyId(=" + organizationPartyId + ")! however is " + invoice.get("partyIdFrom") + "! invoice: " + + currentInvoiceId); } @@ -3768,10 +3789,12 @@ public class InvoiceServices { newErrMsgs = new LinkedList<>(); try { if (UtilValidate.isEmpty(invoiceItem.get("invoiceItemSeqId"))) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory item sequence Id missing for invoice: " + currentInvoiceId); + newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory item sequence Id missing for invoice: " + + currentInvoiceId); } if (UtilValidate.isEmpty(invoiceItem.get("invoiceItemTypeId"))) { - newErrMsgs.add("Line number " + rec.getRecordNumber() + ": Mandatory invoice item type missing for invoice: " + currentInvoiceId); + 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( @@ -3820,7 +3843,8 @@ public class InvoiceServices { return ServiceUtil.returnError(errMsgs); } - Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(RESOURCE, "AccountingNewInvoicesCreated", UtilMisc.toMap("invoicesCreated", invoicesCreated), locale)); + Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(RESOURCE, "AccountingNewInvoicesCreated", + UtilMisc.toMap("invoicesCreated", invoicesCreated), locale)); result.put("organizationPartyId", organizationPartyId); return result; } diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/test/FinAccountTests.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/test/FinAccountTests.java index 6037788..c24099c 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/test/FinAccountTests.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/test/FinAccountTests.java @@ -36,6 +36,10 @@ public class FinAccountTests extends OFBizTestCase { super(name); } + /** + * Test fin account operations. + * @throws Exception the exception + */ public void testFinAccountOperations() throws Exception { GenericValue userLogin = getUserLogin("system"); Map<String, Object> ctx = new HashMap<>(); @@ -43,13 +47,13 @@ public class FinAccountTests extends OFBizTestCase { ctx.put("finAccountName", "Test Financial Account"); ctx.put("finAccountTypeId", "BANK_ACCOUNT"); ctx.put("userLogin", userLogin); - Map<String, Object> resp = dispatcher.runSync("createFinAccount", ctx); + Map<String, Object> resp = getDispatcher().runSync("createFinAccount", ctx); assertTrue("Service 'createFinAccount' result success", ServiceUtil.isSuccess(resp)); ctx.clear(); ctx.put("finAccountId", "TESTACCOUNT1"); ctx.put("amount", new BigDecimal("100.00")); ctx.put("userLogin", userLogin); - resp = dispatcher.runSync("finAccountDeposit", ctx); + resp = getDispatcher().runSync("finAccountDeposit", ctx); assertTrue("Service 'finAccountDeposit' result success", ServiceUtil.isSuccess(resp)); BigDecimal balance = (BigDecimal) resp.get("balance"); assertEquals(balance.toPlainString(), "100.00"); @@ -57,7 +61,7 @@ public class FinAccountTests extends OFBizTestCase { ctx.put("finAccountId", "TESTACCOUNT1"); ctx.put("amount", new BigDecimal("50.00")); ctx.put("userLogin", userLogin); - resp = dispatcher.runSync("finAccountWithdraw", ctx); + resp = getDispatcher().runSync("finAccountWithdraw", ctx); assertTrue("Service 'finAccountWithdraw' result success", ServiceUtil.isSuccess(resp)); BigDecimal previousBalance = (BigDecimal) resp.get("previousBalance"); balance = ((BigDecimal) resp.get("balance")); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AuthorizeResponse.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AuthorizeResponse.java index 99c6ced..97a33b8 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AuthorizeResponse.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/authorizedotnet/AuthorizeResponse.java @@ -42,11 +42,11 @@ public class AuthorizeResponse { public static final String AVS_RESULT_CODE = "AVS_RESULT_CODE"; public static final String CVV_RESULT_CODE = "CVV_RESULT_CODE"; public static final String TRANSACTION_ID = "TRANSACTION_ID"; - public static final String AMOUNT = "AMOUNT"; + public static final String AMOUNT = "AMOUNT"; // singletons - private static final AIMRespPositions aimPos = new AIMRespPositions(); - private static final CPRespPositions cpPos = new CPRespPositions(); + private static final AIMRespPositions AIM_POS = new AIMRespPositions(); + private static final CPRespPositions CP_POS = new CPRespPositions(); public AuthorizeResponse(String resp, int responseType) { this(resp, "\\|", responseType); @@ -55,35 +55,80 @@ public class AuthorizeResponse { this.rawResp = resp; this.response = resp.split(delim); if (responseType == CP_RESPONSE) { - pos = cpPos; + pos = CP_POS; } else { - pos = aimPos; + pos = AIM_POS; } } + + /** + * Is approved boolean. + * @return the boolean + */ public boolean isApproved() { return pos.getApprovalString().equals(getResponseCode()); } + + /** + * Gets transaction id. + * @return the transaction id + */ public String getTransactionId() { return getResponseField(TRANSACTION_ID); } + + /** + * Gets authorization code. + * @return the authorization code + */ public String getAuthorizationCode() { return getResponseField(AUTHORIZATION_CODE); } + + /** + * Gets response code. + * @return the response code + */ public String getResponseCode() { return getResponseField(RESPONSE_CODE); } + + /** + * Gets reason code. + * @return the reason code + */ public String getReasonCode() { return getResponseField(REASON_CODE); } + + /** + * Gets reason text. + * @return the reason text + */ public String getReasonText() { return getResponseField(REASON_TEXT); } + + /** + * Gets avs result. + * @return the avs result + */ public String getAvsResult() { return getResponseField(AVS_RESULT_CODE); } + + /** + * Gets cv result. + * @return the cv result + */ public String getCvResult() { return getResponseField(CVV_RESULT_CODE); } + + /** + * Gets amount. + * @return the amount + */ public BigDecimal getAmount() { BigDecimal amount = BigDecimal.ZERO; String amtStr = getResponseField(AMOUNT); @@ -92,6 +137,11 @@ public class AuthorizeResponse { } return amount; } + + /** + * Gets raw response. + * @return the raw response + */ public String getRawResponse() { return this.rawResp; } @@ -107,7 +157,7 @@ public class AuthorizeResponse { return null; } else { // positions always start at 1; arrays start at 0 - return response[position-1]; + return response[position - 1]; } } @Override diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/clearcommerce/CCServicesTest.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/clearcommerce/CCServicesTest.java index 49f283f..16f14ef 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/clearcommerce/CCServicesTest.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/clearcommerce/CCServicesTest.java @@ -90,7 +90,7 @@ public class CCServicesTest extends OFBizTestCase { serviceInput.put("processAmount", new BigDecimal("200.00")); // run the service (make sure in payment - Map<String, Object> result = dispatcher.runSync("clearCommerceCCAuth", serviceInput); + Map<String, Object> result = getDispatcher().runSync("clearCommerceCCAuth", serviceInput); // verify the results String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); @@ -122,7 +122,7 @@ public class CCServicesTest extends OFBizTestCase { "creditCard", creditCard, "creditAmount", new BigDecimal("200.00")); // run the service - Map<String, Object> result = dispatcher.runSync("clearCommerceCCCredit", serviceMap); + Map<String, Object> result = getDispatcher().runSync("clearCommerceCCCredit", serviceMap); // verify the results String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); @@ -156,7 +156,7 @@ public class CCServicesTest extends OFBizTestCase { serviceMap.put("creditAmount", new BigDecimal("200.00")); // run the service - Map<String, Object> result = dispatcher.runSync("clearCommerceCCCredit", serviceMap); + Map<String, Object> result = getDispatcher().runSync("clearCommerceCCCredit", serviceMap); // verify the results String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); @@ -208,7 +208,7 @@ public class CCServicesTest extends OFBizTestCase { "paymentConfig", configFile); // run the service - Map<String, Object> result = dispatcher.runSync("clearCommerceCCReport", serviceMap); + Map<String, Object> result = getDispatcher().runSync("clearCommerceCCReport", serviceMap); // verify the results String responseMessage = (String) result.get(ModelService.RESPONSE_MESSAGE); diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/gosoftware/PcChargeApi.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/gosoftware/PcChargeApi.java index 32e5a13..d707f8e 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/gosoftware/PcChargeApi.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/gosoftware/PcChargeApi.java @@ -36,9 +36,9 @@ import org.xml.sax.SAXException; public class PcChargeApi { private static final String MODULE = PcChargeApi.class.getName(); - public static final String xschema = "x-schema:..\\dtd\\stnd.xdr"; - public static final String rootElement = "XML_FILE"; - public static final String reqElement = "XML_REQUEST"; + public static final String X_SCHEMA = "x-schema:..\\dtd\\stnd.xdr"; + public static final String ROOT_ELEMENT = "XML_FILE"; + public static final String REQ_ELEMENT = "XML_REQUEST"; public static final String USER_ID = "USER_ID"; public static final String USER_PW = "USER_PW"; @@ -77,43 +77,43 @@ public class PcChargeApi { public static final String CARD_ID_CODE = "CARD_ID_CODE"; public static final String CVV2_CODE = "CVV2_CODE"; - private static final String[] validOut = {RESULT, TRANS_DATE, AVS_CODE, CVV2_CODE, CARD_ID_CODE, TICKET }; - private static final String[] validIn = {PROCESSOR_ID, MERCH_NUM, ACCT_NUM, EXP_DATE, TRANS_AMOUNT, TRACK_DATA, + private static final String[] VALID_OUT = {RESULT, TRANS_DATE, AVS_CODE, CVV2_CODE, CARD_ID_CODE, TICKET }; + private static final String[] VALID_IN = {PROCESSOR_ID, MERCH_NUM, ACCT_NUM, EXP_DATE, TRANS_AMOUNT, TRACK_DATA, CUSTOMER_CODE, TAX_AMOUNT, PRINT_RECEIPTS_FLAG, PERIODIC_PAYMENT_FLAG, OFFLINE_FLAG, VOID_FLAG, ZIP_CODE, STREET, TICKET_NUM, CARDHOLDER, TRANS_STORE, TOTAL_AUTH, MULTI_FLAG, PRESENT_FLAG, CVV2 }; protected static final int MODE_OUT = 20; protected static final int MODE_IN = 10; - protected Document document = null; - protected Element req = null; - protected String host = null; - protected int port = 0; - protected int mode = 0; + private Document document = null; + private Element req = null; + private String host = null; + private int port = 0; + private int mode = 0; public PcChargeApi(Document document) { this.document = document; Element rootElement = this.document.getDocumentElement(); - if (reqElement.equals(rootElement.getNodeName())) { + if (REQ_ELEMENT.equals(rootElement.getNodeName())) { this.req = rootElement; } else { - this.req = UtilXml.firstChildElement(rootElement, reqElement); + this.req = UtilXml.firstChildElement(rootElement, REQ_ELEMENT); } this.mode = MODE_OUT; } public PcChargeApi(boolean isFile) { // initialize the document - String initialElement = rootElement; + String initialElement = ROOT_ELEMENT; if (!isFile) { - initialElement = reqElement; + initialElement = REQ_ELEMENT; } this.document = UtilXml.makeEmptyXmlDocument(initialElement); Element root = this.document.getDocumentElement(); if (isFile) { - root.setAttribute("xmlns", xschema); - this.req = UtilXml.addChildElement(root, reqElement, document); + root.setAttribute("xmlns", X_SCHEMA); + this.req = UtilXml.addChildElement(root, REQ_ELEMENT, document); } else { this.req = root; } @@ -130,6 +130,11 @@ public class PcChargeApi { this(true); } + /** + * Set. + * @param name the name + * @param value the value + */ public void set(String name, Object value) { if (!checkIn(name)) { throw new IllegalArgumentException("Field [" + name + "] is not a valid IN parameter"); @@ -152,6 +157,11 @@ public class PcChargeApi { UtilXml.addChildElementValue(req, name, objString, document); } + /** + * Get string. + * @param name the name + * @return the string + */ public String get(String name) { if (!checkOut(name)) { throw new IllegalArgumentException("Field [" + name + "] is not a valid OUT parameter"); @@ -170,10 +180,20 @@ public class PcChargeApi { } } + /** + * Gets document. + * @return the document + */ public Document getDocument() { return this.document; } + /** + * Send pc charge api. + * @return the pc charge api + * @throws IOException the io exception + * @throws GeneralException the general exception + */ public PcChargeApi send() throws IOException, GeneralException { if (host == null || port == 0) { throw new GeneralException("TCP transaction not supported without valid host/port configuration"); @@ -208,7 +228,7 @@ public class PcChargeApi { } private static boolean checkIn(String name) { - for (String element : validOut) { + for (String element : VALID_OUT) { if (name.equals(element)) { return false; } @@ -217,7 +237,7 @@ public class PcChargeApi { } private static boolean checkOut(String name) { - for (String element : validIn) { + for (String element : VALID_IN) { if (name.equals(element)) { return false; } 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 f0df0dc..fd02b24 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 @@ -63,7 +63,7 @@ public class PayPalEvents { private static final String RESOURCE = "AccountingUiLabels"; private static final String RES_ERROR = "AccountingErrorUiLabels"; - public static final String commonResource = "CommonUiLabels"; + public static final String COMMON_RES = "CommonUiLabels"; private static final String MODULE = PayPalEvents.class.getName(); /** Initiate PayPal Request */ @@ -94,12 +94,14 @@ public class PayPalEvents { if (productStore == null) { Debug.logError("ProductStore is null", 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"; } // get the payment properties file - GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), "EXT_PAYPAL", null, true); + GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), + "EXT_PAYPAL", null, true); String configString = null; String paymentGatewayConfigId = null; if (paymentConfig != null) { @@ -116,7 +118,7 @@ public class PayPalEvents { // create the item name String itemName = UtilProperties.getMessage(RESOURCE, "AccountingOrderNr", locale) + orderId + " " - + (company != null ? UtilProperties.getMessage(commonResource, "CommonFrom", locale) + " "+ company : ""); + + (company != null ? UtilProperties.getMessage(COMMON_RES, "CommonFrom", locale) + " " + company : ""); String itemNumber = "0"; // get the redirect url @@ -129,7 +131,8 @@ public class PayPalEvents { String returnUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "returnUrl", configString, "payment.paypal.return"); // get the cancel return urls - String cancelReturnUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "cancelReturnUrl", configString, "payment.paypal.cancelReturn"); + String cancelReturnUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "cancelReturnUrl", + configString, "payment.paypal.cancelReturn"); // get the image url String imageUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "imageUrl", configString, "payment.paypal.image"); @@ -195,12 +198,14 @@ public class PayPalEvents { GenericValue productStore = ProductStoreWorker.getProductStore(request); if (productStore == null) { Debug.logError("ProductStore is null", 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"; } // get the payment properties file - GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), "EXT_PAYPAL", null, true); + GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), + "EXT_PAYPAL", null, true); String configString = null; String paymentGatewayConfigId = null; @@ -214,14 +219,17 @@ public class PayPalEvents { } // get the confirm URL - String confirmUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "confirmUrl", configString, "payment.paypal.confirm"); + String confirmUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "confirmUrl", + configString, "payment.paypal.confirm"); // get the redirect URL - String redirectUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "redirectUrl", configString, "payment.paypal.redirect"); + String redirectUrl = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "redirectUrl", + configString, "payment.paypal.redirect"); if (UtilValidate.isEmpty(confirmUrl) || UtilValidate.isEmpty(redirectUrl)) { Debug.logError("Payment properties is not configured properly, no confirm URL 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"; } @@ -252,8 +260,8 @@ public class PayPalEvents { for (String name : parametersMap.keySet()) { String value = request.getParameter(name); Debug.logError("### Param: " + name + " => " + value, MODULE); - if (UtilValidate.isNotEmpty(name) && "payer_status".equalsIgnoreCase(name) - && UtilValidate.isNotEmpty(value) && "verified".equalsIgnoreCase(value)) { + if (UtilValidate.isNotEmpty(name) && "payer_status".equalsIgnoreCase(name) && UtilValidate.isNotEmpty(value) + && "verified".equalsIgnoreCase(value)) { verified = true; } } @@ -388,11 +396,13 @@ public class PayPalEvents { return "success"; } - private static boolean setPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, HttpServletRequest request) { + private static boolean setPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, + String orderId, HttpServletRequest request) { Debug.logVerbose("Setting payment prefrences..", MODULE); List<GenericValue> paymentPrefs = null; try { - paymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED").queryList(); + paymentPrefs = EntityQuery.use(delegator).from("OrderPaymentPreference").where("orderId", orderId, "statusId", "PAYMENT_NOT_RECEIVED") + .queryList(); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get payment preferences for order #" + orderId, MODULE); return false; @@ -400,14 +410,16 @@ public class PayPalEvents { if (!paymentPrefs.isEmpty()) { for (GenericValue pref : paymentPrefs) { boolean okay = setPaymentPreference(dispatcher, userLogin, pref, request); - if (!okay) + if (!okay) { return false; + } } } return true; } - private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, HttpServletRequest request) { + private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, + HttpServletRequest request) { Locale locale = UtilHttp.getLocale(request); String paymentDate = request.getParameter("payment_date"); String paymentType = request.getParameter("payment_type"); @@ -454,7 +466,7 @@ public class PayPalEvents { response.set("amount", new BigDecimal(paymentAmount)); response.set("referenceNum", transactionId); response.set("gatewayCode", paymentStatus); - response.set("gatewayFlag", paymentStatus.substring(0,1)); + response.set("gatewayFlag", paymentStatus.substring(0, 1)); response.set("gatewayMessage", paymentType); response.set("transactionDate", authDate); toStore.add(response); @@ -474,7 +486,8 @@ public class PayPalEvents { "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "comments", comment)); } catch (GenericServiceException e) { Debug.logError(e, "Failed to execute service createPaymentFromPreference", MODULE); - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "payPalEvents.failedToExecuteServiceCreatePaymentFromPreference", locale)); + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, + "payPalEvents.failedToExecuteServiceCreatePaymentFromPreference", locale)); return false; } @@ -492,7 +505,8 @@ public class PayPalEvents { String returnValue = ""; if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { try { - GenericValue payPal = EntityQuery.use(delegator).from("PaymentGatewayPayPal").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); + GenericValue payPal = EntityQuery.use(delegator).from("PaymentGatewayPayPal").where("paymentGatewayConfigId", + paymentGatewayConfigId).queryOne(); if (payPal != null) { String payPalField = payPal.getString(paymentGatewayConfigParameterName); if (payPalField != null) { diff --git a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/worldpay/WorldPayEvents.java b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/worldpay/WorldPayEvents.java index a9c0cf7..3bd05f5 100644 --- a/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/worldpay/WorldPayEvents.java +++ b/applications/accounting/src/main/java/org/apache/ofbiz/accounting/thirdparty/worldpay/WorldPayEvents.java @@ -57,7 +57,7 @@ public class WorldPayEvents { private static final String RESOURCE = "AccountingUiLabels"; private static final String RES_ERROR = "AccountingErrorUiLabels"; - public static final String commonResource = "CommonUiLabels"; + public static final String COMMON_RES = "CommonUiLabels"; private static final String MODULE = WorldPayEvents.class.getName(); public static String worldPayRequest(HttpServletRequest request, HttpServletResponse response) { @@ -80,11 +80,13 @@ public class WorldPayEvents { GenericValue productStore = ProductStoreWorker.getProductStore(request); if (productStore == null) { Debug.logError("ProductStore is null", MODULE); - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "worldPayEvents.problemsGettingMerchantConfiguration", locale)); + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "worldPayEvents.problemsGettingMerchantConfiguration", + locale)); return "error"; } // get the payment properties file - GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), "EXT_WORLDPAY", null, true); + GenericValue paymentConfig = ProductStoreWorker.getProductStorePaymentSetting(delegator, productStore.getString("productStoreId"), + "EXT_WORLDPAY", null, true); String configString = null; String paymentGatewayConfigId = null; if (paymentConfig != null) { @@ -94,28 +96,41 @@ public class WorldPayEvents { if (configString == null) { configString = "payment.properties"; } - String redirectURL = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "redirectUrl", configString, "payment.worldpay.redirectUrl", ""); - String instId = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "instId", configString, "payment.worldpay.instId", "NONE"); - String authMode = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "authMode", configString, "payment.worldpay.authMode", "A"); - String fixContact = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "fixContact", configString, "payment.worldpay.fixContact", "N"); - String hideContact = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "hideContact", configString, "payment.worldpay.hideContact", "N"); - String hideCurrency = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "hideCurrency", configString, "payment.worldpay.hideCurrency", "N"); - String langId = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "langId", configString, "payment.worldpay.langId", ""); - String noLanguageMenu = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "noLanguageMenu", configString, "payment.worldpay.noLanguageMenu", "N"); - String withDelivery = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "withDelivery", configString, "payment.worldpay.withDelivery", "N"); - String testMode = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "testMode", configString, "payment.worldpay.testMode", "100"); + String redirectURL = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "redirectUrl", + configString, "payment.worldpay.redirectUrl", ""); + String instId = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "instId", + configString, "payment.worldpay.instId", "NONE"); + String authMode = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "authMode", + configString, "payment.worldpay.authMode", "A"); + String fixContact = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "fixContact", + configString, "payment.worldpay.fixContact", "N"); + String hideContact = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "hideContact", + configString, "payment.worldpay.hideContact", "N"); + String hideCurrency = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "hideCurrency", + configString, "payment.worldpay.hideCurrency", "N"); + String langId = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "langId", + configString, "payment.worldpay.langId", ""); + String noLanguageMenu = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "noLanguageMenu", + configString, "payment.worldpay.noLanguageMenu", "N"); + String withDelivery = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "withDelivery", + configString, "payment.worldpay.withDelivery", "N"); + String testMode = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, "testMode", + configString, "payment.worldpay.testMode", "100"); // get the contact address to pass over GenericValue contactAddress = null; GenericValue contactAddressShip = null; GenericValue addressOcm = null; GenericValue shippingAddress = null; try { - addressOcm = EntityQuery.use(delegator).from("OrderContactMech").where("orderId", orderId, "contactMechPurposeTypeId", "BILLING_LOCATION").queryFirst(); - shippingAddress = EntityQuery.use(delegator).from("OrderContactMech").where("orderId", orderId, "contactMechPurposeTypeId", "SHIPPING_LOCATION").queryFirst(); + addressOcm = EntityQuery.use(delegator).from("OrderContactMech").where("orderId", orderId, + "contactMechPurposeTypeId", "BILLING_LOCATION").queryFirst(); + shippingAddress = EntityQuery.use(delegator).from("OrderContactMech").where("orderId", orderId, "contactMechPurposeTypeId", + "SHIPPING_LOCATION").queryFirst(); if (addressOcm == null) { addressOcm = shippingAddress; } - contactAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", addressOcm.getString("contactMechId")).queryOne(); + contactAddress = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", + addressOcm.getString("contactMechId")).queryOne(); } catch (GenericEntityException e) { Debug.logWarning(e, "Problems getting order contact information", MODULE); } @@ -135,10 +150,11 @@ public class WorldPayEvents { // string of customer's name String name = ""; if (contactAddress != null) { - if (UtilValidate.isNotEmpty(contactAddress.getString("attnName"))) + if (UtilValidate.isNotEmpty(contactAddress.getString("attnName"))) { name = contactAddress.getString("attnName"); - else if (UtilValidate.isNotEmpty(contactAddress.getString("toName"))) + } else if (UtilValidate.isNotEmpty(contactAddress.getString("toName"))) { name = contactAddress.getString("toName"); + } } // build an address string StringBuilder address = new StringBuilder(); @@ -173,7 +189,8 @@ public class WorldPayEvents { String emailAddress = null; GenericValue emailContact = null; try { - GenericValue emailOcm = EntityQuery.use(delegator).from("OrderContactMech").where("orderId", orderId, "contactMechPurposeTypeId", "ORDER_EMAIL").queryFirst(); + GenericValue emailOcm = EntityQuery.use(delegator).from("OrderContactMech").where("orderId", orderId, + "contactMechPurposeTypeId", "ORDER_EMAIL").queryFirst(); emailContact = emailOcm.getRelatedOne("ContactMech", false); emailAddress = emailContact.getString("infoString"); } catch (GenericEntityException e) { @@ -185,7 +202,8 @@ public class WorldPayEvents { String shipName = ""; if (shippingAddress != null) { try { - contactAddressShip = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", shippingAddress.get("contactMechId")).queryOne(); + contactAddressShip = EntityQuery.use(delegator).from("PostalAddress").where("contactMechId", shippingAddress.get("contactMechId")) + .queryOne(); if (UtilValidate.isNotEmpty(contactAddressShip)) { if (UtilValidate.isNotEmpty(contactAddressShip.getString("attnName"))) { shipName = contactAddressShip.getString("attnName"); @@ -227,7 +245,7 @@ public class WorldPayEvents { String defCur = UtilFormatOut.checkEmpty(productStore.getString("defaultCurrencyUomId"), "USD"); // order description String description = UtilProperties.getMessage(RESOURCE, "AccountingOrderNr", locale) + orderId + " " - + (company != null ? UtilProperties.getMessage(commonResource, "CommonFrom", locale) + " " + company : ""); + + (company != null ? UtilProperties.getMessage(COMMON_RES, "CommonFrom", locale) + " " + company : ""); // check the instId - very important if (instId == null || "NONE".equals(instId)) { Debug.logError("Worldpay InstId not found, cannot continue", MODULE); @@ -323,7 +341,8 @@ public class WorldPayEvents { userLogin = EntityQuery.use(delegator).from("UserLogin").where("userLoginId", userLoginId).queryOne(); } catch (GenericEntityException e) { Debug.logError(e, "Cannot get UserLogin for: " + userLoginId + "; cannot continue", MODULE); - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "worldPayEvents.problemsGettingAuthenticationUser", locale)); + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "worldPayEvents.problemsGettingAuthenticationUser", + locale)); return "error"; } } @@ -400,7 +419,8 @@ public class WorldPayEvents { return "success"; } - private static boolean setPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, HttpServletRequest request) { + private static boolean setPaymentPreferences(Delegator delegator, LocalDispatcher dispatcher, GenericValue userLogin, String orderId, + HttpServletRequest request) { if (Debug.verboseOn()) { Debug.logVerbose("Setting payment preferences..", MODULE); } @@ -423,7 +443,8 @@ public class WorldPayEvents { return true; } - private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, HttpServletRequest request) { + private static boolean setPaymentPreference(LocalDispatcher dispatcher, GenericValue userLogin, GenericValue paymentPreference, + HttpServletRequest request) { Locale locale = UtilHttp.getLocale(request); String paymentStatus = request.getParameter("transStatus"); String paymentAmount = request.getParameter("authAmount"); @@ -481,7 +502,8 @@ public class WorldPayEvents { "orderPaymentPreferenceId", paymentPreference.get("orderPaymentPreferenceId"), "comments", comment)); } catch (GenericServiceException e) { Debug.logError(e, "Failed to execute service createPaymentFromPreference", MODULE); - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, "worldPayEvents.failedToExecuteServiceCreatePaymentFromPreference", locale)); + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage(RES_ERROR, + "worldPayEvents.failedToExecuteServiceCreatePaymentFromPreference", locale)); return false; } @@ -498,7 +520,8 @@ public class WorldPayEvents { String returnValue = ""; if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { try { - GenericValue worldPay = EntityQuery.use(delegator).from("PaymentGatewayWorldPay").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); + GenericValue worldPay = EntityQuery.use(delegator).from("PaymentGatewayWorldPay").where("paymentGatewayConfigId", + paymentGatewayConfigId).queryOne(); if (UtilValidate.isNotEmpty(worldPay)) { Object worldPayField = worldPay.get(paymentGatewayConfigParameterName); if (worldPayField != null) { @@ -518,7 +541,8 @@ public class WorldPayEvents { } private static String getPaymentGatewayConfigValue(Delegator delegator, String paymentGatewayConfigId, String paymentGatewayConfigParameterName, String resource, String parameterName, String defaultValue) { - String returnValue = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, paymentGatewayConfigParameterName, resource, parameterName); + String returnValue = getPaymentGatewayConfigValue(delegator, paymentGatewayConfigId, paymentGatewayConfigParameterName, + resource, parameterName); if (UtilValidate.isEmpty(returnValue)) { returnValue = defaultValue; } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/ConvertTree.java b/applications/content/src/main/java/org/apache/ofbiz/content/ConvertTree.java index 9e3a98f..ac11beb 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/ConvertTree.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/ConvertTree.java @@ -64,45 +64,46 @@ In order to make this service active add the following to the service definition */ - public static Map<String, Object> convertTree(DispatchContext dctx, Map<String, ? extends Object> context) { + public static Map<String, Object> convertTree(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); GenericValue userLogin = (GenericValue) context.get("userLogin"); String file = (String) context.get("file"); Map<String, Object> result = new HashMap<>(); - String errMsg = "", sucMsg= ""; - GenericValue Entity = null; + String errMsg = ""; + String sucMsg = ""; + GenericValue entity = null; if (UtilValidate.isNotEmpty(file)) { try (BufferedReader input = new BufferedReader(new FileReader(file))) { String line = null; int size = 0; int counterLine = 0; - Entity = delegator.makeValue("Content"); - Entity.set("contentId", "ROOT"); - Entity.set("contentName", "ROOT"); - Entity.set("contentTypeId", "DOCUMENT"); - Entity.set("createdByUserLogin", userLogin.get("userLoginId")); - Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); - Entity.set("createdDate", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); - delegator.create(Entity); + entity = delegator.makeValue("Content"); + entity.set("contentId", "ROOT"); + entity.set("contentName", "ROOT"); + entity.set("contentTypeId", "DOCUMENT"); + entity.set("createdByUserLogin", userLogin.get("userLoginId")); + entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); + entity.set("createdDate", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); + entity.set("createdStamp", UtilDateTime.nowTimestamp()); + entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); + delegator.create(entity); - Entity = delegator.makeValue("Content"); - Entity.set("contentId", "HOME_DOCUMENT"); - Entity.set("contentName", "Home"); - Entity.set("contentTypeId", "DOCUMENT"); - Entity.set("createdByUserLogin", userLogin.get("userLoginId")); - Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); - Entity.set("createdDate", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); - delegator.create(Entity); + entity = delegator.makeValue("Content"); + entity.set("contentId", "HOME_DOCUMENT"); + entity.set("contentName", "Home"); + entity.set("contentTypeId", "DOCUMENT"); + entity.set("createdByUserLogin", userLogin.get("userLoginId")); + entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); + entity.set("createdDate", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); + entity.set("createdStamp", UtilDateTime.nowTimestamp()); + entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); + delegator.create(entity); Map<String, Object> contentAssoc = new HashMap<>(); contentAssoc.put("contentId", "HOME_DOCUMENT"); @@ -115,13 +116,18 @@ In order to make this service active add the following to the service definition } while ((line = input.readLine()) != null) { //start line boolean hasFolder = true; - String rootContent = null, contentId = null; counterLine++; + String rootContent = null; + String contentId = null; counterLine++; if (counterLine > 1) { size = line.length(); - String check = "\\", checkSubContent = ",", contentName = "", contentNameInprogress = "", data = line.substring(3, size); + String check = "\\"; + String checkSubContent = ","; + String contentName = ""; + String contentNameInprogress = ""; + String data = line.substring(3, size); size = data.length(); - for (int index = 0; index< size; index++) { //start character in line + for (int index = 0; index < size; index++) { //start character in line boolean contentNameMatch = false; int contentAssocSize = 0; List<GenericValue> contentAssocs = null; @@ -135,19 +141,21 @@ In order to make this service active add the following to the service definition if (content != null) { contentId = content.getString("contentId"); } - if (content != null && hasFolder == true) { + if (content != null && hasFolder) { if (rootContent != null) { contentAssocs = EntityQuery.use(delegator).from("ContentAssoc") .where("contentId", contentId, "contentIdTo", rootContent) .queryList(); - List<GenericValue> contentAssocCheck = EntityQuery.use(delegator).from("ContentAssoc").where("contentIdTo", rootContent).queryList(); + List<GenericValue> contentAssocCheck = EntityQuery.use(delegator).from("ContentAssoc") + .where("contentIdTo", rootContent).queryList(); Iterator<GenericValue> contentAssChecks = contentAssocCheck.iterator(); - while (contentAssChecks.hasNext() && contentNameMatch == false) { + while (contentAssChecks.hasNext() && !contentNameMatch) { GenericValue contentAss = contentAssChecks.next(); - GenericValue contentcheck = EntityQuery.use(delegator).from("Content").where("contentId", contentAss.get("contentId")).queryOne(); + GenericValue contentcheck = EntityQuery.use(delegator).from("Content").where("contentId", + contentAss.get("contentId")).queryOne(); if (contentcheck != null) { - if (contentcheck.get("contentName").equals(contentName) && contentNameMatch == false) { + if (contentcheck.get("contentName").equals(contentName) && !contentNameMatch) { contentNameMatch = true; contentId = contentcheck.get("contentId").toString(); } @@ -162,16 +170,16 @@ In order to make this service active add the following to the service definition contentAssocSize = contentAssocs.size(); } - if (contentAssocSize == 0 && contentNameMatch == false) { //New Root Content + if (contentAssocSize == 0 && !contentNameMatch) { //New Root Content contentId = delegator.getNextSeqId("Content"); - Entity = delegator.makeValue("Content"); - Entity.set("contentId", contentId); - Entity.set("contentName", contentName); - Entity.set("contentTypeId", "DOCUMENT"); - Entity.set("createdByUserLogin", userLogin.get("userLoginId")); - Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); - Entity.set("createdDate", UtilDateTime.nowTimestamp()); - delegator.create(Entity); + entity = delegator.makeValue("Content"); + entity.set("contentId", contentId); + entity.set("contentName", contentName); + entity.set("contentTypeId", "DOCUMENT"); + entity.set("createdByUserLogin", userLogin.get("userLoginId")); + entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); + entity.set("createdDate", UtilDateTime.nowTimestamp()); + delegator.create(entity); hasFolder = false; } else { hasFolder = true; @@ -198,7 +206,8 @@ In order to make this service active add the following to the service definition } rootContent = contentId; } else { - //Debug.logInfo("ContentAssoc [contentId= " + contentId + ", contentIdTo=" + rootContent + "] already exist.");//ShoW log file + //Debug.logInfo("ContentAssoc [contentId= " + contentId + ", contentIdTo=" + rootContent + // + "] already exist.");//ShoW log file rootContent = contentId; } contentName = ""; @@ -219,7 +228,8 @@ In order to make this service active add the following to the service definition } //end character in line } } //end line - sucMsg = UtilProperties.getMessage("ContentUiLabels", "ContentConvertDocumentsTreeSuccessful", UtilMisc.toMap("counterLine", counterLine), locale); + sucMsg = UtilProperties.getMessage("ContentUiLabels", "ContentConvertDocumentsTreeSuccessful", + UtilMisc.toMap("counterLine", counterLine), locale); } catch (IOException | GenericServiceException | GenericEntityException e) { errMsg = "Exception " + UtilMisc.toMap("errMessage", e.toString()); Debug.logError(e, errMsg, MODULE); @@ -229,14 +239,22 @@ In order to make this service active add the following to the service definition return ServiceUtil.returnSuccess(sucMsg); } - public static Map<String, Object> createSubContent(int index, String line, String rootContent, Map<String, ? extends Object> context, DispatchContext dctx) { + public static Map<String, Object> createSubContent(int index, String line, String rootContent, + Map<String, ? extends Object> context, DispatchContext dctx) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); GenericValue userLogin = (GenericValue) context.get("userLogin"); Map<String, Object> result = new HashMap<>(); - String subContents = null, check = ",", oldChar = "\"", newChar = "", contentNameInprogress = "", contentName = "", contentId = null; - GenericValue Entity = null; - String errMsg = "", sucMsg = ""; + String subContents = null; + String check = ","; + String oldChar = "\""; + String newChar = ""; + String contentNameInprogress = ""; + String contentName = ""; + String contentId = null; + GenericValue entity = null; + String errMsg = ""; + String sucMsg = ""; subContents = line.substring(index + 1, line.length()); subContents = subContents.replace(oldChar, newChar); int size = subContents.length(); @@ -245,13 +263,14 @@ In order to make this service active add the following to the service definition boolean contentNameMatch = false; if (subContents.charAt(index) == check.charAt(0)) { //store data contentName = contentName + contentNameInprogress; - if (contentName.length()>100) { - contentName = contentName.substring(0,100); + if (contentName.length() > 100) { + contentName = contentName.substring(0, 100); } - List<GenericValue> contents = EntityQuery.use(delegator).from("Content").where("contentName", contentName).orderBy("-contentId").queryList(); + List<GenericValue> contents = EntityQuery.use(delegator).from("Content").where("contentName", + contentName).orderBy("-contentId").queryList(); if (contents != null) { Iterator<GenericValue> contentCheck = contents.iterator(); - while (contentCheck.hasNext() && contentNameMatch == false) { + while (contentCheck.hasNext() && !contentNameMatch) { GenericValue contentch = contentCheck.next(); if (contentch != null) { List<GenericValue> contentAssocsChecks = EntityQuery.use(delegator).from("ContentAssoc") @@ -263,7 +282,7 @@ In order to make this service active add the following to the service definition } } } - if (contentNameMatch == false) { + if (!contentNameMatch) { //create DataResource Map<String, Object> data = new HashMap<>(); data.put("userLogin", userLogin); @@ -274,19 +293,19 @@ In order to make this service active add the following to the service definition String dataResourceId = (String) result.get("dataResourceId"); //create Content contentId = delegator.getNextSeqId("Content"); - Entity = delegator.makeValue("Content"); - Entity.set("contentId", contentId); - Entity.set("contentName", contentName); - Entity.set("contentTypeId", "DOCUMENT"); - Entity.set("dataResourceId", dataResourceId); - Entity.set("createdByUserLogin", userLogin.get("userLoginId")); - Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); - Entity.set("createdDate", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); - delegator.create(Entity); + entity = delegator.makeValue("Content"); + entity.set("contentId", contentId); + entity.set("contentName", contentName); + entity.set("contentTypeId", "DOCUMENT"); + entity.set("dataResourceId", dataResourceId); + entity.set("createdByUserLogin", userLogin.get("userLoginId")); + entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); + entity.set("createdDate", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); + entity.set("createdStamp", UtilDateTime.nowTimestamp()); + entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); + delegator.create(entity); //Relation Content Map<String, Object> contentAssoc = new HashMap<>(); @@ -300,7 +319,7 @@ In order to make this service active add the following to the service definition } } contentName = ""; - contentNameInprogress= ""; + contentNameInprogress = ""; } if ((subContents.charAt(index)) != check.charAt(0)) { @@ -316,7 +335,7 @@ In order to make this service active add the following to the service definition List<GenericValue> contents = EntityQuery.use(delegator).from("Content").where("contentName", contentName).queryList(); if (contents != null) { Iterator<GenericValue> contentCheck = contents.iterator(); - while (contentCheck.hasNext() && contentNameMatch == false) { + while (contentCheck.hasNext() && !contentNameMatch) { GenericValue contentch = contentCheck.next(); if (contentch != null) { long contentAssocCount = EntityQuery.use(delegator).from("ContentAssoc") @@ -339,19 +358,19 @@ In order to make this service active add the following to the service definition String dataResourceId = (String) result.get("dataResourceId"); //create Content contentId = delegator.getNextSeqId("Content"); - Entity = delegator.makeValue("Content"); - Entity.set("contentId", contentId); - Entity.set("contentName", contentName); - Entity.set("contentTypeId", "DOCUMENT"); - Entity.set("dataResourceId", dataResourceId); - Entity.set("createdByUserLogin", userLogin.get("userLoginId")); - Entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); - Entity.set("createdDate", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); - Entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdStamp", UtilDateTime.nowTimestamp()); - Entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); - delegator.create(Entity); + entity = delegator.makeValue("Content"); + entity.set("contentId", contentId); + entity.set("contentName", contentName); + entity.set("contentTypeId", "DOCUMENT"); + entity.set("dataResourceId", dataResourceId); + entity.set("createdByUserLogin", userLogin.get("userLoginId")); + entity.set("lastModifiedByUserLogin", userLogin.get("userLoginId")); + entity.set("createdDate", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedStamp", UtilDateTime.nowTimestamp()); + entity.set("lastUpdatedTxStamp", UtilDateTime.nowTimestamp()); + entity.set("createdStamp", UtilDateTime.nowTimestamp()); + entity.set("createdTxStamp", UtilDateTime.nowTimestamp()); + delegator.create(entity); //create ContentAssoc Map<String, Object> contentAssoc = new HashMap<>(); @@ -368,11 +387,11 @@ In order to make this service active add the following to the service definition } return ServiceUtil.returnSuccess(sucMsg); } catch (GenericEntityException e) { - errMsg = "GenericEntityException "+ UtilMisc.toMap("errMessage", e.toString()); + errMsg = "GenericEntityException " + UtilMisc.toMap("errMessage", e.toString()); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (GenericServiceException e) { - errMsg = "GenericServiceException"+ UtilMisc.toMap("errMessage", e.toString()); + errMsg = "GenericServiceException" + UtilMisc.toMap("errMessage", e.toString()); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/blog/BlogRssServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/blog/BlogRssServices.java index c3f7e4e..af908ed 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/blog/BlogRssServices.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/blog/BlogRssServices.java @@ -53,8 +53,8 @@ public class BlogRssServices { private static final String MODULE = BlogRssServices.class.getName(); private static final String RESOURCE = "ContentUiLabels"; - public static final String mimeTypeId = "text/html"; - public static final String mapKey = "SUMMARY"; + public static final String MIME_TYPE_ID = "text/html"; + public static final String MAP_KEY = "SUMMARY"; public static Map<String, Object> generateBlogRssFeed(DispatchContext dctx, Map<String, ? extends Object> context) { GenericValue userLogin = (GenericValue) context.get("userLogin"); @@ -98,7 +98,8 @@ public class BlogRssServices { return resp; } - public static List<SyndEntry> generateEntryList(LocalDispatcher dispatcher, Delegator delegator, String contentId, String entryLink, Locale locale, GenericValue userLogin) { + public static List<SyndEntry> generateEntryList(LocalDispatcher dispatcher, Delegator delegator, String contentId, + String entryLink, Locale locale, GenericValue userLogin) { List<SyndEntry> entries = new LinkedList<>(); List<GenericValue> contentRecs = null; @@ -117,7 +118,7 @@ public class BlogRssServices { String sub = null; try { Map<String, Object> dummy = new HashMap<>(); - sub = ContentWorker.renderSubContentAsText(dispatcher, v.getString("contentId"), mapKey, dummy, locale, mimeTypeId, true); + sub = ContentWorker.renderSubContentAsText(dispatcher, v.getString("contentId"), MAP_KEY, dummy, locale, MIME_TYPE_ID, true); } catch (GeneralException | IOException e) { Debug.logError(e, MODULE); } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentMapFacade.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentMapFacade.java index 5cfcfcd..67a47a4 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentMapFacade.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/ContentMapFacade.java @@ -51,17 +51,17 @@ public class ContentMapFacade implements Map<Object, Object> { private static final String MODULE = ContentMapFacade.class.getName(); - private static final Set<String> mapKeySet = new HashSet<>(); + private static final Set<String> MAP_KEY_SET = new HashSet<>(); static { - mapKeySet.add("fields"); - mapKeySet.add("link"); - mapKeySet.add("data"); - mapKeySet.add("dataresource"); - mapKeySet.add("subcontent"); - mapKeySet.add("subcontent_all"); - mapKeySet.add("metadata"); - mapKeySet.add("content"); - mapKeySet.add("render"); + MAP_KEY_SET.add("fields"); + MAP_KEY_SET.add("link"); + MAP_KEY_SET.add("data"); + MAP_KEY_SET.add("dataresource"); + MAP_KEY_SET.add("subcontent"); + MAP_KEY_SET.add("subcontent_all"); + MAP_KEY_SET.add("metadata"); + MAP_KEY_SET.add("content"); + MAP_KEY_SET.add("render"); } private final LocalDispatcher dispatcher; @@ -86,7 +86,8 @@ public class ContentMapFacade implements Map<Object, Object> { private Content content; private GenericValue fields = null; - public ContentMapFacade(LocalDispatcher dispatcher, GenericValue content, Map<String, Object> context, Locale locale, String mimeTypeId, boolean cache) { + public ContentMapFacade(LocalDispatcher dispatcher, GenericValue content, Map<String, Object> context, Locale locale, + String mimeTypeId, boolean cache) { this.dispatcher = dispatcher; this.value = content; this.context = context; @@ -99,7 +100,8 @@ public class ContentMapFacade implements Map<Object, Object> { init(); } - private ContentMapFacade(LocalDispatcher dispatcher, String contentId, Map<String, Object> context, Locale locale, String mimeTypeId, boolean cache) { + private ContentMapFacade(LocalDispatcher dispatcher, String contentId, Map<String, Object> context, Locale locale, + String mimeTypeId, boolean cache) { this.dispatcher = dispatcher; this.delegator = dispatcher.getDelegator(); this.contentId = contentId; @@ -127,10 +129,18 @@ public class ContentMapFacade implements Map<Object, Object> { this.content = new Content(); } + /** + * Sets render flag. + * @param render the render + */ public void setRenderFlag(boolean render) { this.allowRender = render; } + /** + * Sets is decorated. + * @param isDecorated the is decorated + */ public void setIsDecorated(boolean isDecorated) { this.isDecorated = isDecorated; } @@ -180,7 +190,7 @@ public class ContentMapFacade implements Map<Object, Object> { @Override public Set<Object> keySet() { - return UtilGenerics.cast(mapKeySet); + return UtilGenerics.cast(MAP_KEY_SET); } @Override @@ -195,6 +205,10 @@ public class ContentMapFacade implements Map<Object, Object> { return null; } + /** + * Sets sort order. + * @param obj the obj + */ public void setSortOrder(Object obj) { if (!(obj instanceof String)) { Debug.logWarning("sortOrder parameters must be a string", MODULE); @@ -204,6 +218,10 @@ public class ContentMapFacade implements Map<Object, Object> { this.subContent.setSortOrder(obj); } + /** + * Sets map key filter. + * @param obj the obj + */ public void setMapKeyFilter(Object obj) { if (!(obj instanceof String)) { Debug.logWarning("mapKeyFilter parameters must be a string", MODULE); @@ -212,6 +230,10 @@ public class ContentMapFacade implements Map<Object, Object> { this.mapKeyFilter = (String) obj; } + /** + * Sets status filter. + * @param obj the obj + */ public void setStatusFilter(Object obj) { if (!(obj instanceof String)) { Debug.logWarning("statusFilter parameters must be a string", MODULE); @@ -221,6 +243,10 @@ public class ContentMapFacade implements Map<Object, Object> { this.subContent.setStatusFilter(obj); } + /** + * Sets decorated content. + * @param decoratedContent the decorated content + */ public void setDecoratedContent(ContentMapFacade decoratedContent) { this.decoratedContent = decoratedContent; } @@ -332,6 +358,10 @@ public class ContentMapFacade implements Map<Object, Object> { return null; } + /** + * Render this string. + * @return the string + */ protected String renderThis() { if (!this.allowRender && !this.isDecorated) { String errorMsg = "WARNING: Cannot render content being rendered! (Infinite Recursion NOT allowed!)"; @@ -549,7 +579,8 @@ public class ContentMapFacade implements Map<Object, Object> { } else if ("render".equalsIgnoreCase(name)) { // render just the dataresource try { - return DataResourceWorker.renderDataResourceAsText(dispatcher, delegator, value.getString("dataResourceId"), context, locale, mimeType, cache); + return DataResourceWorker.renderDataResourceAsText(dispatcher, delegator, value.getString("dataResourceId"), + context, locale, mimeType, cache); } catch (GeneralException | IOException e) { Debug.logError(e, MODULE); return e.toString(); 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 53b0e88..4f4171d 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 @@ -73,7 +73,7 @@ import freemarker.ext.dom.NodeModel; public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWorkerInterface { private static final String MODULE = ContentWorker.class.getName(); - static final UtilCodec.SimpleEncoder encoder = UtilCodec.getEncoder("html"); + static final UtilCodec.SimpleEncoder ENCODER = UtilCodec.getEncoder("html"); public ContentWorker() { } @@ -360,7 +360,7 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor || rendered.contains("<input") || rendered.contains("<iframe") || rendered.contains("<a")) { - rendered = encoder.sanitize(rendered, contentTypeId); + rendered = ENCODER.sanitize(rendered, contentTypeId); } return rendered; } @@ -1158,6 +1158,7 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor } List<GenericValue> entityList = UtilGenerics.cast(results.get("entityList")); if (UtilValidate.isEmpty(entityList)) { + Debug.log("No subcontent found."); //throw new IOException("No subcontent found."); } else { view = entityList.get(0); @@ -1630,7 +1631,7 @@ public class ContentWorker implements org.apache.ofbiz.widget.content.ContentWor GenericValue gv = (GenericValue) obj; GenericPK pk = gv.getPrimaryKey(); indent.append(' '); - logMap(s, "GMAP[" + key + " name:" + pk.getEntityName()+ "]", pk, indent); + logMap(s, "GMAP[" + key + " name:" + pk.getEntityName() + "]", pk, indent); indent.setLength(indent.length() - 1); } else if (obj instanceof List<?>) { indent.append(' '); diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/content/PermissionRecorder.java b/applications/content/src/main/java/org/apache/ofbiz/content/content/PermissionRecorder.java index cbcbf6e..1a72dd6 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/content/PermissionRecorder.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/content/PermissionRecorder.java @@ -51,8 +51,8 @@ public class PermissionRecorder { private static final String MODULE = PermissionRecorder.class.getName(); - private static final String[] opFields = {"contentPurposeTypeId", "contentOperationId", "roleTypeId", "statusId", "privilegeEnumId"}; - private static final String[] fieldTitles = {"Purpose", "Operation", "Role", "Status", "Privilege"}; + private static final String[] OP_FIELDS = {"contentPurposeTypeId", "contentOperationId", "roleTypeId", "statusId", "privilegeEnumId"}; + private static final String[] FIELD_TITLES = {"Purpose", "Operation", "Role", "Status", "Privilege"}; public PermissionRecorder() { isOn = UtilProperties.propertyValueEqualsIgnoreCase("content", "permissionRecorderOn", "true"); @@ -170,14 +170,26 @@ public class PermissionRecorder { statusTargets = opList.toArray(new String[opList.size()]); } + /** + * Get target operations string [ ]. + * @return the string [ ] + */ public String[] getTargetOperations() { return targetOperations != null ? targetOperations.clone() : null; } + /** + * Sets target operations. + * @param opList the op list + */ public void setTargetOperations(List<String> opList) { targetOperations = opList.toArray(new String[opList.size()]); } + /** + * Sets current content id. + * @param id the id + */ public void setCurrentContentId(String id) { if (!currentContentId.equals(id)) { currentContentMap = new HashMap<>(); @@ -262,7 +274,17 @@ public class PermissionRecorder { currentContentId = contentId; } - public void record(GenericValue purposeOp, boolean targetOpCond, boolean purposeCond, boolean statusCond, boolean privilegeCond, boolean roleCond) { + /** + * Record. + * @param purposeOp the purpose op + * @param targetOpCond the target op cond + * @param purposeCond the purpose cond + * @param statusCond the status cond + * @param privilegeCond the privilege cond + * @param roleCond the role cond + */ + public void record(GenericValue purposeOp, boolean targetOpCond, boolean purposeCond, boolean statusCond, boolean privilegeCond, + boolean roleCond) { Map<String, Object> map = UtilMisc.makeMapWritable(purposeOp); map.put("contentOperationIdCond", targetOpCond); map.put("contentPurposeTypeIdCond", purposeCond); @@ -295,7 +317,7 @@ public class PermissionRecorder { sb.append("Content Id"); sb.append("</td>"); - for (String opField : fieldTitles) { + for (String opField : FIELD_TITLES) { sb.append("<td class=\"headr\">"); sb.append(opField); sb.append("</td>"); @@ -344,7 +366,7 @@ public class PermissionRecorder { //if (Debug.infoOn()) Debug.logInfo("renderResultRowHtml, (1):" + sb.toString(), MODULE); String str = null; String s = null; - for (String opField : opFields) { + for (String opField : OP_FIELDS) { sb.append("<td class=\"target\">"); s = (String) currentContentResultMap.get(opField); if (s != null) { @@ -366,7 +388,7 @@ public class PermissionRecorder { sb.append("</td>"); boolean isPass = true; - for (String opField : opFields) { + for (String opField : OP_FIELDS) { Boolean bool = (Boolean) rMap.get(opField + "Cond"); String cls = (bool) ? "pass" : "fail"; if (!bool) { diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/output/OutputServices.java b/applications/content/src/main/java/org/apache/ofbiz/content/output/OutputServices.java index 51311f9..92aa39b 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/output/OutputServices.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/output/OutputServices.java @@ -84,7 +84,7 @@ public class OutputServices { private static final String MODULE = OutputServices.class.getName(); - protected static final FoFormRenderer foFormRenderer = new FoFormRenderer(); + protected static final FoFormRenderer FO_FORM_RENDERED = new FoFormRenderer(); private static final String RESOURCE = "ContentUiLabels"; public static Map<String, Object> sendPrintFromScreen(DispatchContext dctx, Map<String, ? extends Object> serviceContext) { @@ -122,7 +122,7 @@ public class OutputServices { ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer); screensAtt.populateContextForService(dctx, screenContext); screenContextTmp.putAll(screenContext); - screensAtt.getContext().put("formStringRenderer", foFormRenderer); + screensAtt.getContext().put("formStringRenderer", FO_FORM_RENDERED); screensAtt.render(screenLocation); // create the input stream for the generation @@ -166,11 +166,13 @@ public class OutputServices { printer = printServices[0]; Debug.logInfo("Using printer: " + printer.getName(), MODULE); if (!printer.isDocFlavorSupported(psInFormat)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentPrinterNotSupportDocFlavorFormat", UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentPrinterNotSupportDocFlavorFormat", + UtilMisc.toMap("psInFormat", psInFormat, "printerName", printer.getName()), locale)); } } if (printer == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentPrinterNotFound", UtilMisc.toMap("printerName", printerName), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentPrinterNotFound", + UtilMisc.toMap("printerName", printerName), locale)); } } else { @@ -198,7 +200,8 @@ public class OutputServices { job.print(myDoc, praset); } catch (PrintException | IOException | TemplateException | GeneralException | SAXException | ParserConfigurationException e) { Debug.logError(e, "Error rendering [" + contentType + "]: " + e.toString(), MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentRenderingError", UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ContentRenderingError", + UtilMisc.toMap("contentType", contentType, "errorString", e.toString()), locale)); } return ServiceUtil.returnSuccess(); @@ -236,7 +239,7 @@ public class OutputServices { ScreenRenderer screensAtt = new ScreenRenderer(writer, screenContextTmp, foScreenStringRenderer); screensAtt.populateContextForService(dctx, screenContext); screenContextTmp.putAll(screenContext); - screensAtt.getContext().put("formStringRenderer", foFormRenderer); + screensAtt.getContext().put("formStringRenderer", FO_FORM_RENDERED); screensAtt.render(screenLocation); // create the input stream for the generation 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 d5ee911..b3bee59 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,8 @@ 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[] SAVED_KEY_NAMES = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", + "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() @@ -92,7 +93,7 @@ public class EditRenderSubContentCacheTransform implements TemplateTransformMode List<Map<String, ? extends Object>> trail = UtilGenerics.cast(templateCtx.get("globalNodeTrail")); String contentAssocPredicateId = (String) templateCtx.get("contentAssocPredicateId"); String strNullThruDatesOnly = (String) templateCtx.get("nullThruDatesOnly"); - Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE :Boolean.FALSE; + Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE; GenericValue val = null; try { val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId); @@ -128,7 +129,7 @@ public class EditRenderSubContentCacheTransform implements TemplateTransformMode templateCtx.put("subContentIdSub", subContentIdSub); templateCtx.put("subDataResourceTypeId", subDataResourceTypeId); final Map<String, Object> savedValues = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateCtx, SAVED_KEY_NAMES, savedValues); return new Writer(out) { diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LimitedSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LimitedSubContentCacheTransform.java index e335d73..a6f43ce 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LimitedSubContentCacheTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LimitedSubContentCacheTransform.java @@ -56,8 +56,8 @@ public class LimitedSubContentCacheTransform implements TemplateTransformModel { private static final String MODULE = LimitedSubContentCacheTransform.class.getName(); - static final String[] upSaveKeyNames = {"globalNodeTrail" }; - static final String[] saveKeyNames = {"contentId", "subContentId", "entityList", "entityIndex", + static final String[] UP_SAVE_KEY_NAMES = {"globalNodeTrail" }; + static final String[] SAVE_KEY_NAMES = {"contentId", "subContentId", "entityList", "entityIndex", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", "entityList", "viewSize", "viewIndex", "highIndex", "lowIndex", "listSize", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail", "outputIndex" }; @@ -97,7 +97,7 @@ public class LimitedSubContentCacheTransform implements TemplateTransformModel { final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env); FreeMarkerWorker.getSiteParameters(request, templateRoot); final Map<String, Object> savedValuesUp = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.saveContextValues(templateRoot, UP_SAVE_KEY_NAMES, savedValuesUp); final Map<String, Object> savedValues = new HashMap<>(); FreeMarkerWorker.overrideWithArgs(templateRoot, args); @@ -148,7 +148,8 @@ public class LimitedSubContentCacheTransform implements TemplateTransformModel { Map<String, Object> results = null; String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId"); try { - results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "From", fromDate, null, assocTypes, null, Boolean.TRUE, contentAssocPredicateId, orderBy); + results = ContentServicesComplex.getAssocAndContentAndDataResourceCacheMethod(delegator, contentId, null, "From", + fromDate, null, assocTypes, null, Boolean.TRUE, contentAssocPredicateId, orderBy); } catch (MiniLangException | GenericEntityException e) { throw new RuntimeException(e.getMessage(), e); } @@ -173,7 +174,7 @@ public class LimitedSubContentCacheTransform implements TemplateTransformModel { if (pickedEntityIds.size() < returnLimit) { inProgress = getNextMatchingEntity(templateRoot, delegator, env); } - FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateRoot, SAVE_KEY_NAMES, savedValues); if (inProgress) { return TransformControl.EVALUATE_BODY; } @@ -193,7 +194,7 @@ public class LimitedSubContentCacheTransform implements TemplateTransformModel { inProgress = getNextMatchingEntity(templateRoot, delegator, env); } - FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateRoot, SAVE_KEY_NAMES, savedValues); if (inProgress) { return TransformControl.REPEAT_EVALUATION; } diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LoopSubContentTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LoopSubContentTransform.java index 0b5af2a..2aefc4d 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LoopSubContentTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/LoopSubContentTransform.java @@ -53,8 +53,10 @@ public class LoopSubContentTransform implements TemplateTransformModel { private static final String MODULE = LoopSubContentTransform.class.getName(); - static final String[] saveKeyNames = {"contentId", "subContentId", "mimeType", "subContentDataResourceView", "wrapTemplateId", "contentTemplateId"}; - static final String[] removeKeyNames = {"wrapTemplateId", "entityList", "entityIndex", "textData", "dataResourceId", "drDataResourceId", "subContentIdSub", "parentContent", "wrappedFTL"}; + static final String[] SAVE_KEY_NAMES = {"contentId", "subContentId", "mimeType", "subContentDataResourceView", "wrapTemplateId", + "contentTemplateId"}; + static final String[] REMOVE_KEY_NAMES = {"wrapTemplateId", "entityList", "entityIndex", "textData", "dataResourceId", "drDataResourceId", + "subContentIdSub", "parentContent", "wrappedFTL"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() @@ -155,7 +157,7 @@ public class LoopSubContentTransform implements TemplateTransformModel { final Map<String, Object> templateCtx = FreeMarkerWorker.getWrappedObject("context", env); final LocalDispatcher dispatcher = FreeMarkerWorker.getWrappedObject("dispatcher", env); final Delegator delegator = FreeMarkerWorker.getWrappedObject("delegator", env); - final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, saveKeyNames); + final Map<String, Object> savedValues = FreeMarkerWorker.saveValues(templateCtx, SAVE_KEY_NAMES); FreeMarkerWorker.overrideWithArgs(templateCtx, args); String contentAssocTypeId = (String) templateCtx.get("contentAssocTypeId"); @@ -185,7 +187,8 @@ public class LoopSubContentTransform implements TemplateTransformModel { //DEJ20080730 Should always use contentId, not subContentId since we're searching for that and it is confusing String thisMapKey = (String) templateCtx.get("mapKey"); - Map<String, Object> results = ContentServicesComplex.getAssocAndContentAndDataResourceMethod(delegator, thisContentId, thisMapKey, null, fromDate, null, null, null, assocTypes, null); + Map<String, Object> results = ContentServicesComplex.getAssocAndContentAndDataResourceMethod(delegator, thisContentId, + thisMapKey, null, fromDate, null, null, null, assocTypes, null); List<GenericValue> entityList = UtilGenerics.cast(results.get("entityList")); templateCtx.put("entityList", entityList); @@ -254,7 +257,7 @@ public class LoopSubContentTransform implements TemplateTransformModel { out.write(wrappedFTL); } } - FreeMarkerWorker.removeValues(templateCtx, removeKeyNames); + FreeMarkerWorker.removeValues(templateCtx, REMOVE_KEY_NAMES); FreeMarkerWorker.reloadValues(templateCtx, savedValues, env); } }; diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/OfbizContentAltUrlTransforms.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/OfbizContentAltUrlTransforms.java index c3681e1..fd0a4e8 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/OfbizContentAltUrlTransforms.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/OfbizContentAltUrlTransforms.java @@ -47,8 +47,14 @@ import freemarker.template.TemplateTransformModel; public class OfbizContentAltUrlTransforms implements TemplateTransformModel { private static final String MODULE = OfbizContentAltUrlTransforms.class.getName(); - private static final String defaultViewRequest = "contentViewInfo"; - + private static final String DEF_VIEW_REQUEST = "contentViewInfo"; + + /** + * Gets string arg. + * @param args the args + * @param key the key + * @return the string arg + */ public String getStringArg(Map<String, Object> args, String key) { Object o = args.get(key); if (o instanceof SimpleScalar) { @@ -136,7 +142,7 @@ public class OfbizContentAltUrlTransforms implements TemplateTransformModel { if (UtilValidate.isEmpty(url)) { if (UtilValidate.isEmpty(viewContent)) { - viewContent = defaultViewRequest; + viewContent = DEF_VIEW_REQUEST; } url = makeContentUrl(request, response, contentId, viewContent); } @@ -157,7 +163,7 @@ public class OfbizContentAltUrlTransforms implements TemplateTransformModel { if (UtilValidate.isNotEmpty(viewContent)) { urlBuilder.append("/" + viewContent); } else { - urlBuilder.append("/" + defaultViewRequest); + urlBuilder.append("/" + DEF_VIEW_REQUEST); } urlBuilder.append("?contentId=" + contentId); return urlBuilder.toString(); 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 70c1eb8..27ad2a3 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 @@ -52,8 +52,9 @@ import freemarker.template.TemplateTransformModel; 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[] UP_SAVE_KEY_NAMES = {"globalNodeTrail"}; + static final String[] SAVE_KEY_NAMES = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", + "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; @Override @SuppressWarnings("unchecked") @@ -68,7 +69,7 @@ public class RenderContentAsText implements TemplateTransformModel { } FreeMarkerWorker.getSiteParameters(request, templateRoot); final Map<String, Object> savedValuesUp = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.saveContextValues(templateRoot, UP_SAVE_KEY_NAMES, savedValuesUp); FreeMarkerWorker.overrideWithArgs(templateRoot, args); if (Debug.verboseOn()) { Debug.logVerbose("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), MODULE); @@ -126,7 +127,7 @@ public class RenderContentAsText implements TemplateTransformModel { Debug.logVerbose("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), MODULE); Debug.logVerbose("in RenderSubContent, subContentId(2):" + templateRoot.get("subContentId"), MODULE); } - FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateRoot, SAVE_KEY_NAMES, savedValues); try { String txt = ContentWorker.renderContentAsText(dispatcher, thisContentId, templateRoot, locale, mimeTypeId, true); if ("true".equals(xmlEscape)) { 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 ceb02b2..9b72309 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 @@ -48,8 +48,9 @@ import freemarker.template.TemplateTransformModel; 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[] UP_SAVE_KEY_NAMES = {"globalNodeTrail"}; + public static final String[] SAVE_KEY_NAMES = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", "locale", + "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; @Override @SuppressWarnings("unchecked") @@ -63,7 +64,7 @@ public class RenderSubContentAsText implements TemplateTransformModel { } FreeMarkerWorker.getSiteParameters(request, templateRoot); final Map<String, Object> savedValuesUp = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.saveContextValues(templateRoot, UP_SAVE_KEY_NAMES, savedValuesUp); FreeMarkerWorker.overrideWithArgs(templateRoot, args); if (Debug.infoOn()) { Debug.logInfo("in RenderSubContent, contentId(2):" + templateRoot.get("contentId"), MODULE); @@ -121,7 +122,7 @@ public class RenderSubContentAsText implements TemplateTransformModel { openEditWrap(out, editStyle); } - FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateRoot, SAVE_KEY_NAMES, savedValues); try { String txt = ContentWorker.renderSubContentAsText(dispatcher, thisContentId, thisMapKey, templateRoot, locale, mimeTypeId, true); if ("true".equals(xmlEscape)) { diff --git a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentCacheTransform.java b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentCacheTransform.java index 555cdaa..4d1d2f5 100644 --- a/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentCacheTransform.java +++ b/applications/content/src/main/java/org/apache/ofbiz/content/webapp/ftl/RenderSubContentCacheTransform.java @@ -52,7 +52,7 @@ import freemarker.template.TemplateTransformModel; public class RenderSubContentCacheTransform implements TemplateTransformModel { private static final String MODULE = RenderSubContentCacheTransform.class.getName(); - static final String[] upSaveKeyNames = {"globalNodeTrail" }; + static final String[] UP_SAVE_KEY_NAMES = {"globalNodeTrail" }; @Override @SuppressWarnings("unchecked") @@ -65,13 +65,13 @@ public class RenderSubContentCacheTransform implements TemplateTransformModel { final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env); FreeMarkerWorker.getSiteParameters(request, templateRoot); final Map<String, Object> savedValuesUp = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.saveContextValues(templateRoot, UP_SAVE_KEY_NAMES, savedValuesUp); FreeMarkerWorker.overrideWithArgs(templateRoot, args); final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env); List<Map<String, ? extends Object>> trail = UtilGenerics.cast(templateRoot.get("globalNodeTrail")); String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId"); String strNullThruDatesOnly = (String) templateRoot.get("nullThruDatesOnly"); - Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE :Boolean.FALSE; + Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE; String thisSubContentId = (String) templateRoot.get("subContentId"); final boolean directAssocMode = UtilValidate.isNotEmpty(thisSubContentId) ? true : false; GenericValue val = null; @@ -151,8 +151,9 @@ public class RenderSubContentCacheTransform implements TemplateTransformModel { String mimeTypeId = (String) templateRoot.get("mimeTypeId"); Locale locale = (Locale) templateRoot.get("locale"); - if (locale == null) + if (locale == null) { locale = Locale.getDefault(); + } if (UtilValidate.isNotEmpty(editRequestName)) { String editStyle = getEditStyle(); @@ -199,26 +200,36 @@ public class RenderSubContentCacheTransform implements TemplateTransformModel { } if (view != null) { ModelEntity modelEntity = view.getModelEntity(); - if (UtilValidate.isEmpty(contentId) && modelEntity.getField("caContentId") != null) + if (UtilValidate.isEmpty(contentId) && modelEntity.getField("caContentId") != null) { contentId = view.getString("caContentId"); - if (UtilValidate.isEmpty(contentId) && modelEntity.getField("contentId") != null) + } + if (UtilValidate.isEmpty(contentId) && modelEntity.getField("contentId") != null) { contentId = view.getString("contentId"); - if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("caContentIdTo") != null) + } + if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("caContentIdTo") != null) { contentIdTo = view.getString("caContentIdTo"); - if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("contentIdTo") != null) + } + if (UtilValidate.isEmpty(contentIdTo) && modelEntity.getField("contentIdTo") != null) { contentIdTo = view.getString("contentIdTo"); - if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("caContentAssocTypeId") != null) + } + if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("caContentAssocTypeId") != null) { contentAssocTypeId = view.getString("caContentAssocTypeId"); - if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("contentAssocTypeId") != null) + } + if (UtilValidate.isEmpty(contentAssocTypeId) && modelEntity.getField("contentAssocTypeId") != null) { contentAssocTypeId = view.getString("contentAssocTypeId"); - if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("caMapKey") != null) + } + if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("caMapKey") != null) { mapKey = view.getString("caMapKey"); - if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("mapKey") != null) + } + if (UtilValidate.isEmpty(mapKey) && modelEntity.getField("mapKey") != null) { mapKey = view.getString("mapKey"); - if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("caFromDate") != null) + } + if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("caFromDate") != null) { fromDate = view.getString("caFromDate"); - if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("fromDate") != null) + } + if (UtilValidate.isEmpty(fromDate) && modelEntity.getField("fromDate") != null) { fromDate = view.getString("fromDate"); + } } } else { contentId = (String) templateRoot.get("subContentId"); 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 dd58e09..6a85c6d 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 @@ -49,8 +49,9 @@ import freemarker.template.TransformControl; 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[] UP_SAVE_KEY_NAMES = {"globalNodeTrail"}; + static final String[] SAVE_KEY_NAMES = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", + "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly", "globalNodeTrail"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() @@ -84,7 +85,7 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel final Environment env = Environment.getCurrentEnvironment(); final Map<String, Object> templateRoot = FreeMarkerWorker.createEnvironmentMap(env); final Map<String, Object> savedValuesUp = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateRoot, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.saveContextValues(templateRoot, UP_SAVE_KEY_NAMES, savedValuesUp); final Map<String, Object> savedValues = new HashMap<>(); FreeMarkerWorker.overrideWithArgs(templateRoot, args); String startContentAssocTypeId = (String) templateRoot.get("contentAssocTypeId"); @@ -95,7 +96,7 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel List<Map<String, ? extends Object>> globalNodeTrail = UtilGenerics.cast(templateRoot.get("globalNodeTrail")); String strNullThruDatesOnly = (String) templateRoot.get("nullThruDatesOnly"); String contentAssocPredicateId = (String) templateRoot.get("contentAssocPredicateId"); - Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE :Boolean.FALSE; + Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE; try { // getCurrentContent puts the "current" node on the end of globalNodeTrail. // It may have already been there, but getCurrentContent will compare its contentId @@ -166,7 +167,7 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel Boolean isReturnBeforePickBool = (Boolean) node.get("isReturnBeforePick"); if (isReturnBeforePickBool != null && isReturnBeforePickBool) { return TransformControl.SKIP_BODY; - } + } ContentWorker.selectKids(node, traverseContext); nodeTrail.add(node); @@ -174,13 +175,12 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel Boolean isPickBool = (Boolean) node.get("isPick"); Boolean isFollowBool = (Boolean) node.get("isFollow"); boolean isPick = true; - if ((isPickBool == null || !isPickBool) - && (isFollowBool != null && isFollowBool)) { + if ((isPickBool == null || !isPickBool) && (isFollowBool != null && isFollowBool)) { isPick = ContentWorker.traverseSubContent(traverseContext); } if (isPick) { populateContext(traverseContext, templateRoot); - FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateRoot, SAVE_KEY_NAMES, savedValues); return TransformControl.EVALUATE_BODY; } else { return TransformControl.SKIP_BODY; @@ -193,7 +193,7 @@ public class TraverseSubContentCacheTransform implements TemplateTransformModel boolean inProgress = ContentWorker.traverseSubContent(traverseContext); if (inProgress) { populateContext(traverseContext, templateRoot); - FreeMarkerWorker.saveContextValues(templateRoot, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateRoot, SAVE_KEY_NAMES, savedValues); return TransformControl.REPEAT_EVALUATION; } else { return TransformControl.END_EVALUATION; 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 23b9e90..8182943 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 @@ -49,8 +49,9 @@ import freemarker.template.TemplateTransformModel; 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[] UP_SAVE_KEY_NAMES = {"globalNodeTrail"}; + static final String[] SAVE_KEY_NAMES = {"contentId", "subContentId", "subDataResourceTypeId", "mimeTypeId", "whenMap", + "locale", "wrapTemplateId", "encloseWrapText", "nullThruDatesOnly"}; /** * @deprecated use FreeMarkerWorker.getWrappedObject() @@ -94,14 +95,14 @@ public class WrapSubContentCacheTransform implements TemplateTransformModel { final HttpServletRequest request = FreeMarkerWorker.getWrappedObject("request", env); FreeMarkerWorker.getSiteParameters(request, templateCtx); final Map<String, Object> savedValuesUp = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateCtx, upSaveKeyNames, savedValuesUp); + FreeMarkerWorker.saveContextValues(templateCtx, UP_SAVE_KEY_NAMES, savedValuesUp); FreeMarkerWorker.overrideWithArgs(templateCtx, args); final String wrapTemplateId = (String) templateCtx.get("wrapTemplateId"); final GenericValue userLogin = FreeMarkerWorker.getWrappedObject("userLogin", env); List<Map<String, ? extends Object>> trail = UtilGenerics.cast(templateCtx.get("globalNodeTrail")); String contentAssocPredicateId = (String) templateCtx.get("contentAssocPredicateId"); String strNullThruDatesOnly = (String) templateCtx.get("nullThruDatesOnly"); - Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE :Boolean.FALSE; + Boolean nullThruDatesOnly = (strNullThruDatesOnly != null && "true".equalsIgnoreCase(strNullThruDatesOnly)) ? Boolean.TRUE : Boolean.FALSE; GenericValue val = null; try { val = ContentWorker.getCurrentContent(delegator, trail, userLogin, templateCtx, nullThruDatesOnly, contentAssocPredicateId); @@ -130,7 +131,7 @@ public class WrapSubContentCacheTransform implements TemplateTransformModel { // being passed. } final Map<String, Object> savedValues = new HashMap<>(); - FreeMarkerWorker.saveContextValues(templateCtx, saveKeyNames, savedValues); + FreeMarkerWorker.saveContextValues(templateCtx, SAVE_KEY_NAMES, savedValues); // This order is taken so that the mimeType can be overridden in the transform arguments. String mimeTypeId = ContentWorker.getMimeTypeId(delegator, view, templateCtx); templateCtx.put("drDataResourceId", dataResourceId); diff --git a/applications/marketing/src/main/java/org/apache/ofbiz/marketing/marketing/MarketingServices.java b/applications/marketing/src/main/java/org/apache/ofbiz/marketing/marketing/MarketingServices.java index 83818b8..b3a9cc9 100644 --- a/applications/marketing/src/main/java/org/apache/ofbiz/marketing/marketing/MarketingServices.java +++ b/applications/marketing/src/main/java/org/apache/ofbiz/marketing/marketing/MarketingServices.java @@ -44,7 +44,7 @@ import org.apache.ofbiz.service.ServiceUtil; public class MarketingServices { private static final String MODULE = MarketingServices.class.getName(); - public static final String resourceMarketing = "MarketingUiLabels"; + public static final String RESOURCE = "MarketingUiLabels"; private static final String RES_ORDER = "OrderUiLabels"; public static Map<String, Object> signUpForContactList(DispatchContext dctx, Map<String, ? extends Object> context) { @@ -58,7 +58,7 @@ public class MarketingServices { String partyId = (String) context.get("partyId"); if (!UtilValidate.isEmail(email)) { - String error = UtilProperties.getMessage(resourceMarketing, "MarketingCampaignInvalidEmailInput", locale); + String error = UtilProperties.getMessage(RESOURCE, "MarketingCampaignInvalidEmailInput", locale); return ServiceUtil.returnError(error); } @@ -66,7 +66,8 @@ public class MarketingServices { // locate the contact list GenericValue contactList = EntityQuery.use(delegator).from("ContactList").where("contactListId", contactListId).queryOne(); if (contactList == null) { - String error = UtilProperties.getMessage(resourceMarketing, "MarketingContactListNotFound", UtilMisc.<String, Object>toMap("contactListId", contactListId), locale); + String error = UtilProperties.getMessage(RESOURCE, "MarketingContactListNotFound", UtilMisc.<String, Object>toMap("contactListId", + contactListId), locale); return ServiceUtil.returnError(error); } @@ -89,7 +90,8 @@ public class MarketingServices { partyId = "_NA_"; } } - Map<String, Object> input = UtilMisc.toMap("userLogin", userLogin, "emailAddress", email, "partyId", partyId, "fromDate", fromDate, "contactMechPurposeTypeId", "OTHER_EMAIL"); + Map<String, Object> input = UtilMisc.toMap("userLogin", userLogin, "emailAddress", email, "partyId", partyId, + "fromDate", fromDate, "contactMechPurposeTypeId", "OTHER_EMAIL"); Map<String, Object> serviceResults = dispatcher.runSync("createPartyEmailAddress", input); if (ServiceUtil.isError(serviceResults)) { throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResults)); @@ -97,7 +99,8 @@ public class MarketingServices { String contactMechId = (String) serviceResults.get("contactMechId"); // create a new association at this fromDate to the anonymous party with status accepted input = UtilMisc.toMap("userLogin", userLogin, "contactListId", contactList.get("contactListId"), - "partyId", partyId, "fromDate", fromDate, "statusId", "CLPT_PENDING", "preferredContactMechId", contactMechId, "baseLocation", context.get("baseLocation")); + "partyId", partyId, "fromDate", fromDate, "statusId", "CLPT_PENDING", "preferredContactMechId", contactMechId, "baseLocation", + context.get("baseLocation")); serviceResults = dispatcher.runSync("createContactListParty", input); if (ServiceUtil.isError(serviceResults)) { throw new GenericServiceException(ServiceUtil.getErrorMessage(serviceResults)); @@ -107,7 +110,7 @@ public class MarketingServices { Debug.logInfo(e, error + e.getMessage(), MODULE); return ServiceUtil.returnError(error); } catch (GenericServiceException e) { - String error = UtilProperties.getMessage(resourceMarketing, "MarketingServiceError", locale); + String error = UtilProperties.getMessage(RESOURCE, "MarketingServiceError", locale); Debug.logInfo(e, error + e.getMessage(), MODULE); return ServiceUtil.returnError(error); } 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 c4a9c97..f30c501 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 @@ -62,17 +62,17 @@ public class OrderListState implements Serializable { public static final String VIEW_INDEX_PARAM = "viewIndex"; // state variables - protected int viewSize; - protected int viewIndex; - protected Map<String, String> orderStatusState; - protected Map<String, String> orderTypeState; - protected Map<String, String> orderFilterState; - protected int orderListSize; + private int viewSize; + private int viewIndex; + private Map<String, String> orderStatusState; + private Map<String, String> orderTypeState; + private Map<String, String> orderFilterState; + private int orderListSize; // parameter to ID maps - protected static final Map<String, String> parameterToOrderStatusId; - protected static final Map<String, String> parameterToOrderTypeId; - protected static final Map<String, String> parameterToFilterId; + protected static final Map<String, String> PARAM_TO_ORDER_STATUS_ID; + protected static final Map<String, String> PARAM_TO_ORDER_TYPE_ID; + protected static final Map<String, String> PARAM_TO_FILTER_ID; static { Map<String, String> map = new HashMap<>(); map.put("viewcompleted", "ORDER_COMPLETED"); @@ -82,12 +82,12 @@ public class OrderListState implements Serializable { map.put("viewcreated", "ORDER_CREATED"); map.put("viewprocessing", "ORDER_PROCESSING"); map.put("viewhold", "ORDER_HOLD"); - parameterToOrderStatusId = map; + PARAM_TO_ORDER_STATUS_ID = map; map = new HashMap<>(); map.put("view_SALES_ORDER", "SALES_ORDER"); map.put("view_PURCHASE_ORDER", "PURCHASE_ORDER"); - parameterToOrderTypeId = map; + PARAM_TO_ORDER_TYPE_ID = map; map = new HashMap<>(); map.put("filterInventoryProblems", "filterInventoryProblems"); @@ -95,7 +95,7 @@ public class OrderListState implements Serializable { map.put("filterPartiallyReceivedPOs", "filterPartiallyReceivedPOs"); map.put("filterPOsOpenPastTheirETA", "filterPOsOpenPastTheirETA"); map.put("filterPOsWithRejectedItems", "filterPOsWithRejectedItems"); - parameterToFilterId = map; + PARAM_TO_FILTER_ID = map; } //============= Initialization and Request methods ===================// @@ -165,7 +165,7 @@ public class OrderListState implements Serializable { } private void changeOrderListStates(HttpServletRequest request) { - for (String param : parameterToOrderStatusId.keySet()) { + for (String param : PARAM_TO_ORDER_STATUS_ID.keySet()) { String value = request.getParameter(param); if ("Y".equals(value)) { orderStatusState.put(param, "Y"); @@ -173,7 +173,7 @@ public class OrderListState implements Serializable { orderStatusState.put(param, "N"); } } - for (String param : parameterToOrderTypeId.keySet()) { + for (String param : PARAM_TO_ORDER_TYPE_ID.keySet()) { String value = request.getParameter(param); if ("Y".equals(value)) { orderTypeState.put(param, "Y"); @@ -181,7 +181,7 @@ public class OrderListState implements Serializable { orderTypeState.put(param, "N"); } } - for (String param : parameterToFilterId.keySet()) { + for (String param : PARAM_TO_FILTER_ID.keySet()) { String value = request.getParameter(param); if ("Y".equals(value)) { orderFilterState.put(param, "Y"); @@ -336,14 +336,14 @@ public class OrderListState implements Serializable { if (!hasStatus(status)) { continue; } - statusConditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, parameterToOrderStatusId.get(status))); + statusConditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, PARAM_TO_ORDER_STATUS_ID.get(status))); } List<EntityCondition> typeConditions = new LinkedList<>(); for (String type : orderTypeState.keySet()) { if (!hasType(type)) { continue; } - typeConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, parameterToOrderTypeId.get(type))); + typeConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, PARAM_TO_ORDER_TYPE_ID.get(type))); } EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions, EntityOperator.OR); 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 ec32473..cf32fd4 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 @@ -279,7 +279,7 @@ public class OrderLookupServices { String shipmentMethod = (String) context.get("shipmentMethod"); if (UtilValidate.isNotEmpty(shipmentMethod)) { String carrierPartyId = shipmentMethod.substring(0, shipmentMethod.indexOf('@')); - String ShippingMethodTypeId = shipmentMethod.substring(shipmentMethod.indexOf('@') + 1); + String shippingMethodTypeId = shipmentMethod.substring(shipmentMethod.indexOf('@') + 1); dve.addMemberEntity("OISG", "OrderItemShipGroup"); dve.addAlias("OISG", "shipmentMethodTypeId"); dve.addAlias("OISG", "carrierPartyId"); @@ -290,9 +290,9 @@ public class OrderLookupServices { conditions.add(makeExpr("carrierPartyId", carrierPartyId)); } - if (UtilValidate.isNotEmpty(ShippingMethodTypeId)) { - paramList.add("ShippingMethodTypeId=" + ShippingMethodTypeId); - conditions.add(makeExpr("shipmentMethodTypeId", ShippingMethodTypeId)); + if (UtilValidate.isNotEmpty(shippingMethodTypeId)) { + paramList.add("shippingMethodTypeId=" + shippingMethodTypeId); + conditions.add(makeExpr("shipmentMethodTypeId", shippingMethodTypeId)); } } // PaymentGatewayResponse @@ -353,7 +353,8 @@ public class OrderLookupServices { String goodIdentificationIdValue = (String) context.get("goodIdentificationIdValue"); boolean hasGoodIdentification = UtilValidate.isNotEmpty(goodIdentificationTypeId) && UtilValidate.isNotEmpty(goodIdentificationIdValue); - if (correspondingPoId != null || subscriptionId != null || productId != null || budgetId != null || quoteId != null || hasGoodIdentification) { + if (correspondingPoId != null || subscriptionId != null || productId != null || budgetId != null || quoteId != null + || hasGoodIdentification) { dve.addMemberEntity("OI", "OrderItem"); dve.addAlias("OI", "correspondingPoId"); dve.addAlias("OI", "subscriptionId"); @@ -423,7 +424,8 @@ public class OrderLookupServices { conditions.add(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId)); } } else { - String failMsg = UtilProperties.getMessage("OrderErrorUiLabels", "OrderFindOrderProductInvalid", UtilMisc.toMap("productId", productId), locale); + String failMsg = UtilProperties.getMessage("OrderErrorUiLabels", "OrderFindOrderProductInvalid", + UtilMisc.toMap("productId", productId), locale); return ServiceUtil.returnFailure(failMsg); } } @@ -639,7 +641,8 @@ public class OrderLookupServices { return result; } - public static void filterInventoryProblems(Map<String, ? extends Object> context, Map<String, Object> result, List<GenericValue> orderList, List<String> paramList) { + public static void filterInventoryProblems(Map<String, ? extends Object> context, Map<String, Object> result, List<GenericValue> + orderList, List<String> paramList) { List<String> filterInventoryProblems = new LinkedList<>(); String doFilter = (String) context.get("filterInventoryProblems"); @@ -698,11 +701,9 @@ public class OrderLookupServices { if ("PURCHASE_ORDER".equals(orderType)) { if ("Y".equals(filterPOReject) && orh.getRejectedOrderItems()) { filterPOsWithRejectedItems.add(orderId); - } - else if ("Y".equals(filterPOPast) && orh.getPastEtaOrderItems(orderId)) { + } else if ("Y".equals(filterPOPast) && orh.getPastEtaOrderItems(orderId)) { filterPOsOpenPastTheirETA.add(orderId); - } - else if ("Y".equals(filterPartRec) && orh.getPartiallyReceivedItems()) { + } else if ("Y".equals(filterPartRec) && orh.getPartiallyReceivedItems()) { filterPartiallyReceivedPOs.add(orderId); } } @@ -725,16 +726,14 @@ public class OrderLookupServices { if (value.startsWith("*")) { op = EntityOperator.LIKE; value = "%" + value.substring(1); - } - else if (value.startsWith("%")) { + } else if (value.startsWith("%")) { op = EntityOperator.LIKE; } if (value.endsWith("*")) { op = EntityOperator.LIKE; value = value.substring(0, value.length() - 1) + "%"; - } - else if (value.endsWith("%")) { + } else if (value.endsWith("%")) { op = EntityOperator.LIKE; } 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 a497c02..18b3bfb 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 @@ -194,7 +194,7 @@ public class ShoppingCartHelper { } // Create a HashMap of product attributes - From ShoppingCartItem.attributeNames[] - for (String attributeName : ShoppingCartItem.attributeNames) { + for (String attributeName : Arrays.asList(ShoppingCartItem.ATTRIBUTE_NAMES)) { if (attributes == null) { attributes = new HashMap<>(); } 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 78791e6..3a311df 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 @@ -74,7 +74,7 @@ import org.apache.ofbiz.service.ServiceUtil; public class ShoppingCartItem implements java.io.Serializable { public static final MathContext GEN_ROUNDING = new MathContext(10); - protected static final String[] attributeNames = {"shoppingListId", "shoppingListItemSeqId", "surveyResponses", + protected static final String[] ATTRIBUTE_NAMES = {"shoppingListId", "shoppingListItemSeqId", "surveyResponses", "itemDesiredDeliveryDate", "itemComment", "fromInventoryItemId"}; private static final String MODULE = ShoppingCartItem.class.getName(); private static final String RESOURCE = "OrderUiLabels"; @@ -83,11 +83,11 @@ public class ShoppingCartItem implements java.io.Serializable { /** * the actual or variant product */ - private transient GenericValue _product = null; + private transient GenericValue product = null; /** - * the virtual product if _product is a variant + * the virtual product if product is a variant */ - private transient GenericValue _parentProduct = null; + private transient GenericValue parentProduct = null; private String delegatorName = null; private String prodCatalogId = null; @@ -180,14 +180,14 @@ public class ShoppingCartItem implements java.io.Serializable { public ShoppingCartItem(ShoppingCartItem item) { this.delegator = item.getDelegator(); try { - this._product = item.getProduct(); + this.product = item.getProduct(); } catch (IllegalStateException e) { - this._product = null; + this.product = null; } try { - this._parentProduct = item.getParentProduct(); + this.parentProduct = item.getParentProduct(); } catch (IllegalStateException e) { - this._parentProduct = null; + this.parentProduct = null; } this.delegatorName = item.delegatorName; this.prodCatalogId = item.getProdCatalogId(); @@ -297,17 +297,17 @@ public class ShoppingCartItem implements java.io.Serializable { protected ShoppingCartItem(GenericValue product, Map<String, GenericValue> additionalProductFeatureAndAppls, Map<String, Object> attributes, String prodCatalogId, ProductConfigWrapper configWrapper, Locale locale, String itemType, ShoppingCart.ShoppingCartItemGroup itemGroup, GenericValue parentProduct) { - this._product = product; - this.productId = _product.getString("productId"); - this._parentProduct = parentProduct; + this.product = product; + this.productId = product.getString("productId"); + this.parentProduct = parentProduct; if (parentProduct != null) { - this.parentProductId = _parentProduct.getString("productId"); + this.parentProductId = parentProduct.getString("productId"); } if (UtilValidate.isEmpty(itemType)) { - if (UtilValidate.isNotEmpty(_product.getString("productTypeId"))) { - if ("ASSET_USAGE".equals(_product.getString("productTypeId"))) { + if (UtilValidate.isNotEmpty(product.getString("productTypeId"))) { + if ("ASSET_USAGE".equals(product.getString("productTypeId"))) { this.itemType = "RENTAL_ORDER_ITEM"; // will create additional workeffort/asset usage records - } else if ("ASSET_USAGE_OUT_IN".equals(_product.getString("productTypeId"))) { + } else if ("ASSET_USAGE_OUT_IN".equals(product.getString("productTypeId"))) { this.itemType = "RENTAL_ORDER_ITEM"; } else { this.itemType = "PRODUCT_ORDER_ITEM"; @@ -324,8 +324,8 @@ public class ShoppingCartItem implements java.io.Serializable { this.itemGroup = itemGroup; this.prodCatalogId = prodCatalogId; this.attributes = (attributes == null ? new HashMap<>() : attributes); - this.delegator = _product.getDelegator(); - this.delegatorName = _product.getDelegator().getDelegatorName(); + this.delegator = product.getDelegator(); + this.delegatorName = product.getDelegator().getDelegatorName(); this.addAllProductFeatureAndAppls(additionalProductFeatureAndAppls); this.locale = locale; if (UtilValidate.isNotEmpty(configWrapper)) { @@ -989,14 +989,26 @@ public class ShoppingCartItem implements java.io.Serializable { return itemDescription; } + /** + * Gets prod catalog id. + * @return the prod catalog id + */ public String getProdCatalogId() { return this.prodCatalogId; } + /** + * Gets external id. + * @return the external id + */ public String getExternalId() { return this.externalId; } + /** + * Sets external id. + * @param externalId the external id + */ public void setExternalId(String externalId) { this.externalId = externalId; } @@ -1054,6 +1066,14 @@ public class ShoppingCartItem implements java.io.Serializable { this.setQuantity(quantity, dispatcher, cart, triggerExternalOps, resetShipGroup, updateProductPrice, false); } + /** + * Is inventory available or not required boolean. + * @param quantity the quantity + * @param productStoreId the product store id + * @param dispatcher the dispatcher + * @return the boolean + * @throws CartItemModifyException the cart item modify exception + */ protected boolean isInventoryAvailableOrNotRequired(BigDecimal quantity, String productStoreId, LocalDispatcher dispatcher) throws CartItemModifyException { boolean inventoryAvailable = true; @@ -1075,6 +1095,17 @@ public class ShoppingCartItem implements java.io.Serializable { return inventoryAvailable; } + /** + * Sets quantity. + * @param quantity the quantity + * @param dispatcher the dispatcher + * @param cart the cart + * @param triggerExternalOps the trigger external ops + * @param resetShipGroup the reset ship group + * @param updateProductPrice the update product price + * @param skipInventoryChecks the skip inventory checks + * @throws CartItemModifyException the cart item modify exception + */ protected void setQuantity(BigDecimal quantity, LocalDispatcher dispatcher, ShoppingCart cart, boolean triggerExternalOps, boolean resetShipGroup, boolean updateProductPrice, boolean skipInventoryChecks) throws CartItemModifyException { if (this.quantity.compareTo(quantity) == 0) { @@ -1093,7 +1124,7 @@ public class ShoppingCartItem implements java.io.Serializable { if (!skipInventoryChecks && !"PURCHASE_ORDER".equals(cart.getOrderType())) { // check inventory if new quantity is greater than old quantity; don't worry about inventory getting pulled out from under, // that will be handled at checkout time - if (_product != null && quantity.compareTo(this.quantity) > 0) { + if (product != null && quantity.compareTo(this.quantity) > 0) { if (!isInventoryAvailableOrNotRequired(quantity, productStoreId, dispatcher)) { Map<String, Object> messageMap = UtilMisc.<String, Object>toMap("requestedQuantity", UtilFormatOut.formatQuantity(quantity.doubleValue()), "productName", this.getName(dispatcher), "productId", productId); @@ -1140,6 +1171,9 @@ public class ShoppingCartItem implements java.io.Serializable { } } + /** + * Calc deposit adjustments. + */ public void calcDepositAdjustments() { List<GenericValue> itemAdjustments = this.getAdjustments(); try { @@ -1169,9 +1203,15 @@ public class ShoppingCartItem implements java.io.Serializable { } } + /** + * Update price. + * @param dispatcher the dispatcher + * @param cart the cart + * @throws CartItemModifyException the cart item modify exception + */ public void updatePrice(LocalDispatcher dispatcher, ShoppingCart cart) throws CartItemModifyException { // set basePrice using the calculateProductPrice service - if (_product != null && isModifiedPrice == false) { + if (product != null && isModifiedPrice == false) { try { Map<String, Object> priceContext = new HashMap<>(); @@ -1197,7 +1237,7 @@ public class ShoppingCartItem implements java.io.Serializable { pieces = new BigDecimal(originalProduct.getLong("piecesIncluded")); } priceContext.put("product", originalProduct); - this._parentProduct = null; + this.parentProduct = null; } else { priceContext.put("product", this.getProduct()); } @@ -1486,7 +1526,15 @@ public class ShoppingCartItem implements java.io.Serializable { return this.quantityUsedPerPromoFailed.entrySet().iterator(); } - public synchronized BigDecimal addPromoQuantityCandidateUse(BigDecimal quantityDesired, GenericValue productPromoCondAction, boolean checkAvailableOnly) { + /** + * Add promo quantity candidate use big decimal. + * @param quantityDesired the quantity desired + * @param productPromoCondAction the product promo cond action + * @param checkAvailableOnly the check available only + * @return the big decimal + */ + public synchronized BigDecimal addPromoQuantityCandidateUse(BigDecimal quantityDesired, GenericValue productPromoCondAction, + boolean checkAvailableOnly) { if (quantityDesired.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } @@ -1836,15 +1884,28 @@ public class ShoppingCartItem implements java.io.Serializable { this.orderItemSeqId = orderItemSeqId; } + /** + * Sets shopping list. + * @param shoppingListId the shopping list id + * @param itemSeqId the item seq id + */ public void setShoppingList(String shoppingListId, String itemSeqId) { attributes.put("shoppingListId", shoppingListId); attributes.put("shoppingListItemSeqId", itemSeqId); } + /** + * Gets shopping list id. + * @return the shopping list id + */ public String getShoppingListId() { return (String) attributes.get("shoppingListId"); } + /** + * Gets shopping list item seq id. + * @return the shopping list item seq id + */ public String getShoppingListItemSeqId() { return (String) attributes.get("shoppingListItemSeqId"); } @@ -2228,6 +2289,10 @@ public class ShoppingCartItem implements java.io.Serializable { return BigDecimal.ZERO; } + /** + * Gets item product info. + * @return the item product info + */ public Map<String, Object> getItemProductInfo() { Map<String, Object> itemInfo = new HashMap<>(); itemInfo.put("productId", this.getProductId()); @@ -2250,6 +2315,7 @@ public class ShoppingCartItem implements java.io.Serializable { /** * Returns the base price. + * @return the base price */ public BigDecimal getBasePrice() { BigDecimal curBasePrice; @@ -2263,11 +2329,16 @@ public class ShoppingCartItem implements java.io.Serializable { /** * Sets the base price for the item; use with caution + * @param basePrice the base price */ public void setBasePrice(BigDecimal basePrice) { this.basePrice = basePrice; } + /** + * Gets display price. + * @return the display price + */ public BigDecimal getDisplayPrice() { BigDecimal curDisplayPrice; if (this.displayPrice == null) { @@ -2284,19 +2355,32 @@ public class ShoppingCartItem implements java.io.Serializable { /** * Sets the display price for the item; use with caution + * @param displayPrice the display price */ public void setDisplayPrice(BigDecimal displayPrice) { this.displayPrice = displayPrice; } + /** + * Gets special promo price. + * @return the special promo price + */ public BigDecimal getSpecialPromoPrice() { return this.specialPromoPrice; } + /** + * Sets special promo price. + * @param specialPromoPrice the special promo price + */ public void setSpecialPromoPrice(BigDecimal specialPromoPrice) { this.specialPromoPrice = specialPromoPrice; } + /** + * Gets recurring base price. + * @return the recurring base price + */ public BigDecimal getRecurringBasePrice() { if (this.recurringBasePrice == null) { return null; @@ -2778,6 +2862,10 @@ public class ShoppingCartItem implements java.io.Serializable { this.isPromo = isPromo; } + /** + * Gets alternative option product ids. + * @return the alternative option product ids + */ public List<String> getAlternativeOptionProductIds() { return this.alternativeOptionProductIds; } @@ -2951,17 +3039,17 @@ public class ShoppingCartItem implements java.io.Serializable { /** Gets the Product entity. If it is not already retreived gets it from the delegator */ public GenericValue getProduct() { - if (this._product != null) { - return this._product; + if (this.product != null) { + return this.product; } if (this.productId != null) { try { - this._product = this.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), true); + this.product = this.getDelegator().findOne("Product", UtilMisc.toMap("productId", productId), true); } catch (GenericEntityException e) { throw new RuntimeException("Entity Engine error getting Product (" + e.getMessage() + ")"); } } - return this._product; + return this.product; } /** @@ -2969,16 +3057,16 @@ public class ShoppingCartItem implements java.io.Serializable { * @return the parent product */ public GenericValue getParentProduct() { - if (this._parentProduct != null) { - return this._parentProduct; + if (this.parentProduct != null) { + return this.parentProduct; } if (this.productId == null) { throw new IllegalStateException("Bad product id"); } - this._parentProduct = ProductWorker.getParentProduct(productId, this.getDelegator()); + this.parentProduct = ProductWorker.getParentProduct(productId, this.getDelegator()); - return this._parentProduct; + return this.parentProduct; } /** @@ -2998,7 +3086,7 @@ public class ShoppingCartItem implements java.io.Serializable { * @return the optional product features */ public Map<String, List<GenericValue>> getOptionalProductFeatures() { - if (_product != null) { + if (product != null) { return ProductWorker.getOptionalProductFeatures(getDelegator(), this.productId); } // non-product items do not have features diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/test/FinAccountTest.java b/applications/order/src/main/java/org/apache/ofbiz/order/test/FinAccountTest.java index 35064fb..5514c72 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/test/FinAccountTest.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/test/FinAccountTest.java @@ -32,6 +32,10 @@ public class FinAccountTest extends OFBizTestCase { super(name); } + /** + * Test create fin account basic. + * @throws Exception the exception + */ public void testCreateFinAccountBasic() throws Exception { String finAccountCode; GenericValue account; diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/test/OrderTest.java b/applications/order/src/main/java/org/apache/ofbiz/order/test/OrderTest.java index b0bf9fa..597d5a2 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/test/OrderTest.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/test/OrderTest.java @@ -32,10 +32,14 @@ public class OrderTest extends OFBizTestCase { super(name); } + /** + * Test admin get next order seq id. + * @throws Exception the exception + */ public void testAdminGetNextOrderSeqId() throws Exception { Map<String, Object> ctx = new HashMap<>(); ctx.put("partyId", "admin"); //party with no AcctgPref prefix - Map<String, Object> resp = dispatcher.runSync("getNextOrderId", ctx); + Map<String, Object> resp = getDispatcher().runSync("getNextOrderId", ctx); if (ServiceUtil.isError(resp)) { Debug.logError(ServiceUtil.getErrorMessage(resp), MODULE); return; @@ -45,10 +49,14 @@ public class OrderTest extends OFBizTestCase { assertTrue(orderId.matches("\\d{5,}")); } + /** + * Test company get next order seq id. + * @throws Exception the exception + */ public void testCompanyGetNextOrderSeqId() throws Exception { Map<String, Object> ctx = new HashMap<>(); ctx.put("partyId", "Company"); //party with AcctgPref prefix : CO - Map<String, Object> resp = dispatcher.runSync("getNextOrderId", ctx); + Map<String, Object> resp = getDispatcher().runSync("getNextOrderId", ctx); if (ServiceUtil.isError(resp)) { Debug.logError(ServiceUtil.getErrorMessage(resp), MODULE); return; @@ -58,11 +66,15 @@ public class OrderTest extends OFBizTestCase { assertTrue(orderId.startsWith("CO")); } + /** + * Test complete get next order seq id. + * @throws Exception the exception + */ public void testCompleteGetNextOrderSeqId() throws Exception { Map<String, Object> ctx = new HashMap<>(); ctx.put("partyId", "Company"); //party with AcctgPref prefix : CO ctx.put("productStoreId", "9000"); // prefix WS - Map<String, Object> resp = dispatcher.runSync("getNextOrderId", ctx); + Map<String, Object> resp = getDispatcher().runSync("getNextOrderId", ctx); if (ServiceUtil.isError(resp)) { Debug.logError(ServiceUtil.getErrorMessage(resp), MODULE); return; diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/test/PurchaseOrderTest.java b/applications/order/src/main/java/org/apache/ofbiz/order/test/PurchaseOrderTest.java index 1a1ab87..d292740 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/test/PurchaseOrderTest.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/test/PurchaseOrderTest.java @@ -33,8 +33,8 @@ import org.apache.ofbiz.service.ServiceUtil; public class PurchaseOrderTest extends OFBizTestCase { private static final String MODULE = OFBizTestCase.class.getName(); - protected String orderId = null; - protected String statusId = null; + private String orderId = null; + private String statusId = null; public PurchaseOrderTest(String name) { super(name); @@ -44,6 +44,10 @@ public class PurchaseOrderTest extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test create purchase order. + * @throws Exception the exception + */ public void testCreatePurchaseOrder() throws Exception { Map<String, Object> ctx = new HashMap<>(); ctx.put("partyId", "Company"); @@ -51,7 +55,8 @@ public class PurchaseOrderTest extends OFBizTestCase { ctx.put("currencyUom", "USD"); ctx.put("productStoreId", "9000"); - GenericValue orderItem = delegator.makeValue("OrderItem", UtilMisc.toMap("orderItemSeqId", "00001", "orderItemTypeId", "PRODUCT_ORDER_ITEM", "prodCatalogId", "DemoCatalog", "productId", "GZ-1000", "quantity", new BigDecimal("2"), "isPromo", "N")); + GenericValue orderItem = delegator.makeValue("OrderItem", UtilMisc.toMap("orderItemSeqId", "00001", "orderItemTypeId", + "PRODUCT_ORDER_ITEM", "prodCatalogId", "DemoCatalog", "productId", "GZ-1000", "quantity", new BigDecimal("2"), "isPromo", "N")); orderItem.set("unitPrice", new BigDecimal("1399.5")); orderItem.set("unitListPrice", BigDecimal.ZERO); orderItem.set("isModifiedPrice", "N"); @@ -60,17 +65,20 @@ public class PurchaseOrderTest extends OFBizTestCase { orderItems.add(orderItem); ctx.put("orderItems", orderItems); - GenericValue orderContactMech = delegator.makeValue("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "SHIPPING_LOCATION", "contactMechId", "9000")); + GenericValue orderContactMech = delegator.makeValue("OrderContactMech", UtilMisc.toMap("contactMechPurposeTypeId", + "SHIPPING_LOCATION", "contactMechId", "9000")); List<GenericValue> orderContactMechs = new LinkedList<>(); orderContactMechs.add(orderContactMech); ctx.put("orderContactMechs", orderContactMechs); - GenericValue orderItemContactMech = delegator.makeValue("OrderItemContactMech", UtilMisc.toMap("contactMechPurposeTypeId", "SHIPPING_LOCATION", "contactMechId", "9000", "orderItemSeqId", "00001")); + GenericValue orderItemContactMech = delegator.makeValue("OrderItemContactMech", UtilMisc.toMap("contactMechPurposeTypeId", + "SHIPPING_LOCATION", "contactMechId", "9000", "orderItemSeqId", "00001")); List<GenericValue> orderItemContactMechs = new LinkedList<>(); orderItemContactMechs.add(orderItemContactMech); ctx.put("orderItemContactMechs", orderItemContactMechs); - GenericValue orderItemShipGroup = delegator.makeValue("OrderItemShipGroup", UtilMisc.toMap("carrierPartyId", "UPS", "contactMechId", "9000", "isGift", "N", "maySplit", "N", "shipGroupSeqId", "00001", "shipmentMethodTypeId", "NEXT_DAY")); + GenericValue orderItemShipGroup = delegator.makeValue("OrderItemShipGroup", UtilMisc.toMap("carrierPartyId", "UPS", + "contactMechId", "9000", "isGift", "N", "maySplit", "N", "shipGroupSeqId", "00001", "shipmentMethodTypeId", "NEXT_DAY")); orderItemShipGroup.set("carrierRoleTypeId", "CARRIER"); List<GenericValue> orderItemShipGroupInfo = new LinkedList<>(); orderItemShipGroupInfo.add(orderItemShipGroup); @@ -88,7 +96,7 @@ public class PurchaseOrderTest extends OFBizTestCase { ctx.put("supplierAgentPartyId", "DemoSupplier"); ctx.put("userLogin", getUserLogin("system")); - Map<String, Object> resp = dispatcher.runSync("storeOrder", ctx); + Map<String, Object> resp = getDispatcher().runSync("storeOrder", ctx); if (ServiceUtil.isError(resp)) { Debug.logError(ServiceUtil.getErrorMessage(resp), MODULE); return; diff --git a/applications/order/src/main/java/org/apache/ofbiz/order/test/SalesOrderTest.java b/applications/order/src/main/java/org/apache/ofbiz/order/test/SalesOrderTest.java index a071181..47d5bf6 100644 --- a/applications/order/src/main/java/org/apache/ofbiz/order/test/SalesOrderTest.java +++ b/applications/order/src/main/java/org/apache/ofbiz/order/test/SalesOrderTest.java @@ -41,6 +41,10 @@ public class SalesOrderTest extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test create sales order. + * @throws Exception the exception + */ public void testCreateSalesOrder() throws Exception { Map<String, Object> ctx = UtilMisc.<String, Object>toMap("partyId", "DemoCustomer", "orderTypeId", "SALES_ORDER", "currencyUom", "USD", "productStoreId", "9000"); @@ -146,7 +150,7 @@ public class SalesOrderTest extends OFBizTestCase { ctx.put("billFromVendorPartyId", "Company"); ctx.put("userLogin", getUserLogin("system")); - Map<String, Object> resp = dispatcher.runSync("storeOrder", ctx); + Map<String, Object> resp = getDispatcher().runSync("storeOrder", ctx); if (ServiceUtil.isError(resp)) { Debug.logError(ServiceUtil.getErrorMessage(resp), MODULE); return; diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java index 8e67c8a..6f9c6f9 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlFilter.java @@ -55,7 +55,15 @@ public class CatalogUrlFilter implements Filter { private static String defaultLocaleString; private static String redirectUrl; - protected FilterConfig config; + private FilterConfig config; + + /** + * Gets config. + * @return the config + */ + public FilterConfig getConfig() { + return config; + } @Override public void init(FilterConfig filterConfig) throws ServletException { @@ -87,16 +95,19 @@ public class CatalogUrlFilter implements Filter { List<EntityCondition> productContentConds = new LinkedList<>(); productContentConds.add(EntityCondition.makeCondition("productContentTypeId", "ALTERNATIVE_URL")); productContentConds.add(EntityUtil.getFilterByDateExpr()); - List<GenericValue> productContentInfos = EntityQuery.use(delegator).from("ProductContentAndInfo").where(productContentConds).orderBy("-fromDate").cache(true).queryList(); + List<GenericValue> productContentInfos = EntityQuery.use(delegator).from("ProductContentAndInfo").where(productContentConds) + .orderBy("-fromDate").cache(true).queryList(); if (UtilValidate.isNotEmpty(productContentInfos)) { for (GenericValue productContentInfo : productContentInfos) { String contentId = (String) productContentInfo.get("contentId"); - List<GenericValue> ContentAssocDataResourceViewTos = EntityQuery.use(delegator).from("ContentAssocDataResourceViewTo").where("contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", "ELECTRONIC_TEXT").cache(true).queryList(); - if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) { - for (GenericValue ContentAssocDataResourceViewTo : ContentAssocDataResourceViewTos) { - GenericValue ElectronicText = ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); - if (ElectronicText != null) { - String textData = (String) ElectronicText.get("textData"); + List<GenericValue> contentAssocDataResourceViewTos = EntityQuery.use(delegator).from("ContentAssocDataResourceViewTo") + .where("contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", + "ELECTRONIC_TEXT").cache(true).queryList(); + if (UtilValidate.isNotEmpty(contentAssocDataResourceViewTos)) { + for (GenericValue contentAssocDataResourceViewTo : contentAssocDataResourceViewTos) { + GenericValue electronicText = contentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); + if (electronicText != null) { + String textData = (String) electronicText.get("textData"); textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { String productIdStr = null; @@ -112,11 +123,12 @@ public class CatalogUrlFilter implements Filter { } } if (UtilValidate.isEmpty(productId)) { - List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView").where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT").cache(true).queryList(); + List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView") + .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT").cache(true).queryList(); for (GenericValue contentDataResourceView : contentDataResourceViews) { - GenericValue ElectronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); - if (UtilValidate.isNotEmpty(ElectronicText)) { - String textData = (String) ElectronicText.get("textData"); + GenericValue electronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); + if (UtilValidate.isNotEmpty(electronicText)) { + String textData = (String) electronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { @@ -142,16 +154,19 @@ public class CatalogUrlFilter implements Filter { List<EntityCondition> productCategoryContentConds = new LinkedList<>(); productCategoryContentConds.add(EntityCondition.makeCondition("prodCatContentTypeId", "ALTERNATIVE_URL")); productCategoryContentConds.add(EntityUtil.getFilterByDateExpr()); - List<GenericValue> productCategoryContentInfos = EntityQuery.use(delegator).from("ProductCategoryContentAndInfo").where(productCategoryContentConds).orderBy("-fromDate").cache(true).queryList(); + List<GenericValue> productCategoryContentInfos = EntityQuery.use(delegator).from("ProductCategoryContentAndInfo") + .where(productCategoryContentConds).orderBy("-fromDate").cache(true).queryList(); if (UtilValidate.isNotEmpty(productCategoryContentInfos)) { for (GenericValue productCategoryContentInfo : productCategoryContentInfos) { String contentId = (String) productCategoryContentInfo.get("contentId"); - List<GenericValue> ContentAssocDataResourceViewTos = EntityQuery.use(delegator).from("ContentAssocDataResourceViewTo").where("contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", "ELECTRONIC_TEXT").cache(true).queryList(); - if (UtilValidate.isNotEmpty(ContentAssocDataResourceViewTos)) { - for (GenericValue ContentAssocDataResourceViewTo : ContentAssocDataResourceViewTos) { - GenericValue ElectronicText = ContentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); - if (ElectronicText != null) { - String textData = (String) ElectronicText.get("textData"); + List<GenericValue> contentAssocDataResourceViewTos = EntityQuery.use(delegator).from("ContentAssocDataResourceViewTo") + .where("contentIdStart", contentId, "caContentAssocTypeId", "ALTERNATE_LOCALE", "drDataResourceTypeId", + "ELECTRONIC_TEXT").cache(true).queryList(); + if (UtilValidate.isNotEmpty(contentAssocDataResourceViewTos)) { + for (GenericValue contentAssocDataResourceViewTo : contentAssocDataResourceViewTos) { + GenericValue electronicText = contentAssocDataResourceViewTo.getRelatedOne("ElectronicText", true); + if (electronicText != null) { + String textData = (String) electronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { @@ -169,11 +184,12 @@ public class CatalogUrlFilter implements Filter { } } if (UtilValidate.isEmpty(productCategoryId)) { - List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView").where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT").cache(true).queryList(); + List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView") + .where("contentId", contentId, "drDataResourceTypeId", "ELECTRONIC_TEXT").cache(true).queryList(); for (GenericValue contentDataResourceView : contentDataResourceViews) { - GenericValue ElectronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); - if (ElectronicText != null) { - String textData = (String) ElectronicText.get("textData"); + GenericValue electronicText = contentDataResourceView.getRelatedOne("ElectronicText", true); + if (electronicText != null) { + String textData = (String) electronicText.get("textData"); if (UtilValidate.isNotEmpty(textData)) { textData = UrlServletHelper.invalidCharacter(textData); if (alternativeUrl.matches(textData + ".+$")) { @@ -206,7 +222,8 @@ public class CatalogUrlFilter implements Filter { List<EntityCondition> conds = new LinkedList<>(); conds.add(EntityCondition.makeCondition("productId", productId)); conds.add(EntityUtil.getFilterByDateExpr()); - List<GenericValue> productCategoryMembers = EntityQuery.use(delegator).select("productCategoryId").from("ProductCategoryMember").where(conds).orderBy("-fromDate").cache(true).queryList(); + List<GenericValue> productCategoryMembers = EntityQuery.use(delegator).select("productCategoryId").from("ProductCategoryMember") + .where(conds).orderBy("-fromDate").cache(true).queryList(); if (UtilValidate.isNotEmpty(productCategoryMembers)) { GenericValue productCategoryMember = EntityUtil.getFirst(productCategoryMembers); productCategoryId = productCategoryMember.getString("productCategoryId"); @@ -221,7 +238,8 @@ public class CatalogUrlFilter implements Filter { // generate trail belong to a top category String topCategoryId = CategoryWorker.getCatalogTopCategory(httpRequest, null); - List<GenericValue> trailCategories = CategoryWorker.getRelatedCategoriesRet(httpRequest, "trailCategories", topCategoryId, false, false, true); + List<GenericValue> trailCategories = CategoryWorker.getRelatedCategoriesRet(httpRequest, "trailCategories", + topCategoryId, false, false, true); List<String> trailCategoryIds = EntityUtil.getFieldListFromEntityList(trailCategories, "productCategoryId", true); // look for productCategoryId from productId @@ -230,7 +248,8 @@ public class CatalogUrlFilter implements Filter { List<EntityCondition> rolllupConds = new LinkedList<>(); rolllupConds.add(EntityCondition.makeCondition("productId", productId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); - List<GenericValue> productCategoryMembers = EntityQuery.use(delegator).from("ProductCategoryMember").where(rolllupConds).orderBy("-fromDate").cache(true).queryList(); + List<GenericValue> productCategoryMembers = EntityQuery.use(delegator).from("ProductCategoryMember").where(rolllupConds) + .orderBy("-fromDate").cache(true).queryList(); for (GenericValue productCategoryMember : productCategoryMembers) { String trailCategoryId = productCategoryMember.getString("productCategoryId"); if (trailCategoryIds.contains(trailCategoryId)) { @@ -254,7 +273,8 @@ public class CatalogUrlFilter implements Filter { List<EntityCondition> rolllupConds = new LinkedList<>(); rolllupConds.add(EntityCondition.makeCondition("productCategoryId", parentProductCategoryId)); rolllupConds.add(EntityUtil.getFilterByDateExpr()); - List<GenericValue> productCategoryRollups = EntityQuery.use(delegator).from("ProductCategoryRollup").where(rolllupConds).orderBy("-fromDate").cache(true).queryList(); + List<GenericValue> productCategoryRollups = EntityQuery.use(delegator).from("ProductCategoryRollup").where(rolllupConds) + .orderBy("-fromDate").cache(true).queryList(); if (UtilValidate.isNotEmpty(productCategoryRollups)) { // add only categories that belong to the top category to trail for (GenericValue productCategoryRollup : productCategoryRollups) { @@ -338,17 +358,21 @@ public class CatalogUrlFilter implements Filter { String searchString) { Delegator delegator = (Delegator) request.getAttribute("delegator"); try { - GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId).cache().queryOne(); + GenericValue productCategory = EntityQuery.use(delegator).from("ProductCategory").where("productCategoryId", productCategoryId) + .cache().queryOne(); CategoryContentWrapper wrapper = new CategoryContentWrapper(productCategory, request); List<String> trail = CategoryWorker.getTrail(request); - return makeCategoryUrl(delegator, wrapper, trail, request.getContextPath(), previousCategoryId, productCategoryId, productId, viewSize, viewIndex, viewSort, searchString); + return makeCategoryUrl(delegator, wrapper, trail, request.getContextPath(), previousCategoryId, productCategoryId, productId, + viewSize, viewIndex, viewSort, searchString); } catch (GenericEntityException e) { Debug.logWarning(e, "Cannot create category's URL for: " + productCategoryId, MODULE); return redirectUrl; } } - public static String makeCategoryUrl(Delegator delegator, CategoryContentWrapper wrapper, List<String> trail, String contextPath, String previousCategoryId, String productCategoryId, String productId, String viewSize, String viewIndex, String viewSort, String searchString) { + public static String makeCategoryUrl(Delegator delegator, CategoryContentWrapper wrapper, List<String> trail, String contextPath, + String previousCategoryId, String productCategoryId, String productId, String viewSize, String viewIndex, String viewSort, + String searchString) { String url = ""; StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url"); @@ -395,7 +419,7 @@ public class CatalogUrlFilter implements Filter { urlBuilder.append("searchString=" + searchString + "&"); } if (urlBuilder.toString().endsWith("&")) { - return urlBuilder.toString().substring(0, urlBuilder.toString().length()-1); + return urlBuilder.toString().substring(0, urlBuilder.toString().length() - 1); } url = urlBuilder.toString(); @@ -422,7 +446,8 @@ public class CatalogUrlFilter implements Filter { return url; } - public static String makeProductUrl(ProductContentWrapper wrapper, List<String> trail, String contextPath, String previousCategoryId, String productCategoryId, String productId) { + public static String makeProductUrl(ProductContentWrapper wrapper, List<String> trail, String contextPath, String previousCategoryId, + String productCategoryId, String productId) { String url = ""; StringWrapper alternativeUrl = wrapper.get("ALTERNATIVE_URL", "url"); if (UtilValidate.isNotEmpty(alternativeUrl) && UtilValidate.isNotEmpty(alternativeUrl.toString())) { diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlSeoFilter.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlSeoFilter.java index 8c0378f..72683aa 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlSeoFilter.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/CatalogUrlSeoFilter.java @@ -37,8 +37,8 @@ public class CatalogUrlSeoFilter extends CatalogUrlFilter { private static final String MODULE = CatalogUrlSeoFilter.class.getName(); - protected String defaultLocaleString = null; - protected String redirectUrl = null; + private String defaultLocaleString = null; + private String redirectUrl = null; @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { @@ -47,19 +47,19 @@ public class CatalogUrlSeoFilter extends CatalogUrlFilter { Delegator delegator = (Delegator) httpRequest.getSession().getServletContext().getAttribute("delegator"); // Get ServletContext - ServletContext servletContext = config.getServletContext(); + ServletContext servletContext = getConfig().getServletContext(); // Set request attribute and session UrlServletHelper.setRequestAttributes(request, delegator, servletContext); // set initial parameters - String initDefaultLocalesString = config.getInitParameter("defaultLocaleString"); - String initRedirectUrl = config.getInitParameter("redirectUrl"); + String initDefaultLocalesString = getConfig().getInitParameter("defaultLocaleString"); + String initRedirectUrl = getConfig().getInitParameter("redirectUrl"); defaultLocaleString = UtilValidate.isNotEmpty(initDefaultLocalesString) ? initDefaultLocalesString : ""; redirectUrl = UtilValidate.isNotEmpty(initRedirectUrl) ? initRedirectUrl : ""; // set the ServletContext in the request for future use - httpRequest.setAttribute("servletContext", config.getServletContext()); + httpRequest.setAttribute("servletContext", getConfig().getServletContext()); if (CatalogUrlSeoTransform.forwardUri(httpRequest, httpResponse, delegator, ControlServlet.getControlServlet())) { return; } 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 5fd01af..3e35ac6 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 @@ -54,12 +54,13 @@ public class CategoryContentWrapper implements ContentWrapper { private static final String MODULE = CategoryContentWrapper.class.getName(); public static final String SEPARATOR = "::"; // cache key separator - private static final UtilCache<String, String> categoryContentCache = UtilCache.createUtilCache("category.content", true); // use soft reference to free up memory if needed + private static final UtilCache<String, String> CATEGORY_CONTENT_CACHE = UtilCache.createUtilCache("category.content", true); + // use soft reference to free up memory if needed - protected LocalDispatcher dispatcher; - protected GenericValue productCategory; - protected Locale locale; - protected String mimeTypeId; + private LocalDispatcher dispatcher; + private GenericValue productCategory; + private Locale locale; + private String mimeTypeId; public static CategoryContentWrapper makeCategoryContentWrapper(GenericValue productCategory, HttpServletRequest request) { return new CategoryContentWrapper(productCategory, request); @@ -76,30 +77,38 @@ public class CategoryContentWrapper implements ContentWrapper { this.dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); this.productCategory = productCategory; this.locale = UtilHttp.getLocale(request); - this.mimeTypeId = EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", (Delegator) request.getAttribute("delegator")); + this.mimeTypeId = EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", + (Delegator) request.getAttribute("delegator")); } @Override public StringUtil.StringWrapper get(String prodCatContentTypeId, String encoderType) { - return StringUtil.makeStringWrapper(getProductCategoryContentAsText(productCategory, prodCatContentTypeId, locale, mimeTypeId, productCategory.getDelegator(), dispatcher, encoderType)); + return StringUtil.makeStringWrapper(getProductCategoryContentAsText(productCategory, prodCatContentTypeId, locale, + mimeTypeId, productCategory.getDelegator(), dispatcher, encoderType)); } - public static String getProductCategoryContentAsText(GenericValue productCategory, String prodCatContentTypeId, HttpServletRequest request, String encoderType) { + public static String getProductCategoryContentAsText(GenericValue productCategory, String prodCatContentTypeId, HttpServletRequest request, + String encoderType) { LocalDispatcher dispatcher = (LocalDispatcher) request.getAttribute("dispatcher"); - String mimeTypeId = EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", productCategory.getDelegator()); - return getProductCategoryContentAsText(productCategory, prodCatContentTypeId, UtilHttp.getLocale(request), mimeTypeId, productCategory.getDelegator(), dispatcher, encoderType); + String mimeTypeId = EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", + productCategory.getDelegator()); + return getProductCategoryContentAsText(productCategory, prodCatContentTypeId, UtilHttp.getLocale(request), mimeTypeId, + productCategory.getDelegator(), dispatcher, encoderType); } - public static String getProductCategoryContentAsText(GenericValue productCategory, String prodCatContentTypeId, Locale locale, LocalDispatcher dispatcher, String encoderType) { + public static String getProductCategoryContentAsText(GenericValue productCategory, String prodCatContentTypeId, Locale locale, + LocalDispatcher dispatcher, String encoderType) { return getProductCategoryContentAsText(productCategory, prodCatContentTypeId, locale, null, null, dispatcher, encoderType); } - public static String getProductCategoryContentAsText(GenericValue productCategory, String prodCatContentTypeId, Locale locale, String mimeTypeId, Delegator delegator, LocalDispatcher dispatcher, String encoderType) { + public static String getProductCategoryContentAsText(GenericValue productCategory, String prodCatContentTypeId, Locale locale, String mimeTypeId, + Delegator delegator, LocalDispatcher dispatcher, String encoderType) { String candidateFieldName = ModelUtil.dbNameToVarName(prodCatContentTypeId); UtilCodec.SimpleEncoder encoder = UtilCodec.getEncoder(encoderType); - String cacheKey = prodCatContentTypeId + SEPARATOR + locale + SEPARATOR + mimeTypeId + SEPARATOR + productCategory.get("productCategoryId") + SEPARATOR + encoderType + SEPARATOR + delegator; + String cacheKey = prodCatContentTypeId + SEPARATOR + locale + SEPARATOR + mimeTypeId + SEPARATOR + productCategory.get("productCategoryId") + + SEPARATOR + encoderType + SEPARATOR + delegator; try { - String cachedValue = categoryContentCache.get(cacheKey); + String cachedValue = CATEGORY_CONTENT_CACHE.get(cacheKey); if (cachedValue != null) { return cachedValue; } @@ -107,11 +116,11 @@ public class CategoryContentWrapper implements ContentWrapper { getProductCategoryContentAsText(null, productCategory, prodCatContentTypeId, locale, mimeTypeId, delegator, dispatcher, outWriter, false); String outString = outWriter.toString(); if (UtilValidate.isEmpty(outString)) { - outString = productCategory.getModelEntity().isField(candidateFieldName) ? productCategory.getString(candidateFieldName): ""; + outString = productCategory.getModelEntity().isField(candidateFieldName) ? productCategory.getString(candidateFieldName) : ""; outString = outString == null ? "" : outString; } outString = encoder.sanitize(outString, null); - categoryContentCache.put(cacheKey, outString); + CATEGORY_CONTENT_CACHE.put(cacheKey, outString); return outString; } catch (GeneralException | IOException e) { Debug.logError(e, "Error rendering CategoryContent, inserting empty String", MODULE); @@ -119,11 +128,15 @@ public class CategoryContentWrapper implements ContentWrapper { } } - public static void getProductCategoryContentAsText(String productCategoryId, GenericValue productCategory, String prodCatContentTypeId, Locale locale, String mimeTypeId, Delegator delegator, LocalDispatcher dispatcher, Writer outWriter) throws GeneralException, IOException { + public static void getProductCategoryContentAsText(String productCategoryId, GenericValue productCategory, String prodCatContentTypeId, + Locale locale, String mimeTypeId, Delegator delegator, LocalDispatcher dispatcher, Writer outWriter) + throws GeneralException, IOException { getProductCategoryContentAsText(null, productCategory, prodCatContentTypeId, locale, mimeTypeId, delegator, dispatcher, outWriter, true); } - public static void getProductCategoryContentAsText(String productCategoryId, GenericValue productCategory, String prodCatContentTypeId, Locale locale, String mimeTypeId, Delegator delegator, LocalDispatcher dispatcher, Writer outWriter, boolean cache) throws GeneralException, IOException { + public static void getProductCategoryContentAsText(String productCategoryId, GenericValue productCategory, String prodCatContentTypeId, + Locale locale, String mimeTypeId, Delegator delegator, LocalDispatcher dispatcher, Writer outWriter, boolean cache) + throws GeneralException, IOException { if (productCategoryId == null && productCategory != null) { productCategoryId = productCategory.getString("productCategoryId"); } @@ -140,14 +153,16 @@ public class CategoryContentWrapper implements ContentWrapper { throw new GeneralRuntimeException("Unable to find a delegator to use!"); } - List<GenericValue> categoryContentList = EntityQuery.use(delegator).from("ProductCategoryContent").where("productCategoryId", productCategoryId, "prodCatContentTypeId", prodCatContentTypeId).orderBy("-fromDate").cache(cache).filterByDate().queryList(); + List<GenericValue> categoryContentList = EntityQuery.use(delegator).from("ProductCategoryContent").where("productCategoryId", + productCategoryId, "prodCatContentTypeId", prodCatContentTypeId).orderBy("-fromDate").cache(cache).filterByDate().queryList(); GenericValue categoryContent = EntityUtil.getFirst(categoryContentList); if (categoryContent != null) { // when rendering the category content, always include the Product Category and ProductCategoryContent records that this comes from Map<String, Object> inContext = new HashMap<>(); inContext.put("productCategory", productCategory); inContext.put("categoryContent", categoryContent); - ContentWorker.renderContentAsText(dispatcher, categoryContent.getString("contentId"), outWriter, inContext, locale, mimeTypeId, null, null, cache); + ContentWorker.renderContentAsText(dispatcher, categoryContent.getString("contentId"), outWriter, inContext, + locale, mimeTypeId, null, null, cache); return; } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContentUrlFilter.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContentUrlFilter.java index 27bb0b0..7969609 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContentUrlFilter.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/SeoContentUrlFilter.java @@ -44,8 +44,8 @@ import org.apache.ofbiz.entity.util.EntityQuery; public class SeoContentUrlFilter implements Filter { private static final String MODULE = SeoContentUrlFilter.class.getName(); - protected static final String defaultLocaleString = null; - protected static final String redirectUrl = null; + protected static final String DEFAULT_LOCALE_STRING = null; + protected static final String REDIRECT_URL = null; private FilterConfig config; @Override @@ -65,11 +65,13 @@ public class SeoContentUrlFilter implements Filter { String alternativeUrl = pathInfo.substring(pathInfo.lastIndexOf('/')); if (alternativeUrl.endsWith("-content")) { try { - List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView").where("drObjectInfo", alternativeUrl).queryList(); + List<GenericValue> contentDataResourceViews = EntityQuery.use(delegator).from("ContentDataResourceView") + .where("drObjectInfo", alternativeUrl).queryList(); if (!contentDataResourceViews.isEmpty()) { contentDataResourceViews = EntityUtil.orderBy(contentDataResourceViews, UtilMisc.toList("createdDate DESC")); GenericValue contentDataResourceView = EntityUtil.getFirst(contentDataResourceViews); - List<GenericValue> contents = EntityQuery.use(delegator).from("ContentAssoc").where("contentAssocTypeId", "ALTERNATIVE_URL", "contentIdTo", contentDataResourceView.getString("contentId")).filterByDate().queryList(); + List<GenericValue> contents = EntityQuery.use(delegator).from("ContentAssoc").where("contentAssocTypeId", + "ALTERNATIVE_URL", "contentIdTo", contentDataResourceView.getString("contentId")).filterByDate().queryList(); if (!contents.isEmpty()) { GenericValue content = EntityUtil.getFirst(contents); urlContentId = content.getString("contentId"); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java index 35033eb..679c151 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/category/ftl/CatalogUrlSeoTransform.java @@ -69,7 +69,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel { private static Map<String, String> categoryNameIdMap = null; private static Map<String, String> categoryIdNameMap = null; private static boolean categoryMapInitialed = false; - private static final String asciiRegexp = "^[0-9-_a-zA-Z]*$"; + private static final String ASCII_REG_EXP = "^[0-9-_a-zA-Z]*$"; private static Pattern asciiPattern = null; public static final String URL_HYPHEN = "-"; @@ -79,7 +79,7 @@ public class CatalogUrlSeoTransform implements TemplateTransformModel { } try { Perl5Compiler perlCompiler = new Perl5Compiler(); - asciiPattern = perlCompiler.compile(asciiRegexp, Perl5Compiler.READ_ONLY_MASK); + asciiPattern = perlCompiler.compile(ASCII_REG_EXP, Perl5Compiler.READ_ONLY_MASK); } catch (MalformedPatternException e1) { Debug.logWarning(e1, MODULE); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/image/ScaleImage.java b/applications/product/src/main/java/org/apache/ofbiz/product/image/ScaleImage.java index 71a201a..637b112 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/image/ScaleImage.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/image/ScaleImage.java @@ -53,7 +53,7 @@ public class ScaleImage { private static final String MODULE = ScaleImage.class.getName(); private static final String RESOURCE = "ProductErrorUiLabels"; /* public so that other code can easily use the imageUrlMap returned by scaleImageInAllSize */ - public static final List<String> sizeTypeList = UtilMisc.toList("small", "medium", "large", "detail"); + public static final List<String> SIZE_TYPE_LIST = UtilMisc.toList("small", "medium", "large", "detail"); public ScaleImage() { @@ -73,7 +73,8 @@ public class ScaleImage { * @throws IOException Error prevents the document from being fully parsed * @throws JDOMException Errors occur in parsing */ - public static Map<String, Object> scaleImageInAllSize(Map<String, ? extends Object> context, String filenameToUse, String viewType, String viewNumber) + public static Map<String, Object> scaleImageInAllSize(Map<String, ? extends Object> context, String filenameToUse, + String viewType, String viewNumber) throws IllegalArgumentException, ImagingOpException, IOException, JDOMException { /* VARIABLES */ @@ -81,8 +82,10 @@ public class ScaleImage { int index; Map<String, Map<String, String>> imgPropertyMap = new HashMap<>(); - BufferedImage bufImg, bufNewImg; - double imgHeight, imgWidth; + BufferedImage bufImg; + BufferedImage bufNewImg; + double imgHeight; + double imgWidth; Map<String, String> imgUrlMap = new HashMap<>(); Map<String, Object> resultXMLMap = new HashMap<>(); Map<String, Object> resultBufImgMap = new HashMap<>(); @@ -111,10 +114,12 @@ public class ScaleImage { Map<String, Object> imageContext = new HashMap<>(); imageContext.putAll(context); imageContext.put("tenantId", ((Delegator) context.get("delegator")).getDelegatorTenantId()); - String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", (Delegator) context.get("delegator")), imageContext); - String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", (Delegator) context.get("delegator")), imageContext); - imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length()-1) : imageServerPath; - imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length()-1) : imageUrlPrefix; + String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.server.path", (Delegator) context.get("delegator")), imageContext); + String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.url.prefix", (Delegator) context.get("delegator")), imageContext); + imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath; + imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix; FlexibleStringExpander filenameExpander; String fileLocation = null; String id = null; @@ -124,7 +129,8 @@ public class ScaleImage { id = (String) context.get("productId"); fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "type", "original")); } else if (viewType.toLowerCase(Locale.getDefault()).contains("additional") && viewNumber != null && !"0".equals(viewNumber)) { - String filenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", (Delegator) context.get("delegator")); + String filenameFormat = EntityUtilProperties.getPropertyValue("catalog", + "image.filename.additionalviewsize.format", (Delegator) context.get("delegator")); filenameExpander = FlexibleStringExpander.getInstance(filenameFormat); id = (String) context.get("productId"); if (filenameFormat.endsWith("${id}")) { @@ -132,7 +138,8 @@ public class ScaleImage { } else { viewType = "additional" + viewNumber; } - fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", "original")); + fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, + "sizetype", "original")); } else { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ProductImageViewType", UtilMisc.toMap("viewType", viewType), locale)); } @@ -147,7 +154,8 @@ public class ScaleImage { imgHeight = bufImg.getHeight(); imgWidth = bufImg.getWidth(); if (imgHeight == 0.0 || imgWidth == 0.0) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.one_current_image_dimension_is_null", locale) + " : imgHeight = " + imgHeight + " ; imgWidth = " + imgWidth; + String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.one_current_image_dimension_is_null", locale) + " : imgHeight = " + + imgHeight + " ; imgWidth = " + imgWidth; Debug.logError(errMsg, MODULE); result.put(ModelService.ERROR_MESSAGE, errMsg); return result; @@ -170,11 +178,13 @@ public class ScaleImage { if (viewType.toLowerCase(Locale.getDefault()).contains("main")) { newFileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "type", sizeType)); } else if (viewType.toLowerCase(Locale.getDefault()).contains("additional")) { - newFileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", sizeType)); + newFileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", + viewType, "sizetype", sizeType)); } String newFilePathPrefix = ""; if (newFileLocation != null && newFileLocation.lastIndexOf('/') != -1) { - newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf('/') + 1); // adding 1 to include the trailing slash + newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf('/') + 1); + // adding 1 to include the trailing slash } // Directory String targetDirectory = imageServerPath + "/" + newFilePathPrefix; @@ -184,7 +194,8 @@ public class ScaleImage { if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory; + String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.unable_to_create_target_directory", locale) + + " - " + targetDirectory; Debug.logFatal(errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -224,7 +235,7 @@ public class ScaleImage { } // Save each Url - if (sizeTypeList.contains(sizeType)) { + if (SIZE_TYPE_LIST.contains(sizeType)) { String imageUrl = imageUrlPrefix + "/" + newFileLocation + "." + imgExtension; imgUrlMap.put(sizeType, imageUrl); } @@ -245,7 +256,8 @@ public class ScaleImage { } } - public static Map<String, Object> scaleImageManageInAllSize(Map<String, ? extends Object> context, String filenameToUse, String viewType, String viewNumber, String imageType) + public static Map<String, Object> scaleImageManageInAllSize(Map<String, ? extends Object> context, String filenameToUse, + String viewType, String viewNumber, String imageType) throws IllegalArgumentException, ImagingOpException, IOException, JDOMException { /* VARIABLES */ @@ -259,8 +271,10 @@ public class ScaleImage { int index; Map<String, Map<String, String>> imgPropertyMap = new HashMap<>(); - BufferedImage bufImg, bufNewImg; - double imgHeight, imgWidth; + BufferedImage bufImg; + BufferedImage bufNewImg; + double imgHeight; + double imgWidth; Map<String, String> imgUrlMap = new HashMap<>(); Map<String, Object> resultXMLMap = new HashMap<>(); Map<String, Object> resultBufImgMap = new HashMap<>(); @@ -291,10 +305,12 @@ public class ScaleImage { imageContext.put("tenantId", ((Delegator) context.get("delegator")).getDelegatorTenantId()); String mainFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.format", (Delegator) context.get("delegator")); - String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", (Delegator) context.get("delegator")), imageContext); - String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", (Delegator) context.get("delegator")), imageContext); - imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length()-1) : imageServerPath; - imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length()-1) : imageUrlPrefix; + String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.server.path", (Delegator) context.get("delegator")), imageContext); + String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.url.prefix", (Delegator) context.get("delegator")), imageContext); + imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath; + imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix; String id = null; String type = null; if (viewType.toLowerCase().contains("main")) { @@ -315,7 +331,8 @@ public class ScaleImage { } if (context.get("contentId") != null) { - resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + context.get("productId") + "/" + context.get("clientFileName"), locale)); + resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + context.get("productId") + "/" + + context.get("clientFileName"), locale)); } else { /* get original BUFFERED IMAGE */ resultBufImgMap.putAll(ImageTransform.getBufferedImage(imageServerPath + "/" + filePathPrefix + filenameToUse, locale)); @@ -328,7 +345,8 @@ public class ScaleImage { imgHeight = bufImg.getHeight(); imgWidth = bufImg.getWidth(); if (imgHeight == 0.0 || imgWidth == 0.0) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.one_current_image_dimension_is_null", locale) + " : imgHeight = " + imgHeight + " ; imgWidth = " + imgWidth; + String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.one_current_image_dimension_is_null", locale) + + " : imgHeight = " + imgHeight + " ; imgWidth = " + imgWidth; Debug.logError(errMsg, MODULE); result.put(ModelService.ERROR_MESSAGE, errMsg); return result; @@ -337,7 +355,8 @@ public class ScaleImage { // new Filename Format FlexibleStringExpander addFilenameExpander = mainFilenameExpander; if (viewType.toLowerCase(Locale.getDefault()).contains("additional")) { - String addFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", (Delegator) context.get("delegator")); + String addFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", + "image.filename.additionalviewsize.format", (Delegator) context.get("delegator")); addFilenameExpander = FlexibleStringExpander.getInstance(addFilenameFormat); } @@ -353,11 +372,13 @@ public class ScaleImage { if (viewType.toLowerCase(Locale.getDefault()).contains("main")) { newFileLocation = mainFilenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "type", sizeType)); } else if (viewType.toLowerCase(Locale.getDefault()).contains("additional")) { - newFileLocation = addFilenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", sizeType)); + newFileLocation = addFilenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, + "viewtype", viewType, "sizetype", sizeType)); } String newFilePathPrefix = ""; if (newFileLocation != null && newFileLocation.lastIndexOf('/') != -1) { - newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf('/') + 1); // adding 1 to include the trailing slash + newFilePathPrefix = newFileLocation.substring(0, newFileLocation.lastIndexOf('/') + 1); + // adding 1 to include the trailing slash } String targetDirectory = imageServerPath + "/" + newFilePathPrefix; @@ -365,7 +386,8 @@ public class ScaleImage { if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory; + String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.unable_to_create_target_directory", locale) + + " - " + targetDirectory; Debug.logFatal(errMsg, MODULE); return ServiceUtil.returnError(errMsg); } 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 ff08f10..fbb6c6b 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 @@ -121,7 +121,8 @@ public class ProductServices { products.add(EntityQuery.use(delegator).from("Product").where("productId", oneVariant.getString("productIdTo")).queryOne()); } catch (GenericEntityException e) { Map<String, String> messageMap = UtilMisc.toMap("errProductFeatures", e.toString()); - String errMsg = UtilProperties.getMessage(RES_ERROR, "productservices.problem_reading_product_features_errors", messageMap, locale); + String errMsg = UtilProperties.getMessage(RES_ERROR, "productservices.problem_reading_product_features_errors", + messageMap, locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -144,11 +145,13 @@ public class ProductServices { productFeatureApplTypeId = "SELECTABLE_FEATURE"; } Locale locale = (Locale) context.get("locale"); - String errMsg=null; + String errMsg = null; Set<String> featureSet = new LinkedHashSet<>(); try { - List<GenericValue> features = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureApplTypeId", productFeatureApplTypeId).orderBy("sequenceNum", "productFeatureTypeId").cache(true).filterByDate().queryList(); + List<GenericValue> features = EntityQuery.use(delegator).from("ProductFeatureAndAppl") + .where("productId", productId, "productFeatureApplTypeId", productFeatureApplTypeId).orderBy("sequenceNum", + "productFeatureTypeId").cache(true).filterByDate().queryList(); for (GenericValue v: features) { featureSet.add(v.getString("productFeatureTypeId")); } @@ -220,7 +223,8 @@ public class ProductServices { if (productTo.get("introductionDate") != null && nowTimestamp.before(productTo.getTimestamp("introductionDate"))) { if (Debug.verboseOn()) { String excMsg = "Tried to view the Product " + productTo.getString("productName") - + " (productId: " + productTo.getString("productId") + ") as a variant. This product has not yet been made available for sale, so not adding for view."; + + " (productId: " + productTo.getString("productId") + + ") as a variant. This product has not yet been made available for sale, so not adding for view."; Debug.logVerbose(excMsg, MODULE); } @@ -231,7 +235,8 @@ public class ProductServices { if (productTo.get("salesDiscontinuationDate") != null && nowTimestamp.after(productTo.getTimestamp("salesDiscontinuationDate"))) { if (Debug.verboseOn()) { String excMsg = "Tried to view the Product " + productTo.getString("productName") - + " (productId: " + productTo.getString("productId") + ") as a variant. This product is no longer available for sale, so not adding for view."; + + " (productId: " + productTo.getString("productId") + + ") as a variant. This product is no longer available for sale, so not adding for view."; Debug.logVerbose(excMsg, MODULE); } @@ -242,7 +247,8 @@ public class ProductServices { Boolean checkInventory = (Boolean) context.get("checkInventory"); try { if (checkInventory) { - Map<String, Object> invReqResult = dispatcher.runSync("isStoreInventoryAvailableOrNotRequired", UtilMisc.<String, Object>toMap("productStoreId", productStoreId, "productId", productIdTo, "quantity", BigDecimal.ONE)); + Map<String, Object> invReqResult = dispatcher.runSync("isStoreInventoryAvailableOrNotRequired", + UtilMisc.<String, Object>toMap("productStoreId", productStoreId, "productId", productIdTo, "quantity", BigDecimal.ONE)); if (ServiceUtil.isError(invReqResult)) { return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ProductFeatureTreeCannotCallIsStoreInventoryRequired", locale), null, null, invReqResult); @@ -272,7 +278,8 @@ public class ProductServices { // Make the selectable feature list List<GenericValue> selectableFeatures = null; try { - selectableFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureApplTypeId", "SELECTABLE_FEATURE").orderBy("sequenceNum").cache(true).filterByDate().queryList(); + selectableFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureApplTypeId", + "SELECTABLE_FEATURE").orderBy("sequenceNum").cache(true).filterByDate().queryList(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, @@ -339,7 +346,7 @@ public class ProductServices { String distinct = (String) context.get("distinct"); String type = (String) context.get("type"); Locale locale = (Locale) context.get("locale"); - String errMsg=null; + String errMsg = null; List<GenericValue> features = null; try { @@ -351,7 +358,8 @@ public class ProductServices { if (type != null) { fields.put("productFeatureApplTypeId", type); } - features = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where(fields).orderBy("sequenceNum", "productFeatureTypeId").cache(true).queryList(); + features = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where(fields).orderBy("sequenceNum", "productFeatureTypeId") + .cache(true).queryList(); result.put("productFeatures", features); result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); } catch (GenericEntityException e) { @@ -387,7 +395,8 @@ public class ProductServices { GenericValue mainProduct = product; if (product.get("isVariant") != null && "Y".equalsIgnoreCase(product.getString("isVariant"))) { - List<GenericValue> c = product.getRelated("AssocProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_VARIANT"), null, true); + List<GenericValue> c = product.getRelated("AssocProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_VARIANT"), + null, true); c = EntityUtil.filterByDate(c); if (!c.isEmpty()) { GenericValue asV = c.iterator().next(); @@ -482,7 +491,8 @@ public class ProductServices { UtilMisc.toList( EntityCondition.makeCondition("productId", productId), EntityCondition.makeCondition("productIdTo", productId)), EntityJoinOperator.OR); - productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where(EntityCondition.makeCondition(cond, EntityCondition.makeCondition("productAssocTypeId", type))).orderBy(orderBy).cache(true).queryList(); + productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where(EntityCondition.makeCondition(cond, + EntityCondition.makeCondition("productAssocTypeId", type))).orderBy(orderBy).cache(true).queryList(); } else { if (productIdTo == null) { productAssocs = product.getRelated("MainProductAssoc", UtilMisc.toMap("productAssocTypeId", type), orderBy, true); @@ -497,7 +507,8 @@ public class ProductServices { String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, prodCatalogId); if (viewProductCategoryId != null) { if (productIdTo == null) { - productAssocs = CategoryWorker.filterProductsInCategory(delegator, productAssocs, viewProductCategoryId, "productIdTo"); + productAssocs = CategoryWorker.filterProductsInCategory(delegator, productAssocs, viewProductCategoryId, + "productIdTo"); } else { productAssocs = CategoryWorker.filterProductsInCategory(delegator, productAssocs, viewProductCategoryId, "productId"); } @@ -520,7 +531,8 @@ public class ProductServices { } // Builds a product feature tree - private static Map<String, Object> makeGroup(Delegator delegator, Map<String, List<String>> featureList, List<String> items, List<String> order, int index) + private static Map<String, Object> makeGroup(Delegator delegator, Map<String, List<String>> featureList, List<String> items, + List<String> order, int index) throws IllegalArgumentException, IllegalStateException { Map<String, List<String>> tempGroup = new HashMap<>(); Map<String, Object> group = new LinkedHashMap<>(); @@ -624,7 +636,8 @@ public class ProductServices { } // builds a variant sample (a single sku for a featureType) - private static Map<String, GenericValue> makeVariantSample(Delegator delegator, Map<String, List<String>> featureList, List<String> items, String feature) { + private static Map<String, GenericValue> makeVariantSample(Delegator delegator, Map<String, List<String>> featureList, + List<String> items, String feature) { Map<String, GenericValue> tempSample = new HashMap<>(); Map<String, GenericValue> sample = new LinkedHashMap<>(); for (String productId: items) { @@ -667,7 +680,7 @@ public class ProductServices { Delegator delegator = dctx.getDelegator(); Map<String, Object> result = new HashMap<>(); Locale locale = (Locale) context.get("locale"); - String errMsg=null; + String errMsg = null; String productId = (String) context.get("productId"); String variantProductId = (String) context.get("productVariantId"); String productFeatureIds = (String) context.get("productFeatureIds"); @@ -727,11 +740,12 @@ public class ProductServices { while (st.hasMoreTokens()) { String productFeatureId = st.nextToken(); - GenericValue productFeature = EntityQuery.use(delegator).from("ProductFeature").where("productFeatureId", productFeatureId).queryOne(); + GenericValue productFeature = EntityQuery.use(delegator).from("ProductFeature") + .where("productFeatureId", productFeatureId).queryOne(); GenericValue productFeatureAppl = delegator.makeValue("ProductFeatureAppl", - UtilMisc.toMap("productId", variantProductId, "productFeatureId", productFeatureId, - "productFeatureApplTypeId", "STANDARD_FEATURE", "fromDate", UtilDateTime.nowTimestamp())); + UtilMisc.toMap("productId", variantProductId, "productFeatureId", productFeatureId, + "productFeatureApplTypeId", "STANDARD_FEATURE", "fromDate", UtilDateTime.nowTimestamp())); // set the default seq num if it's there... if (productFeature != null) { @@ -817,7 +831,8 @@ public class ProductServices { variantProductsById.put(variantProductId, variantProduct); } else { // is a GoodIdentification.idValue? - List<GenericValue> goodIdentificationList = EntityQuery.use(delegator).from("GoodIdentification").where("idValue", variantProductId).queryList(); + List<GenericValue> goodIdentificationList = EntityQuery.use(delegator).from("GoodIdentification") + .where("idValue", variantProductId).queryList(); if (UtilValidate.isEmpty(goodIdentificationList)) { // whoops, nothing found... return error return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, @@ -826,7 +841,9 @@ public class ProductServices { if (goodIdentificationList.size() > 1) { // what to do here? for now just log a warning and add all of them as variants; they can always be dissociated later - Debug.logWarning("Warning creating a virtual with variants: the ID [" + variantProductId + "] was not a productId and resulted in [" + goodIdentificationList.size() + "] GoodIdentification records: " + goodIdentificationList, MODULE); + Debug.logWarning("Warning creating a virtual with variants: the ID [" + variantProductId + + "] was not a productId and resulted in [" + goodIdentificationList.size() + "] GoodIdentification records: " + + goodIdentificationList, MODULE); } for (GenericValue goodIdentification: goodIdentificationList) { @@ -872,7 +889,8 @@ public class ProductServices { productAssoc.create(); } } catch (GenericEntityException e) { - String errMsg = UtilProperties.getMessage(RES_ERROR, "ProductErrorCreatingNewVirtualProductFromVariantProducts", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RES_ERROR, "ProductErrorCreatingNewVirtualProductFromVariantProducts", + UtilMisc.toMap("errorString", e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -909,7 +927,8 @@ public class ProductServices { if (salesDiscontinuationDate != null && salesDiscontinuationDate.before(UtilDateTime.nowTimestamp())) { Map<String, Object> invRes = null; try { - invRes = dispatcher.runSync("getProductInventoryAvailable", UtilMisc.<String, Object>toMap("productId", productId, "userLogin", userLogin)); + invRes = dispatcher.runSync("getProductInventoryAvailable", + UtilMisc.<String, Object>toMap("productId", productId, "userLogin", userLogin)); if (ServiceUtil.isError(invRes)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(invRes)); } @@ -963,10 +982,12 @@ public class ProductServices { imageContext.put("tenantId", delegator.getDelegatorTenantId()); String imageFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.additionalviewsize.format", delegator); - String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", delegator), imageContext); - String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", delegator), imageContext); - imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length()-1) : imageServerPath; - imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length()-1) : imageUrlPrefix; + String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.server.path", delegator), imageContext); + String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.url.prefix", delegator), imageContext); + imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath; + imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix; FlexibleStringExpander filenameExpander = FlexibleStringExpander.getInstance(imageFilenameFormat); String viewNumber = String.valueOf(productContentTypeId.charAt(productContentTypeId.length() - 1)); String viewType = "additional" + viewNumber; @@ -975,7 +996,8 @@ public class ProductServices { id = productId + "_View_" + viewNumber; viewType = "additional"; } - String fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, "viewtype", viewType, "sizetype", "original")); + String fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "id", id, + "viewtype", viewType, "sizetype", "original")); String filePathPrefix = ""; String filenameToUse = fileLocation; if (fileLocation.lastIndexOf('/') != -1) { @@ -1007,7 +1029,8 @@ public class ProductServices { if (!targetDir.exists()) { boolean created = targetDir.mkdirs(); if (!created) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.unable_to_create_target_directory", locale) + " - " + targetDirectory; + String errMsg = UtilProperties.getMessage(RESOURCE, "ScaleImage.unable_to_create_target_directory", locale) + + " - " + targetDirectory; Debug.logFatal(errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -1047,7 +1070,7 @@ public class ProductServices { } // Write try { - File file = new File(imageServerPath + "/" + fileLocation + "." + extension.getString("fileExtensionId")); + File file = new File(imageServerPath + "/" + fileLocation + "." + extension.getString("fileExtensionId")); try { RandomAccessFile out = new RandomAccessFile(file, "rw"); out.write(imageData.array()); @@ -1079,7 +1102,7 @@ public class ProductServices { "ProductImageViewParsingError", UtilMisc.toMap("errorString", e.toString()), locale)); } - String imageUrl = imageUrlPrefix + "/" + fileLocation + "." + extension.getString("fileExtensionId"); + String imageUrl = imageUrlPrefix + "/" + fileLocation + "." + extension.getString("fileExtensionId"); /* store the imageUrl version of the image, for backwards compatibility with code that does not use scaled versions */ Map<String, Object> result = addImageResource(dispatcher, delegator, context, imageUrl, productContentTypeId); @@ -1090,7 +1113,7 @@ public class ProductServices { /* now store the image versions created by ScaleImage.scaleImageInAllSize */ /* have to shrink length of productContentTypeId, as otherwise value is too long for database field */ Map<String, String> imageUrlMap = UtilGenerics.cast(resultResize.get("imageUrlMap")); - for (String sizeType : ScaleImage.sizeTypeList) { + for (String sizeType : ScaleImage.SIZE_TYPE_LIST) { imageUrl = imageUrlMap.get(sizeType); if (UtilValidate.isNotEmpty(imageUrl)) { try { @@ -1100,7 +1123,8 @@ public class ProductServices { .cache() .queryOne(); if (UtilValidate.isNotEmpty(productContentType)) { - result = addImageResource(dispatcher, delegator, context, imageUrl, "XTRA_IMG_" + viewNumber + "_" + sizeType.toUpperCase(Locale.getDefault())); + result = addImageResource(dispatcher, delegator, context, imageUrl, "XTRA_IMG_" + + viewNumber + "_" + sizeType.toUpperCase(Locale.getDefault())); if (ServiceUtil.isError(result)) { Debug.logError(ServiceUtil.getErrorMessage(result), MODULE); return result; @@ -1117,7 +1141,7 @@ public class ProductServices { } private static Map<String, Object> addImageResource(LocalDispatcher dispatcher, Delegator delegator, Map<String, ? extends Object> context, - String imageUrl, String productContentTypeId ) { + String imageUrl, String productContentTypeId) { GenericValue userLogin = (GenericValue) context.get("userLogin"); String productId = (String) context.get("productId"); @@ -1246,7 +1270,7 @@ public class ProductServices { } } } - return ServiceUtil.returnSuccess(); + return ServiceUtil.returnSuccess(); } /** @@ -1263,7 +1287,7 @@ public class ProductServices { String searchAllIdContext = (String) context.get("searchAllId"); boolean searchProductFirst = UtilValidate.isNotEmpty(searchProductFirstContext) && "N".equals(searchProductFirstContext) ? false : true; - boolean searchAllId = UtilValidate.isNotEmpty(searchAllIdContext)&& "Y".equals(searchAllIdContext) ? true : false; + boolean searchAllId = UtilValidate.isNotEmpty(searchAllIdContext) && "Y".equals(searchAllIdContext) ? true : false; GenericValue product = null; List<GenericValue> productsFound = null; @@ -1305,10 +1329,12 @@ public class ProductServices { imageContext.put("tenantId", delegator.getDelegatorTenantId()); String imageFilenameFormat = EntityUtilProperties.getPropertyValue("catalog", "image.filename.format", delegator); - String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.server.path", delegator), imageContext); - String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", "image.url.prefix", delegator), imageContext); - imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length()-1) : imageServerPath; - imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length()-1) : imageUrlPrefix; + String imageServerPath = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.server.path", delegator), imageContext); + String imageUrlPrefix = FlexibleStringExpander.expandString(EntityUtilProperties.getPropertyValue("catalog", + "image.url.prefix", delegator), imageContext); + imageServerPath = imageServerPath.endsWith("/") ? imageServerPath.substring(0, imageServerPath.length() - 1) : imageServerPath; + imageUrlPrefix = imageUrlPrefix.endsWith("/") ? imageUrlPrefix.substring(0, imageUrlPrefix.length() - 1) : imageUrlPrefix; FlexibleStringExpander filenameExpander = FlexibleStringExpander.getInstance(imageFilenameFormat); String id = productPromoId + "_Image_" + productPromoContentTypeId.charAt(productPromoContentTypeId.length() - 1); String fileLocation = filenameExpander.expandString(UtilMisc.toMap("location", "products", "type", "promo", "id", id)); 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 f8fa945..359a78c 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 @@ -64,7 +64,8 @@ public final class ProductWorker { String errMsg = ""; if (product != null) { String productTypeId = product.getString("productTypeId"); - if ("SERVICE".equals(productTypeId) || "SERVICE_PRODUCT".equals(productTypeId) || (ProductWorker.isDigital(product) && !ProductWorker.isPhysical(product))) { + if ("SERVICE".equals(productTypeId) || "SERVICE_PRODUCT".equals(productTypeId) || (ProductWorker.isDigital(product) + && !ProductWorker.isPhysical(product))) { // don't charge shipping on services or digital goods return false; } @@ -116,8 +117,8 @@ public final class ProductWorker { for (GenericValue productGeo: includeGeos) { List<GenericValue> includeGeoGroup = GeoWorker.expandGeoGroup(productGeo.getString("geoId"), delegator); if (GeoWorker.containsGeo(includeGeoGroup, postalAddress.getString("countryGeoId"), delegator) - || GeoWorker.containsGeo(includeGeoGroup, postalAddress.getString("stateProvinceGeoId"), delegator) - || GeoWorker.containsGeo(includeGeoGroup, postalAddress.getString("postalCodeGeoId"), delegator)) { + || GeoWorker.containsGeo(includeGeoGroup, postalAddress.getString("stateProvinceGeoId"), delegator) + || GeoWorker.containsGeo(includeGeoGroup, postalAddress.getString("postalCodeGeoId"), delegator)) { return true; } } @@ -127,7 +128,7 @@ public final class ProductWorker { } return false; } - public static boolean isSerialized (Delegator delegator, String productId) { + public static boolean isSerialized(Delegator delegator, String productId) { try { GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne(); if (product != null) { @@ -155,8 +156,10 @@ public final class ProductWorker { public static String getInstanceAggregatedId(Delegator delegator, String instanceProductId) throws GenericEntityException { GenericValue instanceProduct = EntityQuery.use(delegator).from("Product").where("productId", instanceProductId).queryOne(); - if (instanceProduct != null && EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", instanceProduct.getString("productTypeId"), "parentTypeId", "AGGREGATED")) { - GenericValue productAssoc = EntityUtil.getFirst(EntityUtil.filterByDate(instanceProduct.getRelated("AssocProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_CONF"), null, false))); + if (instanceProduct != null && EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", + instanceProduct.getString("productTypeId"), "parentTypeId", "AGGREGATED")) { + GenericValue productAssoc = EntityUtil.getFirst(EntityUtil.filterByDate(instanceProduct.getRelated("AssocProductAssoc", + UtilMisc.toMap("productAssocTypeId", "PRODUCT_CONF"), null, false))); if (productAssoc != null) { return productAssoc.getString("productId"); } @@ -180,8 +183,10 @@ public final class ProductWorker { public static List<GenericValue> getAggregatedAssocs(Delegator delegator, String aggregatedProductId) throws GenericEntityException { GenericValue aggregatedProduct = EntityQuery.use(delegator).from("Product").where("productId", aggregatedProductId).queryOne(); - if (aggregatedProduct != null && ("AGGREGATED".equals(aggregatedProduct.getString("productTypeId")) || "AGGREGATED_SERVICE".equals(aggregatedProduct.getString("productTypeId")))) { - List<GenericValue> productAssocs = EntityUtil.filterByDate(aggregatedProduct.getRelated("MainProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_CONF"), null, false)); + if (aggregatedProduct != null && ("AGGREGATED".equals(aggregatedProduct.getString("productTypeId")) + || "AGGREGATED_SERVICE".equals(aggregatedProduct.getString("productTypeId")))) { + List<GenericValue> productAssocs = EntityUtil.filterByDate(aggregatedProduct.getRelated("MainProductAssoc", + UtilMisc.toMap("productAssocTypeId", "PRODUCT_CONF"), null, false)); return productAssocs; } return null; @@ -201,7 +206,8 @@ public final class ProductWorker { public static List<GenericValue> getVariantVirtualAssocs(GenericValue variantProduct) throws GenericEntityException { if (variantProduct != null && "Y".equals(variantProduct.getString("isVariant"))) { - List<GenericValue> productAssocs = EntityUtil.filterByDate(variantProduct.getRelated("AssocProductAssoc", UtilMisc.toMap("productAssocTypeId", "PRODUCT_VARIANT"), null, true)); + List<GenericValue> productAssocs = EntityUtil.filterByDate(variantProduct.getRelated("AssocProductAssoc", + UtilMisc.toMap("productAssocTypeId", "PRODUCT_VARIANT"), null, true)); return productAssocs; } return null; @@ -211,7 +217,8 @@ public final class ProductWorker { * invokes the getInventoryAvailableByFacility service, returns true if specified quantity is available, else false * this is only used in the related method that uses a ProductConfigWrapper, until that is refactored into a service as well... */ - private static boolean isProductInventoryAvailableByFacility(String productId, String inventoryFacilityId, BigDecimal quantity, LocalDispatcher dispatcher) { + private static boolean isProductInventoryAvailableByFacility(String productId, String inventoryFacilityId, BigDecimal quantity, + LocalDispatcher dispatcher) { BigDecimal availableToPromise = null; try { @@ -221,7 +228,8 @@ public final class ProductWorker { availableToPromise = (BigDecimal) result.get("availableToPromiseTotal"); if (availableToPromise == null) { - Debug.logWarning("The getInventoryAvailableByFacility service returned a null availableToPromise, the error message was:\n" + result.get(ModelService.ERROR_MESSAGE), MODULE); + Debug.logWarning("The getInventoryAvailableByFacility service returned a null availableToPromise, the error message was:\n" + + result.get(ModelService.ERROR_MESSAGE), MODULE); return false; } } catch (GenericServiceException e) { @@ -232,7 +240,8 @@ public final class ProductWorker { // check to see if we got enough back... if (availableToPromise.compareTo(quantity) >= 0) { if (Debug.infoOn()) { - Debug.logInfo("Inventory IS available in facility with id " + inventoryFacilityId + " for product id " + productId + "; desired quantity is " + quantity + ", available quantity is " + availableToPromise, MODULE); + Debug.logInfo("Inventory IS available in facility with id " + inventoryFacilityId + " for product id " + productId + + "; desired quantity is " + quantity + ", available quantity is " + availableToPromise, MODULE); } return true; } @@ -248,7 +257,8 @@ public final class ProductWorker { * Invokes the getInventoryAvailableByFacility service, returns true if specified quantity is available for all the selected parts, else false. * Also, set the available flag for all the product configuration's options. **/ - public static boolean isProductInventoryAvailableByFacility(ProductConfigWrapper productConfig, String inventoryFacilityId, BigDecimal quantity, LocalDispatcher dispatcher) { + public static boolean isProductInventoryAvailableByFacility(ProductConfigWrapper productConfig, String inventoryFacilityId, + BigDecimal quantity, LocalDispatcher dispatcher) { boolean available = true; List<ConfigOption> options = productConfig.getSelectedOptions(); for (ConfigOption ci: options) { @@ -273,7 +283,8 @@ public final class ProductWorker { /** * Gets ProductFeature GenericValue for all distinguishing features of a variant product. - * Distinguishing means all features that are selectable on the corresponding virtual product and standard on the variant plus all DISTINGUISHING_FEAT assoc type features on the variant. + * Distinguishing means all features that are selectable on the corresponding virtual product and standard on the variant + * plus all DISTINGUISHING_FEAT assoc type features on the variant. */ public static Set<GenericValue> getVariantDistinguishingFeatures(GenericValue variantProduct) throws GenericEntityException { if (variantProduct == null) { @@ -288,7 +299,8 @@ public final class ProductWorker { // find all selectable features on the virtual product that are also standard features on the variant Set<GenericValue> distFeatures = new HashSet<>(); - List<GenericValue> variantDistinguishingFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", variantProduct.get("productId"), "productFeatureApplTypeId", "DISTINGUISHING_FEAT").cache(true).queryList(); + List<GenericValue> variantDistinguishingFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl") + .where("productId", variantProduct.get("productId"), "productFeatureApplTypeId", "DISTINGUISHING_FEAT").cache(true).queryList(); for (GenericValue variantDistinguishingFeature: EntityUtil.filterByDate(variantDistinguishingFeatures)) { GenericValue dummyFeature = delegator.makeValue("ProductFeature"); @@ -296,14 +308,16 @@ public final class ProductWorker { distFeatures.add(dummyFeature); } - List<GenericValue> virtualSelectableFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", virtualProductId, "productFeatureApplTypeId", "SELECTABLE_FEATURE").cache(true).queryList(); + List<GenericValue> virtualSelectableFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl") + .where("productId", virtualProductId, "productFeatureApplTypeId", "SELECTABLE_FEATURE").cache(true).queryList(); Set<String> virtualSelectableFeatureIds = new HashSet<>(); for (GenericValue virtualSelectableFeature: EntityUtil.filterByDate(virtualSelectableFeatures)) { virtualSelectableFeatureIds.add(virtualSelectableFeature.getString("productFeatureId")); } - List<GenericValue> variantStandardFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", variantProduct.get("productId"), "productFeatureApplTypeId", "STANDARD_FEATURE").cache(true).queryList(); + List<GenericValue> variantStandardFeatures = EntityQuery.use(delegator).from("ProductFeatureAndAppl") + .where("productId", variantProduct.get("productId"), "productFeatureApplTypeId", "STANDARD_FEATURE").cache(true).queryList(); for (GenericValue variantStandardFeature: EntityUtil.filterByDate(variantStandardFeatures)) { if (virtualSelectableFeatureIds.contains(variantStandardFeature.get("productFeatureId"))) { @@ -318,11 +332,14 @@ public final class ProductWorker { /** * Get the name to show to the customer for GWP alternative options. - * If the alternative is a variant, find the distinguishing features and show those instead of the name; if it is not a variant then show the PRODUCT_NAME content. + * If the alternative is a variant, find the distinguishing features and show those instead of the name; if it is not a variant then show the + * PRODUCT_NAME content. */ - public static String getGwpAlternativeOptionName(LocalDispatcher dispatcher, Delegator delegator, String alternativeOptionProductId, Locale locale) { + public static String getGwpAlternativeOptionName(LocalDispatcher dispatcher, Delegator delegator, String alternativeOptionProductId, + Locale locale) { try { - GenericValue alternativeOptionProduct = EntityQuery.use(delegator).from("Product").where("productId", alternativeOptionProductId).cache().queryOne(); + GenericValue alternativeOptionProduct = EntityQuery.use(delegator).from("Product").where("productId", alternativeOptionProductId) + .cache().queryOne(); if (alternativeOptionProduct != null) { if ("Y".equals(alternativeOptionProduct.getString("isVariant"))) { Set<GenericValue> distFeatures = getVariantDistinguishingFeatures(alternativeOptionProduct); @@ -344,7 +361,8 @@ public final class ProductWorker { } // got to here, default to PRODUCT_NAME - String alternativeProductName = ProductContentWrapper.getProductContentAsText(alternativeOptionProduct, "PRODUCT_NAME", locale, dispatcher, "html"); + String alternativeProductName = ProductContentWrapper.getProductContentAsText(alternativeOptionProduct, "PRODUCT_NAME", + locale, dispatcher, "html"); return alternativeProductName; } } catch (GenericEntityException e) { @@ -425,10 +443,9 @@ public final class ProductWorker { Delegator delegator = product.getDelegator(); List<GenericValue> featuresSorted = EntityQuery.use(delegator) .from("ProductFeatureAndAppl") - .where("productId", product.getString("productId"), "productFeatureApplTypeId", "SELECTABLE_FEATURE") - .orderBy("productFeatureTypeId", "sequenceNum") - .cache(true) - .queryList(); + .where("productId", product.getString("productId"), + "productFeatureApplTypeId", "SELECTABLE_FEATURE") + .orderBy("productFeatureTypeId", "sequenceNum").cache(true).queryList(); String oldType = null; List<Map<String, String>> featureList = new LinkedList<>(); for (GenericValue productFeatureAppl: featuresSorted) { @@ -438,7 +455,8 @@ public final class ProductWorker { featureTypeFeatures.add(featureList); featureList = new LinkedList<>(); } - GenericValue productFeatureType = EntityQuery.use(delegator).from("ProductFeatureType").where("productFeatureTypeId", productFeatureAppl.getString("productFeatureTypeId")).queryOne(); + GenericValue productFeatureType = EntityQuery.use(delegator).from("ProductFeatureType").where("productFeatureTypeId", + productFeatureAppl.getString("productFeatureTypeId")).queryOne(); featureList.add(UtilMisc.<String, String>toMap("productFeatureTypeId", productFeatureAppl.getString("productFeatureTypeId"), "description", productFeatureType.getString("description"))); oldType = productFeatureAppl.getString("productFeatureTypeId"); @@ -510,7 +528,8 @@ public final class ProductWorker { List<GenericValue> productFeatureAppls = null; try { - productFeatureAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, "productFeatureApplTypeId", "OPTIONAL_FEATURE").orderBy("productFeatureTypeId", "sequenceNum").queryList(); + productFeatureAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId, + "productFeatureApplTypeId", "OPTIONAL_FEATURE").orderBy("productFeatureTypeId", "sequenceNum").queryList(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } @@ -532,11 +551,13 @@ public final class ProductWorker { // product calc methods - public static BigDecimal calcOrderAdjustments(List<GenericValue> orderHeaderAdjustments, BigDecimal subTotal, boolean includeOther, boolean includeTax, boolean includeShipping) { + public static BigDecimal calcOrderAdjustments(List<GenericValue> orderHeaderAdjustments, BigDecimal subTotal, boolean includeOther, + boolean includeTax, boolean includeShipping) { BigDecimal adjTotal = BigDecimal.ZERO; if (UtilValidate.isNotEmpty(orderHeaderAdjustments)) { - List<GenericValue> filteredAdjs = filterOrderAdjustments(orderHeaderAdjustments, includeOther, includeTax, includeShipping, false, false); + List<GenericValue> filteredAdjs = filterOrderAdjustments(orderHeaderAdjustments, includeOther, includeTax, includeShipping, + false, false); for (GenericValue orderAdjustment: filteredAdjs) { adjTotal = adjTotal.add(calcOrderAdjustment(orderAdjustment, subTotal)); } @@ -549,14 +570,14 @@ public final class ProductWorker { if (orderAdjustment.get("amount") != null) { adjustment = adjustment.add(orderAdjustment.getBigDecimal("amount")); - } - else if (orderAdjustment.get("sourcePercentage") != null) { + } else if (orderAdjustment.get("sourcePercentage") != null) { adjustment = adjustment.add(orderAdjustment.getBigDecimal("sourcePercentage").multiply(orderSubTotal)); } return adjustment; } - public static List<GenericValue> filterOrderAdjustments(List<GenericValue> adjustments, boolean includeOther, boolean includeTax, boolean includeShipping, boolean forTax, boolean forShipping) { + public static List<GenericValue> filterOrderAdjustments(List<GenericValue> adjustments, boolean includeOther, boolean includeTax, + boolean includeShipping, boolean forTax, boolean forShipping) { List<GenericValue> newOrderAdjustmentsList = new LinkedList<>(); if (UtilValidate.isNotEmpty(adjustments)) { @@ -577,12 +598,14 @@ public final class ProductWorker { } } - // default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included + // default to yes, include for shipping; so only exclude if includeInShipping is N, or false; + // if Y or null or anything else it will be included if (forTax && "N".equals(orderAdjustment.getString("includeInTax"))) { includeAdjustment = false; } - // default to yes, include for shipping; so only exclude if includeInShipping is N, or false; if Y or null or anything else it will be included + // default to yes, include for shipping; so only exclude if includeInShipping is N, or false; + // if Y or null or anything else it will be included if (forShipping && "N".equals(orderAdjustment.getString("includeInShipping"))) { includeAdjustment = false; } @@ -708,7 +731,7 @@ public final class ProductWorker { //get parent product public static GenericValue getParentProduct(String productId, Delegator delegator) { - GenericValue _parentProduct = null; + GenericValue parentProduct = null; if (productId == null) { Debug.logWarning("Bad product id", MODULE); } @@ -732,12 +755,12 @@ public final class ProductWorker { if (UtilValidate.isNotEmpty(virtualProductAssocs)) { //found one, set this first as the parent product GenericValue productAssoc = EntityUtil.getFirst(virtualProductAssocs); - _parentProduct = productAssoc.getRelatedOne("MainProduct", true); + parentProduct = productAssoc.getRelatedOne("MainProduct", true); } } catch (GenericEntityException e) { throw new RuntimeException("Entity Engine error getting Parent Product (" + e.getMessage() + ")"); } - return _parentProduct; + return parentProduct; } public static boolean isDigital(GenericValue product) { @@ -835,7 +858,8 @@ public final class ProductWorker { if (desiredUomId != null && product.get("weightUomId") != null && !desiredUomId.equals(product.get("weightUomId"))) { Map<String, Object> result = new HashMap<>(); try { - result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", desiredUomId, "originalValue", weight)); + result = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", + desiredUomId, "originalValue", weight)); } catch (GenericServiceException e) { Debug.logError(e, MODULE); } @@ -870,7 +894,8 @@ public final class ProductWorker { boolean searchProductFirst, boolean searchAllId) throws GenericEntityException { if (Debug.verboseOn()) { - Debug.logVerbose("Analyze goodIdentification: entered id = " + idToFind + ", goodIdentificationTypeId = " + goodIdentificationTypeId, MODULE); + Debug.logVerbose("Analyze goodIdentification: entered id = " + idToFind + ", goodIdentificationTypeId = " + + goodIdentificationTypeId, MODULE); } GenericValue product = null; @@ -887,7 +912,8 @@ public final class ProductWorker { if (UtilValidate.isNotEmpty(goodIdentificationTypeId)) { conditions.put("goodIdentificationTypeId", goodIdentificationTypeId); } - productsFound = EntityQuery.use(delegator).from("GoodIdentificationAndProduct").where(conditions).orderBy("productId").cache(true).queryList(); + productsFound = EntityQuery.use(delegator).from("GoodIdentificationAndProduct").where(conditions) + .orderBy("productId").cache(true).queryList(); } if (!searchProductFirst) { @@ -931,7 +957,8 @@ public final class ProductWorker { return product; } - public static List<GenericValue> findProducts(Delegator delegator, String idToFind, String goodIdentificationTypeId) throws GenericEntityException { + public static List<GenericValue> findProducts(Delegator delegator, String idToFind, String goodIdentificationTypeId) + throws GenericEntityException { List<GenericValue> productsByIds = findProductsById(delegator, idToFind, goodIdentificationTypeId); List<GenericValue> products = null; if (UtilValidate.isNotEmpty(productsByIds)) { @@ -989,13 +1016,15 @@ public final class ProductWorker { Set<String> productIdSet = new HashSet<>(); // find associated refurb items, we want serial number for main item or any refurb items too - List<GenericValue> refubProductAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_REFURB").filterByDate().queryList(); + List<GenericValue> refubProductAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, + "productAssocTypeId", "PRODUCT_REFURB").filterByDate().queryList(); for (GenericValue refubProductAssoc: refubProductAssocs) { productIdSet.add(refubProductAssoc.getString("productIdTo")); } // see if this is a refurb productId to, and find product(s) it is a refurb of - List<GenericValue> refubProductToAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productIdTo", productId, "productAssocTypeId", "PRODUCT_REFURB").filterByDate().queryList(); + List<GenericValue> refubProductToAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productIdTo", + productId, "productAssocTypeId", "PRODUCT_REFURB").filterByDate().queryList(); for (GenericValue refubProductToAssoc: refubProductToAssocs) { productIdSet.add(refubProductToAssoc.getString("productId")); } @@ -1048,12 +1077,15 @@ public final class ProductWorker { } } // find variant - List<GenericValue> productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList(); + List<GenericValue> productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, + "productAssocTypeId", "PRODUCT_VARIANT").filterByDate().queryList(); boolean productFound = false; 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(); + List<GenericValue> pAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productId", + productAssoc.getString("productIdTo"), "productFeatureId", featureId, "productFeatureApplTypeId", "STANDARD_FEATURE") + .cache(true).queryList(); if (UtilValidate.isEmpty(pAppls)) { continue nextProd; } @@ -1064,8 +1096,8 @@ public final class ProductWorker { } /** - * 1. variant not found so create new variant product and use the virtual product as basis, new one is a variant type and not a virtual type. - * adjust the prices according the selected features + * 1. variant not found so create new variant product and use the virtual product as basis, new one + * is a variant type and not a virtual type. adjust the prices according the selected features */ if (!productFound) { // copy product to be variant @@ -1084,16 +1116,18 @@ public final class ProductWorker { productFeatureAppl.create(); } //add standard features too - List<GenericValue> stdFeaturesAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productId", productId, "productFeatureApplTypeId", "STANDARD_FEATURE").filterByDate().queryList(); + 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.create(); } - /* 3. use the price of the virtual product(Entity:ProductPrice) as a basis and adjust according the prices in the feature price table. - * take the default price from the vitual product, go to the productfeature table and retrieve all the prices for the difFerent features - * add these to the price of the virtual product, store the result as the default price on the variant you created. + /* 3. use the price of the virtual product(Entity:ProductPrice) as a basis and adjust according the prices in the feature price table + * take the default price from the virtual product, go to the productfeature table and retrieve all the prices for the different + * features. Add these to the price of the virtual product, store the result as the default price on the variant you created. */ - List<GenericValue> productPrices = EntityQuery.use(delegator).from("ProductPrice").where("productId", productId).filterByDate().queryList(); + List<GenericValue> productPrices = EntityQuery.use(delegator).from("ProductPrice").where("productId", productId) + .filterByDate().queryList(); for (GenericValue productPrice: productPrices) { for (String selectedFeaturedId: selectedFeatures) { List<GenericValue> productFeaturePrices = EntityQuery.use(delegator).from("ProductFeaturePrice") @@ -1113,13 +1147,15 @@ public final class ProductWorker { productPrice.create(); } // add the product association - GenericValue productAssoc = delegator.makeValue("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", product.getString("productId"), "productAssocTypeId", "PRODUCT_VARIANT")); + GenericValue productAssoc = delegator.makeValue("ProductAssoc", UtilMisc.toMap("productId", productId, "productIdTo", + product.getString("productId"), "productAssocTypeId", "PRODUCT_VARIANT")); productAssoc.put("fromDate", UtilDateTime.nowTimestamp()); productAssoc.create(); Debug.logInfo("set the productId to: " + product.getString("productId"), MODULE); // copy the supplier - List<GenericValue> supplierProducts = EntityQuery.use(delegator).from("SupplierProduct").where("productId", productId).cache(true).queryList(); + 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")); @@ -1127,7 +1163,8 @@ public final class ProductWorker { } // copy the content - List<GenericValue> productContents = EntityQuery.use(delegator).from("ProductContent").where("productId", productId).cache(true).queryList(); + 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")); @@ -1175,7 +1212,8 @@ public final class ProductWorker { if (isAlternativePacking) { List<GenericValue> productAssocs = null; try { - productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "ALTERNATIVE_PACKAGE").filterByDate().queryList(); + productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", + "ALTERNATIVE_PACKAGE").filterByDate().queryList(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } @@ -1202,8 +1240,10 @@ public final class ProductWorker { if (UtilValidate.isEmpty(productStoreId)) { return Boolean.TRUE; } - String allowDecimalStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache(true).queryOne().getString("orderDecimalQuantity"); - String allowDecimalProduct = EntityQuery.use(delegator).from("Product").where("productId", productId).cache(true).queryOne().getString("orderDecimalQuantity"); + String allowDecimalStore = EntityQuery.use(delegator).from("ProductStore").where("productStoreId", productStoreId).cache(true) + .queryOne().getString("orderDecimalQuantity"); + String allowDecimalProduct = EntityQuery.use(delegator).from("Product").where("productId", productId).cache(true).queryOne() + .getString("orderDecimalQuantity"); if ("N".equals(allowDecimalProduct) || (UtilValidate.isEmpty(allowDecimalProduct) && "N".equals(allowDecimalStore))) { return Boolean.FALSE; @@ -1225,14 +1265,16 @@ public final class ProductWorker { } // Method to filter-out out of stock products - public static List<GenericValue> filterOutOfStockProducts (List<GenericValue> productsToFilter, LocalDispatcher dispatcher, Delegator delegator) throws GeneralException { + public static List<GenericValue> filterOutOfStockProducts(List<GenericValue> productsToFilter, LocalDispatcher dispatcher, Delegator delegator) + throws GeneralException { List<GenericValue> productsInStock = new ArrayList<>(); if (UtilValidate.isNotEmpty(productsToFilter)) { for (GenericValue genericRecord : productsToFilter) { String productId = genericRecord.getString("productId"); GenericValue product = null; product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache(true).queryOne(); - Boolean isMarketingPackage = EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG"); + boolean isMarketingPackage = EntityTypeUtil.hasParentType(delegator, "ProductType", "productTypeId", + product.getString("productTypeId"), "parentTypeId", "MARKETING_PKG"); if (UtilValidate.isNotEmpty(isMarketingPackage) && isMarketingPackage) { Map<String, Object> resultOutput = new HashMap<>(); 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 cdacb0b..884d33a 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 @@ -57,8 +57,8 @@ public class PromoServices { private static final String MODULE = PromoServices.class.getName(); private static final String RESOURCE = "ProductUiLabels"; - private static final char[] smartChars = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', - 'Z', '2', '3', '4', '5', '6', '7', '8', '9' }; + private static final char[] SMART_CHARS = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', + 'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' }; public static Map<String, Object> createProductPromoCodeSet(DispatchContext dctx, Map<String, ? extends Object> context) { Locale locale = (Locale) context.get("locale"); @@ -87,13 +87,14 @@ public class PromoServices { while (!foundUniqueNewCode) { if (useSmartLayout) { - newPromoCodeId = RandomStringUtils.random(codeLength, smartChars); + newPromoCodeId = RandomStringUtils.random(codeLength, SMART_CHARS); } else if (useNormalLayout) { newPromoCodeId = RandomStringUtils.randomAlphanumeric(codeLength); } GenericValue existingPromoCode = null; try { - existingPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", newPromoCodeId).cache().queryOne(); + existingPromoCode = EntityQuery.use(delegator).from("ProductPromoCode").where("productPromoCodeId", + newPromoCodeId).cache().queryOne(); } catch (GenericEntityException e) { Debug.logWarning("Could not find ProductPromoCode for just generated ID: " + newPromoCodeId, MODULE); } @@ -115,7 +116,8 @@ public class PromoServices { } if (ServiceUtil.isError(createProductPromoCodeMap)) { // what to do here? try again? - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ProductPromoCodeCannotBeCreated", locale), null, null, createProductPromoCodeMap); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ProductPromoCodeCannotBeCreated", locale), null, + null, createProductPromoCodeMap); } bankOfNumbers.append((String) createProductPromoCodeMap.get("productPromoCodeId")); bankOfNumbers.append(","); diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/test/InventoryItemTransferTest.java b/applications/product/src/main/java/org/apache/ofbiz/product/test/InventoryItemTransferTest.java index 1524a3e..c696354 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/test/InventoryItemTransferTest.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/test/InventoryItemTransferTest.java @@ -29,8 +29,8 @@ import org.apache.ofbiz.service.testtools.OFBizTestCase; public class InventoryItemTransferTest extends OFBizTestCase { - static String inventoryTransferId = null; - protected BigDecimal transferQty = BigDecimal.ONE; + private static String inventoryTransferId = null; + private BigDecimal transferQty = BigDecimal.ONE; public InventoryItemTransferTest(String name) { super(name); @@ -40,6 +40,10 @@ public class InventoryItemTransferTest extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test create inventory items transfer. + * @throws Exception the exception + */ public void testCreateInventoryItemsTransfer() throws Exception { GenericValue userLogin = getUserLogin("system"); // create @@ -52,7 +56,7 @@ public class InventoryItemTransferTest extends OFBizTestCase { ctx.put("receiveDate", UtilDateTime.nowTimestamp()); ctx.put("xferQty", transferQty); ctx.put("userLogin", userLogin); - Map<String, Object> resp = dispatcher.runSync("createInventoryTransfer", ctx); + Map<String, Object> resp = getDispatcher().runSync("createInventoryTransfer", ctx); setInventoryTransferId((String) resp.get("inventoryTransferId")); assertNotNull(inventoryTransferId); @@ -62,7 +66,7 @@ public class InventoryItemTransferTest extends OFBizTestCase { ctx.put("inventoryItemId", inventoryItemId); ctx.put("statusId", "IXF_COMPLETE"); ctx.put("userLogin", userLogin); - resp = dispatcher.runSync("updateInventoryTransfer", ctx); + resp = getDispatcher().runSync("updateInventoryTransfer", ctx); String respMsg = (String) resp.get("responseMessage"); assertNotSame("error", respMsg); } diff --git a/applications/product/src/main/java/org/apache/ofbiz/product/test/StockMovesTest.java b/applications/product/src/main/java/org/apache/ofbiz/product/test/StockMovesTest.java index df1eed1..c8b1aca 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/product/test/StockMovesTest.java +++ b/applications/product/src/main/java/org/apache/ofbiz/product/test/StockMovesTest.java @@ -41,6 +41,10 @@ public class StockMovesTest extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test stock moves. + * @throws Exception the exception + */ public void testStockMoves() throws Exception { GenericValue userLogin = getUserLogin("system"); Map<String, Object> fsmnCtx = new HashMap<>(); @@ -49,7 +53,7 @@ public class StockMovesTest extends OFBizTestCase { fsmnCtx.put("facilityId", "WebStoreWarehouse"); fsmnCtx.put("userLogin", userLogin); - Map<String, Object> respMap1 = dispatcher.runSync("findStockMovesNeeded", fsmnCtx); + Map<String, Object> respMap1 = getDispatcher().runSync("findStockMovesNeeded", fsmnCtx); stockMoveHandled = UtilGenerics.cast(respMap1.get("stockMoveHandled")); warningList = UtilGenerics.cast(respMap1.get("warningMessageList")); assertNull(warningList); @@ -57,7 +61,7 @@ public class StockMovesTest extends OFBizTestCase { if (stockMoveHandled != null) { fsmnCtx.put("stockMoveHandled", stockMoveHandled); } - Map<String, Object> respMap2 = dispatcher.runSync("findStockMovesRecommended", fsmnCtx); + Map<String, Object> respMap2 = getDispatcher().runSync("findStockMovesRecommended", fsmnCtx); warningList = UtilGenerics.cast(respMap2.get("warningMessageList")); assertNull(warningList); @@ -68,6 +72,6 @@ public class StockMovesTest extends OFBizTestCase { ppsmCtx.put("targetLocationSeqId", "TLTLTLLL01"); ppsmCtx.put("quantityMoved", new BigDecimal("5")); ppsmCtx.put("userLogin", userLogin); - dispatcher.runSync("processPhysicalStockMove", ppsmCtx); + getDispatcher().runSync("processPhysicalStockMove", ppsmCtx); } } diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/test/IssuanceTest.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/test/IssuanceTest.java index 17d5686..ceee9ab 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/test/IssuanceTest.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/test/IssuanceTest.java @@ -42,17 +42,21 @@ public class IssuanceTest extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test multiple inventory item issuance. + * @throws Exception the exception + */ public void testMultipleInventoryItemIssuance() throws Exception { String facilityId = "WebStoreWarehouse"; - String productId="GZ-2644"; - String orderId="DEMO81015"; - String orderItemSeqId="00001"; - String shipGroupSeqId="00001"; + String productId = "GZ-2644"; + String orderId = "DEMO81015"; + String orderItemSeqId = "00001"; + String shipGroupSeqId = "00001"; String shipmentItemSeqId = "00001"; - PackingSession packSession = new PackingSession(dispatcher, getUserLogin("system"), facilityId, null, orderId, shipGroupSeqId); + PackingSession packSession = new PackingSession(getDispatcher(), getUserLogin("system"), facilityId, null, orderId, shipGroupSeqId); packSession.addOrIncreaseLine(orderId, orderItemSeqId, shipGroupSeqId, productId, BigDecimal.valueOf(6L), 1, - BigDecimal.valueOf(1000L), false); + BigDecimal.valueOf(1000L), false); String shipmentId = packSession.complete(false); GenericValue orderHeader = EntityQuery.use(delegator).from("OrderHeader").where("orderId", orderId).queryOne(); diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java index 9bb69a3..a8d5850 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/dhl/DhlServices.java @@ -78,7 +78,7 @@ import org.xml.sax.SAXException; public class DhlServices { private static final String MODULE = DhlServices.class.getName(); - public static final String shipmentPropertiesFile = "shipment.properties"; + public static final String SHIPMENT_PROPERTIES_FILE = "shipment.properties"; public static final String DHL_WEIGHT_UOM_ID = "WT_lb"; // weight Uom used by DHL private static final String RES_ERROR = "ProductUiLabels"; @@ -184,14 +184,18 @@ public class DhlServices { Debug.logError(e, "Failed to get rate estimate: " + e.getMessage(), MODULE); } - String RESOURCE = (String) context.get("serviceConfigProps"); + String resource = (String) context.get("serviceConfigProps"); String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId"); // shipping credentials (configured in properties) - String userid = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", RESOURCE, "shipment.dhl.access.userid"); - String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", RESOURCE, "shipment.dhl.access.password"); - String shippingKey = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessShippingKey", RESOURCE, "shipment.dhl.access.shippingKey"); - String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", RESOURCE, "shipment.dhl.access.accountNbr"); + String userid = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessUserId", resource, "shipment.dhl.access.userid"); + String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessPassword", resource, "shipment.dhl.access.password"); + String shippingKey = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessShippingKey", resource, "shipment.dhl.access.shippingKey"); + String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessAccountNbr", resource, "shipment.dhl.access.accountNbr"); if ((shippingKey.isEmpty()) || (accountNbr.isEmpty())) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlGatewayNotAvailable", locale)); @@ -212,7 +216,7 @@ public class DhlServices { } if ((shippableWeight == null) || (shippableWeight.compareTo(BigDecimal.ZERO) <= 0)) { - String tmpValue = EntityUtilProperties.getPropertyValue(shipmentPropertiesFile, "shipment.default.weight.value", delegator); + String tmpValue = EntityUtilProperties.getPropertyValue(SHIPMENT_PROPERTIES_FILE, "shipment.default.weight.value", delegator); if (tmpValue != null) { try { shippableWeight = new BigDecimal(tmpValue); @@ -228,14 +232,16 @@ public class DhlServices { Debug.logWarning("DHL Estimate: Weight is less than 1 lb, submitting DHL minimum of 1 lb for estimate.", MODULE); shippableWeight = BigDecimal.ONE; } - if (("G".equals(dhlShipmentDetailCode) && shippableWeight.compareTo(new BigDecimal("999")) > 0) || (shippableWeight.compareTo(new BigDecimal("150")) > 0)) { + if (("G".equals(dhlShipmentDetailCode) && shippableWeight.compareTo(new BigDecimal("999")) > 0) + || (shippableWeight.compareTo(new BigDecimal("150")) > 0)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlShippableWeightExceed", locale)); } String weight = shippableWeight.toString(); // create AccessRequest XML doc using FreeMarker template - String templateName = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "rateEstimateTemplate", RESOURCE, "shipment.dhl.template.rate.estimate"); + String templateName = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "rateEstimateTemplate", resource, "shipment.dhl.template.rate.estimate"); if (templateName.trim().isEmpty()) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlShipmentTemplateLocationNotFound", locale)); @@ -253,7 +259,7 @@ public class DhlServices { inContext.put("state", shipToAddress.getString("stateProvinceGeoId")); // DHL ShipIT API does not accept ZIP+4 if ((shipToAddress.getString("postalCode") != null) && (shipToAddress.getString("postalCode").length() > 5)) { - inContext.put("postalCode", shipToAddress.getString("postalCode").substring(0,5)); + inContext.put("postalCode", shipToAddress.getString("postalCode").substring(0, 5)); } else { inContext.put("postalCode", shipToAddress.getString("postalCode")); } @@ -272,7 +278,7 @@ public class DhlServices { // send the request String rateResponseString = null; try { - rateResponseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, RESOURCE, locale); + rateResponseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, resource, locale); if (Debug.verboseOn()) { Debug.logVerbose(rateResponseString, MODULE); } @@ -321,11 +327,9 @@ public class DhlServices { String dateGenerated = UtilXml.childElementValue( responseEstimateDetailElement, "DateGenerated"); - Element responseServiceLevelCommitmentElement = UtilXml - .firstChildElement(responseEstimateDetailElement, + Element responseServiceLevelCommitmentElement = UtilXml.firstChildElement(responseEstimateDetailElement, "ServiceLevelCommitment"); - String responseServiceLevelCommitmentDescription = UtilXml - .childElementValue(responseServiceLevelCommitmentElement, + String responseServiceLevelCommitmentDescription = UtilXml.childElementValue(responseServiceLevelCommitmentElement, "Desc"); Element responseRateEstimateElement = UtilXml.firstChildElement( @@ -376,19 +380,19 @@ public class DhlServices { */ public static Map<String, Object> dhlRegisterInquire(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); - String RESOURCE = (String) context.get("serviceConfigProps"); + String resource = (String) context.get("serviceConfigProps"); String shipmentGatewayConfigId = (String) context.get("shipmentGatewayConfigId"); Locale locale = (Locale) context.get("locale"); Map<String, Object> result; String postalCode = (String) context.get("postalCode"); String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", - RESOURCE, "shipment.dhl.access.accountNbr"); + resource, "shipment.dhl.access.accountNbr"); if (accountNbr.isEmpty()) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlAccessAccountNbrMandotoryForRegisterAccount", locale)); } // create AccessRequest XML doc - Document requestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, RESOURCE); + Document requestDocument = createAccessRequestDocument(delegator, shipmentGatewayConfigId, resource); String requestString = null; Element requesElement = requestDocument.getDocumentElement(); @@ -411,7 +415,7 @@ public class DhlServices { // send the request String registerResponseString = null; try { - registerResponseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, RESOURCE, locale); + registerResponseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, resource, locale); Debug.logInfo("DHL request for DHL Register Account:" + registerResponseString, MODULE); } catch (DhlConnectException e) { String uceErrMsg = "Error sending DHL request for DHL Register Account: " + e.toString(); @@ -475,8 +479,8 @@ public class DhlServices { Map<String, Object> shipmentGatewayConfig = ShipmentServices.getShipmentGatewayConfigFromShipment(delegator, shipmentId, locale); String shipmentGatewayConfigId = (String) shipmentGatewayConfig.get("shipmentGatewayConfigId"); - String RESOURCE = (String) shipmentGatewayConfig.get("configProps"); - if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(RESOURCE)) { + String resource = (String) shipmentGatewayConfig.get("configProps"); + if (UtilValidate.isEmpty(shipmentGatewayConfigId) && UtilValidate.isEmpty(resource)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlGatewayNotAvailable", locale)); } @@ -487,7 +491,8 @@ public class DhlServices { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductShipmentNotFoundId", locale) + shipmentId); } - GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); + GenericValue shipmentRouteSegment = EntityQuery.use(delegator).from("ShipmentRouteSegment").where("shipmentId", shipmentId, + "shipmentRouteSegmentId", shipmentRouteSegmentId).queryOne(); if (shipmentRouteSegment == null) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "ProductShipmentRouteSegmentNotFound", @@ -501,7 +506,8 @@ public class DhlServices { } // add ShipmentRouteSegment carrierServiceStatusId, check before all DHL services - if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("carrierServiceStatusId")) && !"SHRSCS_NOT_STARTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) { + if (UtilValidate.isNotEmpty(shipmentRouteSegment.getString("carrierServiceStatusId")) + && !"SHRSCS_NOT_STARTED".equals(shipmentRouteSegment.getString("carrierServiceStatusId"))) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlRouteSegmentStatusNotStarted", UtilMisc.toMap("shipmentRouteSegmentId", shipmentRouteSegmentId, "shipmentId", shipmentId, @@ -523,7 +529,8 @@ public class DhlServices { } String originPhoneNumber = originTelecomNumber.getString("areaCode") + originTelecomNumber.getString("contactNumber"); // don't put on country code if not specified or is the US country code (UPS wants it this way and assuming DHL will accept this) - if (UtilValidate.isNotEmpty(originTelecomNumber.getString("countryCode")) && !"001".equals(originTelecomNumber.getString("countryCode"))) { + if (UtilValidate.isNotEmpty(originTelecomNumber.getString("countryCode")) + && !"001".equals(originTelecomNumber.getString("countryCode"))) { originPhoneNumber = originTelecomNumber.getString("countryCode") + originPhoneNumber; } originPhoneNumber = StringUtil.replaceString(originPhoneNumber, "-", ""); @@ -551,7 +558,8 @@ public class DhlServices { if (destTelecomNumber != null) { destPhoneNumber = destTelecomNumber.getString("areaCode") + destTelecomNumber.getString("contactNumber"); // don't put on country code if not specified or is the US country code (UPS wants it this way) - if (UtilValidate.isNotEmpty(destTelecomNumber.getString("countryCode")) && !"001".equals(destTelecomNumber.getString("countryCode"))) { + if (UtilValidate.isNotEmpty(destTelecomNumber.getString("countryCode")) + && !"001".equals(destTelecomNumber.getString("countryCode"))) { destPhoneNumber = destTelecomNumber.getString("countryCode") + destPhoneNumber; } destPhoneNumber = StringUtil.replaceString(destPhoneNumber, "-", ""); @@ -559,7 +567,8 @@ public class DhlServices { } String recipientEmail = null; - Map<String, Object> results = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", shipment.get("partyIdTo"), "userLogin", userLogin)); + Map<String, Object> results = dispatcher.runSync("getPartyEmail", UtilMisc.toMap("partyId", + shipment.get("partyIdTo"), "userLogin", userLogin)); if (ServiceUtil.isError(results)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results)); } @@ -575,7 +584,8 @@ public class DhlServices { UtilMisc.toMap("shipmentId", shipmentId, "shipmentRouteSegmentId", shipmentRouteSegmentId), locale)); } - List<GenericValue> shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", null, UtilMisc.toList("+shipmentPackageSeqId"), false); + List<GenericValue> shipmentPackageRouteSegs = shipmentRouteSegment.getRelated("ShipmentPackageRouteSeg", + null, UtilMisc.toList("+shipmentPackageSeqId"), false); if (UtilValidate.isEmpty(shipmentPackageRouteSegs)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentPackageRouteSegsNotFound", @@ -597,7 +607,8 @@ public class DhlServices { billingWeightUomId = "WT_lb"; // TODO: this should be specified in a properties file } // convert - results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", billingWeightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", billingWeight)); + results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", billingWeightUomId, "uomIdTo", + DHL_WEIGHT_UOM_ID, "originalValue", billingWeight)); if (ServiceUtil.isError(results) || (results.get("convertedValue") == null)) { Debug.logWarning("Unable to convert billing weights for shipmentId " + shipmentId, MODULE); // try getting the weight from package instead @@ -613,9 +624,9 @@ public class DhlServices { GenericValue shipmentPackage = shipmentPackageRouteSeg.getRelatedOne("ShipmentPackage", false); GenericValue shipmentBoxType = shipmentPackage.getRelatedOne("ShipmentBoxType", false); - if (shipmentBoxType != null) { + //if (shipmentBoxType != null) { // TODO: determine what default UoM is (assuming inches) - there should be a defaultDimensionUomId in Facility - } + //} // next step is weight determination, so skip if we have a billing weight if (hasBillingWeight) continue; @@ -626,7 +637,8 @@ public class DhlServices { } else { // use default weight if available try { - packageWeight = EntityUtilProperties.getPropertyAsBigDecimal(shipmentPropertiesFile, "shipment.default.weight.value", BigDecimal.ZERO); + packageWeight = EntityUtilProperties.getPropertyAsBigDecimal(SHIPMENT_PROPERTIES_FILE, + "shipment.default.weight.value", BigDecimal.ZERO); } catch (NumberFormatException ne) { Debug.logWarning("Default shippable weight not configured (shipment.default.weight.value)", MODULE); packageWeight = BigDecimal.ONE; @@ -638,11 +650,13 @@ public class DhlServices { Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId, MODULE); weightUomId = "WT_lb"; // TODO: this should be specified in a properties file } - results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", DHL_WEIGHT_UOM_ID, "originalValue", packageWeight)); + results = dispatcher.runSync("convertUom", UtilMisc.<String, Object>toMap("uomId", weightUomId, "uomIdTo", + DHL_WEIGHT_UOM_ID, "originalValue", packageWeight)); if (ServiceUtil.isError(results)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(results)); } - if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) || (results.get("convertedValue") == null)) { + if ((results == null) || (results.get(ModelService.RESPONSE_MESSAGE).equals(ModelService.RESPOND_ERROR)) + || (results.get("convertedValue") == null)) { Debug.logWarning("Unable to convert weights for shipmentId " + shipmentId, MODULE); packageWeight = BigDecimal.ONE; } else { @@ -674,20 +688,25 @@ public class DhlServices { dhlShipmentDetailCode = carrierShipmentMethod.getString("carrierServiceCode"); // shipping credentials (configured in properties) - String userid = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", RESOURCE, "shipment.dhl.access.userid"); - String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", RESOURCE, "shipment.dhl.access.password"); - String shippingKey = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessShippingKey", RESOURCE, "shipment.dhl.access.shippingKey"); - String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessAccountNbr", RESOURCE, "shipment.dhl.access.accountNbr"); + String userid = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessUserId", resource, "shipment.dhl.access.userid"); + String password = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessPassword", resource, "shipment.dhl.access.password"); + String shippingKey = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessShippingKey", resource, "shipment.dhl.access.shippingKey"); + String accountNbr = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "accessAccountNbr", resource, "shipment.dhl.access.accountNbr"); if ((shippingKey.isEmpty()) || (accountNbr.isEmpty())) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlGatewayNotAvailable", locale)); } // label image preference (PNG or GIF) - String labelImagePreference = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "labelImageFormat", RESOURCE, "shipment.dhl.label.image.format"); + String labelImagePreference = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "labelImageFormat", resource, "shipment.dhl.label.image.format"); if (labelImagePreference.isEmpty()) { Debug.logInfo("shipment.dhl.label.image.format not specified, assuming PNG", MODULE); - labelImagePreference="PNG"; + labelImagePreference = "PNG"; } else if (!("PNG".equals(labelImagePreference) || "GIF".equals(labelImagePreference))) { Debug.logError("Illegal shipment.dhl.label.image.format: " + labelImagePreference, MODULE); return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, @@ -696,7 +715,8 @@ public class DhlServices { } // create AccessRequest XML doc using FreeMarker template - String templateName = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "rateEstimateTemplate", RESOURCE, "shipment.dhl.template.rate.estimate"); + String templateName = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "rateEstimateTemplate", resource, "shipment.dhl.template.rate.estimate"); if ((templateName.trim().isEmpty())) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDhlRateEstimateTemplateNotConfigured", locale)); @@ -721,7 +741,7 @@ public class DhlServices { // DHL ShipIT API does not accept ZIP+4 if ((destPostalAddress.getString("postalCode") != null) && (destPostalAddress.getString("postalCode").length() > 5)) { - inContext.put("postalCode", destPostalAddress.getString("postalCode").substring(0,5)); + inContext.put("postalCode", destPostalAddress.getString("postalCode").substring(0, 5)); } else { inContext.put("postalCode", destPostalAddress.getString("postalCode")); } @@ -745,7 +765,7 @@ public class DhlServices { // send the request String responseString = null; try { - responseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, RESOURCE, locale); + responseString = sendDhlRequest(requestString, delegator, shipmentGatewayConfigId, resource, locale); if (Debug.verboseOn()) { Debug.logVerbose(responseString, MODULE); } @@ -803,8 +823,9 @@ public class DhlServices { int size = encodedImageString.length(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < size; i++) { - if (encodedImageString.charAt(i) == '\n') + if (encodedImageString.charAt(i) == '\n') { continue; + } sb.append(encodedImageString.charAt(i)); } byte[] labelBytes = Base64.getMimeDecoder().decode(sb.toString().getBytes(StandardCharsets.UTF_8)); @@ -830,15 +851,19 @@ public class DhlServices { } - public static Document createAccessRequestDocument(Delegator delegator, String shipmentGatewayConfigId, String RESOURCE) { + public static Document createAccessRequestDocument(Delegator delegator, String shipmentGatewayConfigId, String resource) { Document eCommerceRequestDocument = UtilXml.makeEmptyXmlDocument("eCommerce"); Element eCommerceRequesElement = eCommerceRequestDocument.getDocumentElement(); - eCommerceRequesElement.setAttribute("version", getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "headVersion", RESOURCE, "shipment.dhl.head.version")); - eCommerceRequesElement.setAttribute("action", getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "headAction", RESOURCE, "shipment.dhl.head.action")); + eCommerceRequesElement.setAttribute("version", getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, + "headVersion", resource, "shipment.dhl.head.version")); + eCommerceRequesElement.setAttribute("action", getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "headAction", resource, "shipment.dhl.head.action")); Element requestorRequestElement = UtilXml.addChildElement(eCommerceRequesElement, "Requestor", eCommerceRequestDocument); - UtilXml.addChildElementValue(requestorRequestElement, "ID", getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessUserId", RESOURCE, "shipment.dhl.access.userid"), + UtilXml.addChildElementValue(requestorRequestElement, "ID", getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "accessUserId", resource, "shipment.dhl.access.userid"), eCommerceRequestDocument); - UtilXml.addChildElementValue(requestorRequestElement, "Password", getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, "accessPassword", RESOURCE, "shipment.dhl.access.password"), + UtilXml.addChildElementValue(requestorRequestElement, "Password", getShipmentGatewayConfigValue(delegator, + shipmentGatewayConfigId, "accessPassword", resource, "shipment.dhl.access.password"), eCommerceRequestDocument); return eCommerceRequestDocument; } @@ -869,12 +894,13 @@ public class DhlServices { } } - private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, String shipmentGatewayConfigParameterName, - String resource, String parameterName) { + private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, String + shipmentGatewayConfigParameterName, String resource, String parameterName) { String returnValue = ""; if (UtilValidate.isNotEmpty(shipmentGatewayConfigId)) { try { - GenericValue dhl = EntityQuery.use(delegator).from("ShipmentGatewayDhl").where("shipmentGatewayConfigId", shipmentGatewayConfigId).queryOne(); + GenericValue dhl = EntityQuery.use(delegator).from("ShipmentGatewayDhl").where("shipmentGatewayConfigId", + shipmentGatewayConfigId).queryOne(); if (UtilValidate.isNotEmpty(dhl)) { Object dhlField = dhl.get(shipmentGatewayConfigParameterName); if (dhlField != null) { @@ -892,9 +918,10 @@ public class DhlServices { } return returnValue; } - private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, String shipmentGatewayConfigParameterName, - String resource, String parameterName, String defaultValue) { - String returnValue = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, shipmentGatewayConfigParameterName, resource, parameterName); + private static String getShipmentGatewayConfigValue(Delegator delegator, String shipmentGatewayConfigId, String + shipmentGatewayConfigParameterName, String resource, String parameterName, String defaultValue) { + String returnValue = getShipmentGatewayConfigValue(delegator, shipmentGatewayConfigId, shipmentGatewayConfigParameterName, + resource, parameterName); if (UtilValidate.isEmpty(returnValue)) { returnValue = defaultValue; } diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java index f42af02..d005b43 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/fedex/FedexServices.java @@ -78,7 +78,7 @@ import org.xml.sax.SAXException; public class FedexServices { private static final String MODULE = FedexServices.class.getName(); - public static final String shipmentPropertiesFile = "shipment.properties"; + public static final String SHIPMENT_PROPERTIES_FILE = "shipment.properties"; private static final String RES_ERROR = "ProductUiLabels"; /** @@ -435,7 +435,7 @@ public class FedexServices { } // Get the weight units to be used in the request - String weightUomId = EntityUtilProperties.getPropertyValue(shipmentPropertiesFile, "shipment.default.weight.uom", delegator); + String weightUomId = EntityUtilProperties.getPropertyValue(SHIPMENT_PROPERTIES_FILE, "shipment.default.weight.uom", delegator); if (UtilValidate.isEmpty(weightUomId)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDefaultWeightUomIdNotFound", locale)); @@ -445,7 +445,7 @@ public class FedexServices { } // Get the dimension units to be used in the request - String dimensionsUomId = EntityUtilProperties.getPropertyValue(shipmentPropertiesFile, "shipment.default.dimension.uom", delegator); + String dimensionsUomId = EntityUtilProperties.getPropertyValue(SHIPMENT_PROPERTIES_FILE, "shipment.default.dimension.uom", delegator); if (UtilValidate.isEmpty(dimensionsUomId)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "FacilityShipmentDefaultDimensionUomIdNotFound", locale)); @@ -761,7 +761,7 @@ public class FedexServices { if ((billingWeight != null) && (billingWeight.compareTo(BigDecimal.ZERO) > 0)) { hasBillingWeight = true; if (billingWeightUomId == null) { - Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId + ", assuming default shipment.fedex.weightUomId of " + weightUomId + " from " + shipmentPropertiesFile, MODULE); + Debug.logWarning("Shipment Route Segment missing billingWeightUomId in shipmentId " + shipmentId + ", assuming default shipment.fedex.weightUomId of " + weightUomId + " from " + SHIPMENT_PROPERTIES_FILE, MODULE); billingWeightUomId = weightUomId; } @@ -828,7 +828,7 @@ public class FedexServices { if (!UtilValidate.isEmpty(boxDimensionsUom)) { boxDimensionsUomId = boxDimensionsUom.getString("uomId"); } else { - Debug.logWarning("Packaging type for package " + shipmentPackage.getString("shipmentPackageSeqId") + " of shipmentRouteSegment " + shipmentRouteSegmentId + " of shipment " + shipmentId + " is missing dimensionUomId, assuming default shipment.default.dimension.uom of " + dimensionsUomId + " from " + shipmentPropertiesFile, MODULE); + Debug.logWarning("Packaging type for package " + shipmentPackage.getString("shipmentPackageSeqId") + " of shipmentRouteSegment " + shipmentRouteSegmentId + " of shipment " + shipmentId + " is missing dimensionUomId, assuming default shipment.default.dimension.uom of " + dimensionsUomId + " from " + SHIPMENT_PROPERTIES_FILE, MODULE); boxDimensionsUomId = dimensionsUomId; } if (dimensionsLength != null && dimensionsLength.compareTo(BigDecimal.ZERO) > 0) { @@ -878,7 +878,7 @@ public class FedexServices { // Use default weight if available try { - packageWeight = EntityUtilProperties.getPropertyAsBigDecimal(shipmentPropertiesFile, "shipment.default.weight.value", BigDecimal.ZERO); + packageWeight = EntityUtilProperties.getPropertyAsBigDecimal(SHIPMENT_PROPERTIES_FILE, "shipment.default.weight.value", BigDecimal.ZERO); } catch (NumberFormatException ne) { Debug.logWarning("Default shippable weight not configured (shipment.default.weight.value), assuming 1.0" + weightUomId, MODULE); packageWeight = BigDecimal.ONE; @@ -888,7 +888,8 @@ public class FedexServices { // Convert weight if necessary String packageWeightUomId = shipmentPackage.getString("weightUomId"); if (UtilValidate.isEmpty(packageWeightUomId)) { - Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId + ", assuming shipment.default.weight.uom of " + weightUomId + " from " + shipmentPropertiesFile, MODULE); + Debug.logWarning("Shipment Route Segment missing weightUomId in shipmentId " + shipmentId + + ", assuming shipment.default.weight.uom of " + weightUomId + " from " + SHIPMENT_PROPERTIES_FILE, MODULE); packageWeightUomId = weightUomId; } if (!packageWeightUomId.equals(weightUomId)) { diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServicesTests.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServicesTests.java index 9fd7fb7..cadef84 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServicesTests.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/thirdparty/usps/UspsServicesTests.java @@ -52,10 +52,15 @@ public class UspsServicesTests extends OFBizTestCase { protected void tearDown() throws Exception { } + /** + * Test usps track confirm. + * @throws Exception the exception + */ public void testUspsTrackConfirm() throws Exception { // run the service - Map<String, Object> result = dispatcher.runSync("uspsTrackConfirm", UtilMisc.toMap("trackingId", "EJ958083578US", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); + Map<String, Object> result = getDispatcher().runSync("uspsTrackConfirm", + UtilMisc.toMap("trackingId", "EJ958083578US", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); if (ServiceUtil.isError(result)) { String errorMessage = ServiceUtil.getErrorMessage(result); throw new GeneralException(errorMessage); @@ -87,13 +92,17 @@ public class UspsServicesTests extends OFBizTestCase { "May 29 9:55 am ACCEPT OR PICKUP EDGEWATER NJ 07020.", trackingDetailList.get(2)); } + /** + * Test usps address validation. + * @throws Exception the exception + */ public void testUspsAddressValidation() throws Exception { // run the service Map<String, String> paramInp = UtilMisc.toMap("address1", "6406 Ivy Lane", "city", "Greenbelt", "state", "MD"); paramInp.put("shipmentGatewayConfigId", "USPS_CONFIG"); paramInp.put("configProps", "shipment"); - Map<String, Object> result = dispatcher.runSync("uspsAddressValidation", paramInp); + Map<String, Object> result = getDispatcher().runSync("uspsAddressValidation", paramInp); if (ServiceUtil.isError(result)) { String errorMessage = ServiceUtil.getErrorMessage(result); throw new GeneralException(errorMessage); @@ -125,10 +134,15 @@ public class UspsServicesTests extends OFBizTestCase { assertEquals("zip4 is correct", "1440", zip4); } + /** + * Test usps city state lookup. + * @throws Exception the exception + */ public void testUspsCityStateLookup() throws Exception { // run the service - Map<String, Object> result = dispatcher.runSync("uspsCityStateLookup", UtilMisc.toMap("zip5", "90210", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); + Map<String, Object> result = getDispatcher().runSync("uspsCityStateLookup", + UtilMisc.toMap("zip5", "90210", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); if (ServiceUtil.isError(result)) { String errorMessage = ServiceUtil.getErrorMessage(result); throw new GeneralException(errorMessage); @@ -147,10 +161,15 @@ public class UspsServicesTests extends OFBizTestCase { assertEquals("state is correct", "CA", state); } + /** + * Test usps priority mail standard. + * @throws Exception the exception + */ public void testUspsPriorityMailStandard() throws Exception { // run the service - Map<String, Object> result = dispatcher.runSync("uspsPriorityMailStandard", UtilMisc.toMap("originZip", "4", "destinationZip", "4", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); + Map<String, Object> result = getDispatcher().runSync("uspsPriorityMailStandard", + UtilMisc.toMap("originZip", "4", "destinationZip", "4", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); if (ServiceUtil.isError(result)) { String errorMessage = ServiceUtil.getErrorMessage(result); throw new GeneralException(errorMessage); @@ -165,10 +184,15 @@ public class UspsServicesTests extends OFBizTestCase { assertEquals("days is correct", "1", days); } + /** + * Test usps package services standard. + * @throws Exception the exception + */ public void testUspsPackageServicesStandard() throws Exception { // run the service - Map<String, Object> result = dispatcher.runSync("uspsPackageServicesStandard", UtilMisc.toMap("originZip", "4", "destinationZip", "4", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); + Map<String, Object> result = getDispatcher().runSync("uspsPackageServicesStandard", + UtilMisc.toMap("originZip", "4", "destinationZip", "4", "shipmentGatewayConfigId", "USPS_CONFIG", "configProps", "shipment")); if (ServiceUtil.isError(result)) { String errorMessage = ServiceUtil.getErrorMessage(result); throw new GeneralException(errorMessage); @@ -183,6 +207,10 @@ public class UspsServicesTests extends OFBizTestCase { assertEquals("days is correct", "2", days); } + /** + * Test usps domestic rate. + * @throws Exception the exception + */ public void testUspsDomesticRate() throws Exception { // prepare the context @@ -200,7 +228,7 @@ public class UspsServicesTests extends OFBizTestCase { context.put("configProps", "shipment"); // run the service - Map<String, Object> result = dispatcher.runSync("uspsDomesticRate", context); + Map<String, Object> result = getDispatcher().runSync("uspsDomesticRate", context); if (ServiceUtil.isError(result)) { String errorMessage = ServiceUtil.getErrorMessage(result); throw new GeneralException(errorMessage); @@ -220,6 +248,6 @@ public class UspsServicesTests extends OFBizTestCase { String restrictionDesc = (String) result.get("restrictionDesc"); Debug.logInfo("[testUspsDomesticRate] restrictionDesc: " + restrictionDesc, MODULE); - assertEquals("restrictionDesc is correct", "B. Form 2976-A", restrictionDesc.substring(0,14)); + assertEquals("restrictionDesc is correct", "B. Form 2976-A", restrictionDesc.substring(0, 14)); } } diff --git a/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java b/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java index 9accc43..c0a8ad1 100644 --- a/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java +++ b/applications/product/src/main/java/org/apache/ofbiz/shipment/verify/VerifyPickSession.java @@ -57,36 +57,56 @@ public class VerifyPickSession implements Serializable { private String facilityId = null; private List<VerifyPickSessionRow> pickRows = null; - private transient Delegator _delegator = null; - private transient LocalDispatcher _dispatcher = null; + private transient Delegator delegator = null; + private transient LocalDispatcher dispatcher = null; public VerifyPickSession() { } public VerifyPickSession(LocalDispatcher dispatcher, GenericValue userLogin) { - this._dispatcher = dispatcher; + this.dispatcher = dispatcher; this.dispatcherName = dispatcher.getName(); - this._delegator = _dispatcher.getDelegator(); - this.delegatorName = _delegator.getDelegatorName(); + this.delegator = dispatcher.getDelegator(); + this.delegatorName = delegator.getDelegatorName(); this.userLogin = userLogin; this.pickRows = new LinkedList<>(); } + /** + * Gets dispatcher. + * @return the dispatcher + */ public LocalDispatcher getDispatcher() { - if (_dispatcher == null) { - _dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, this.getDelegator()); + if (dispatcher == null) { + dispatcher = ServiceContainer.getLocalDispatcher(dispatcherName, this.getDelegator()); } - return _dispatcher; + return dispatcher; } + /** + * Gets delegator. + * @return the delegator + */ public Delegator getDelegator() { - if (_delegator == null) { - _delegator = DelegatorFactory.getDelegator(delegatorName); + if (delegator == null) { + delegator = DelegatorFactory.getDelegator(delegatorName); } - return _delegator; + return delegator; } - public void createRow(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String originGeoId, BigDecimal quantity, Locale locale) throws GeneralException { + /** + * Create row. + * @param orderId the order id + * @param orderItemSeqId the order item seq id + * @param shipGroupSeqId the ship group seq id + * @param productId the product id + * @param originGeoId the origin geo id + * @param quantity the quantity + * @param locale the locale + * @throws GeneralException the general exception + */ + public void createRow(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String originGeoId, + BigDecimal quantity, Locale locale) throws GeneralException { if (orderItemSeqId == null && productId != null) { orderItemSeqId = this.findOrderItemSeqId(productId, orderId, shipGroupSeqId, quantity, locale); @@ -97,11 +117,13 @@ public class VerifyPickSession implements Serializable { inventoryLookupMap.put("orderId", orderId); inventoryLookupMap.put("orderItemSeqId", orderItemSeqId); inventoryLookupMap.put("shipGroupSeqId", shipGroupSeqId); - List<GenericValue> reservations = this.getDelegator().findByAnd("OrderItemShipGrpInvRes", inventoryLookupMap, UtilMisc.toList("quantity DESC"), false); + List<GenericValue> reservations = this.getDelegator().findByAnd("OrderItemShipGrpInvRes", inventoryLookupMap, + UtilMisc.toList("quantity DESC"), false); // no reservations we cannot add this item if (UtilValidate.isEmpty(reservations)) { - throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorNoInventoryReservationsAvailableCannotVerifyThisItem", locale)); + throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", + "ProductErrorNoInventoryReservationsAvailableCannotVerifyThisItem", locale)); } if (reservations.size() == 1) { @@ -119,7 +141,8 @@ public class VerifyPickSession implements Serializable { continue; } BigDecimal reservedQty = reservation.getBigDecimal("quantity"); - BigDecimal resVerifiedQty = this.getVerifiedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, reservation.getString("inventoryItemId")); + BigDecimal resVerifiedQty = this.getVerifiedQuantity(orderId, orderItemSeqId, shipGroupSeqId, productId, + reservation.getString("inventoryItemId")); if (resVerifiedQty.compareTo(reservedQty) >= 0) { continue; } else { @@ -150,11 +173,22 @@ public class VerifyPickSession implements Serializable { this.createVerifyPickRow(2, reservation, orderId, orderItemSeqId, shipGroupSeqId, productId, originGeoId, qty, locale); } } else { - throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorNotEnoughInventoryReservationAvailableCannotVerifyTheItem", locale)); + throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", + "ProductErrorNotEnoughInventoryReservationAvailableCannotVerifyTheItem", locale)); } } } + /** + * Find order item seq id string. + * @param productId the product id + * @param orderId the order id + * @param shipGroupSeqId the ship group seq id + * @param quantity the quantity + * @param locale the locale + * @return the string + * @throws GeneralException the general exception + */ protected String findOrderItemSeqId(String productId, String orderId, String shipGroupSeqId, BigDecimal quantity, Locale locale) throws GeneralException { @@ -188,10 +222,22 @@ public class VerifyPickSession implements Serializable { if (orderItemSeqId != null) { return orderItemSeqId; } else { - throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorNoValidOrderItemFoundForProductWithEnteredQuantity", UtilMisc.toMap("productId", productId, "quantity", quantity), locale)); + throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", + "ProductErrorNoValidOrderItemFoundForProductWithEnteredQuantity", + UtilMisc.toMap("productId", productId, "quantity", quantity), locale)); } } + /** + * Check row for add int. + * @param reservation the reservation + * @param orderId the order id + * @param orderItemSeqId the order item seq id + * @param shipGroupSeqId the ship group seq id + * @param productId the product id + * @param quantity the quantity + * @return the int + */ protected int checkRowForAdd(GenericValue reservation, String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, BigDecimal quantity) { // check to see if the reservation can hold the requested quantity amount @@ -216,13 +262,27 @@ public class VerifyPickSession implements Serializable { } } + /** + * Create verify pick row. + * @param checkCode the check code + * @param res the res + * @param orderId the order id + * @param orderItemSeqId the order item seq id + * @param shipGroupSeqId the ship group seq id + * @param productId the product id + * @param originGeoId the origin geo id + * @param quantity the quantity + * @param locale the locale + * @throws GeneralException the general exception + */ protected void createVerifyPickRow(int checkCode, GenericValue res, String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String originGeoId, BigDecimal quantity, Locale locale) throws GeneralException { // process the result; add new item if necessary switch (checkCode) { case 0: // not enough reserved - throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorNotEnoughInventoryReservationAvailableCannotVerifyTheItem", locale)); + throw new GeneralException(UtilProperties.getMessage("ProductErrorUiLabels", + "ProductErrorNotEnoughInventoryReservationAvailableCannotVerifyTheItem", locale)); case 1: // we're all good to go; quantity already updated break; @@ -300,6 +360,13 @@ public class VerifyPickSession implements Serializable { return pickVerifyRows; } + /** + * Gets ready to verify quantity. + * @param orderId the order id + * @param orderSeqId the order seq id + * @return the ready to verify quantity + * @throws GeneralException the general exception + */ public BigDecimal getReadyToVerifyQuantity(String orderId, String orderSeqId) throws GeneralException { BigDecimal readyToVerifyQty = BigDecimal.ZERO; for (VerifyPickSessionRow line: this.getPickRows()) { @@ -310,6 +377,15 @@ public class VerifyPickSession implements Serializable { return readyToVerifyQty; } + /** + * Gets pick row. + * @param orderId the order id + * @param orderItemSeqId the order item seq id + * @param shipGroupSeqId the ship group seq id + * @param productId the product id + * @param inventoryItemId the inventory item id + * @return the pick row + */ public VerifyPickSessionRow getPickRow(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String inventoryItemId) { for (VerifyPickSessionRow line : this.getPickRows(orderId)) { if (orderItemSeqId.equals(line.getOrderItemSeqId()) && shipGroupSeqId.equals(line.getShipGroupSeqId()) @@ -320,6 +396,15 @@ public class VerifyPickSession implements Serializable { return null; } + /** + * Gets verified quantity. + * @param orderId the order id + * @param orderItemSeqId the order item seq id + * @param shipGroupSeqId the ship group seq id + * @param productId the product id + * @param inventoryItemId the inventory item id + * @return the verified quantity + */ public BigDecimal getVerifiedQuantity(String orderId, String orderItemSeqId, String shipGroupSeqId, String productId, String inventoryItemId) { BigDecimal total = BigDecimal.ZERO; for (VerifyPickSessionRow pickRow : this.getPickRows(orderId)) { @@ -369,25 +454,42 @@ public class VerifyPickSession implements Serializable { return shipmentId; } + /** + * Check reserved qty. + * @param orderId the order id + * @param locale the locale + * @throws GeneralException the general exception + */ protected void checkReservedQty(String orderId, Locale locale) throws GeneralException { List<String> errorList = new LinkedList<>(); for (VerifyPickSessionRow pickRow : this.getPickRows(orderId)) { BigDecimal reservedQty = this.getReservedQty(pickRow.getOrderId(), pickRow.getOrderItemSeqId(), pickRow.getShipGroupSeqId()); BigDecimal verifiedQty = this.getReadyToVerifyQuantity(pickRow.getOrderId(), pickRow.getOrderItemSeqId()); if (verifiedQty.compareTo(reservedQty) != 0) { - errorList.add(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorVerifiedQtyDoesNotMatchTheReservedQtyForItem", UtilMisc.toMap("productId", pickRow.getProductId(), "verifiedQty", pickRow.getReadyToVerifyQty(), "reservedQty", reservedQty), locale)); + errorList.add(UtilProperties.getMessage("ProductErrorUiLabels", "ProductErrorVerifiedQtyDoesNotMatchTheReservedQtyForItem", + UtilMisc.toMap("productId", pickRow.getProductId(), "verifiedQty", pickRow.getReadyToVerifyQty(), "reservedQty", + reservedQty), locale)); } } if (!errorList.isEmpty()) { - throw new GeneralException(UtilProperties.getMessage("OrderErrorUiLabels", "OrderErrorAttemptToVerifyOrderFailed", UtilMisc.toMap("orderId", orderId), locale), errorList); + throw new GeneralException(UtilProperties.getMessage("OrderErrorUiLabels", "OrderErrorAttemptToVerifyOrderFailed", + UtilMisc.toMap("orderId", orderId), locale), errorList); } } + /** + * Gets reserved qty. + * @param orderId the order id + * @param orderItemSeqId the order item seq id + * @param shipGroupSeqId the ship group seq id + * @return the reserved qty + */ public BigDecimal getReservedQty(String orderId, String orderItemSeqId, String shipGroupSeqId) { BigDecimal reservedQty = BigDecimal.ZERO; try { - GenericValue reservation = EntityUtil.getFirst(this.getDelegator().findByAnd("OrderItemAndShipGrpInvResAndItemSum", UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId), null, false)); + GenericValue reservation = EntityUtil.getFirst(this.getDelegator().findByAnd("OrderItemAndShipGrpInvResAndItemSum", + UtilMisc.toMap("orderId", orderId, "orderItemSeqId", orderItemSeqId, "shipGroupSeqId", shipGroupSeqId), null, false)); reservedQty = reservation.getBigDecimal("totQuantityAvailable"); } catch (GenericEntityException e) { Debug.logError(e, MODULE); @@ -395,12 +497,19 @@ public class VerifyPickSession implements Serializable { return reservedQty; } + /** + * Check verified qty. + * @param orderId the order id + * @param locale the locale + * @throws GeneralException the general exception + */ protected void checkVerifiedQty(String orderId, Locale locale) throws GeneralException { BigDecimal verifiedQty = BigDecimal.ZERO; BigDecimal orderedQty = BigDecimal.ZERO; - List<GenericValue> orderItems = this.getDelegator().findByAnd("OrderItem", UtilMisc.toMap("orderId", orderId, "statusId", "ITEM_APPROVED"), null, false); + List<GenericValue> orderItems = this.getDelegator().findByAnd("OrderItem", UtilMisc.toMap("orderId", orderId, + "statusId", "ITEM_APPROVED"), null, false); for (GenericValue orderItem : orderItems) { orderedQty = orderedQty.add(orderItem.getBigDecimal("quantity")); } @@ -414,17 +523,30 @@ public class VerifyPickSession implements Serializable { } } + /** + * Issue items to shipment. + * @param shipmentId the shipment id + * @param locale the locale + * @throws GeneralException the general exception + */ protected void issueItemsToShipment(String shipmentId, Locale locale) throws GeneralException { List<VerifyPickSessionRow> processedRows = new LinkedList<>(); for (VerifyPickSessionRow pickRow : this.getPickRows()) { if (this.checkLine(processedRows, pickRow)) { - BigDecimal totalVerifiedQty = this.getVerifiedQuantity(pickRow.getOrderId(), pickRow.getOrderItemSeqId(), pickRow.getShipGroupSeqId(), pickRow.getProductId(), pickRow.getInventoryItemId()); + BigDecimal totalVerifiedQty = this.getVerifiedQuantity(pickRow.getOrderId(), pickRow.getOrderItemSeqId(), + pickRow.getShipGroupSeqId(), pickRow.getProductId(), pickRow.getInventoryItemId()); pickRow.issueItemToShipment(shipmentId, picklistBinId, userLogin, totalVerifiedQty, getDispatcher(), locale); processedRows.add(pickRow); } } } + /** + * Check line boolean. + * @param processedRows the processed rows + * @param pickrow the pickrow + * @return the boolean + */ protected boolean checkLine(List<VerifyPickSessionRow> processedRows, VerifyPickSessionRow pickrow) { for (VerifyPickSessionRow processedRow : processedRows) { if (pickrow.isSameItem(processedRow)) { @@ -435,6 +557,12 @@ public class VerifyPickSession implements Serializable { return true; } + /** + * Create shipment string. + * @param line the line + * @return the string + * @throws GeneralException the general exception + */ protected String createShipment(VerifyPickSessionRow line) throws GeneralException { Delegator delegator = this.getDelegator(); String orderId = line.getOrderId(); @@ -445,26 +573,31 @@ public class VerifyPickSession implements Serializable { newShipment.put("shipmentTypeId", "OUTGOING_SHIPMENT"); newShipment.put("statusId", "SHIPMENT_SCHEDULED"); newShipment.put("userLogin", this.getUserLogin()); - GenericValue orderRoleShipTo = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, "roleTypeId", "SHIP_TO_CUSTOMER").queryFirst(); + GenericValue orderRoleShipTo = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, "roleTypeId", + "SHIP_TO_CUSTOMER").queryFirst(); if (UtilValidate.isNotEmpty(orderRoleShipTo)) { newShipment.put("partyIdTo", orderRoleShipTo.getString("partyId")); } String partyIdFrom = null; - GenericValue orderItemShipGroup = EntityQuery.use(delegator).from("OrderItemShipGroup").where("orderId", orderId, "shipGroupSeqId", line.getShipGroupSeqId()).queryFirst(); + GenericValue orderItemShipGroup = EntityQuery.use(delegator).from("OrderItemShipGroup").where("orderId", orderId, "shipGroupSeqId", + line.getShipGroupSeqId()).queryFirst(); if (UtilValidate.isNotEmpty(orderItemShipGroup.getString("vendorPartyId"))) { partyIdFrom = orderItemShipGroup.getString("vendorPartyId"); } else if (UtilValidate.isNotEmpty(orderItemShipGroup.getString("facilityId"))) { - GenericValue facility = EntityQuery.use(delegator).from("Facility").where("facilityId", orderItemShipGroup.getString("facilityId")).queryOne(); + GenericValue facility = EntityQuery.use(delegator).from("Facility").where("facilityId", + orderItemShipGroup.getString("facilityId")).queryOne(); if (UtilValidate.isNotEmpty(facility.getString("ownerPartyId"))) { partyIdFrom = facility.getString("ownerPartyId"); } } if (UtilValidate.isEmpty(partyIdFrom)) { - GenericValue orderRoleShipFrom = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, "roleTypeId", "SHIP_FROM_VENDOR").queryFirst(); + GenericValue orderRoleShipFrom = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, + "roleTypeId", "SHIP_FROM_VENDOR").queryFirst(); if (UtilValidate.isNotEmpty(orderRoleShipFrom)) { partyIdFrom = orderRoleShipFrom.getString("partyId"); } else { - orderRoleShipFrom = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, "roleTypeId", "BILL_FROM_VENDOR").queryFirst(); + orderRoleShipFrom = EntityQuery.use(delegator).from("OrderRole").where("orderId", orderId, "roleTypeId", + "BILL_FROM_VENDOR").queryFirst(); partyIdFrom = orderRoleShipFrom.getString("partyId"); } } @@ -477,6 +610,10 @@ public class VerifyPickSession implements Serializable { return shipmentId; } + /** + * Update product. + * @throws GeneralException the general exception + */ protected void updateProduct() throws GeneralException { for (VerifyPickSessionRow pickRow : this.getPickRows()) { if (UtilValidate.isNotEmpty(pickRow.getOriginGeoId())) { diff --git a/applications/securityext/src/main/java/org/apache/ofbiz/securityext/login/LoginEvents.java b/applications/securityext/src/main/java/org/apache/ofbiz/securityext/login/LoginEvents.java index 35e2955..a0579d2 100644 --- a/applications/securityext/src/main/java/org/apache/ofbiz/securityext/login/LoginEvents.java +++ b/applications/securityext/src/main/java/org/apache/ofbiz/securityext/login/LoginEvents.java @@ -59,7 +59,7 @@ public class LoginEvents { private static final String MODULE = LoginEvents.class.getName(); private static final String RESOURCE = "SecurityextUiLabels"; - public static final String usernameCookieName = "OFBiz.Username"; + public static final String USERNAME_COOKIE_NAME = "OFBiz.Username"; /** * Save USERNAME and PASSWORD for use by auth pages even if we start in non-auth pages. * @param request The HTTP request object for the current JSP or Servlet request. @@ -109,9 +109,11 @@ public class LoginEvents { * @return String specifying the exit status of this event */ public static String forgotPassword(HttpServletRequest request, HttpServletResponse response) { - if (UtilValidate.isNotEmpty(request.getParameter("GET_PASSWORD_HINT")) || UtilValidate.isNotEmpty(request.getParameter("GET_PASSWORD_HINT.x"))) { + if (UtilValidate.isNotEmpty(request.getParameter("GET_PASSWORD_HINT")) + || UtilValidate.isNotEmpty(request.getParameter("GET_PASSWORD_HINT.x"))) { return showPasswordHint(request, response); - } else if ((UtilValidate.isNotEmpty(request.getParameter("EMAIL_PASSWORD"))) || (UtilValidate.isNotEmpty(request.getParameter("EMAIL_PASSWORD.x")))) { + } else if ((UtilValidate.isNotEmpty(request.getParameter("EMAIL_PASSWORD"))) + || (UtilValidate.isNotEmpty(request.getParameter("EMAIL_PASSWORD.x")))) { return emailPasswordRequest(request, response); } @@ -207,9 +209,8 @@ public class LoginEvents { // check login is associated to a party GenericValue userParty = userLogin.getRelatedOne("Party", false); if (userParty == null) { - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.username_not_found_reenter", - UtilHttp.getLocale(request)); - request.setAttribute("_ERROR_MESSAGE_", errMsg); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.username_not_found_reenter", UtilHttp.getLocale(request)); + request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } @@ -233,7 +234,8 @@ public class LoginEvents { // get the ProductStore email settings GenericValue productStoreEmail = null; try { - productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", productStoreId, "emailType", "PRDS_PWD_RETRIEVE").queryOne(); + productStoreEmail = EntityQuery.use(delegator).from("ProductStoreEmailSetting").where("productStoreId", + productStoreId, "emailType", "PRDS_PWD_RETRIEVE").queryOne(); } catch (GenericEntityException e) { Debug.logError(e, "Problem getting ProductStoreEmailSetting", MODULE); } @@ -266,7 +268,8 @@ public class LoginEvents { } else { GenericValue emailTemplateSetting = null; try { - emailTemplateSetting = EntityQuery.use(delegator).from("EmailTemplateSetting").where("emailTemplateSettingId", "EMAIL_PASSWORD").cache().queryOne(); + emailTemplateSetting = EntityQuery.use(delegator).from("EmailTemplateSetting").where("emailTemplateSettingId", + "EMAIL_PASSWORD").cache().queryOne(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); } @@ -276,7 +279,8 @@ public class LoginEvents { serviceContext.put("subject", subject); serviceContext.put("sendFrom", emailTemplateSetting.get("fromAddress")); } else { - serviceContext.put("subject", UtilProperties.getMessage(RESOURCE, "loginservices.password_reminder_subject", UtilMisc.toMap("userLoginId", userLoginId), UtilHttp.getLocale(request))); + serviceContext.put("subject", UtilProperties.getMessage(RESOURCE, "loginservices.password_reminder_subject", + UtilMisc.toMap("userLoginId", userLoginId), UtilHttp.getLocale(request))); serviceContext.put("sendFrom", EntityUtilProperties.getPropertyValue("general", "defaultFromEmailAddress", delegator)); } } @@ -293,13 +297,15 @@ public class LoginEvents { if (ServiceUtil.isError(result)) { Map<String, Object> messageMap = UtilMisc.toMap("errorMessage", result.get(ModelService.ERROR_MESSAGE)); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.error_unable_email_password_contact_customer_service_errorwas", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.error_unable_email_password_contact_customer_service_errorwas", + messageMap, UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } } catch (GeneralException e) { Debug.logWarning(e, "", MODULE); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.error_unable_email_password_contact_customer_service", UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.error_unable_email_password_contact_customer_service", + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); return "error"; } diff --git a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/ICalConverter.java b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/ICalConverter.java index ebaaee4..5a85158 100644 --- a/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/ICalConverter.java +++ b/applications/workeffort/src/main/java/org/apache/ofbiz/workeffort/workeffort/ICalConverter.java @@ -105,23 +105,23 @@ import net.fortuna.ical4j.model.property.XProperty; public class ICalConverter { protected static final String MODULE = ICalConverter.class.getName(); - protected static final String partyIdXParamName = "X-ORG-APACHE-OFBIZ-PARTY-ID"; - protected static final ProdId prodId = new ProdId("-//Apache OFBiz//Work Effort Calendar//EN"); - protected static final String uidPrefix = "ORG-APACHE-OFBIZ-WE-"; - protected static final String workEffortIdXPropName = "X-ORG-APACHE-OFBIZ-WORKEFFORT-ID"; - protected static final String reminderXPropName = "X-ORG-APACHE-OFBIZ-REMINDER-ID"; - protected static final Map<String, String> fromStatusMap = UtilMisc.toMap("TENTATIVE", "CAL_TENTATIVE", + protected static final String PARTY_ID_X_PARAM_NAME = "X-ORG-APACHE-OFBIZ-PARTY-ID"; + protected static final ProdId PROD_ID = new ProdId("-//Apache OFBiz//Work Effort Calendar//EN"); + protected static final String UID_PREFIX = "ORG-APACHE-OFBIZ-WE-"; + protected static final String WORKEFFORT_ID_X_PROP_NAME = "X-ORG-APACHE-OFBIZ-WORKEFFORT-ID"; + protected static final String REMINDER_X_PROP_NAME = "X-ORG-APACHE-OFBIZ-REMINDER-ID"; + protected static final Map<String, String> FROM_STATUS_MAP = UtilMisc.toMap("TENTATIVE", "CAL_TENTATIVE", "CONFIRMED", "CAL_CONFIRMED", "CANCELLED", "CAL_CANCELLED", "NEEDS-ACTION", "CAL_NEEDS_ACTION", "COMPLETED", "CAL_COMPLETED", "IN-PROCESS", "CAL_ACCEPTED"); - protected static final Map<String, Status> toStatusMap = UtilMisc.toMap("CAL_TENTATIVE", Status.VEVENT_TENTATIVE, + protected static final Map<String, Status> TO_STATUS_MAP = UtilMisc.toMap("CAL_TENTATIVE", Status.VEVENT_TENTATIVE, "CAL_CONFIRMED", Status.VEVENT_CONFIRMED, "CAL_CANCELLED", Status.VEVENT_CANCELLED, "CAL_NEEDS_ACTION", Status.VTODO_NEEDS_ACTION, "CAL_COMPLETED", Status.VTODO_COMPLETED, "CAL_ACCEPTED", Status.VTODO_IN_PROCESS); - protected static final Map<String, PartStat> toPartStatusMap = UtilMisc.toMap( + protected static final Map<String, PartStat> TO_PARTY_STATUS_MAP = UtilMisc.toMap( "PRTYASGN_OFFERED", PartStat.TENTATIVE, "PRTYASGN_ASSIGNED", PartStat.ACCEPTED); - protected static final Map<String, String> fromPartStatusMap = UtilMisc.toMap( + protected static final Map<String, String> FROM_PART_STATUS_MAP = UtilMisc.toMap( "TENTATIVE", "PRTYASGN_OFFERED", "ACCEPTED", "PRTYASGN_ASSIGNED"); - protected static final Map<String, String> fromRoleMap = UtilMisc.toMap("ATTENDEE", "CAL_ATTENDEE", + protected static final Map<String, String> FROM_ROLE_MAP = UtilMisc.toMap("ATTENDEE", "CAL_ATTENDEE", "CONTACT", "CONTACT", "ORGANIZER", "CAL_ORGANIZER"); protected static VAlarm createAlarm(GenericValue workEffortEventReminder) { @@ -162,7 +162,7 @@ public class ICalConverter { } String workEffortId = (String) serviceResult.get("workEffortId"); if (workEffortId != null) { - replaceProperty(component.getProperties(), toXProperty(workEffortIdXPropName, workEffortId)); + replaceProperty(component.getProperties(), toXProperty(WORKEFFORT_ID_X_PROP_NAME, workEffortId)); serviceMap.clear(); serviceMap.put("workEffortIdFrom", context.get("workEffortId")); serviceMap.put("workEffortIdTo", workEffortId); @@ -251,7 +251,7 @@ public class ICalConverter { if (status == null) { return null; } - return fromPartStatusMap.get(status.getValue()); + return FROM_PART_STATUS_MAP.get(status.getValue()); } protected static Long fromPercentComplete(PropertyList propertyList) { @@ -275,7 +275,7 @@ public class ICalConverter { if (iCalObj == null) { return null; } - return fromStatusMap.get(iCalObj.getValue()); + return FROM_STATUS_MAP.get(iCalObj.getValue()); } protected static String fromSummary(PropertyList propertyList) { @@ -326,7 +326,8 @@ public class ICalConverter { Summary summary = new Summary(UtilProperties.getMessage("WorkEffortUiLabels", "WorkEffortEventReminder", Locale.getDefault())); Delegator delegator = workEffort.getDelegator(); String workEffortId = workEffort.getString("workEffortId"); - List<GenericValue> reminderList = EntityQuery.use(delegator).from("WorkEffortEventReminder").where("workEffortId", workEffort.get("workEffortId")).queryList(); + List<GenericValue> reminderList = EntityQuery.use(delegator).from("WorkEffortEventReminder").where("workEffortId", + workEffort.get("workEffortId")).queryList(); for (GenericValue reminder : reminderList) { String reminderId = workEffortId + "-" + reminder.getString("sequenceId"); VAlarm alarm = null; @@ -335,7 +336,7 @@ public class ICalConverter { Iterator<VAlarm> i = UtilGenerics.cast(alarms.iterator()); while (i.hasNext()) { alarm = i.next(); - Property xProperty = alarm.getProperty(reminderXPropName); + Property xProperty = alarm.getProperty(REMINDER_X_PROP_NAME); if (xProperty != null && reminderId.equals(xProperty.getValue())) { newAlarm = false; alarmProps = alarm.getProperties(); @@ -348,7 +349,7 @@ public class ICalConverter { alarm = createAlarm(reminder); alarms.add(alarm); alarmProps = alarm.getProperties(); - alarmProps.add(new XProperty(reminderXPropName, reminderId)); + alarmProps.add(new XProperty(REMINDER_X_PROP_NAME, reminderId)); } GenericValue contactMech = reminder.getRelatedOne("ContactMech", false); if (contactMech != null && "EMAIL_ADDRESS".equals(contactMech.get("contactMechTypeId"))) { @@ -481,7 +482,8 @@ public class ICalConverter { } } } catch (GeneralException e) { - String errMsg = UtilProperties.getMessage("WorkEffortUiLabels", "WorkeffortErrorWhileCreatingServiceMapForService", UtilMisc.toMap("serviceName", serviceName), locale); + String errMsg = UtilProperties.getMessage("WorkEffortUiLabels", "WorkeffortErrorWhileCreatingServiceMapForService", + UtilMisc.toMap("serviceName", serviceName), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg + e); } @@ -522,7 +524,7 @@ public class ICalConverter { } } ParameterList parameterList = property.getParameters(); - replaceParameter(parameterList, toXParameter(partyIdXParamName, partyAssign.getString("partyId"))); + replaceParameter(parameterList, toXParameter(PARTY_ID_X_PARAM_NAME, partyAssign.getString("partyId"))); replaceParameter(parameterList, new Cn(makePartyName(partyAssign))); replaceParameter(parameterList, toParticipationStatus(partyAssign.getString("assignmentStatusId"))); } @@ -540,7 +542,7 @@ public class ICalConverter { Iterator<Attendee> i = UtilGenerics.cast(attendees.iterator()); while (i.hasNext()) { attendee = i.next(); - Parameter xParameter = attendee.getParameter(partyIdXParamName); + Parameter xParameter = attendee.getParameter(PARTY_ID_X_PARAM_NAME); if (xParameter != null && partyId.equals(xParameter.getValue())) { loadPartyAssignment(attendee, partyValue, context); newAttendee = false; @@ -571,7 +573,7 @@ public class ICalConverter { // Don't overwrite UIDs created by calendar clients replaceProperty(componentProps, toUid(workEffort.getString("workEffortId"))); } - replaceProperty(componentProps, toXProperty(workEffortIdXPropName, workEffort.getString("workEffortId"))); + replaceProperty(componentProps, toXProperty(WORKEFFORT_ID_X_PROP_NAME, workEffort.getString("workEffortId"))); } protected static Calendar makeCalendar(GenericValue workEffort, Map<String, Object> context) throws GenericEntityException { @@ -592,7 +594,7 @@ public class ICalConverter { Debug.logVerbose("iCalendar Data found, using saved Calendar", MODULE); } try (StringReader reader = new StringReader(iCalData)) { - CalendarBuilder builder = new CalendarBuilder(); + CalendarBuilder builder = new CalendarBuilder(); calendar = builder.build(reader); newCalendar = false; } catch (Exception e) { @@ -601,8 +603,8 @@ public class ICalConverter { } } PropertyList propList = calendar.getProperties(); - replaceProperty(propList, prodId); - replaceProperty(propList, new XProperty(workEffortIdXPropName, workEffort.getString("workEffortId"))); + replaceProperty(propList, PROD_ID); + replaceProperty(propList, new XProperty(WORKEFFORT_ID_X_PROP_NAME, workEffort.getString("workEffortId"))); if (newCalendar) { propList.add(Version.VERSION_2_0); propList.add(CalScale.GREGORIAN); @@ -657,7 +659,7 @@ public class ICalConverter { Map<String, Object> resultMap = invokeService("findPartyFromEmailAddress", serviceMap, context); String partyId = (String) resultMap.get("partyId"); if (partyId != null) { - replaceParameter(property.getParameters(), toXParameter(partyIdXParamName, partyId)); + replaceParameter(property.getParameters(), toXParameter(PARTY_ID_X_PARAM_NAME, partyId)); } } @@ -713,7 +715,7 @@ public class ICalConverter { if (Debug.verboseOn()) { Debug.logVerbose("Processing calendar:\r\n" + calendar, MODULE); } - String workEffortId = fromXProperty(calendar.getProperties(), workEffortIdXPropName); + String workEffortId = fromXProperty(calendar.getProperties(), WORKEFFORT_ID_X_PROP_NAME); if (workEffortId == null) { workEffortId = (String) context.get("workEffortId"); } @@ -747,7 +749,7 @@ public class ICalConverter { ResponseProperties responseProps = null; for (Component component : components) { if (Component.VEVENT.equals(component.getName()) || Component.VTODO.equals(component.getName())) { - workEffortId = fromXProperty(component.getProperties(), workEffortIdXPropName); + workEffortId = fromXProperty(component.getProperties(), WORKEFFORT_ID_X_PROP_NAME); if (workEffortId == null) { Property uid = component.getProperty(Uid.UID); if (uid != null) { @@ -759,7 +761,7 @@ public class ICalConverter { } if (workEffortId != null) { if (validWorkEfforts.contains(workEffortId)) { - replaceProperty(component.getProperties(), toXProperty(workEffortIdXPropName, workEffortId)); + replaceProperty(component.getProperties(), toXProperty(WORKEFFORT_ID_X_PROP_NAME, workEffortId)); responseProps = storeWorkEffort(component, context); } else { Debug.logWarning("Spoof attempt: unrelated workEffortId " + workEffortId @@ -796,7 +798,7 @@ public class ICalConverter { partyList.addAll(UtilGenerics.checkCollection(component.getProperties("CONTACT"), Property.class)); partyList.addAll(UtilGenerics.checkCollection(component.getProperties("ORGANIZER"), Property.class)); for (Property property : partyList) { - String partyId = fromXParameter(property.getParameters(), partyIdXParamName); + String partyId = fromXParameter(property.getParameters(), PARTY_ID_X_PARAM_NAME); if (partyId == null) { serviceMap.clear(); String address = property.getValue(); @@ -809,12 +811,12 @@ public class ICalConverter { if (partyId == null) { continue; } - replaceParameter(property.getParameters(), toXParameter(partyIdXParamName, partyId)); + replaceParameter(property.getParameters(), toXParameter(PARTY_ID_X_PARAM_NAME, partyId)); } serviceMap.clear(); serviceMap.put("workEffortId", workEffortId); serviceMap.put("partyId", partyId); - serviceMap.put("roleTypeId", fromRoleMap.get(property.getName())); + serviceMap.put("roleTypeId", FROM_ROLE_MAP.get(property.getName())); Delegator delegator = (Delegator) context.get("delegator"); List<GenericValue> assignments = null; try { @@ -834,7 +836,7 @@ public class ICalConverter { protected static ResponseProperties storeWorkEffort(Component component, Map<String, Object> context) throws GenericEntityException { PropertyList propertyList = component.getProperties(); - String workEffortId = fromXProperty(propertyList, workEffortIdXPropName); + String workEffortId = fromXProperty(propertyList, WORKEFFORT_ID_X_PROP_NAME); Delegator delegator = (Delegator) context.get("delegator"); GenericValue workEffort = EntityQuery.use(delegator).from("WorkEffort").where("workEffortId", workEffortId).queryOne(); if (workEffort == null) { @@ -873,7 +875,7 @@ public class ICalConverter { Iterator<Component> i = UtilGenerics.cast(resultList.iterator()); while (i.hasNext()) { result = i.next(); - Property xProperty = result.getProperty(workEffortIdXPropName); + Property xProperty = result.getProperty(WORKEFFORT_ID_X_PROP_NAME); if (xProperty != null && workEffortId.equals(xProperty.getValue())) { newComponent = false; break; @@ -917,7 +919,8 @@ public class ICalConverter { if (workEffort.get("estimatedCompletionDate") == null) { replaceProperty(componentProps, toDuration(workEffort.getDouble("estimatedMilliSeconds"))); } - List<GenericValue> relatedParties = EntityQuery.use(delegator).from("WorkEffortPartyAssignView").where("workEffortId", workEffortId).cache(true).filterByDate().queryList(); + List<GenericValue> relatedParties = EntityQuery.use(delegator).from("WorkEffortPartyAssignView").where("workEffortId", + workEffortId).filterByDate().queryList(); if (!relatedParties.isEmpty()) { loadRelatedParties(relatedParties, componentProps, context); } @@ -1013,7 +1016,7 @@ public class ICalConverter { if (statusId == null) { return null; } - return toPartStatusMap.get(statusId); + return TO_PARTY_STATUS_MAP.get(statusId); } protected static PercentComplete toPercentComplete(Long javaObj) { @@ -1034,7 +1037,7 @@ public class ICalConverter { if (javaObj == null) { return null; } - return toStatusMap.get(javaObj); + return TO_STATUS_MAP.get(javaObj); } protected static Summary toSummary(String javaObj) { @@ -1048,7 +1051,7 @@ public class ICalConverter { if (javaObj == null) { return null; } - return new Uid(uidPrefix.concat(javaObj)); + return new Uid(UID_PREFIX.concat(javaObj)); } protected static XParameter toXParameter(String name, String value) { |
Free forum by Nabble | Edit this page |