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-plugins.git The following commit(s) were added to refs/heads/trunk by this push: new 30f7961 Improved: Corrected some line is longer than 150 characters checkstyle issues. Also fixed some extra spaces and naming conventions related checkstyle issues. (OFBIZ-11921) new b65d9c9 Merge branch 'trunk' of https://gitbox.apache.org/repos/asf/ofbiz-plugins into trunk 30f7961 is described below commit 30f796146c48bffe52e36136073f5cc80e7fb267 Author: Suraj Khurana <[hidden email]> AuthorDate: Mon Aug 3 10:07:16 2020 +0530 Improved: Corrected some line is longer than 150 characters checkstyle issues. Also fixed some extra spaces and naming conventions related checkstyle issues. (OFBIZ-11921) --- .../ofbiz/assetmaint/FixedAssetMaintServices.java | 15 +- .../java/org/apache/ofbiz/birt/BirtFactory.java | 2 +- .../java/org/apache/ofbiz/birt/BirtWorker.java | 90 ++++--- .../apache/ofbiz/birt/email/BirtEmailServices.java | 39 ++- .../birt/flexible/BirtMasterReportServices.java | 37 ++- .../apache/ofbiz/birt/flexible/BirtServices.java | 88 ++++--- .../org/apache/ofbiz/birt/flexible/BirtUtil.java | 20 +- .../ofbiz/birt/flexible/ReportDesignGenerator.java | 40 ++- .../birt/report/servlet/BirtEngineServlet.java | 2 +- .../birt/report/servlet/BirtViewerServlet.java | 2 +- .../birt/report/servlet/ViewerServletRequest.java | 2 +- .../cmssite/multisite/MultiSiteRequestWrapper.java | 60 ++--- .../ofbiz/cmssite/multisite/WebSiteFilter.java | 2 +- .../java/org/apache/ofbiz/ebay/EbayHelper.java | 2 +- .../apache/ofbiz/ebay/ProductsExportToEbay.java | 101 +++++--- .../org/apache/ofbiz/ebaystore/EbayEvents.java | 8 +- .../java/org/apache/ofbiz/ebaystore/EbayStore.java | 2 +- .../ofbiz/ebaystore/EbayStoreAutoPreferences.java | 4 +- .../ofbiz/ebaystore/EbayStoreCategoryFacade.java | 2 +- .../ofbiz/ebaystore/EbayStoreSiteFacade.java | 2 +- .../ofbiz/ecommerce/misc/ThirdPartyEvents.java | 4 +- .../apache/ofbiz/example/ExamplePrintServices.java | 15 +- .../FirstDataPaymentServices.java | 68 +++-- .../org/apache/ofbiz/ldap/LdapLoginWorker.java | 51 ++-- .../ofbiz/content/search/ProductDocument.java | 219 ++++++++-------- .../ofbiz/content/search/SearchServices.java | 27 +- .../org/apache/ofbiz/content/test/LuceneTests.java | 2 +- .../java/org/apache/ofbiz/msg91/Msg91Services.java | 2 +- .../ofbiz/passport/user/GitHubAuthenticator.java | 2 +- .../ofbiz/htmlreport/AbstractHtmlReport.java | 4 +- .../ofbiz/htmlreport/AbstractReportThread.java | 2 +- .../org/apache/ofbiz/htmlreport/HtmlReport.java | 8 +- .../apache/ofbiz/htmlreport/InterfaceReport.java | 2 +- .../ofbiz/htmlreport/util/ReportEncoder.java | 14 +- .../apache/ofbiz/pricat/AbstractPricatParser.java | 116 +++++---- .../apache/ofbiz/pricat/InterfacePricatParser.java | 82 +++--- .../ofbiz/pricat/PricatParseExcelHtmlThread.java | 63 +++-- .../ofbiz/pricat/sample/SamplePricatParser.java | 278 +++++++++++---------- .../apache/ofbiz/pricat/util/OFBizPricatUtil.java | 2 +- .../java/org/apache/ofbiz/project/Various.java | 3 +- .../java/org/apache/ofbiz/scrum/ScrumEvents.java | 21 +- .../java/org/apache/ofbiz/scrum/ScrumServices.java | 52 ++-- .../java/org/apache/ofbiz/solr/CategoryUtil.java | 2 +- .../ofbiz/solr/control/OFBizSolrLoginWorker.java | 2 +- .../ofbiz/solr/webapp/OFBizSolrContextFilter.java | 90 ++++--- .../java/org/apache/ofbiz/webpos/WebPosEvents.java | 17 +- .../apache/ofbiz/webpos/search/WebPosSearch.java | 20 +- .../webpos/transaction/WebPosTransaction.java | 19 +- 48 files changed, 982 insertions(+), 725 deletions(-) diff --git a/assetmaint/src/main/java/org/apache/ofbiz/assetmaint/FixedAssetMaintServices.java b/assetmaint/src/main/java/org/apache/ofbiz/assetmaint/FixedAssetMaintServices.java index 023631c..0f15196 100644 --- a/assetmaint/src/main/java/org/apache/ofbiz/assetmaint/FixedAssetMaintServices.java +++ b/assetmaint/src/main/java/org/apache/ofbiz/assetmaint/FixedAssetMaintServices.java @@ -60,14 +60,16 @@ public class FixedAssetMaintServices { try { GenericValue product = ProductWorker.findProduct(delegator, productId); if (product == null) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintInvalidPartProductIdError", UtilMisc.toMap("productId", productId), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintInvalidPartProductIdError", UtilMisc.toMap( + "productId", productId), locale)); } Map<String, ? extends Object> findCurrInventoryParams = UtilMisc.toMap("productId", productId, "facilityId", facilityId); GenericValue userLogin = (GenericValue) context.get("userLogin"); // Call issuance service Map<String, Object> result = dispatcher.runSync("getInventoryAvailableByFacility", findCurrInventoryParams); if (ServiceUtil.isError(result)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintProblemGettingInventoryLevel", locale) + productId, null, null, result); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintProblemGettingInventoryLevel", locale) + productId, + null, null, result); } Object atpObj = result.get("availableToPromiseTotal"); double atp = 0.0; @@ -75,14 +77,16 @@ public class FixedAssetMaintServices { atp = Double.parseDouble(atpObj.toString()); } if (requestedQty > atp) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintLowPartInventoryError", UtilMisc.toMap("productId", productId, "quantity", Double.toString(atp)), locale)); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintLowPartInventoryError", UtilMisc.toMap("productId", + productId, "quantity", Double.toString(atp)), locale)); } EntityConditionList<EntityExpr> ecl = EntityCondition.makeCondition(UtilMisc.toList( EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityCondition.makeCondition("facilityId", EntityOperator.EQUALS, facilityId), EntityCondition.makeCondition("availableToPromiseTotal", EntityOperator.GREATER_THAN, "0")), EntityOperator.AND); - List<GenericValue> inventoryItems = EntityQuery.use(delegator).from("InventoryItem").where(ecl).queryList(); //&& inventoryItems.size() > 0 + List<GenericValue> inventoryItems = EntityQuery.use(delegator).from("InventoryItem").where(ecl).queryList(); //&& inventoryItems.size + // () > 0 Iterator<GenericValue> itr = inventoryItems.iterator(); while (requestedQty > 0 && itr.hasNext()) { GenericValue inventoryItem = itr.next(); @@ -104,7 +108,8 @@ public class FixedAssetMaintServices { // Call issuance service result = dispatcher.runSync("issueInventoryItemToFixedAssetMaint", itemIssuanceCtx); if (ServiceUtil.isError(result)) { - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintProblemCallingService", locale), null, null, result); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "AssetMaintProblemCallingService", locale), null, null, + result); } requestedQty = requestedQty - issueQuantity; } diff --git a/birt/src/main/java/org/apache/ofbiz/birt/BirtFactory.java b/birt/src/main/java/org/apache/ofbiz/birt/BirtFactory.java index 1de779b..84498d6 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/BirtFactory.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/BirtFactory.java @@ -37,7 +37,7 @@ import org.xml.sax.SAXException; */ public class BirtFactory { - public final static String MODULE = BirtFactory.class.getName(); + private static final String MODULE = BirtFactory.class.getName(); private static IReportEngine engine; diff --git a/birt/src/main/java/org/apache/ofbiz/birt/BirtWorker.java b/birt/src/main/java/org/apache/ofbiz/birt/BirtWorker.java index 3b34f72..1827b6c 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/BirtWorker.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/BirtWorker.java @@ -61,29 +61,29 @@ import org.eclipse.birt.report.engine.api.RenderOption; public final class BirtWorker { - public final static String MODULE = BirtWorker.class.getName(); + private static final String MODULE = BirtWorker.class.getName(); - private final static String BIRT_PARAMETERS = "birtParameters"; - private final static String BIRT_LOCALE = "birtLocale"; - private final static String BIRT_IMAGE_DIRECTORY = "birtImageDirectory"; - private final static String BIRT_CONTENT_TYPE = "birtContentType"; - private final static String BIRT_OUTPUT_FILE_NAME = "birtOutputFileName"; + private static final String BIRT_PARAMETERS = "birtParameters"; + private static final String BIRT_LOCALE = "birtLocale"; + private static final String BIRT_IMAGE_DIRECTORY = "birtImageDirectory"; + private static final String BIRT_CONTENT_TYPE = "birtContentType"; + private static final String BIRT_OUTPUT_FILE_NAME = "birtOutputFileName"; private static final String RES_ERROR = "BirtErrorUiLabels"; - private final static HTMLServerImageHandler imageHandler = new HTMLServerImageHandler(); + private static final HTMLServerImageHandler IMAGE_HANDLER = new HTMLServerImageHandler(); private BirtWorker() { } - private static final Map<Integer, Level> levelIntMap = new HashMap<>(); + private static final Map<Integer, Level> LEVEL_INT_MAP = new HashMap<>(); static { - levelIntMap.put(Debug.ERROR, Level.SEVERE); - levelIntMap.put(Debug.TIMING, Level.FINE); - levelIntMap.put(Debug.INFO, Level.INFO); - levelIntMap.put(Debug.IMPORTANT, Level.INFO); - levelIntMap.put(Debug.WARNING, Level.WARNING); - levelIntMap.put(Debug.ERROR, Level.SEVERE); - levelIntMap.put(Debug.FATAL, Level.ALL); - levelIntMap.put(Debug.ALWAYS, Level.ALL); + LEVEL_INT_MAP.put(Debug.ERROR, Level.SEVERE); + LEVEL_INT_MAP.put(Debug.TIMING, Level.FINE); + LEVEL_INT_MAP.put(Debug.INFO, Level.INFO); + LEVEL_INT_MAP.put(Debug.IMPORTANT, Level.INFO); + LEVEL_INT_MAP.put(Debug.WARNING, Level.WARNING); + LEVEL_INT_MAP.put(Debug.ERROR, Level.SEVERE); + LEVEL_INT_MAP.put(Debug.FATAL, Level.ALL); + LEVEL_INT_MAP.put(Debug.ALWAYS, Level.ALL); } /** @@ -138,7 +138,7 @@ public final class BirtWorker { HTMLRenderOption htmlOptions = new HTMLRenderOption(options); htmlOptions.setImageDirectory(birtImageDirectory); htmlOptions.setBaseImageURL(birtImageDirectory); - options.setImageHandler(imageHandler); + options.setImageHandler(IMAGE_HANDLER); } else if ("application/pdf".equals(contentType)) { // PDF PDFRenderOption pdfOptions = new PDFRenderOption(options); pdfOptions.setOption(IPDFRenderOption.PAGE_OVERFLOW, Boolean.TRUE); @@ -165,7 +165,7 @@ public final class BirtWorker { * @param response */ public static void setWebContextObjects(Map<String, Object> appContext, HttpServletRequest request, HttpServletResponse response) - throws GeneralException { + throws GeneralException { HttpSession session = request.getSession(); ServletContext servletContext = session.getServletContext(); @@ -181,23 +181,23 @@ public final class BirtWorker { appContext.put("dispatcher", WebAppUtil.getDispatcher(servletContext)); } - public static String getBirtParameters () { + public static String getBirtParameters() { return BIRT_PARAMETERS; } - public static String getBirtLocale () { + public static String getBirtLocale() { return BIRT_LOCALE; } - public static String getBirtImageDirectory () { + public static String getBirtImageDirectory() { return BIRT_IMAGE_DIRECTORY; } - public static String getBirtContentType () { + public static String getBirtContentType() { return BIRT_CONTENT_TYPE; } - public static String getBirtOutputFileName () { + public static String getBirtOutputFileName() { return BIRT_OUTPUT_FILE_NAME; } @@ -231,12 +231,12 @@ public final class BirtWorker { EntityCondition entityConditionRpt = EntityCondition.makeCondition("contentTypeId", "RPTDESIGN"); String templatePathLocation = BirtUtil.resolveTemplatePathLocation(); File templatePathLocationDir = new File(templatePathLocation); - if (!templatePathLocationDir.exists()) { - boolean created = templatePathLocationDir.mkdirs(); - if (!created) { - throw new GeneralException(UtilProperties.getMessage(RES_ERROR, "BirtErrorCannotLocateReportFolder", locale)); - } + if (!templatePathLocationDir.exists()) { + boolean created = templatePathLocationDir.mkdirs(); + if (!created) { + throw new GeneralException(UtilProperties.getMessage(RES_ERROR, "BirtErrorCannotLocateReportFolder", locale)); } + } int i = 0; String templateFileLocation = null; EntityCondition ecl = null; @@ -252,14 +252,16 @@ public final class BirtWorker { } while (EntityQuery.use(delegator).from("ContentDataResourceView").where(ecl).queryCount() > 0); //resolve the initial form structure from master content - Map<String, Object> resultElectronicText = dispatcher.runSync("getElectronicText", UtilMisc.toMap("contentId", masterContentId, "locale", locale, "userLogin", userLogin)); + Map<String, Object> resultElectronicText = dispatcher.runSync("getElectronicText", UtilMisc.toMap("contentId", masterContentId, "locale", + locale, "userLogin", userLogin)); if (ServiceUtil.isError(resultElectronicText)) { throw new GeneralException(ServiceUtil.getErrorMessage(resultElectronicText)); } String reportForm = (String) resultElectronicText.get("textData"); if (!reportForm.startsWith("<?xml")) { StringBuffer xmlHeaderForm = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); - xmlHeaderForm.append("<forms xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://ofbiz.apache.org/dtds/widget-form.xsd\">"); + xmlHeaderForm.append("<forms xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://ofbiz" + + ".apache.org/dtds/widget-form.xsd\">"); xmlHeaderForm.append(reportForm); xmlHeaderForm.append("</forms>"); reportForm = xmlHeaderForm.toString(); @@ -269,15 +271,18 @@ public final class BirtWorker { //create content and dataressource strucutre Map<String, Object> result = null; - result = dispatcher.runSync("createDataResource", UtilMisc.toMap("dataResourceId", dataResourceId, "dataResourceTypeId", "ELECTRONIC_TEXT", "dataTemplateTypeId", "FORM_COMBINED", "userLogin", userLogin)); + result = dispatcher.runSync("createDataResource", UtilMisc.toMap("dataResourceId", dataResourceId, "dataResourceTypeId", "ELECTRONIC_TEXT", + "dataTemplateTypeId", "FORM_COMBINED", "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("createElectronicTextForm", UtilMisc.toMap("dataResourceId", dataResourceId, "textData", reportForm, "userLogin", userLogin)); + result = dispatcher.runSync("createElectronicTextForm", UtilMisc.toMap("dataResourceId", dataResourceId, "textData", reportForm, "userLogin", + userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("createContent", UtilMisc.toMap("contentId", contentId, "contentTypeId", "FLEXIBLE_REPORT", "dataResourceId", dataResourceId, "statusId", "CTNT_IN_PROGRESS", "contentName", reportName, "description", description, "userLogin", userLogin)); + result = dispatcher.runSync("createContent", UtilMisc.toMap("contentId", contentId, "contentTypeId", "FLEXIBLE_REPORT", "dataResourceId", + dataResourceId, "statusId", "CTNT_IN_PROGRESS", "contentName", reportName, "description", description, "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } @@ -287,23 +292,29 @@ public final class BirtWorker { if (!rptDesignName.endsWith(".rptdesign")) { rptDesignName = rptDesignName.concat(".rptdesign"); } - result = dispatcher.runSync("createDataResource", UtilMisc.toMap("dataResourceId", dataResourceIdRpt, "dataResourceTypeId", "LOCAL_FILE", "mimeTypeId", "text/rptdesign", "dataResourceName", rptDesignName, "objectInfo", templateFileLocation, "userLogin", userLogin)); + result = dispatcher.runSync("createDataResource", UtilMisc.toMap("dataResourceId", dataResourceIdRpt, "dataResourceTypeId", "LOCAL_FILE", + "mimeTypeId", "text/rptdesign", "dataResourceName", rptDesignName, "objectInfo", templateFileLocation, "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("createContent", UtilMisc.toMap("contentId", contentIdRpt, "contentTypeId", "RPTDESIGN", "dataResourceId", dataResourceIdRpt, "statusId", "CTNT_PUBLISHED", "contentName", reportName, "description", description + " (.rptDesign file)", "userLogin", userLogin)); + result = dispatcher.runSync("createContent", UtilMisc.toMap("contentId", contentIdRpt, "contentTypeId", "RPTDESIGN", "dataResourceId", + dataResourceIdRpt, "statusId", "CTNT_PUBLISHED", "contentName", reportName, "description", description + " (.rptDesign file)", + "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("createContentAssoc", UtilMisc.toMap("contentId", masterContentId, "contentIdTo", contentId, "contentAssocTypeId", "SUB_CONTENT", "userLogin", userLogin)); + result = dispatcher.runSync("createContentAssoc", UtilMisc.toMap("contentId", masterContentId, "contentIdTo", contentId, + "contentAssocTypeId", "SUB_CONTENT", "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("createContentAssoc", UtilMisc.toMap("contentId", contentId, "contentIdTo", contentIdRpt, "contentAssocTypeId", "SUB_CONTENT", "userLogin", userLogin)); + result = dispatcher.runSync("createContentAssoc", UtilMisc.toMap("contentId", contentId, "contentIdTo", contentIdRpt, "contentAssocTypeId", + "SUB_CONTENT", "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("createContentAttribute", UtilMisc.toMap("contentId", contentId, "attrName", workflowType, "attrValue", modelElementName, "userLogin", userLogin)); + result = dispatcher.runSync("createContentAttribute", UtilMisc.toMap("contentId", contentId, "attrName", workflowType, "attrValue", + modelElementName, "userLogin", userLogin)); if (ServiceUtil.isError(result)) { throw new GeneralException(ServiceUtil.getErrorMessage(result)); } @@ -324,6 +335,7 @@ public final class BirtWorker { break; } } - config.setLogConfig(UtilProperties.getPropertyValue("debug", "log4j.appender.css.dir", ofbizHome + "/runtime/logs/"), levelIntMap.get(lowerLevel)); + config.setLogConfig(UtilProperties.getPropertyValue("debug", "log4j.appender.css.dir", ofbizHome + "/runtime/logs/"), + LEVEL_INT_MAP.get(lowerLevel)); } } diff --git a/birt/src/main/java/org/apache/ofbiz/birt/email/BirtEmailServices.java b/birt/src/main/java/org/apache/ofbiz/birt/email/BirtEmailServices.java index 9facddf..01c5487 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/email/BirtEmailServices.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/email/BirtEmailServices.java @@ -118,11 +118,13 @@ public class BirtEmailServices { try { screenStringRenderer = new MacroScreenRenderer("screen", visualTheme.getModelTheme().getScreenRendererLocation("screen")); } catch (TemplateException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), + locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (IOException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), + locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -134,19 +136,23 @@ public class BirtEmailServices { try { screens.render(bodyScreenUri); } catch (GeneralException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingScreenForEmail", UtilMisc.toMap("errorString", + e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (IOException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorIORenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorIORenderingScreenForEmail", UtilMisc.toMap("errorString", + e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (SAXException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorSAXRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorSAXRenderingScreenForEmail", UtilMisc.toMap("errorString", + e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (ParserConfigurationException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorParserConfigRenderingScreenForEmail", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorParserConfigRenderingScreenForEmail", UtilMisc.toMap("errorString", + e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -199,31 +205,38 @@ public class BirtEmailServices { bodyParts.add(UtilMisc.toMap("content", baos.toByteArray(), "type", "application/pdf", "filename", attachmentName)); serviceContext.put("bodyParts", bodyParts); } catch (GeneralException ge) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", ge.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", ge.toString()), locale); Debug.logError(ge, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (IOException ie) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorIORenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", ie.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorIORenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", ie.toString()), locale); Debug.logError(ie, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (FOPException fe) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorFOPRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", fe.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorFOPRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", fe.toString()), locale); Debug.logError(fe, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (SAXException se) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorSAXRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", se.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorSAXRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", se.toString()), locale); Debug.logError(se, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (ParserConfigurationException pe) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorParserRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", pe.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorParserRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", pe.toString()), locale); Debug.logError(pe, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (EngineException ee) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", ee.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", ee.toString()), locale); Debug.logError(ee, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (SQLException se) { - String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorSQLRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", birtContentType, "errorString", se.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "BirtErrorSQLRenderingAttachmentForEmail", UtilMisc.toMap("birtContentType", + birtContentType, "errorString", se.toString()), locale); Debug.logError(se, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } diff --git a/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtMasterReportServices.java b/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtMasterReportServices.java index a4d86cb..506c215 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtMasterReportServices.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtMasterReportServices.java @@ -244,11 +244,15 @@ public class BirtMasterReportServices { productCategoryList = UtilGenerics.cast(parameters.get("productCategoryId")); } // getting productIds in these categories - EntityExpr conditionProductCategory = EntityCondition.makeCondition("primaryProductCategoryId", EntityOperator.IN, productCategoryList); - EntityExpr conditionFromDate = EntityCondition.makeCondition("fromDate", EntityOperator.GREATER_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()); - EntityExpr conditionBeforeDate = EntityCondition.makeCondition("thruDate", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()); + EntityExpr conditionProductCategory = EntityCondition.makeCondition("primaryProductCategoryId", EntityOperator.IN, + productCategoryList); + EntityExpr conditionFromDate = EntityCondition.makeCondition("fromDate", EntityOperator.GREATER_THAN_EQUAL_TO, + UtilDateTime.nowTimestamp()); + EntityExpr conditionBeforeDate = EntityCondition.makeCondition("thruDate", EntityOperator.LESS_THAN_EQUAL_TO, + UtilDateTime.nowTimestamp()); EntityExpr conditionNull = EntityCondition.makeCondition("thruDate", null); - EntityCondition conditionThroughDate = EntityCondition.makeCondition(EntityOperator.OR, UtilMisc.toList(conditionBeforeDate, conditionNull)); + EntityCondition conditionThroughDate = EntityCondition.makeCondition(EntityOperator.OR, UtilMisc.toList(conditionBeforeDate, + conditionNull)); List<GenericValue> listProductIds = EntityQuery.use(delegator) .from("ProductCategoryMember") .where(EntityCondition.makeCondition(UtilMisc.toList(conditionProductCategory, conditionFromDate, conditionThroughDate))) @@ -269,10 +273,12 @@ public class BirtMasterReportServices { } // getting list of invoice Ids linked to these productStore EntityExpr conditionProductStoreId = EntityCondition.makeCondition("productStoreId", EntityOperator.IN, productStoreList); - List<GenericValue> listOrderAndProductStores = EntityQuery.use(delegator).from("OrderAndProductStore").where(conditionProductStoreId).select("orderId").queryList(); + List<GenericValue> listOrderAndProductStores = + EntityQuery.use(delegator).from("OrderAndProductStore").where(conditionProductStoreId).select("orderId").queryList(); List<String> listOrderIds = EntityUtil.getFieldListFromEntityList(listOrderAndProductStores, "orderId", true); EntityExpr conditionOrderId = EntityCondition.makeCondition("orderId", EntityOperator.IN, listOrderIds); - List<GenericValue> listInvoices = EntityQuery.use(delegator).from("OrderItemBilling").where(conditionOrderId).select("invoiceId").queryList(); + List<GenericValue> listInvoices = + EntityQuery.use(delegator).from("OrderItemBilling").where(conditionOrderId).select("invoiceId").queryList(); List<String> listInvoiceString = EntityUtil.getFieldListFromEntityList(listInvoices, "invoiceId", true); EntityExpr conditionInvoiceIdProductStore = EntityCondition.makeCondition("invoiceId", EntityOperator.IN, listInvoiceString); @@ -281,7 +287,8 @@ public class BirtMasterReportServices { // adding mandatory conditions // condition on invoice item type - List<String> listInvoiceItemType = UtilMisc.toList("ITM_PROMOTION_ADJ", "INV_PROD_ITEM", "INV_FPROD_ITEM", "INV_DPROD_ITEM", "INV_FDPROD_ITEM", "INV_PROD_FEATR_ITEM"); + List<String> listInvoiceItemType = UtilMisc.toList("ITM_PROMOTION_ADJ", "INV_PROD_ITEM", "INV_FPROD_ITEM", "INV_DPROD_ITEM", + "INV_FDPROD_ITEM", "INV_PROD_FEATR_ITEM"); listInvoiceItemType.add("ITM_DISCOUNT_ADJ"); listInvoiceItemType.add("CRT_FPROD_ITEM"); listInvoiceItemType.add("CRT_DPROD_ITEM"); @@ -297,11 +304,13 @@ public class BirtMasterReportServices { // condition on invoice ((not cancelled) or null) EntityExpr conditionStatusNotCancelled = EntityCondition.makeCondition("statusId", EntityOperator.NOT_EQUAL, "INVOICE_CANCELLED"); EntityExpr conditionStatusNull = EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, null); - EntityCondition conditionStatus = EntityCondition.makeCondition(UtilMisc.toList(conditionStatusNotCancelled, conditionStatusNull), EntityOperator.OR); + EntityCondition conditionStatus = EntityCondition.makeCondition(UtilMisc.toList(conditionStatusNotCancelled, conditionStatusNull), + EntityOperator.OR); listAllConditions.add(conditionStatus); // condition sales invoice or customer return invoice - EntityExpr conditionSalesInvoice = EntityCondition.makeCondition("invoiceTypeId", EntityOperator.IN, UtilMisc.toList("SALES_INVOICE", "CUST_RTN_INVOICE")); + EntityExpr conditionSalesInvoice = EntityCondition.makeCondition("invoiceTypeId", EntityOperator.IN, UtilMisc.toList("SALES_INVOICE", + "CUST_RTN_INVOICE")); listAllConditions.add(conditionSalesInvoice); // retrieving all invoices @@ -335,9 +344,10 @@ public class BirtMasterReportServices { // adding productStoreId and productStoreName EntityExpr conditionInvoiceId = EntityCondition.makeCondition("invoiceId", invoice.getString("invoiceId")); -// EntityExpr conditionInvoiceItemSeqId = EntityCondition.makeCondition("invoiceItemSeqId", invoice.getString("invoiceItemSeqId")); -// List<GenericValue> listOrderBilling = delegator.findList("OrderItemBilling", EntityCondition.makeCondition -// (UtilMisc.toList(conditionInvoiceId, conditionInvoiceItemSeqId)), UtilMisc.toSet("orderId"), null, null, false); + // EntityExpr conditionInvoiceItemSeqId = EntityCondition.makeCondition("invoiceItemSeqId", invoice.getString + // ("invoiceItemSeqId")); + // List<GenericValue> listOrderBilling = delegator.findList("OrderItemBilling", EntityCondition.makeCondition + // (UtilMisc.toList(conditionInvoiceId, conditionInvoiceItemSeqId)), UtilMisc.toSet("orderId"), null, null, false); GenericValue orderBilling = EntityQuery.use(delegator) .from("OrderItemBilling") .where(conditionInvoiceId) @@ -351,7 +361,8 @@ public class BirtMasterReportServices { .cache() .queryFirst(); if (UtilValidate.isNotEmpty(productStoreList) && !productStoreList.contains(productStore.getString("productStoreId"))) { - continue; // FIXME pretty ugly... but had problems with the rare case where an invoice matches with several orders with more than one productStore + continue; // FIXME pretty ugly... but had problems with the rare case where an invoice matches with several orders with + // more than one productStore } invoiceEditable.put("productStoreId", productStore.getString("productStoreId")); invoiceEditable.put("storeName", productStore.getString("storeName")); diff --git a/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtServices.java b/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtServices.java index 0bf913a..ace537f 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtServices.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtServices.java @@ -91,7 +91,6 @@ public class BirtServices { private static final String MODULE = BirtServices.class.getName(); private static final String RESOURCE = "BirtUiLabels"; private static final String RES_ERROR = "BirtErrorUiLabels"; - private static final String RES_PRODUCT = "BirtUiLabels"; /** * Instantiate a new Flexible report, using the data given in parameters and <code>ReportDesignGenerator</code> class. @@ -115,7 +114,8 @@ public class BirtServices { @Deprecated // TODO lack documentation about the reason of deprecation - // Seems to need to be simply removed since not used at all. But not sure it's not still useful in certain situations, else why not already removed? + // Seems to need to be simply removed since not used at all. + // But not sure it's not still useful in certain situations, else why not already removed? public static Map<String, Object> prepareFlexibleReportOptionFieldsFromEntity(DispatchContext dctx, Map<String, Object> context) { String entityViewName = (String) context.get("entityViewName"); GenericValue userLogin = (GenericValue) context.get("userLogin"); @@ -134,7 +134,8 @@ public class BirtServices { String fieldType = mField.getType(); String birtType = null; try { - Map<String, Object> convertRes = dispatcher.runSync("convertFieldTypeToBirtType", UtilMisc.toMap("fieldType", fieldType, "userLogin", userLogin)); + Map<String, Object> convertRes = dispatcher.runSync("convertFieldTypeToBirtType", UtilMisc.toMap("fieldType", fieldType, + "userLogin", userLogin)); if (ServiceUtil.isError(convertRes)) { String errMsg = UtilProperties.getMessage(RES_ERROR, "BirtErrorConversionFieldToBirtFailed", locale); return ServiceUtil.returnError(errMsg + ServiceUtil.getErrorMessage(convertRes)); @@ -162,7 +163,6 @@ public class BirtServices { /** * Perform find data on given view/entity and return these into Birt compatible format. * This service is meant to be used as default for View/entity report design - * */ public static Map<String, Object> callPerformFindFromBirt(DispatchContext dctx, Map<String, Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); @@ -183,7 +183,7 @@ public class BirtServices { } try { - resultPerformFind = dispatcher.runSync("performFind", UtilMisc.<String, Object>toMap("entityName", entityViewName, + resultPerformFind = dispatcher.runSync("performFind", UtilMisc.<String, Object>toMap("entityName", entityViewName, "inputFields", inputFields, "userLogin", userLogin, "noConditionFind", "Y", "locale", locale)); if (ServiceUtil.isError(resultPerformFind)) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "BirtErrorRunningPerformFind", locale)); @@ -212,8 +212,8 @@ public class BirtServices { * Analyse given master and create report design from its data * Two cases are implemented : * <ul> - * <li>Entity : data retieval is based on a simple view/entity</li> - * <li>Service : data retrieval is based on service</li> + * <li>Entity : data retieval is based on a simple view/entity</li> + * <li>Service : data retrieval is based on service</li> * </ul> */ public static Map<String, Object> createFlexibleReportFromMaster(DispatchContext dctx, Map<String, Object> context) { @@ -248,8 +248,10 @@ public class BirtServices { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "BirtErrorEntityViewNotExist", locale) + " " + entityViewName); } try { - Map<String, Object> resultContent = dispatcher.runSync("createFlexibleReportFromMasterEntityWorkflow", UtilMisc.toMap("entityViewName", entityViewName, - "reportName", reportName, "description", description, "writeFilters", writeFilters, "masterContentId", masterContentId, "userLogin", userLogin, "locale", locale)); + Map<String, Object> resultContent = dispatcher.runSync("createFlexibleReportFromMasterEntityWorkflow", UtilMisc.toMap( + "entityViewName", entityViewName, + "reportName", reportName, "description", description, "writeFilters", writeFilters, "masterContentId", masterContentId, + "userLogin", userLogin, "locale", locale)); if (ServiceUtil.isError(resultContent)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resultContent)); } @@ -261,8 +263,9 @@ public class BirtServices { } else if ("Service".equalsIgnoreCase(attrName)) { String serviceName = masterContentAttribute.getString("attrValue"); try { - Map<String, Object> resultContent = dispatcher.runSync("createFlexibleReportFromMasterServiceWorkflow", UtilMisc.toMap("serviceName", serviceName, - "reportName", reportName, "description", description, "writeFilters", writeFilters, "masterContentId", masterContentId, "userLogin", userLogin, "locale", locale)); + Map<String, Object> resultContent = dispatcher.runSync("createFlexibleReportFromMasterServiceWorkflow", UtilMisc.toMap( + "serviceName", serviceName, "reportName", reportName, "description", description, "writeFilters", writeFilters, + "masterContentId", masterContentId, "userLogin", userLogin, "locale", locale)); if (ServiceUtil.isError(resultContent)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resultContent)); } @@ -280,23 +283,28 @@ public class BirtServices { String textForm; Map<String, Object> resultFormDisplay; try { - resultFormDisplay = dispatcher.runSync("prepareFlexibleReportSearchFormToEdit", UtilMisc.toMap("reportContentId", reportContentId, "userLogin", userLogin, "locale", locale)); + resultFormDisplay = dispatcher.runSync("prepareFlexibleReportSearchFormToEdit", UtilMisc.toMap("reportContentId", reportContentId, + "userLogin", userLogin, "locale", locale)); if (ServiceUtil.isError(resultFormDisplay)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resultFormDisplay)); } textForm = (String) resultFormDisplay.get("textForm"); } catch (GenericServiceException e) { Debug.logError(e, MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "BirtErrorCreatingDefaultSearchForm", locale).concat(": ").concat(e.getMessage())); + return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, + "BirtErrorCreatingDefaultSearchForm", locale).concat(": ").concat(e.getMessage())); } - Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(RESOURCE, "BirtFlexibleReportSuccessfullyGenerated", locale).concat(" ").concat(reportName)); + Map<String, Object> result = ServiceUtil.returnSuccess(UtilProperties.getMessage(RESOURCE, "BirtFlexibleReportSuccessfullyGenerated", + locale).concat(" ").concat(reportName)); result.put("textForm", textForm); result.put("reportContentId", reportContentId); return result; } - // TODO check: I'm not a big fan of how I did the createFormForDisplay / overrideReportForm. Could probably be improved using a proper formForReport object or something similar. + // TODO check: I'm not a big fan of how I did the createFormForDisplay / overrideReportForm. Could probably be improved using a proper + // formForReport object or something similar. + /** * Update search form of a report design */ @@ -310,18 +318,21 @@ public class BirtServices { // safety check : do not accept "${groovy", "${bsh" and "javascript" String overideFiltersNoWhiteSpace = overrideFilters.replaceAll("\\s", ""); - if (overideFiltersNoWhiteSpace.contains("${groovy:") || overideFiltersNoWhiteSpace.contains("${bsh:") || overideFiltersNoWhiteSpace.contains("javascript:")) { + if (overideFiltersNoWhiteSpace.contains("${groovy:") || overideFiltersNoWhiteSpace.contains("${bsh:") + || overideFiltersNoWhiteSpace.contains("javascript:")) { return ServiceUtil.returnError(UtilProperties.getMessage(RES_ERROR, "BirtErrorUnauthorisedCharacter", locale)); } try { GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", reportContentId).queryOne(); String dataResourceId = content.getString("dataResourceId"); - StringBuffer newForm = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <forms xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://ofbiz.apache.org/dtds/widget-form.xsd\">"); + StringBuffer newForm = new StringBuffer("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <forms xmlns:xsi=\"http://www.w3" + + ".org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://ofbiz.apache.org/dtds/widget-form.xsd\">"); newForm.append(overrideFilters); newForm.append("</forms>"); Document xmlForm = UtilXml.readXmlDocument(newForm.toString()); - Map<String, Object> result = dispatcher.runSync("updateElectronicTextForm", UtilMisc.toMap("dataResourceId", dataResourceId, "textData", UtilXml.writeXmlDocument(xmlForm), + Map<String, Object> result = dispatcher.runSync("updateElectronicTextForm", UtilMisc.toMap("dataResourceId", dataResourceId, + "textData", UtilXml.writeXmlDocument(xmlForm), "userLogin", userLogin, "locale", locale)); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); @@ -348,7 +359,8 @@ public class BirtServices { String contentId = null; Map<String, Object> result = ServiceUtil.returnSuccess(); try { - Map<String, Object> resultMapsForGeneration = dispatcher.runSync("prepareFlexibleReportFieldsFromEntity", UtilMisc.toMap("modelEntity", modelEntity, + Map<String, Object> resultMapsForGeneration = dispatcher.runSync("prepareFlexibleReportFieldsFromEntity", UtilMisc.toMap("modelEntity", + modelEntity, "userLogin", userLogin, "locale", locale)); if (ServiceUtil.isError(resultMapsForGeneration)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resultMapsForGeneration)); @@ -427,7 +439,7 @@ public class BirtServices { } try { @SuppressWarnings("unused") // Used only to passively check - ModelService modelService = dctx.getModelService(serviceName); + ModelService modelService = dctx.getModelService(serviceName); } catch (GenericServiceException e) { Debug.logError(e, MODULE); return ServiceUtil.returnError("No service define with name " + serviceName); //TODO labelise @@ -477,7 +489,8 @@ public class BirtServices { List<String> listEntityFields = modelEntity.getAllFieldNames(); Map<Object, Object> uiLabelMap = new HashMap<>(); - final String[] resourceGlob = {"OrderUiLabels", "ProductUiLabels", "PartyUiLabels", "ContentUiLabels", "AccountingUiLabels", "CommonUiLabels", "BirtUiLabels"}; + final String[] resourceGlob = {"OrderUiLabels", "ProductUiLabels", "PartyUiLabels", "ContentUiLabels", "AccountingUiLabels", + "CommonUiLabels", "BirtUiLabels"}; for (String res : resourceGlob) { uiLabelMap.putAll(UtilProperties.getProperties(res, locale)); } @@ -507,15 +520,20 @@ public class BirtServices { filterMap.put(field.concat("_fld0_op"), "short-varchar"); filterMap.put(field.concat("_fld1_value"), mField.getType()); filterMap.put(field.concat("_fld1_op"), "short-varchar"); - filterDisplayLabels.put(field.concat("_fld0_value"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, "BirtFindFieldOptionValue0", locale))); - filterDisplayLabels.put(field.concat("_fld0_op"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, "BirtFindFieldOptionValue0", locale).concat(UtilProperties.getMessage(RESOURCE, "BirtFindCompareOperator", locale)))); - filterDisplayLabels.put(field.concat("_fld1_value"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, "BirtFindFieldOptionValue1", locale))); - filterDisplayLabels.put(field.concat("_fld1_op"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, "BirtFindFieldOptionValue1", locale).concat(UtilProperties.getMessage(RESOURCE, "BirtFindCompareOperator", locale)))); + filterDisplayLabels.put(field.concat("_fld0_value"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, + "BirtFindFieldOptionValue0", locale))); + filterDisplayLabels.put(field.concat("_fld0_op"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, + "BirtFindFieldOptionValue0", locale).concat(UtilProperties.getMessage(RESOURCE, "BirtFindCompareOperator", locale)))); + filterDisplayLabels.put(field.concat("_fld1_value"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, + "BirtFindFieldOptionValue1", locale))); + filterDisplayLabels.put(field.concat("_fld1_op"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, + "BirtFindFieldOptionValue1", locale).concat(UtilProperties.getMessage(RESOURCE, "BirtFindCompareOperator", locale)))); } else { // remaining types need 4 fields (fld0-1_op-value) filterMap.put(field, mField.getType()); filterMap.put(field.concat("_op"), "short-varchar"); filterDisplayLabels.put(field, fieldDisplayLabels.get(field)); - filterDisplayLabels.put(field.concat("_op"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, "BirtFindCompareOperator", locale))); + filterDisplayLabels.put(field.concat("_op"), fieldDisplayLabels.get(field).concat(UtilProperties.getMessage(RESOURCE, + "BirtFindCompareOperator", locale))); } } Map<String, Object> result = ServiceUtil.returnSuccess(); @@ -544,7 +562,8 @@ public class BirtServices { try { GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", reportContentId).cache().queryOne(); String dataResourceId = content.getString("dataResourceId"); - GenericValue electronicText = EntityQuery.use(delegator).from("ElectronicText").where("dataResourceId", dataResourceId).cache().queryOne(); + GenericValue electronicText = + EntityQuery.use(delegator).from("ElectronicText").where("dataResourceId", dataResourceId).cache().queryOne(); textData = electronicText.getString("textData"); } catch (GenericEntityException e) { Debug.logError(e, MODULE); @@ -590,7 +609,8 @@ public class BirtServices { try { for (String contentId : listContentId) { - Map<String, Object> returnMap = dispatcher.runSync("deleteFlexibleReport", UtilMisc.toMap("contentId", contentId, "userLogin", userLogin, "locale", locale)); + Map<String, Object> returnMap = dispatcher.runSync("deleteFlexibleReport", UtilMisc.toMap("contentId", contentId, "userLogin", + userLogin, "locale", locale)); if (ServiceUtil.isError(returnMap)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(returnMap)); } @@ -646,11 +666,13 @@ public class BirtServices { } try { delegator.removeByAnd("ContentAttribute", UtilMisc.toMap("contentId", contentId)); - Map<String, Object> result = dispatcher.runSync("removeContentAndRelated", UtilMisc.toMap("contentId", contentId, "userLogin", userLogin, "locale", locale)); + Map<String, Object> result = dispatcher.runSync("removeContentAndRelated", UtilMisc.toMap("contentId", contentId, "userLogin", + userLogin, "locale", locale)); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); } - result = dispatcher.runSync("removeContentAndRelated", UtilMisc.toMap("contentId", contentIdRpt, "userLogin", userLogin, "locale", locale)); + result = dispatcher.runSync("removeContentAndRelated", UtilMisc.toMap("contentId", contentIdRpt, "userLogin", userLogin, "locale", + locale)); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); } @@ -794,7 +816,8 @@ public class BirtServices { } } - // FXIME ? adding simple master page => All these casts and other occurrences ... It's ugly, but it's so hard that when I find a solution that works ... + // FXIME ? adding simple master page => All these casts and other occurrences ... It's ugly, but it's so hard that when I find a + // solution that works ... @SuppressWarnings("unchecked") List<DesignElementHandle> listMasterPages = designFromUser.getMasterPages().getContents(); for (DesignElementHandle masterPage : listMasterPages) { @@ -866,5 +889,4 @@ public class BirtServices { result = ServiceUtil.returnSuccess(listSuccessMessage); return result; } - -} \ No newline at end of file +} diff --git a/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtUtil.java b/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtUtil.java index 322534f..45467b3 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtUtil.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/flexible/BirtUtil.java @@ -39,9 +39,9 @@ import org.eclipse.birt.report.model.api.elements.DesignChoiceConstants; public final class BirtUtil { - public final static String MODULE = BirtUtil.class.getName(); + private static final String MODULE = BirtUtil.class.getName(); - private final static Map<String, String> entityFieldTypeBirtTypeMap = MapUtils.unmodifiableMap(UtilMisc.toMap( + private static final Map<String, String> ENTITY_FIELD_TYPE_BIRT_TYPE_MAP = MapUtils.unmodifiableMap(UtilMisc.toMap( "id", DesignChoiceConstants.COLUMN_DATA_TYPE_STRING, "url", DesignChoiceConstants.COLUMN_DATA_TYPE_STRING, "name", DesignChoiceConstants.COLUMN_DATA_TYPE_STRING, @@ -70,7 +70,7 @@ public final class BirtUtil { "object", DesignChoiceConstants.COLUMN_DATA_TYPE_JAVA_OBJECT, "blob", DesignChoiceConstants.COLUMN_DATA_TYPE_BLOB)); - private final static Map<String, String> entityFieldTypeBirtParameterTypeMap = MapUtils.unmodifiableMap(UtilMisc.toMap( + private static final Map<String, String> ENTITY_FIELD_TYPE_BIRT_PARAM_TYPE_MAP = MapUtils.unmodifiableMap(UtilMisc.toMap( "id", DesignChoiceConstants.PARAM_TYPE_STRING, "url", DesignChoiceConstants.PARAM_TYPE_STRING, "name", DesignChoiceConstants.PARAM_TYPE_STRING, @@ -99,7 +99,7 @@ public final class BirtUtil { "object", DesignChoiceConstants.PARAM_TYPE_JAVA_OBJECT, "blob", DesignChoiceConstants.PARAM_TYPE_JAVA_OBJECT)); - private final static Map<String, String> mimeTypeOutputFormatMap = UtilMisc.toMap( + private static final Map<String, String> MIME_TYPE_OUTPUT_FORMAT_MAP = UtilMisc.toMap( "text/html", RenderOption.OUTPUT_FORMAT_HTML, "application/pdf", RenderOption.OUTPUT_FORMAT_PDF, "application/postscript", "postscript", @@ -124,11 +124,11 @@ public final class BirtUtil { if (UtilValidate.isEmpty(entityFieldType)) { return null; } - return entityFieldTypeBirtTypeMap.get(entityFieldType.toLowerCase()); + return ENTITY_FIELD_TYPE_BIRT_TYPE_MAP.get(entityFieldType.toLowerCase()); } /** - * Return birt parameter type corresponding to given entity field type + * Return birt parameter type corresponding to given entity field type * @param entityFieldType * @return birt parameter type corresponding to given entity field type */ @@ -136,7 +136,7 @@ public final class BirtUtil { if (UtilValidate.isEmpty(entityFieldType)) { return null; } - return entityFieldTypeBirtParameterTypeMap.get(entityFieldType.toLowerCase()); + return ENTITY_FIELD_TYPE_BIRT_PARAM_TYPE_MAP.get(entityFieldType.toLowerCase()); } /** @@ -145,7 +145,7 @@ public final class BirtUtil { * @return true if mime type related to a contentType is supported by Birt */ public static boolean isSupportedMimeType(String contentType) { - return mimeTypeOutputFormatMap.containsKey(contentType); + return MIME_TYPE_OUTPUT_FORMAT_MAP.containsKey(contentType); } /** @@ -156,7 +156,7 @@ public final class BirtUtil { */ public static String getMimeTypeOutputFormat(String contentType) throws GeneralException { if (isSupportedMimeType(contentType)) { - return mimeTypeOutputFormatMap.get(contentType); + return MIME_TYPE_OUTPUT_FORMAT_MAP.get(contentType); } throw new GeneralException("Unknown content type : " + contentType); } @@ -237,4 +237,4 @@ public final class BirtUtil { if (UtilValidate.isEmpty(reportName)) return ""; return StringUtil.replaceString(StringUtil.removeRegex(reportName.trim(), "[^\\p{L}\\s]"), " ", "_"); } -} \ No newline at end of file +} diff --git a/birt/src/main/java/org/apache/ofbiz/birt/flexible/ReportDesignGenerator.java b/birt/src/main/java/org/apache/ofbiz/birt/flexible/ReportDesignGenerator.java index fb6f48f..adb910f 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/flexible/ReportDesignGenerator.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/flexible/ReportDesignGenerator.java @@ -67,22 +67,27 @@ import com.ibm.icu.util.ULocale; public class ReportDesignGenerator { private static final String MODULE = ReportDesignGenerator.class.getName(); + private static final String RES_ERROR = "BirtErrorUiLabels"; private Locale locale; private ElementFactory factory; - /** The generated design */ + /** + * The generated design + */ private ReportDesignHandle design; private Map<String, String> dataMap; - /** Map of all filter supported by the report design */ + /** + * Map of all filter supported by the report design + */ private Map<String, String> filterMap; - /** Service name to populate dataset of the report design*/ + /** + * Service name to populate dataset of the report design + */ private String serviceName; private Map<String, String> fieldDisplayLabels; private Map<String, String> filterDisplayLabels; private String rptDesignName; private boolean generateFilters = false; - private static final String RES_ERROR = "BirtErrorUiLabels"; - public ReportDesignGenerator(Map<String, Object> context, DispatchContext dctx) throws GeneralException, SemanticException { locale = (Locale) context.get("locale"); dataMap = UtilGenerics.cast(context.get("dataMap")); @@ -102,14 +107,16 @@ public class ReportDesignGenerator { /** * Generate report design (rtdesign file). + * * @throws IOException * @throws GeneralException - * @throws BirtException + * @throws BirtException */ public void buildReport() throws IOException, GeneralException, BirtException { DesignConfig config = new DesignConfig(); Platform.startup(); - IDesignEngine engine = ((IDesignEngineFactory) Platform.createFactoryObject(IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY)).createDesignEngine(config); + IDesignEngine engine = ((IDesignEngineFactory) Platform.createFactoryObject( + IDesignEngineFactory.EXTENSION_DESIGN_ENGINE_FACTORY)).createDesignEngine(config); // creating main design elements SessionHandle session = engine.newSessionHandle(ULocale.forLocale(locale)); @@ -156,10 +163,13 @@ public class ReportDesignGenerator { displayFilterName = filter; } ScalarParameterHandle scalParam = factory.newScalarParameter(filter); - // scalParam.setDisplayName(displayFilterName); // TODO has no incidence at all right now, is only displayed when using birt's report parameter system. Not our case. I leave it here if any idea arise of how to translate these. + // scalParam.setDisplayName(displayFilterName); // TODO has no incidence at all right now, is only displayed when using birt's + // report parameter system. Not our case. I leave it here if any idea arise of how to translate these. scalParam.setPromptText(displayFilterName); - if ("javaObject".equals(birtType)) { //Fields of type='blob' are rejected by Birt: org.eclipse.birt.report.model.api.metadata.PropertyValueException: The choice value "javaObject" is not allowed. - throw new GeneralException("Fields of type='blob' are rejected by Birt. Create a view entity, based on the requested entity, where you exclude the field of type='blob'"); + if ("javaObject".equals(birtType)) { //Fields of type='blob' are rejected by Birt: org.eclipse.birt.report.model.api.metadata + // .PropertyValueException: The choice value "javaObject" is not allowed. + throw new GeneralException("Fields of type='blob' are rejected by Birt. Create a view entity, based on the requested entity, " + + "where you exclude the field of type='blob'"); } else { scalParam.setDataType(birtType); } @@ -250,6 +260,7 @@ public class ReportDesignGenerator { * Create the script that will define the OFBiz dataset in Birt Report design. * <p>This dataset will populate the OFBiz datasource of the design * with <code>records</code> returned by <code>serviceName</code> service</p> + * * @throws SemanticException * @throws GeneralException */ @@ -272,7 +283,8 @@ public class ReportDesignGenerator { StringBuffer dataSetOpenScript = new StringBuffer("importPackage(Packages.org.apache.ofbiz.birt);\n"); dataSetOpenScript.append("Debug.logInfo(\"#### In open\", MODULE)\n"); dataSetOpenScript.append("try {\n"); - dataSetOpenScript.append(" listRes = dispatcher.runSync(\"" + serviceName + "\", UtilMisc.toMap(\"userLogin\", reportContext.getParameterValue(\"userLogin\"), \"locale\", reportContext.getParameterValue(\"locale\"), \"reportContext\", reportContext));\n"); + dataSetOpenScript.append(" listRes = dispatcher.runSync(\"" + serviceName + "\", UtilMisc.toMap(\"userLogin\", reportContext" + + ".getParameterValue(\"userLogin\"), \"locale\", reportContext.getParameterValue(\"locale\"), \"reportContext\", reportContext));\n"); dataSetOpenScript.append(" if (ServiceUtil.isError(listRes)) {\n"); dataSetOpenScript.append(" Debug.logError(ServiceUtil.getErrorMessage(listRes));\n"); dataSetOpenScript.append(" }\n"); @@ -312,7 +324,7 @@ public class ReportDesignGenerator { resultSetCol.setColumnName(field); String birtType = BirtUtil.convertFieldTypeToBirtType(dataMap.get(field)); if (birtType == null) { - throw new GeneralException(UtilProperties.getMessage(RES_ERROR, "BirtErrorConversionFieldToBirtFailed", locale)); + throw new GeneralException(UtilProperties.getMessage(RES_ERROR, "BirtErrorConversionFieldToBirtFailed", locale)); } resultSetCol.setPosition(i); resultSetCol.setDataType(birtType); @@ -336,7 +348,9 @@ public class ReportDesignGenerator { design.getDataSets().add(dataSetHandle); } - /** Create new dataSource named OFBiz */ + /** + * Create new dataSource named OFBiz + */ private void createScriptedDataSource() throws SemanticException { ScriptDataSourceHandle dataSource = factory.newScriptDataSource("OFBiz"); design.getDataSources().add(dataSource); diff --git a/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtEngineServlet.java b/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtEngineServlet.java index 8903e3a..dd979b4 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtEngineServlet.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtEngineServlet.java @@ -36,7 +36,7 @@ import org.apache.ofbiz.birt.BirtWorker; @SuppressWarnings("serial") public class BirtEngineServlet extends org.eclipse.birt.report.servlet.BirtEngineServlet { - public final static String MODULE = BirtEngineServlet.class.getName(); + private static final String MODULE = BirtEngineServlet.class.getName(); @Override protected IContext __getContext(HttpServletRequest request, HttpServletResponse response) throws BirtException { diff --git a/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtViewerServlet.java b/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtViewerServlet.java index d744ea2..a449f39 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtViewerServlet.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/BirtViewerServlet.java @@ -37,7 +37,7 @@ import org.apache.ofbiz.birt.BirtWorker; @SuppressWarnings("serial") public class BirtViewerServlet extends ViewerServlet { - public final static String MODULE = BirtViewerServlet.class.getName(); + private static final String MODULE = BirtViewerServlet.class.getName(); @Override protected IContext __getContext(HttpServletRequest request, HttpServletResponse response) throws BirtException { diff --git a/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/ViewerServletRequest.java b/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/ViewerServletRequest.java index a1c371c..abb00a8 100644 --- a/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/ViewerServletRequest.java +++ b/birt/src/main/java/org/apache/ofbiz/birt/report/servlet/ViewerServletRequest.java @@ -30,7 +30,7 @@ import org.apache.ofbiz.base.location.FlexibleLocation; import org.apache.ofbiz.base.util.Debug; public class ViewerServletRequest extends HttpServletRequestWrapper { - public final static String MODULE = ViewerServletRequest.class.getName(); + private static final String MODULE = ViewerServletRequest.class.getName(); protected String originalReportParam = null; diff --git a/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/MultiSiteRequestWrapper.java b/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/MultiSiteRequestWrapper.java index 65305b3..149ad92 100644 --- a/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/MultiSiteRequestWrapper.java +++ b/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/MultiSiteRequestWrapper.java @@ -54,7 +54,9 @@ public class MultiSiteRequestWrapper implements HttpServletRequest { } @Override - public String changeSessionId() { return request.changeSessionId(); } + public String changeSessionId() { + return request.changeSessionId(); + } @Override public String getAuthType() { @@ -278,134 +280,134 @@ public class MultiSiteRequestWrapper implements HttpServletRequest { public String getProtocol() { return request.getProtocol(); } - + /** get reader */ @Override public BufferedReader getReader() throws IOException { return request.getReader(); } - + /** get real path */ @Override @Deprecated public String getRealPath(String arg0) { return request.getServletContext().getRealPath(arg0); } - + /** get remote addr */ @Override public String getRemoteAddr() { return request.getRemoteAddr(); } - + /** get remote host */ @Override public String getRemoteHost() { return request.getRemoteHost(); } - + /** get remote port */ @Override public int getRemotePort() { return request.getRemotePort(); } - + /** get request dispatcher */ @Override public RequestDispatcher getRequestDispatcher(String arg0) { return request.getRequestDispatcher(arg0); } - + /** get scheme */ @Override public String getScheme() { return request.getScheme(); } - + /** get server name */ @Override public String getServerName() { return request.getServerName(); } - + /** get server port */ @Override public int getServerPort() { return request.getServerPort(); } - + /** is secure */ @Override public boolean isSecure() { return request.isSecure(); } - + /** remove attribute */ @Override public void removeAttribute(String arg0) { request.removeAttribute(arg0); } - + /** set attribute */ @Override public void setAttribute(String arg0, Object arg1) { request.setAttribute(arg0, arg1); } - + /** set character encoding */ @Override public void setCharacterEncoding(String arg0) throws UnsupportedEncodingException { request.setCharacterEncoding(arg0); } - + /** authenticate */ @Override public boolean authenticate(HttpServletResponse arg0) throws IOException, ServletException { return request.authenticate(arg0); } - + /** get part */ @Override public Part getPart(String arg0) throws IOException, IllegalStateException, ServletException { return request.getPart(arg0); } - + /** get parts */ @Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { return request.getParts(); } - + /** login */ @Override public void login(String arg0, String arg1) throws ServletException { request.login(arg0, arg1); } - + /** logout */ @Override public void logout() throws ServletException { request.logout(); } - + /** get async context */ @Override public AsyncContext getAsyncContext() { return request.getAsyncContext(); } - + /** get dispatcher type */ @Override public DispatcherType getDispatcherType() { return request.getDispatcherType(); } - + /** get servlet context */ @Override public ServletContext getServletContext() { return request.getServletContext(); } - + /** is async started */ @Override public boolean isAsyncStarted() { return request.isAsyncStarted(); } - + /** is async supported */ @Override public boolean isAsyncSupported() { return request.isAsyncSupported(); } - + /** start async */ @Override public AsyncContext startAsync() { return request.startAsync(); } - + /** start async */ @Override public AsyncContext startAsync(ServletRequest arg0, ServletResponse arg1) { return request.startAsync(arg0, arg1); } - + /** upgrade */ @Override - public <T extends HttpUpgradeHandler> T upgrade (Class<T> handlerClass) throws IOException, ServletException { + public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException { return request.upgrade(handlerClass); } -} \ No newline at end of file +} diff --git a/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/WebSiteFilter.java b/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/WebSiteFilter.java index 001bdc3..20cc00a 100644 --- a/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/WebSiteFilter.java +++ b/cmssite/src/main/java/org/apache/ofbiz/cmssite/multisite/WebSiteFilter.java @@ -109,7 +109,7 @@ public class WebSiteFilter implements Filter { if (!webSiteId.equals(session.getAttribute("webSiteId"))) { ShoppingCart cart = (ShoppingCart) session.getAttribute("shoppingCart"); if (cart != null && !(webSite.getString("productStoreId").equals(cart.getProductStoreId())) ) { - // clearing cart items from previous store + // clearing cart items from previous store cart.clear(); // Put product Store for this webSite in cart cart.setProductStoreId(webSite.getString("productStoreId")); diff --git a/ebay/src/main/java/org/apache/ofbiz/ebay/EbayHelper.java b/ebay/src/main/java/org/apache/ofbiz/ebay/EbayHelper.java index b914e30..2b1fa1c 100644 --- a/ebay/src/main/java/org/apache/ofbiz/ebay/EbayHelper.java +++ b/ebay/src/main/java/org/apache/ofbiz/ebay/EbayHelper.java @@ -220,7 +220,7 @@ public class EbayHelper { return false; } } - } + } } catch (GenericEntityException gee) { Debug.logError(gee, "Cannot get payment preferences for order #" + orderId, MODULE); return false; diff --git a/ebay/src/main/java/org/apache/ofbiz/ebay/ProductsExportToEbay.java b/ebay/src/main/java/org/apache/ofbiz/ebay/ProductsExportToEbay.java index 324d006..07738dc 100755 --- a/ebay/src/main/java/org/apache/ofbiz/ebay/ProductsExportToEbay.java +++ b/ebay/src/main/java/org/apache/ofbiz/ebay/ProductsExportToEbay.java @@ -57,7 +57,7 @@ import org.w3c.dom.Node; public class ProductsExportToEbay { private static final String RESOURCE = "EbayUiLabels"; - private static final String configFileName = "ebayExport.properties"; + private static final String CONFIG_FILE_NAME = "ebayExport.properties"; private static final String MODULE = ProductsExportToEbay.class.getName(); private static List<String> productExportSuccessMessageList = new LinkedList<>(); private static List<String> productExportFailureMessageList = new LinkedList<>(); @@ -72,12 +72,15 @@ public class ProductsExportToEbay { Map<String, Object> response = null; try { List<String> selectResult = UtilGenerics.checkCollection(context.get("selectResult"), String.class); - List<GenericValue> productsList = EntityQuery.use(delegator).from("Product").where(EntityCondition.makeCondition("productId", EntityOperator.IN, selectResult)).queryList(); + List<GenericValue> productsList = EntityQuery.use(delegator).from("Product").where(EntityCondition.makeCondition("productId", + EntityOperator.IN, selectResult)).queryList(); if (UtilValidate.isNotEmpty(productsList)) { for (GenericValue product : productsList) { - GenericValue startPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(product.getRelated("ProductPrice", UtilMisc.toMap("productPricePurposeId", "EBAY", "productPriceTypeId", "MINIMUM_PRICE"), null, false))); + GenericValue startPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(product.getRelated("ProductPrice", UtilMisc.toMap( + "productPricePurposeId", "EBAY", "productPriceTypeId", "MINIMUM_PRICE"), null, false))); if (UtilValidate.isEmpty(startPriceValue)) { - String startPriceMissingMsg = "Unable to find a starting price for auction of product with id (" + product.getString("productId") + "), So Ignoring the export of this product to eBay."; + String startPriceMissingMsg = "Unable to find a starting price for auction of product with id (" + product.getString( + "productId") + "), So Ignoring the export of this product to eBay."; productExportFailureMessageList.add(startPriceMissingMsg); // Ignore the processing of product having no start price value continue; @@ -86,7 +89,10 @@ public class ProductsExportToEbay { StringBuffer dataItemsXml = new StringBuffer(); Map<String, Object> resultMap = buildDataItemsXml(dctx, context, dataItemsXml, eBayConfigResult.get("token").toString(), product); if (!ServiceUtil.isFailure(resultMap)) { - response = postItem(eBayConfigResult.get("xmlGatewayUri").toString(), dataItemsXml, eBayConfigResult.get("devID").toString(), eBayConfigResult.get("appID").toString(), eBayConfigResult.get("certID").toString(), "AddItem", eBayConfigResult.get("compatibilityLevel").toString(), eBayConfigResult.get("siteID").toString()); + response = postItem(eBayConfigResult.get("xmlGatewayUri").toString(), dataItemsXml, + eBayConfigResult.get("devID").toString(), eBayConfigResult.get("appID").toString(), + eBayConfigResult.get("certID").toString(), "AddItem", eBayConfigResult.get("compatibilityLevel").toString(), + eBayConfigResult.get("siteID").toString()); if (ServiceUtil.isFailure(response)) { return ServiceUtil.returnFailure(ServiceUtil.getErrorMessage(response)); } @@ -131,7 +137,7 @@ public class ProductsExportToEbay { } private static Map<String, Object> postItem(String postItemsUrl, StringBuffer dataItems, String devID, String appID, String certID, - String callName, String compatibilityLevel, String siteID) throws IOException { + String callName, String compatibilityLevel, String siteID) throws IOException { if (Debug.verboseOn()) { Debug.logVerbose("Request of " + callName + " To eBay:\n" + dataItems.toString(), MODULE); } @@ -172,7 +178,8 @@ public class ProductsExportToEbay { return result; } - public static Map<String, Object> buildDataItemsXml(DispatchContext dctx, Map<String, Object> context, StringBuffer dataItemsXml, String token, GenericValue prod) { + public static Map<String, Object> buildDataItemsXml(DispatchContext dctx, Map<String, Object> context, StringBuffer dataItemsXml, String token, + GenericValue prod) { Locale locale = (Locale) context.get("locale"); try { Delegator delegator = dctx.getDelegator(); @@ -206,24 +213,27 @@ public class ProductsExportToEbay { String startPrice = (String) context.get("startPrice"); String startPriceCurrencyUomId = null; if (UtilValidate.isEmpty(startPrice)) { - GenericValue startPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(prod.getRelated("ProductPrice", UtilMisc.toMap("productPricePurposeId", "EBAY", "productPriceTypeId", "MINIMUM_PRICE"), null, false))); + GenericValue startPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(prod.getRelated("ProductPrice", UtilMisc.toMap( + "productPricePurposeId", "EBAY", "productPriceTypeId", "MINIMUM_PRICE"), null, false))); if (UtilValidate.isNotEmpty(startPriceValue)) { startPrice = startPriceValue.getString("price"); startPriceCurrencyUomId = startPriceValue.getString("currencyUomId"); } } - // Buy it now is the optional value for a product that you send to eBay. Once this value is entered by user - this option allow user to win auction immediately. + // Buy it now is the optional value for a product that you send to eBay. Once this value is entered by user - this option allow + // user to win auction immediately. String buyItNowPrice = (String) context.get("buyItNowPrice"); String buyItNowCurrencyUomId = null; if (UtilValidate.isEmpty(buyItNowPrice)) { - GenericValue buyItNowPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(prod.getRelated("ProductPrice", UtilMisc.toMap("productPricePurposeId", "EBAY", "productPriceTypeId", "MAXIMUM_PRICE"), null, false))); + GenericValue buyItNowPriceValue = EntityUtil.getFirst(EntityUtil.filterByDate(prod.getRelated("ProductPrice", UtilMisc.toMap( + "productPricePurposeId", "EBAY", "productPriceTypeId", "MAXIMUM_PRICE"), null, false))); if (UtilValidate.isNotEmpty(buyItNowPriceValue)) { buyItNowPrice = buyItNowPriceValue.getString("price"); buyItNowCurrencyUomId = buyItNowPriceValue.getString("currencyUomId"); } } - + Element itemElem = UtilXml.addChildElement(itemRequestElem, "Item", itemDocument); UtilXml.addChildElementValue(itemElem, "Country", (String) context.get("country"), itemDocument); @@ -256,14 +266,15 @@ public class ProductsExportToEbay { startPriceElem.setAttribute("currencyID", startPriceCurrencyUomId); if (UtilValidate.isNotEmpty(buyItNowPrice)) { Element buyNowPriceElem = UtilXml.addChildElementValue(itemElem, "BuyItNowPrice", buyItNowPrice, itemDocument); - if (UtilValidate.isEmpty(buyItNowCurrencyUomId)) { - buyItNowCurrencyUomId = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator); - } - buyNowPriceElem.setAttribute("currencyID", buyItNowCurrencyUomId); + if (UtilValidate.isEmpty(buyItNowCurrencyUomId)) { + buyItNowCurrencyUomId = EntityUtilProperties.getPropertyValue("general", "currency.uom.id.default", "USD", delegator); + } + buyNowPriceElem.setAttribute("currencyID", buyItNowCurrencyUomId); } } - ProductContentWrapper pcw = new ProductContentWrapper(dctx.getDispatcher(), prod, locale, EntityUtilProperties.getPropertyValue("content", "defaultMimeType", "text/html; charset=utf-8", delegator)); + ProductContentWrapper pcw = new ProductContentWrapper(dctx.getDispatcher(), prod, locale, EntityUtilProperties.getPropertyValue( + "content", "defaultMimeType", "text/html; charset=utf-8", delegator)); StringUtil.StringWrapper ebayDescription = pcw.get("EBAY_DESCRIPTION", "html"); if (UtilValidate.isNotEmpty(ebayDescription.toString())) { UtilXml.addChildElementCDATAValue(itemElem, "Description", ebayDescription.toString(), itemDocument); @@ -294,7 +305,8 @@ public class ProductsExportToEbay { if (categoryCode.indexOf("_") != -1) { String[] params = categoryCode.split("_"); if (UtilValidate.isEmpty(params) || params[1].length() == 0) { - ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.parametersNotCorrectInGetEbayCategories", locale)); + ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay" + + ".parametersNotCorrectInGetEbayCategories", locale)); } else { primaryCategoryId = params[1]; } @@ -323,16 +335,19 @@ public class ProductsExportToEbay { dataItemsXml.append(UtilXml.writeXmlDocument(itemDocument)); } catch (Exception e) { Debug.logError("Exception during building data items to eBay: " + e.getMessage(), MODULE); - return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay", + locale)); } } catch (Exception e) { Debug.logError("Exception during building data items to eBay: " + e.getMessage(), MODULE); - return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingDataItemsToEbay", + locale)); } return ServiceUtil.returnSuccess(); } - private static Map<String, Object> buildCategoriesXml(Map<String, Object> context, StringBuffer dataItemsXml, String token, String siteID, String categoryParent, String levelLimit) { + private static Map<String, Object> buildCategoriesXml(Map<String, Object> context, StringBuffer dataItemsXml, String token, String siteID, + String categoryParent, String levelLimit) { Locale locale = (Locale) context.get("locale"); try { Document itemRequest = UtilXml.makeEmptyXmlDocument("GetCategoriesRequest"); @@ -358,13 +373,15 @@ public class ProductsExportToEbay { dataItemsXml.append(UtilXml.writeXmlDocument(itemRequest)); } catch (Exception e) { Debug.logError("Exception during building data items to eBay", MODULE); - return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingGetCategoriesRequest", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingGetCategoriesRequest", + locale)); } return ServiceUtil.returnSuccess(); } /* - private static Map<String, Object> buildSetTaxTableRequestXml(DispatchContext dctx, Map<String, Object> context, StringBuffer setTaxTableRequestXml, String token) { + private static Map<String, Object> buildSetTaxTableRequestXml(DispatchContext dctx, Map<String, Object> context, StringBuffer + setTaxTableRequestXml, String token) { Locale locale = (Locale) context.get("locale"); try { Document taxRequestDocument = UtilXml.makeEmptyXmlDocument("SetTaxTableRequest"); @@ -383,14 +400,13 @@ public class ProductsExportToEbay { setTaxTableRequestXml.append(UtilXml.writeXmlDocument(taxRequestDocument)); } catch (Exception e) { Debug.logError("Exception during building request set tax table to eBay", MODULE); - return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingRequestSetTaxTableToEbay", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay + .exceptionDuringBuildingRequestSetTaxTableToEbay", locale)); } return ServiceUtil.returnSuccess(); } - */ - - /* - private static Map<String, Object> buildAddTransactionConfirmationItemRequest(Map<String, Object> context, StringBuffer dataItemsXml, String token, String itemId) { + private static Map<String, Object> buildAddTransactionConfirmationItemRequest(Map<String, Object> context, StringBuffer dataItemsXml, String + token, String itemId) { Locale locale = (Locale) context.get("locale"); try { Document transDoc = UtilXml.makeEmptyXmlDocument("AddTransactionConfirmationItemRequest"); @@ -410,11 +426,11 @@ public class ProductsExportToEbay { Debug.logInfo(dataItemsXml.toString(), MODULE); } catch (Exception e) { Debug.logError("Exception during building AddTransactionConfirmationItemRequest eBay", MODULE); - return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.exceptionDuringBuildingAddTransactionConfirmationItemRequestToEbay", locale)); + return ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay + .exceptionDuringBuildingAddTransactionConfirmationItemRequestToEbay", locale)); } return ServiceUtil.returnSuccess(); - } - */ + }*/ private static void setPaymentMethodAccepted(Document itemDocument, Element itemElem, Map<String, Object> context) { String payPal = (String) context.get("paymentPayPal"); @@ -491,13 +507,13 @@ public class ProductsExportToEbay { if (UtilValidate.isNotEmpty(customXmlFromUI)) { customXml = customXmlFromUI; } else { - customXml = EntityUtilProperties.getPropertyValue(configFileName, "eBayExport.customXml", delegator); + customXml = EntityUtilProperties.getPropertyValue(CONFIG_FILE_NAME, "eBayExport.customXml", delegator); } if (UtilValidate.isNotEmpty(customXml)) { Document customXmlDoc = UtilXml.readXmlDocument(customXml); if (UtilValidate.isNotEmpty(customXmlDoc)) { Element customXmlElement = customXmlDoc.getDocumentElement(); - for (Element eBayElement: UtilXml.childElementList(customXmlElement)) { + for (Element eBayElement : UtilXml.childElementList(customXmlElement)) { Node importedElement = itemElem.getOwnerDocument().importNode(eBayElement, true); itemElem.appendChild(importedElement); } @@ -519,7 +535,8 @@ public class ProductsExportToEbay { String[] params = categoryCode.split("_"); if (params == null || params.length != 3) { - ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.parametersNotCorrectInGetEbayCategories", locale)); + ServiceUtil.returnFailure(UtilProperties.getMessage(RESOURCE, "productsExportToEbay.parametersNotCorrectInGetEbayCategories", + locale)); } else { categoryParent = params[1]; levelLimit = params[2]; @@ -529,8 +546,11 @@ public class ProductsExportToEbay { } StringBuffer dataItemsXml = new StringBuffer(); - if (!ServiceUtil.isFailure(buildCategoriesXml(context, dataItemsXml, eBayConfigResult.get("token").toString(), eBayConfigResult.get("siteID").toString(), categoryParent, levelLimit))) { - Map<String, Object> resultCat = postItem(eBayConfigResult.get("xmlGatewayUri").toString(), dataItemsXml, eBayConfigResult.get("devID").toString(), eBayConfigResult.get("appID").toString(), eBayConfigResult.get("certID").toString(), "GetCategories", eBayConfigResult.get("compatibilityLevel").toString(), eBayConfigResult.get("siteID").toString()); + if (!ServiceUtil.isFailure(buildCategoriesXml(context, dataItemsXml, eBayConfigResult.get("token").toString(), eBayConfigResult.get( + "siteID").toString(), categoryParent, levelLimit))) { + Map<String, Object> resultCat = postItem(eBayConfigResult.get("xmlGatewayUri").toString(), dataItemsXml, eBayConfigResult.get( + "devID").toString(), eBayConfigResult.get("appID").toString(), eBayConfigResult.get("certID").toString(), "GetCategories", + eBayConfigResult.get("compatibilityLevel").toString(), eBayConfigResult.get("siteID").toString()); String successMessage = (String) resultCat.get("successMessage"); if (successMessage != null) { result = readEbayCategoriesResponse(successMessage, locale); @@ -565,15 +585,17 @@ public class ProductsExportToEbay { for (Element categoryElement : UtilXml.childElementList(categoryArrayElement, "Category")) { Map<String, Object> categ = new HashMap<>(); - String categoryCode = ("true".equalsIgnoreCase((UtilXml.childElementValue(categoryElement, "LeafCategory", "").trim())) ? "Y" : "N") + "_" + - UtilXml.childElementValue(categoryElement, "CategoryID", "").trim() + "_" + - UtilXml.childElementValue(categoryElement, "CategoryLevel", "").trim(); + String categoryCode = ("true".equalsIgnoreCase((UtilXml.childElementValue(categoryElement, "LeafCategory", "").trim())) + ? "Y" : "N") + "_" + + UtilXml.childElementValue(categoryElement, "CategoryID", "").trim() + "_" + + UtilXml.childElementValue(categoryElement, "CategoryLevel", "").trim(); categ.put("CategoryCode", categoryCode); categ.put("CategoryName", UtilXml.childElementValue(categoryElement, "CategoryName")); categories.add(categ); } } - categories = UtilGenerics.cast(UtilMisc.sortMaps(UtilGenerics.<List<Map<Object, Object>>>cast(categories), UtilMisc.toList("CategoryName"))); + categories = UtilGenerics.cast(UtilMisc.sortMaps(UtilGenerics.<List<Map<Object, Object>>>cast(categories), UtilMisc.toList( + "CategoryName"))); results = UtilMisc.toMap("categories", (Object) categories); } } catch (Exception e) { @@ -604,6 +626,7 @@ public class ProductsExportToEbay { } return result; } + public static List<String> getProductExportSuccessMessageList() { return productExportSuccessMessageList; } diff --git a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayEvents.java b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayEvents.java index 29133d4..32d8ab7 100644 --- a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayEvents.java +++ b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayEvents.java @@ -188,7 +188,7 @@ public class EbayEvents { if (UtilValidate.isNotEmpty(productIds)) { try { - // check add new product obj ? to export + // check add new product obj ? to export for (String productId : productIds) { for (Map<String, Object> itObj : itemObjs) { if (UtilValidate.isNotEmpty(itObj.get(productId.concat("_Obj")))) { @@ -394,7 +394,7 @@ public class EbayEvents { List<CategoryType> csCateList = csCateMaps.get(apiContext.getSite()); if (UtilValidate.isNotEmpty(csCateList)) { if (UtilValidate.isNotEmpty(categoryId)) { - // find child of selected ebay categories + // find child of selected ebay categories for (CategoryType csCate : csCateList) { String[] categoryParentIds = csCate.getCategoryParentID(); for (String categoryParentId : categoryParentIds) { @@ -451,7 +451,7 @@ public class EbayEvents { csCateList = csCateMaps.get(apiContext.getSite()); if (UtilValidate.isNotEmpty(csCateList)) { if (UtilValidate.isNotEmpty(categoryId)) { - // find child of selected ebay categories + // find child of selected ebay categories for (StoreCustomCategoryType csCate : csCateList) { if (categoryId.equals(String.valueOf(csCate.getCategoryID()))) { StoreCustomCategoryType[] childCategories = csCate.getChildCategory(); @@ -503,7 +503,7 @@ public class EbayEvents { List<CategoryType> csCateList = csCateMaps.get(apiContext.getSite()); if (UtilValidate.isNotEmpty(csCateList)) { if (UtilValidate.isNotEmpty(categoryId)) { - // find child of selected ebay categories + // find child of selected ebay categories for (CategoryType csCate : csCateList) { if (csCate.getCategoryID().equals(categoryId)) { cate = csCate; diff --git a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStore.java b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStore.java index 4449587..7527477 100644 --- a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStore.java +++ b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStore.java @@ -379,7 +379,7 @@ public class EbayStore { } } catch (Exception e) { Debug.logError(e.getMessage(), MODULE); - // TODO why is there an Exception catching here? + // TODO why is there an Exception catching here? } return storeCustomCategoryTypeArry; } diff --git a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreAutoPreferences.java b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreAutoPreferences.java index 64ed121..f4aec7f 100644 --- a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreAutoPreferences.java +++ b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreAutoPreferences.java @@ -350,8 +350,8 @@ public class EbayStoreAutoPreferences { Calendar shippedTime = orderStatus.getShippedTime(); Calendar afterShippedTime = orderStatus.getShippedTime(); afterShippedTime.add(Calendar.DAY_OF_MONTH, afterDays); - Debug.logInfo("Verify date for send reminder feedback eamil by auto service: buyer " + solditem.getBuyerID() + " seller shippedTime " + - "" + formatter.format(shippedTime) + " codition days " + afterDays + " after shippedTime :" + formatter.format(afterShippedTime) + " now date" + formatter.format(right_now), MODULE); + Debug.logInfo("Verify date for send reminder feedback eamil by auto service: buyer " + solditem.getBuyerID() + " seller shippedTime " + + "" + formatter.format(shippedTime) + " codition days " + afterDays + " after shippedTime :" + formatter.format(afterShippedTime) + " now date" + formatter.format(right_now), MODULE); // if now date is after shipped time follow after days condition would be send reminder email to buyer if (right_now.after(afterShippedTime)) { items.add(solditem); diff --git a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreCategoryFacade.java b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreCategoryFacade.java index ea1054f..634a22c 100644 --- a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreCategoryFacade.java +++ b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreCategoryFacade.java @@ -170,7 +170,7 @@ public class EbayStoreCategoryFacade { } /** - * recursively check the parent category to find out category feature + * recursively check the parent category to find out category feature * @param catId categoryID to be retrieved * @param methodName method name to be invoked * @param categoriesCacheMap cache of all the categories diff --git a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreSiteFacade.java b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreSiteFacade.java index 09cc99e..c8f2bb0 100644 --- a/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreSiteFacade.java +++ b/ebaystore/src/main/java/org/apache/ofbiz/ebaystore/EbayStoreSiteFacade.java @@ -140,7 +140,7 @@ public class EbayStoreSiteFacade { csCat.setCategoryName(cat.getCategoryName()); csCat.setLeafCategory(cat.isLeafCategory()); } else { - //some category has no characteristic sets, + //some category has no characteristic sets, //but it may has custom item specifics csCatsMap.put(cat.getCategoryID(), cat); } diff --git a/ecommerce/src/main/java/org/apache/ofbiz/ecommerce/misc/ThirdPartyEvents.java b/ecommerce/src/main/java/org/apache/ofbiz/ecommerce/misc/ThirdPartyEvents.java index c7e1f03..9d485ab 100644 --- a/ecommerce/src/main/java/org/apache/ofbiz/ecommerce/misc/ThirdPartyEvents.java +++ b/ecommerce/src/main/java/org/apache/ofbiz/ecommerce/misc/ThirdPartyEvents.java @@ -41,8 +41,8 @@ public class ThirdPartyEvents { private static final String MODULE = ThirdPartyEvents.class.getName(); - public final static String DISTRIBUTOR_ID = "_DISTRIBUTOR_ID_"; - public final static String AFFILIATE_ID = "_AFFILIATE_ID_"; + public static final String DISTRIBUTOR_ID = "_DISTRIBUTOR_ID_"; + public static final String AFFILIATE_ID = "_AFFILIATE_ID_"; /** Save the association id(s) specified in the request object into the session. *@param request The HTTPRequest object for the current request diff --git a/example/src/main/java/org/apache/ofbiz/example/ExamplePrintServices.java b/example/src/main/java/org/apache/ofbiz/example/ExamplePrintServices.java index bcf7540..a29db19 100644 --- a/example/src/main/java/org/apache/ofbiz/example/ExamplePrintServices.java +++ b/example/src/main/java/org/apache/ofbiz/example/ExamplePrintServices.java @@ -82,7 +82,8 @@ public class ExamplePrintServices { try { screenStringRenderer = new MacroScreenRenderer("screen", visualTheme.getModelTheme().getScreenRendererLocation("screen")); } catch (TemplateException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleGeneralErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleGeneralErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), + locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (IOException e) { @@ -100,7 +101,8 @@ public class ExamplePrintServices { try { reportScreenRenderer.render(screenLocation, reportScreenName); } catch (GeneralException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleGeneralErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleGeneralErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), + locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (IOException e) { @@ -108,11 +110,13 @@ public class ExamplePrintServices { Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (SAXException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleSAXErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleSAXErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), + locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } catch (ParserConfigurationException e) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleParserConfigurationErrorRenderingScreen", UtilMisc.toMap("errorString", e.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleParserConfigurationErrorRenderingScreen", UtilMisc.toMap("errorString", + e.toString()), locale); Debug.logError(e, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } @@ -159,7 +163,8 @@ public class ExamplePrintServices { try { job.print(myDoc, aset); } catch (PrintException pe) { - String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleUnableToPrintPDFFromXSL-FO", UtilMisc.toMap("errorString", pe.toString()), locale); + String errMsg = UtilProperties.getMessage(RESOURCE, "ExampleUnableToPrintPDFFromXSL-FO", UtilMisc.toMap("errorString", + pe.toString()), locale); Debug.logError(pe, errMsg, MODULE); return ServiceUtil.returnError(errMsg); } diff --git a/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java b/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java index 96ce016..8325e26 100644 --- a/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java +++ b/firstdatapaymentgateway/src/main/java/org/apache/ofbiz/firstdatapaymentgateway/FirstDataPaymentServices.java @@ -66,7 +66,7 @@ public class FirstDataPaymentServices { Delegator delegator = ctx.getDelegator(); BigDecimal processAmount = (BigDecimal) context.get("processAmount"); String orderId = (String) context.get("orderId"); - String currency = (String) context.get("currency"); + String currency = (String) context.get("currency"); String cardSecurityCode = (String) context.get("cardSecurityCode"); GenericValue creditCard = (GenericValue) context.get("creditCard"); String paymentGatewayConfigId = (String) context.get("paymentGatewayConfigId"); @@ -93,7 +93,8 @@ public class FirstDataPaymentServices { ccAuthReqContext.put("expireYear", strYear); StringWriter outWriter = new StringWriter(); - String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.preauth.location", delegator); + String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.preauth" + + ".location", delegator); FreeMarkerWorker.renderTemplate(firstDataPreAuthTemplate, ccAuthReqContext, outWriter); String requestBody = outWriter.toString(); @@ -115,12 +116,14 @@ public class FirstDataPaymentServices { String responseString = EntityUtils.toString(entity); ObjectMapper objectMapper = new ObjectMapper(); - Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() {}); + Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() { + }); String transactionStatus = (String) convertedMap.get("transactionStatus"); String transactionId = (String) convertedMap.get("ipgTransactionId"); String fdOrderId = (String) convertedMap.get("orderId"); - Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() {}); + Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() { + }); String gatewayMessage = (String) processor.get("responseMessage"); int statusCode = response.getStatusLine().getStatusCode(); result.put("authCode", String.valueOf(statusCode)); @@ -133,7 +136,8 @@ public class FirstDataPaymentServices { } } if (!isSuccess) { - String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " Transaction Status: " + transactionStatus; + String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " " + + "Transaction Status: " + transactionStatus; errorMessage = errorMessage + " Message: " + statusCode + "-" + gatewayMessage; result.put(ModelService.ERROR_MESSAGE, errorMessage); } @@ -164,14 +168,17 @@ public class FirstDataPaymentServices { ccPostAuthReqContext.put("currency", currency); StringWriter outWriter = new StringWriter(); - String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.postauth.location", delegator); + String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.postauth" + + ".location", delegator); FreeMarkerWorker.renderTemplate(firstDataPreAuthTemplate, ccPostAuthReqContext, outWriter); String requestBody = outWriter.toString(); String messageSignature = buildMessageSignature(paymentGatewayConfigId, requestBody, clientRequestId, epochTime, delegator); GenericValue paymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse") - .where("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), "paymentMethodId", orderPaymentPreference.getString("paymentMethodId"), "transCodeEnumId", "PGT_AUTHORIZE", "paymentServiceTypeEnumId", "PRDS_PAY_AUTH") + .where("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), "paymentMethodId", + orderPaymentPreference.getString("paymentMethodId"), "transCodeEnumId", "PGT_AUTHORIZE", "paymentServiceTypeEnumId", + "PRDS_PAY_AUTH") .queryFirst(); String authTransactionId = null; if (UtilValidate.isNotEmpty(paymentGatewayResponse.getString("referenceNum"))) { @@ -196,12 +203,14 @@ public class FirstDataPaymentServices { String responseString = EntityUtils.toString(entity); ObjectMapper objectMapper = new ObjectMapper(); - Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() {}); + Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() { + }); String transactionStatus = (String) convertedMap.get("transactionStatus"); String transactionId = (String) convertedMap.get("ipgTransactionId"); String fdOrderId = (String) convertedMap.get("orderId"); - Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() {}); + Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() { + }); String gatewayMessage = (String) processor.get("responseMessage"); int statusCode = response.getStatusLine().getStatusCode(); result.put("captureCode", String.valueOf(statusCode)); @@ -214,7 +223,8 @@ public class FirstDataPaymentServices { } } if (!isSuccess) { - String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " Transaction Status: " + transactionStatus; + String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " " + + "Transaction Status: " + transactionStatus; errorMessage = errorMessage + " Message: " + statusCode + "-" + gatewayMessage; result.put(ModelService.ERROR_MESSAGE, errorMessage); } @@ -245,7 +255,8 @@ public class FirstDataPaymentServices { ccRefundReqContext.put("currency", currency); StringWriter outWriter = new StringWriter(); - String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.refund.location", delegator); + String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.refund" + + ".location", delegator); FreeMarkerWorker.renderTemplate(firstDataPreAuthTemplate, ccRefundReqContext, outWriter); String requestBody = outWriter.toString(); @@ -280,12 +291,14 @@ public class FirstDataPaymentServices { String responseString = EntityUtils.toString(entity); ObjectMapper objectMapper = new ObjectMapper(); - Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() {}); + Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() { + }); String transactionStatus = (String) convertedMap.get("transactionStatus"); String transactionId = (String) convertedMap.get("ipgTransactionId"); String fdOrderId = (String) convertedMap.get("orderId"); - Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() {}); + Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() { + }); String gatewayMessage = (String) processor.get("responseMessage"); int statusCode = response.getStatusLine().getStatusCode(); result.put("refundCode", String.valueOf(statusCode)); @@ -298,7 +311,8 @@ public class FirstDataPaymentServices { } } if (!isSuccess) { - String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " Transaction Status: " + transactionStatus; + String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " " + + "Transaction Status: " + transactionStatus; errorMessage = errorMessage + " Message: " + statusCode + "-" + gatewayMessage; result.put(ModelService.ERROR_MESSAGE, errorMessage); } @@ -325,17 +339,22 @@ public class FirstDataPaymentServices { String epochTime = String.valueOf(System.currentTimeMillis()); Map<String, Object> ccReleaseReqContext = new HashMap<String, Object>(); - ccReleaseReqContext.put("comments", "The amount " + currency + " " + releaseAmount + " against OrderPaymentPreferenceId " + orderPaymentPreference.getString("orderPaymentPreferenceId") + " is released."); + ccReleaseReqContext.put("comments", + "The amount " + currency + " " + releaseAmount + " against OrderPaymentPreferenceId " + orderPaymentPreference.getString( + "orderPaymentPreferenceId") + " is released."); StringWriter outWriter = new StringWriter(); - String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.release.location", delegator); + String firstDataPreAuthTemplate = EntityUtilProperties.getPropertyValue("firstdata", "paymentgateway.firstdata.template.release" + + ".location", delegator); FreeMarkerWorker.renderTemplate(firstDataPreAuthTemplate, ccReleaseReqContext, outWriter); String requestBody = outWriter.toString(); String messageSignature = buildMessageSignature(paymentGatewayConfigId, requestBody, clientRequestId, epochTime, delegator); GenericValue paymentGatewayResponse = EntityQuery.use(delegator).from("PaymentGatewayResponse") - .where("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), "paymentMethodId", orderPaymentPreference.getString("paymentMethodId"), "transCodeEnumId", "PGT_AUTHORIZE", "paymentServiceTypeEnumId", "PRDS_PAY_AUTH") + .where("orderPaymentPreferenceId", orderPaymentPreference.getString("orderPaymentPreferenceId"), "paymentMethodId", + orderPaymentPreference.getString("paymentMethodId"), "transCodeEnumId", "PGT_AUTHORIZE", "paymentServiceTypeEnumId", + "PRDS_PAY_AUTH") .queryFirst(); String releaseTransactionId = null; if (UtilValidate.isNotEmpty(paymentGatewayResponse.getString("referenceNum"))) { @@ -360,12 +379,14 @@ public class FirstDataPaymentServices { String responseString = EntityUtils.toString(entity); ObjectMapper objectMapper = new ObjectMapper(); - Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() {}); + Map<String, Object> convertedMap = objectMapper.readValue(responseString, new TypeReference<Map<String, Object>>() { + }); String transactionStatus = (String) convertedMap.get("transactionStatus"); String transactionId = (String) convertedMap.get("ipgTransactionId"); String fdOrderId = (String) convertedMap.get("orderId"); - Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() {}); + Map<String, Object> processor = objectMapper.convertValue(convertedMap.get("processor"), new TypeReference<Map<String, Object>>() { + }); String gatewayMessage = (String) processor.get("responseMessage"); int statusCode = response.getStatusLine().getStatusCode(); result.put("releaseCode", String.valueOf(statusCode)); @@ -378,7 +399,8 @@ public class FirstDataPaymentServices { } } if (!isSuccess) { - String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " Transaction Status: " + transactionStatus; + String errorMessage = "Transaction Type:" + (String) convertedMap.get("transactionType") + " Transaction Id: " + transactionId + " " + + "Transaction Status: " + transactionStatus; errorMessage = errorMessage + " Message: " + statusCode + "-" + gatewayMessage; result.put(ModelService.ERROR_MESSAGE, errorMessage); } @@ -414,7 +436,8 @@ public class FirstDataPaymentServices { String returnValue = null; if (UtilValidate.isNotEmpty(paymentGatewayConfigId)) { try { - GenericValue paymentGatewayFirstData = EntityQuery.use(delegator).from("PaymentGatewayFirstData").where("paymentGatewayConfigId", paymentGatewayConfigId).queryOne(); + GenericValue paymentGatewayFirstData = EntityQuery.use(delegator).from("PaymentGatewayFirstData").where("paymentGatewayConfigId", + paymentGatewayConfigId).queryOne(); if (paymentGatewayFirstData != null) { Object payflowProField = paymentGatewayFirstData.get(paymentGatewayConfigParameterName); if (payflowProField != null) { @@ -428,7 +451,8 @@ public class FirstDataPaymentServices { return returnValue; } - private static String buildMessageSignature(String paymentGatewayConfigId, String requestBody, String clientRequestId, String epochTime, Delegator delegator) { + private static String buildMessageSignature(String paymentGatewayConfigId, String requestBody, String clientRequestId, String epochTime, + Delegator delegator) { String messageSignature = null; if (FDProperties == null) { buildFDProperties(paymentGatewayConfigId, delegator); diff --git a/ldap/src/main/java/org/apache/ofbiz/ldap/LdapLoginWorker.java b/ldap/src/main/java/org/apache/ofbiz/ldap/LdapLoginWorker.java index 89b28b2..f8f8c26 100644 --- a/ldap/src/main/java/org/apache/ofbiz/ldap/LdapLoginWorker.java +++ b/ldap/src/main/java/org/apache/ofbiz/ldap/LdapLoginWorker.java @@ -46,7 +46,7 @@ import org.xml.sax.SAXException; */ public final class LdapLoginWorker { - private final static String MODULE = LdapLoginWorker.class.getName(); + private static final String MODULE = LdapLoginWorker.class.getName(); private static final String RESOURCE = "SecurityextUiLabels"; private static final String LDAP_CONFIG = "plugins/ldap/config/ldap.xml"; @@ -56,7 +56,7 @@ public final class LdapLoginWorker { * An HTTP WebEvent handler that checks to see is a userLogin is logged in. * If not, the user is forwarded to the login page. * - * @param request The HTTP request object for the current JSP or Servlet request. + * @param request The HTTP request object for the current JSP or Servlet request. * @param response The HTTP response object for the current JSP or Servlet request. * @return String */ @@ -73,15 +73,18 @@ public final class LdapLoginWorker { Element rootElement = getRootElement(request); boolean hasLdapLoggedOut = false; if (rootElement != null) { - String className = UtilXml.childElementValue(rootElement, "AuthenticationHandler", "org.apache.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler"); + String className = UtilXml.childElementValue(rootElement, "AuthenticationHandler", "org.apache.ofbiz.ldap.openldap" + + ".OFBizLdapAuthenticationHandler"); try { Class<?> handlerClass = Class.forName(className); - InterfaceOFBizAuthenticationHandler authenticationHandler = (InterfaceOFBizAuthenticationHandler) handlerClass.getDeclaredConstructor().newInstance(); + InterfaceOFBizAuthenticationHandler authenticationHandler = + (InterfaceOFBizAuthenticationHandler) handlerClass.getDeclaredConstructor().newInstance(); hasLdapLoggedOut = authenticationHandler.hasLdapLoggedOut(request, response, rootElement); } catch (Exception e) { Debug.logError(e, "Error calling checkLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } } @@ -103,25 +106,28 @@ public final class LdapLoginWorker { /** * An HTTP WebEvent handler that logs in a userLogin. This should run before the security check. * - * @param request The HTTP request object for the current JSP or Servlet request. + * @param request The HTTP request object for the current JSP or Servlet request. * @param response The HTTP response object for the current JSP or Servlet request. * @return Return a boolean which specifies whether or not the calling Servlet or - * JSP should generate its own content. This allows an event to override the default content. + * JSP should generate its own content. This allows an event to override the default content. */ public static String login(HttpServletRequest request, HttpServletResponse response) { Element rootElement = getRootElement(request); String result = "error"; if (rootElement != null) { - String className = UtilXml.childElementValue(rootElement, "AuthenticationHandler", "org.apache.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler"); + String className = UtilXml.childElementValue(rootElement, "AuthenticationHandler", "org.apache.ofbiz.ldap.openldap" + + ".OFBizLdapAuthenticationHandler"); try { Class<?> handlerClass = Class.forName(className); - InterfaceOFBizAuthenticationHandler authenticationHandler = (InterfaceOFBizAuthenticationHandler) handlerClass.getDeclaredConstructor().newInstance(); + InterfaceOFBizAuthenticationHandler authenticationHandler = + (InterfaceOFBizAuthenticationHandler) handlerClass.getDeclaredConstructor().newInstance(); result = authenticationHandler.login(request, response, rootElement); } catch (Exception e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } } @@ -138,10 +144,10 @@ public final class LdapLoginWorker { /** * An HTTP WebEvent handler that logs out a userLogin by clearing the session. * - * @param request The HTTP request object for the current request. + * @param request The HTTP request object for the current request. * @param response The HTTP response object for the current request. * @return Return a boolean which specifies whether or not the calling request - * should generate its own content. This allows an event to override the default content. + * should generate its own content. This allows an event to override the default content. */ public static String logout(HttpServletRequest request, HttpServletResponse response) { // run the before-logout events @@ -157,15 +163,18 @@ public final class LdapLoginWorker { String result = "error"; if (rootElement != null) { - String className = UtilXml.childElementValue(rootElement, "AuthenticationHandler", "org.apache.ofbiz.ldap.openldap.OFBizLdapAuthenticationHandler"); + String className = UtilXml.childElementValue(rootElement, "AuthenticationHandler", "org.apache.ofbiz.ldap.openldap" + + ".OFBizLdapAuthenticationHandler"); try { Class<?> handlerClass = Class.forName(className); - InterfaceOFBizAuthenticationHandler authenticationHandler = (InterfaceOFBizAuthenticationHandler) handlerClass.getDeclaredConstructor().newInstance(); + InterfaceOFBizAuthenticationHandler authenticationHandler = + (InterfaceOFBizAuthenticationHandler) handlerClass.getDeclaredConstructor().newInstance(); result = authenticationHandler.logout(request, response, rootElement); } catch (Exception e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } } @@ -188,22 +197,26 @@ public final class LdapLoginWorker { } catch (FileNotFoundException e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } catch (SAXException e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } catch (ParserConfigurationException e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } catch (IOException e) { Debug.logError(e, "Error calling userLogin service", MODULE); Map<String, String> messageMap = UtilMisc.toMap("errorMessage", e.getMessage()); - String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, UtilHttp.getLocale(request)); + String errMsg = UtilProperties.getMessage(RESOURCE, "loginevents.following_error_occurred_during_login", messageMap, + UtilHttp.getLocale(request)); request.setAttribute("_ERROR_MESSAGE_", errMsg); } diff --git a/lucene/src/main/java/org/apache/ofbiz/content/search/ProductDocument.java b/lucene/src/main/java/org/apache/ofbiz/content/search/ProductDocument.java index 5662b86..7ae034a 100644 --- a/lucene/src/main/java/org/apache/ofbiz/content/search/ProductDocument.java +++ b/lucene/src/main/java/org/apache/ofbiz/content/search/ProductDocument.java @@ -50,12 +50,87 @@ import org.apache.ofbiz.entity.util.EntityUtilProperties; public class ProductDocument implements LuceneDocument { private static final String MODULE = ProductDocument.class.getName(); private static final String NULL_STRING = "NULL"; + private static final EntityCondition THRU_DATE_ONLY_CONDITION = EntityCondition.makeCondition( + EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), + EntityOperator.OR, + EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp())); private final Term documentIdentifier; public ProductDocument(String productId) { this.documentIdentifier = new Term("productId", productId); } + // An attempt to boost/weight values in a similar manner to what OFBiz product search does. + private static void addTextField(Document doc, String fieldName, String value, boolean store, String fullTextFieldName, Delegator delegator) { + if (fieldName == null) return; + + Field field = new TextField(fieldName, checkValue(value), (store ? Field.Store.YES : Field.Store.NO)); + doc.add(field); + if (fullTextFieldName != null) { + doc.add(new TextField(fullTextFieldName, checkValue(value), Field.Store.NO)); + } + } + + private static String checkValue(String value) { + if (UtilValidate.isEmpty(value)) { + return NULL_STRING; + } + return value; + } + + private static Timestamp checkSetNextReIndex(Timestamp nextValue, Timestamp currentValue) { + // nextValue is null, stick with what we've got + if (nextValue == null) return currentValue; + // currentValue is null so use nextValue + if (currentValue == null) return nextValue; + // currentValue is after nextValue so use nextValue + if (currentValue.after(nextValue)) return nextValue; + // stick with current value + return currentValue; + } + + private static List<GenericValue> filterByThruDate(List<GenericValue> values) { + return EntityUtil.filterByCondition(values, THRU_DATE_ONLY_CONDITION); + } + + private static List<GenericValue> filterByThruDate(List<GenericValue> values, String thruDateName) { + return EntityUtil.filterByCondition(values, EntityCondition.makeCondition( + EntityCondition.makeCondition(thruDateName, EntityOperator.EQUALS, null), + EntityOperator.OR, + EntityCondition.makeCondition(thruDateName, EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp()))); + } + + private static Timestamp getCategoryCatalogs(Document doc, GenericValue productCategory, Set<String> indexedCatalogIds) throws GenericEntityException { + Timestamp nextReIndex = null; + List<GenericValue> prodCatalogCategories = productCategory.getRelated("ProdCatalogCategory", null, null, false); + prodCatalogCategories = filterByThruDate(prodCatalogCategories); + for (GenericValue prodCatalogCategory : prodCatalogCategories) { + Timestamp fromDate = prodCatalogCategory.getTimestamp("fromDate"); + Timestamp thruDate = prodCatalogCategory.getTimestamp("thruDate"); + if (fromDate != null && fromDate.after(UtilDateTime.nowTimestamp())) { + // fromDate is after now, update reindex date but don't index now + nextReIndex = checkSetNextReIndex(fromDate, nextReIndex); + continue; + } else if (thruDate != null) { + nextReIndex = checkSetNextReIndex(thruDate, nextReIndex); + } + // Skip if we've done this catalog already + if (!indexedCatalogIds.add(prodCatalogCategory.getString("prodCatalogId"))) { + continue; + } + doc.add(new StringField("prodCatalogId", prodCatalogCategory.getString("prodCatalogId"), Field.Store.NO)); + } + return nextReIndex; + } + + private static long quantizeTimestampToDays(Timestamp date) { + long quantizedDate = 0; + if (date != null) { + quantizedDate = date.getTime() / 24 / 3600; + } + return quantizedDate; + } + @Override public String toString() { return getDocumentIdentifier().toString(); @@ -75,7 +150,8 @@ public class ProductDocument implements LuceneDocument { // Return a null document (we will remove the document from the index) return null; } else { - if ("Y".equals(product.getString("isVariant")) && "true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore.variants", delegator))) { + if ("Y".equals(product.getString("isVariant")) && "true".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.ignore" + + ".variants", delegator))) { return null; } Document doc = new Document(); @@ -92,17 +168,21 @@ public class ProductDocument implements LuceneDocument { nextReIndex = checkSetNextReIndex(product.getTimestamp("introductionDate"), nextReIndex); doc.add(new LongPoint("salesDiscontinuationDate", quantizeTimestampToDays(product.getTimestamp("salesDiscontinuationDate")))); nextReIndex = checkSetNextReIndex(product.getTimestamp("salesDiscontinuationDate"), nextReIndex); - doc.add(new StringField("isVariant", product.get("isVariant") != null && product.getBoolean("isVariant") ? "true" : "false", Field.Store.NO)); + doc.add(new StringField("isVariant", product.get("isVariant") != null && product.getBoolean("isVariant") ? "true" : "false", + Field.Store.NO)); // ProductFeature Fields, check that at least one of the fields is set to be indexed if (!"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductFeatureAndAppl.description", "0", delegator)) - || !"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductFeatureAndAppl.abbrev", "0", delegator)) - || !"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductFeatureAndAppl.idCode", "0", delegator))) { + || !"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductFeatureAndAppl.abbrev", "0", + delegator)) + || !"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductFeatureAndAppl.idCode", "0", + delegator))) { - List<GenericValue> productFeatureAndAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", productId).queryList(); + List<GenericValue> productFeatureAndAppls = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where("productId", + productId).queryList(); productFeatureAndAppls = filterByThruDate(productFeatureAndAppls); - for (GenericValue productFeatureAndAppl: productFeatureAndAppls) { + for (GenericValue productFeatureAndAppl : productFeatureAndAppls) { Timestamp fromDate = productFeatureAndAppl.getTimestamp("fromDate"); Timestamp thruDate = productFeatureAndAppl.getTimestamp("thruDate"); if (fromDate != null && fromDate.after(UtilDateTime.nowTimestamp())) { @@ -113,13 +193,15 @@ public class ProductDocument implements LuceneDocument { nextReIndex = checkSetNextReIndex(thruDate, nextReIndex); } doc.add(new StringField("productFeatureId", productFeatureAndAppl.getString("productFeatureId"), Field.Store.NO)); - doc.add(new StringField("productFeatureCategoryId", productFeatureAndAppl.getString("productFeatureCategoryId"), Field.Store.NO)); + doc.add(new StringField("productFeatureCategoryId", productFeatureAndAppl.getString("productFeatureCategoryId"), + Field.Store.NO)); doc.add(new StringField("productFeatureTypeId", productFeatureAndAppl.getString("productFeatureTypeId"), Field.Store.NO)); addTextField(doc, "featureDescription", productFeatureAndAppl.getString("description"), false, "fullText", delegator); addTextField(doc, "featureAbbreviation", productFeatureAndAppl.getString("abbrev"), false, "fullText", delegator); addTextField(doc, "featureCode", productFeatureAndAppl.getString("idCode"), false, "fullText", delegator); // Get the ProductFeatureGroupIds - List<GenericValue> productFeatureGroupAppls = EntityQuery.use(delegator).from("ProductFeatureGroupAppl").where("productFeatureId", productFeatureAndAppl.get("productFeatureId")).queryList(); + List<GenericValue> productFeatureGroupAppls = EntityQuery.use(delegator).from("ProductFeatureGroupAppl").where( + "productFeatureId", productFeatureAndAppl.get("productFeatureId")).queryList(); productFeatureGroupAppls = filterByThruDate(productFeatureGroupAppls); for (GenericValue productFeatureGroupAppl : productFeatureGroupAppls) { fromDate = productFeatureGroupAppl.getTimestamp("fromDate"); @@ -131,17 +213,20 @@ public class ProductDocument implements LuceneDocument { } else if (thruDate != null) { nextReIndex = checkSetNextReIndex(thruDate, nextReIndex); } - doc.add(new StringField("productFeatureGroupId", productFeatureGroupAppl.getString("productFeatureGroupId"), Field.Store.NO)); + doc.add(new StringField("productFeatureGroupId", productFeatureGroupAppl.getString("productFeatureGroupId"), + Field.Store.NO)); } } } // ProductAttribute Fields if (!"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductAttribute.attrName", "0", delegator)) - || !"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductAttribute.attrValue", "0", delegator))) { + || !"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.ProductAttribute.attrValue", "0", + delegator))) { - List<GenericValue> productAttributes = EntityQuery.use(delegator).from("ProductAttribute").where("productId", productId).queryList(); - for (GenericValue productAttribute: productAttributes) { + List<GenericValue> productAttributes = + EntityQuery.use(delegator).from("ProductAttribute").where("productId", productId).queryList(); + for (GenericValue productAttribute : productAttributes) { addTextField(doc, "attributeName", productAttribute.getString("attrName"), false, "fullText", delegator); addTextField(doc, "attributeValue", productAttribute.getString("attrValue"), false, "fullText", delegator); } @@ -149,8 +234,9 @@ public class ProductDocument implements LuceneDocument { // GoodIdentification if (!"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.GoodIdentification.idValue", "0", delegator))) { - List<GenericValue> goodIdentifications = EntityQuery.use(delegator).from("GoodIdentification").where("productId", productId).queryList(); - for (GenericValue goodIdentification: goodIdentifications) { + List<GenericValue> goodIdentifications = + EntityQuery.use(delegator).from("GoodIdentification").where("productId", productId).queryList(); + for (GenericValue goodIdentification : goodIdentifications) { String goodIdentificationTypeId = goodIdentification.getString("goodIdentificationTypeId"); String idValue = goodIdentification.getString("idValue"); doc.add(new StringField("goodIdentificationTypeId", goodIdentificationTypeId, Field.Store.NO)); @@ -162,9 +248,10 @@ public class ProductDocument implements LuceneDocument { // Virtual ProductIds if ("Y".equals(product.getString("isVirtual"))) { if (!"0".equals(EntityUtilProperties.getPropertyValue("prodsearch", "index.weight.Variant.Product.productId", "0", delegator))) { - List<GenericValue> variantProductAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, "productAssocTypeId", "PRODUCT_VARIANT").queryList(); + List<GenericValue> variantProductAssocs = EntityQuery.use(delegator).from("ProductAssoc").where("productId", productId, + "productAssocTypeId", "PRODUCT_VARIANT").queryList(); variantProductAssocs = filterByThruDate(variantProductAssocs); - for (GenericValue variantProductAssoc: variantProductAssocs) { + for (GenericValue variantProductAssoc : variantProductAssocs) { Timestamp fromDate = variantProductAssoc.getTimestamp("fromDate"); Timestamp thruDate = variantProductAssoc.getTimestamp("thruDate"); if (fromDate != null && fromDate.after(UtilDateTime.nowTimestamp())) { @@ -181,16 +268,17 @@ public class ProductDocument implements LuceneDocument { // Index product content String productContentTypes = EntityUtilProperties.getPropertyValue("prodsearch", "index.include.ProductContentTypes", delegator); - for (String productContentTypeId: productContentTypes.split(",")) { + for (String productContentTypeId : productContentTypes.split(",")) { try { EntityUtilProperties.getPropertyAsInteger("prodsearch", "index.weight.ProductContent." + productContentTypeId, 1); } catch (Exception e) { Debug.logWarning("Could not parse weight number: " + e.toString(), MODULE); } - List<GenericValue> productContentAndInfos = EntityQuery.use(delegator).from("ProductContentAndInfo").where("productId", productId, "productContentTypeId", productContentTypeId).queryList(); + List<GenericValue> productContentAndInfos = EntityQuery.use(delegator).from("ProductContentAndInfo").where("productId", + productId, "productContentTypeId", productContentTypeId).queryList(); productContentAndInfos = filterByThruDate(productContentAndInfos); - for (GenericValue productContentAndInfo: productContentAndInfos) { + for (GenericValue productContentAndInfo : productContentAndInfos) { Timestamp fromDate = productContentAndInfo.getTimestamp("fromDate"); Timestamp thruDate = productContentAndInfo.getTimestamp("thruDate"); if (fromDate != null && fromDate.after(UtilDateTime.nowTimestamp())) { @@ -202,7 +290,8 @@ public class ProductDocument implements LuceneDocument { } try { Map<String, Object> drContext = UtilMisc.<String, Object>toMap("product", product); - String contentText = DataResourceWorker.renderDataResourceAsText(null, delegator, productContentAndInfo.getString("dataResourceId"), drContext, null, null, false); + String contentText = DataResourceWorker.renderDataResourceAsText(null, delegator, productContentAndInfo.getString( + "dataResourceId"), drContext, null, null, false); addTextField(doc, "content", contentText, false, "fullText", delegator); } catch (IOException | GeneralException e1) { Debug.logError(e1, "Error getting content text to index", MODULE); @@ -210,7 +299,8 @@ public class ProductDocument implements LuceneDocument { // TODO: Not indexing alternate locales, needs special handling /* - List<GenericValue> alternateViews = productContentAndInfo.getRelated("ContentAssocDataResourceViewTo", UtilMisc.toMap("caContentAssocTypeId", "ALTERNATE_LOCALE"), UtilMisc.toList("-caFromDate")); + List<GenericValue> alternateViews = productContentAndInfo.getRelated("ContentAssocDataResourceViewTo", UtilMisc.toMap + ("caContentAssocTypeId", "ALTERNATE_LOCALE"), UtilMisc.toList("-caFromDate")); alternateViews = EntityUtil.filterByDate(alternateViews, UtilDateTime.nowTimestamp(), "caFromDate", "caThruDate", true); for (GenericValue thisView: alternateViews) { } @@ -221,7 +311,8 @@ public class ProductDocument implements LuceneDocument { // Index the product's directProductCategoryIds (direct parents), productCategoryIds (all ancestors) and prodCatalogIds this.populateCategoryData(doc, product); - // Index ProductPrices, uses dynamic fields in the format ${productPriceTypeId}_${productPricePurposeId}_${currencyUomId}_${productStoreGroupId}_price + // Index ProductPrices, uses dynamic fields in the format + // ${productPriceTypeId}_${productPricePurposeId}_${currencyUomId}_${productStoreGroupId}_price List<GenericValue> productPrices = product.getRelated("ProductPrice", null, null, false); productPrices = filterByThruDate(productPrices); for (GenericValue productPrice : productPrices) { @@ -267,7 +358,8 @@ public class ProductDocument implements LuceneDocument { } // TODO: Add the nextReIndex timestamp to the document for when the product should be automatically re-indexed outside of any ECAs - // based on the next known from/thru date whose passing will cause a change to the document. Need to build a scheduled service to look for these. + // based on the next known from/thru date whose passing will cause a change to the document. Need to build a scheduled service to + // look for these. return doc; } } catch (GenericEntityException e) { @@ -276,58 +368,13 @@ public class ProductDocument implements LuceneDocument { return null; } - // An attempt to boost/weight values in a similar manner to what OFBiz product search does. - private static void addTextField(Document doc, String fieldName, String value, boolean store, String fullTextFieldName, Delegator delegator) { - if (fieldName == null) return; - - Field field = new TextField(fieldName, checkValue(value), (store? Field.Store.YES: Field.Store.NO)); - doc.add(field); - if (fullTextFieldName != null) { - doc.add(new TextField(fullTextFieldName, checkValue(value), Field.Store.NO)); - } - } - - private static String checkValue(String value) { - if (UtilValidate.isEmpty(value)) { - return NULL_STRING; - } - return value; - } - - private static Timestamp checkSetNextReIndex(Timestamp nextValue, Timestamp currentValue) { - // nextValue is null, stick with what we've got - if (nextValue == null) return currentValue; - // currentValue is null so use nextValue - if (currentValue == null) return nextValue; - // currentValue is after nextValue so use nextValue - if (currentValue.after(nextValue)) return nextValue; - // stick with current value - return currentValue; - } - - private static final EntityCondition THRU_DATE_ONLY_CONDITION = EntityCondition.makeCondition( - EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), - EntityOperator.OR, - EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp())); - - private static List<GenericValue> filterByThruDate(List<GenericValue> values) { - return EntityUtil.filterByCondition(values, THRU_DATE_ONLY_CONDITION); - } - - private static List<GenericValue> filterByThruDate(List<GenericValue> values, String thruDateName) { - return EntityUtil.filterByCondition(values, EntityCondition.makeCondition( - EntityCondition.makeCondition(thruDateName, EntityOperator.EQUALS, null), - EntityOperator.OR, - EntityCondition.makeCondition(thruDateName, EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp()))); - } - private Timestamp populateCategoryData(Document doc, GenericValue product) throws GenericEntityException { Timestamp nextReIndex = null; Set<String> indexedCategoryIds = new TreeSet<>(); List<GenericValue> productCategoryMembers = product.getRelated("ProductCategoryMember", null, null, false); productCategoryMembers = filterByThruDate(productCategoryMembers); - for (GenericValue productCategoryMember: productCategoryMembers) { + for (GenericValue productCategoryMember : productCategoryMembers) { String productCategoryId = productCategoryMember.getString("productCategoryId"); doc.add(new StringField("productCategoryId", productCategoryId, Field.Store.NO)); doc.add(new StringField("directProductCategoryId", productCategoryId, Field.Store.NO)); @@ -352,7 +399,8 @@ public class ProductDocument implements LuceneDocument { return this.getParentCategories(doc, productCategory, indexedCategoryIds, new TreeSet<>()); } - private Timestamp getParentCategories(Document doc, GenericValue productCategory, Set<String> indexedCategoryIds, Set<String> indexedCatalogIds) throws GenericEntityException { + private Timestamp getParentCategories(Document doc, GenericValue productCategory, Set<String> indexedCategoryIds, + Set<String> indexedCatalogIds) throws GenericEntityException { Timestamp nextReIndex = null; nextReIndex = getCategoryCatalogs(doc, productCategory, indexedCatalogIds); List<GenericValue> productCategoryRollups = productCategory.getRelated("CurrentProductCategoryRollup", null, null, false); @@ -380,35 +428,4 @@ public class ProductDocument implements LuceneDocument { return nextReIndex; } - private static Timestamp getCategoryCatalogs(Document doc, GenericValue productCategory, Set<String> indexedCatalogIds) throws GenericEntityException { - Timestamp nextReIndex = null; - List<GenericValue> prodCatalogCategories = productCategory.getRelated("ProdCatalogCategory", null, null, false); - prodCatalogCategories = filterByThruDate(prodCatalogCategories); - for (GenericValue prodCatalogCategory : prodCatalogCategories) { - Timestamp fromDate = prodCatalogCategory.getTimestamp("fromDate"); - Timestamp thruDate = prodCatalogCategory.getTimestamp("thruDate"); - if (fromDate != null && fromDate.after(UtilDateTime.nowTimestamp())) { - // fromDate is after now, update reindex date but don't index now - nextReIndex = checkSetNextReIndex(fromDate, nextReIndex); - continue; - } else if (thruDate != null) { - nextReIndex = checkSetNextReIndex(thruDate, nextReIndex); - } - // Skip if we've done this catalog already - if (!indexedCatalogIds.add(prodCatalogCategory.getString("prodCatalogId"))) { - continue; - } - doc.add(new StringField("prodCatalogId", prodCatalogCategory.getString("prodCatalogId"), Field.Store.NO)); - } - return nextReIndex; - } - - private static long quantizeTimestampToDays(Timestamp date) { - long quantizedDate = 0; - if (date != null) { - quantizedDate = date.getTime()/24/3600; - } - return quantizedDate; - } - } diff --git a/lucene/src/main/java/org/apache/ofbiz/content/search/SearchServices.java b/lucene/src/main/java/org/apache/ofbiz/content/search/SearchServices.java index 4aa98d9..f405330 100644 --- a/lucene/src/main/java/org/apache/ofbiz/content/search/SearchServices.java +++ b/lucene/src/main/java/org/apache/ofbiz/content/search/SearchServices.java @@ -36,6 +36,7 @@ import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.ServiceUtil; import org.apache.ofbiz.service.LocalDispatcher; + import java.util.HashMap; /** @@ -73,8 +74,9 @@ public class SearchServices { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); try { - // Only re-index the active appls, future dated ones will get picked up on that product's re-index date - List<GenericValue> productFeatureAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productFeatureId", context.get("productFeatureId")).filterByDate().queryList(); + // Only re-index the active appls, future dated ones will get picked up on that product's re-index date + List<GenericValue> productFeatureAppls = EntityQuery.use(delegator).from("ProductFeatureAppl").where("productFeatureId", context.get( + "productFeatureId")).filterByDate().queryList(); for (GenericValue productFeatureAppl : productFeatureAppls) { try { @@ -116,7 +118,8 @@ public class SearchServices { LocalDispatcher dispatcher = dctx.getDispatcher(); Map<String, Object> result = new HashMap<>(); try { - List<GenericValue> contents = EntityQuery.use(delegator).from("Content").where("dataResourceId", context.get("dataResourceId")).queryList(); + List<GenericValue> contents = + EntityQuery.use(delegator).from("Content").where("dataResourceId", context.get("dataResourceId")).queryList(); for (GenericValue content : contents) { result = dispatcher.runSync("indexProductsFromContent", UtilMisc.toMap( @@ -131,11 +134,13 @@ public class SearchServices { } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> indexProductsFromContent(DispatchContext dctx, Map<String, ? extends Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); try { - List<GenericValue> productContents = EntityQuery.use(delegator).from("ProductContent").where("contentId", context.get("contentId")).queryList(); + List<GenericValue> productContents = + EntityQuery.use(delegator).from("ProductContent").where("contentId", context.get("contentId")).queryList(); for (GenericValue productContent : productContents) { try { Map<String, Object> result = dispatcher.runSync("indexProduct", UtilMisc.toMap("productId", productContent.get("productId"))); @@ -151,6 +156,7 @@ public class SearchServices { } return ServiceUtil.returnSuccess(); } + public static Map<String, Object> indexProductsFromCategory(DispatchContext dctx, Map<String, Object> context) { Delegator delegator = dctx.getDelegator(); LocalDispatcher dispatcher = dctx.getDispatcher(); @@ -163,8 +169,11 @@ public class SearchServices { } return ServiceUtil.returnSuccess(); } - private static void indexProductCategoryRollup(String parentProductCategoryId, Delegator delegator, LocalDispatcher dispatcher, Set<String> excludeProductCategoryIds) throws GenericEntityException { - List<GenericValue> productCategoryRollups = EntityQuery.use(delegator).from("ProductCategoryRollup").where("parentProductCategoryId", parentProductCategoryId).queryList(); + + private static void indexProductCategoryRollup(String parentProductCategoryId, Delegator delegator, LocalDispatcher dispatcher, + Set<String> excludeProductCategoryIds) throws GenericEntityException { + List<GenericValue> productCategoryRollups = EntityQuery.use(delegator).from("ProductCategoryRollup").where("parentProductCategoryId", + parentProductCategoryId).queryList(); for (GenericValue productCategoryRollup : productCategoryRollups) { String productCategoryId = productCategoryRollup.getString("productCategoryId"); // Avoid infinite recursion @@ -176,8 +185,10 @@ public class SearchServices { } } - private static void indexProductCategoryMembers(String productCategoryId, Delegator delegator, LocalDispatcher dispatcher) throws GenericEntityException { - List<GenericValue> productCategoryMembers = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", productCategoryId).queryList(); + private static void indexProductCategoryMembers(String productCategoryId, Delegator delegator, LocalDispatcher dispatcher) + throws GenericEntityException { + List<GenericValue> productCategoryMembers = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", + productCategoryId).queryList(); Map<String, Object> result; for (GenericValue productCategoryMember : productCategoryMembers) { try { diff --git a/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java b/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java index 63a61b0..09d7024 100644 --- a/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java +++ b/lucene/src/main/java/org/apache/ofbiz/content/test/LuceneTests.java @@ -43,7 +43,7 @@ import org.apache.ofbiz.service.testtools.OFBizTestCase; public class LuceneTests extends OFBizTestCase { - public final static String MODULE = LuceneTests.class.getName(); + private static final String MODULE = LuceneTests.class.getName(); public LuceneTests(String name) { super(name); diff --git a/msggateway/src/main/java/org/apache/ofbiz/msg91/Msg91Services.java b/msggateway/src/main/java/org/apache/ofbiz/msg91/Msg91Services.java index fbc6d11..816fdec 100644 --- a/msggateway/src/main/java/org/apache/ofbiz/msg91/Msg91Services.java +++ b/msggateway/src/main/java/org/apache/ofbiz/msg91/Msg91Services.java @@ -35,7 +35,7 @@ import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.ServiceUtil; public class Msg91Services { - public final static String MODULE = Msg91Services.class.getName(); + private static final String MODULE = Msg91Services.class.getName(); public static Map<String, Object> sendMsg91Sms(DispatchContext ctx, Map<String, ? extends Object> context) { Delegator delegator = ctx.getDelegator(); diff --git a/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java b/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java index 3dbf58f..dcc932b 100644 --- a/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java +++ b/passport/src/main/java/org/apache/ofbiz/passport/user/GitHubAuthenticator.java @@ -87,7 +87,7 @@ public class GitHubAuthenticator implements Authenticator { /** * Method to authenticate a user. * For GitHub users, we only check if the username(userLoginId) exists an - * externalAuthId, and the externalAuthId has a valid accessToken in + * externalAuthId, and the externalAuthId has a valid accessToken in * GitHubUser entity. * * @param userLoginId User's login id diff --git a/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java b/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java index 424fc90..dccde2d 100644 --- a/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java +++ b/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractHtmlReport.java @@ -30,8 +30,8 @@ import org.apache.ofbiz.htmlreport.util.ReportStringUtil; public abstract class AbstractHtmlReport extends HtmlReport { private static final String MODULE = AbstractHtmlReport.class.getName(); - public final static String THREAD_TYPE = "thread_type"; - public final static String FILE_REPORT_OUTPUT = "plugins/pricat/template/pricat/report.ftl"; + public static final String THREAD_TYPE = "thread_type"; + public static final String FILE_REPORT_OUTPUT = "plugins/pricat/template/pricat/report.ftl"; /** * Constructs a new report using the provided locale for the output language. diff --git a/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java b/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java index 2d01a40..8d0ed0d 100644 --- a/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java +++ b/pricat/src/main/java/org/apache/ofbiz/htmlreport/AbstractReportThread.java @@ -106,7 +106,7 @@ public abstract class AbstractReportThread extends Thread implements InterfaceRe */ public abstract String getReportUpdate(); - /** + /** * Returns the time this report has been running. * @return the time this report has been running */ diff --git a/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java b/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java index 04bd2e3..04dbda3 100644 --- a/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java +++ b/pricat/src/main/java/org/apache/ofbiz/htmlreport/HtmlReport.java @@ -60,8 +60,8 @@ public class HtmlReport extends AbstractReport { /** Constant for a HTML linebreak with added "real" line break. */ protected static final String LINEBREAK = "<br>"; - /** - * Constant for a HTML linebreak with added "real" line break- + /** + * Constant for a HTML linebreak with added "real" line break- * traditional style for report threads that still use XML templates for their output. */ protected static final String LINEBREAK_TRADITIONAL = "<br>\n"; @@ -1130,7 +1130,7 @@ public class HtmlReport extends AbstractReport { } /** - * Returns the value of the file parameter, + * Returns the value of the file parameter, * or null if this parameter was not provided.<p> * The file parameter selects the file on which the dialog action * is to be performed.<p> @@ -1191,7 +1191,7 @@ public class HtmlReport extends AbstractReport { * as value for the "action" attribute of a html form.<p> * * This URI is the real one.<p> - * + * * @return the http URI of the current dialog */ public String getDialogRealUri(HttpServletRequest request) { diff --git a/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java b/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java index 1a30fe5..58b8fda 100644 --- a/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java +++ b/pricat/src/main/java/org/apache/ofbiz/htmlreport/InterfaceReport.java @@ -91,7 +91,7 @@ public interface InterfaceReport { */ String getReportUpdate(); - /** + /** * Returns the time this report has been running.<p> * @return the time this report has been running */ diff --git a/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java b/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java index ac50900..9e67dad 100644 --- a/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java +++ b/pricat/src/main/java/org/apache/ofbiz/htmlreport/util/ReportEncoder.java @@ -77,7 +77,7 @@ public final class ReportEncoder { } /** - * Adjusts the given String by making sure all characters that can be displayed + * Adjusts the given String by making sure all characters that can be displayed * in the given charset are contained as chars, whereas all other non-displayable * characters are converted to HTML entities.<p> * Just calls {@link #decodeHtmlEntities(String, String)} first and feeds the result @@ -134,7 +134,7 @@ public final class ReportEncoder { try { return new String(bytes, enc); } catch (UnsupportedEncodingException e) { - // this can _never_ happen since the charset was looked up first + // this can _never_ happen since the charset was looked up first } } else { enc = ENCODING_UTF_8; @@ -162,7 +162,7 @@ public final class ReportEncoder { /** * This method is a substitute for <code>URLDecoder.decode()</code>.<p> * In case you don't know what encoding to use, set the value of - * the <code>encoding</code> parameter to <code>null</code>. + * the <code>encoding</code> parameter to <code>null</code>. * This method will then default to UTF-8 encoding, which is probably the right one.<p> * @param source The string to decode * @param encoding The encoding to use (if null, the system default is used) @@ -212,7 +212,7 @@ public final class ReportEncoder { if (c < 128) { // first 128 chars are contained in almost every charset entity = new String(new char[] {(char) c}); - // this is intended as performance improvement since + // this is intended as performance improvement since // the canEncode() operation appears quite CPU heavy } else if (encoder.canEncode((char) c)) { // encoder can encode this char @@ -300,7 +300,7 @@ public final class ReportEncoder { if (c < 128) { // first 128 chars are contained in almost every charset result.append((char) c); - // this is intended as performance improvement since + // this is intended as performance improvement since // the canEncode() operation appears quite CPU heavy } else if (encoder.canEncode((char) c)) { // encoder can encode this char @@ -334,7 +334,7 @@ public final class ReportEncoder { if (c < 128) { // first 128 chars are contained in almost every charset result.append((char) c); - // this is intended as performance improvement since + // this is intended as performance improvement since // the canEncode() operation appears quite CPU heavy } else if (encoder.canEncode((char) c)) { // encoder can encode this char @@ -465,7 +465,7 @@ public final class ReportEncoder { StringBuffer ret = new StringBuffer(source.length() * 2); // URLEncode the text string - // this produces a very similar encoding to JavaSscript encoding, + // this produces a very similar encoding to JavaSscript encoding, // except the blank which is not encoded into "%20" instead of "+" String enc = encode(source, encoding); diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java b/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java index 7bd1d9e..a1f9910 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/AbstractPricatParser.java @@ -99,7 +99,8 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { protected Locale locale; protected long sequenceNum = -1L; - public AbstractPricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, Map<String, String[]> facilities, File pricatFile, GenericValue userLogin) { + public AbstractPricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, + Map<String, String[]> facilities, File pricatFile, GenericValue userLogin) { this.dispatcher = dispatcher; this.delegator = delegator; this.locale = locale; @@ -112,6 +113,39 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { this.pricatFile = pricatFile; initBasicConds(UtilMisc.toList(userLogin.getString("partyId"))); } + + /** + * Check whether a commented file exists. + * + * @param request + * @param sequenceNum + * @return + */ + public static boolean isCommentedExcelExists(HttpServletRequest request, Long sequenceNum) { + GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); + if (UtilValidate.isEmpty(sequenceNum) || UtilValidate.isEmpty(userLogin)) { + Debug.logError("sequenceNum[" + sequenceNum + "] or userLogin is empty", MODULE); + return false; + } + String userLoginId = userLogin.getString("userLoginId"); + Delegator delegator = (Delegator) request.getAttribute("delegator"); + GenericValue historyValue = null; + try { + historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "sequenceNum", + Long.valueOf(sequenceNum)).queryOne(); + } catch (NumberFormatException | GenericEntityException e) { + Debug.logError(e.getMessage(), MODULE); + return false; + } + if (UtilValidate.isEmpty(historyValue)) { + Debug.logError("No ExcelImportHistory value found by sequenceNum[" + sequenceNum + "] and userLoginId[" + userLoginId + "].", MODULE); + return false; + } + File file = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx"); + + return file.exists(); + } + @Override public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet) { report.println(); @@ -224,7 +258,7 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { rowMapping.put(rowNum, errorRow); newRow.setHeight(row.getHeight()); copyRow(row, newRow, factory, errorPatriarch); - newRowNum ++; + newRowNum++; } } } @@ -380,8 +414,8 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { /** * Get data by version definition. * @param row - * @param colNames - * @param size + * @param colNames + * @param size * @return */ @Override @@ -398,8 +432,10 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { } if (cell == null) { if ((Boolean) colNames.get(i)[2]) { - report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING); - errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale)); + report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[]{colNames.get(i)[0]}, locale), + InterfaceReport.FORMAT_WARNING); + errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", + new Object[]{colNames.get(i)[0]}, locale)); foundError = true; continue; } else { @@ -410,17 +446,20 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { String cellValue = formatter.formatCellValue(cell); if (UtilValidate.isNotEmpty(cellValue)) { if (cellType == CellType.FORMULA) { - cellValue = BigDecimal.valueOf(cell.getNumericCellValue()).setScale(FinAccountHelper.getDecimals(), FinAccountHelper.getRounding()).toString(); - report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE); + cellValue = BigDecimal.valueOf(cell.getNumericCellValue()).setScale(FinAccountHelper.getDecimals(), + FinAccountHelper.getRounding()).toString(); + report.print(((i == 0) ? "" : ", ") + cellValue, InterfaceReport.FORMAT_NOTE); } else { - report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE); + report.print(((i == 0) ? "" : ", ") + cellValue, InterfaceReport.FORMAT_NOTE); } } else { - report.print(((i == 0)?"":","), InterfaceReport.FORMAT_NOTE); + report.print(((i == 0) ? "" : ","), InterfaceReport.FORMAT_NOTE); } if ((Boolean) colNames.get(i)[2] && UtilValidate.isEmpty(cellValue)) { - report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING); - errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale)); + report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[]{colNames.get(i)[0]}, locale), + InterfaceReport.FORMAT_WARNING); + errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", + new Object[]{colNames.get(i)[0]}, locale)); foundError = true; results.add(null); continue; @@ -505,7 +544,8 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { if (physicalNumberOfCells > i) { cell = row.getCell(i); } - if (cell != null && UtilValidate.isNotEmpty(formatter.formatCellValue(cell)) && UtilValidate.isNotEmpty(formatter.formatCellValue(cell).trim())) { + if (cell != null && UtilValidate.isNotEmpty(formatter.formatCellValue(cell)) + && UtilValidate.isNotEmpty(formatter.formatCellValue(cell).trim())) { isEmptyRow = false; break; } @@ -539,15 +579,17 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { try { GenericValue historyValue = null; if (sequenceNum < 1L) { - historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "logFileName", logFileName).orderBy("sequenceNum DESC").filterByDate().queryFirst(); + historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "logFileName", logFileName) + .orderBy("sequenceNum DESC").filterByDate().queryFirst(); } else { - historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "sequenceNum", sequenceNum).queryOne(); + historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "sequenceNum", sequenceNum) + .queryOne(); } Timestamp now = UtilDateTime.nowTimestamp(); if (UtilValidate.isEmpty(historyValue)) { historyValue = delegator.makeValue("ExcelImportHistory", UtilMisc.toMap("sequenceNum", sequenceNum, "userLoginId", userLoginId, - "fileName", pricatFile.getName(), "statusId", "EXCEL_IMPORTED", "fromDate", now, - "thruDate", now, "threadName", threadName, "logFileName", logFileName)); + "fileName", pricatFile.getName(), "statusId", "EXCEL_IMPORTED", "fromDate", now, + "thruDate", now, "threadName", threadName, "logFileName", logFileName)); } else { historyValue.set("statusId", "EXCEL_IMPORTED"); historyValue.set("thruDate", now); @@ -561,50 +603,24 @@ public abstract class AbstractPricatParser implements InterfacePricatParser { // do nothing } } + @Override public boolean hasErrorMessages() { return !errorMessages.keySet().isEmpty(); } - /** - * Check whether a commented file exists. - * @param request - * @param sequenceNum - * @return - */ - public static boolean isCommentedExcelExists(HttpServletRequest request, Long sequenceNum) { - GenericValue userLogin = (GenericValue) request.getSession().getAttribute("userLogin"); - if (UtilValidate.isEmpty(sequenceNum) || UtilValidate.isEmpty(userLogin)) { - Debug.logError("sequenceNum[" + sequenceNum + "] or userLogin is empty", MODULE); - return false; - } - String userLoginId = userLogin.getString("userLoginId"); - Delegator delegator = (Delegator) request.getAttribute("delegator"); - GenericValue historyValue = null; - try { - historyValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId, "sequenceNum", Long.valueOf(sequenceNum)).queryOne(); - } catch (NumberFormatException | GenericEntityException e) { - Debug.logError(e.getMessage(), MODULE); - return false; - } - if (UtilValidate.isEmpty(historyValue)) { - Debug.logError("No ExcelImportHistory value found by sequenceNum[" + sequenceNum + "] and userLoginId[" + userLoginId + "].", MODULE); - return false; - } - File file = FileUtil.getFile(tempFilesFolder + userLoginId + "/" + sequenceNum + ".xlsx"); - - return file.exists(); - } - protected void cleanupLogAndCommentedExcel() { try { report.print(UtilProperties.getMessage(RESOURCE, "CLEANUP_LOGANDEXCEL_BEGIN", locale), InterfaceReport.FORMAT_DEFAULT); - List<GenericValue> historyValues = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId).orderBy("sequenceNum DESC").queryList(); + List<GenericValue> historyValues = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId).orderBy( + "sequenceNum DESC").queryList(); if (UtilValidate.isEmpty(historyValues) || historyValues.size() <= HISTORY_MAX_FILENUMBER) { - report.print(UtilProperties.getMessage(RESOURCE, "HistoryLessThan", new Object[] {String.valueOf(HISTORY_MAX_FILENUMBER)}, locale), InterfaceReport.FORMAT_NOTE); + report.print(UtilProperties.getMessage(RESOURCE, "HistoryLessThan", new Object[]{String.valueOf(HISTORY_MAX_FILENUMBER)}, locale), + InterfaceReport.FORMAT_NOTE); report.println(" ... " + UtilProperties.getMessage(RESOURCE, "skipped", locale), InterfaceReport.FORMAT_NOTE); } else { - report.print(" ... " + UtilProperties.getMessage(RESOURCE, "HistoryEntryToRemove", new Object[] {historyValues.size() - HISTORY_MAX_FILENUMBER}, locale), InterfaceReport.FORMAT_NOTE); + report.print(" ... " + UtilProperties.getMessage(RESOURCE, "HistoryEntryToRemove", + new Object[]{historyValues.size() - HISTORY_MAX_FILENUMBER}, locale), InterfaceReport.FORMAT_NOTE); List<GenericValue> valuesToRemove = new ArrayList<>(); for (int i = HISTORY_MAX_FILENUMBER; i < historyValues.size(); i++) { GenericValue historyValue = historyValues.get(i); diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java b/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java index 6a947ed..bd42461 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/InterfacePricatParser.java @@ -35,62 +35,62 @@ import org.apache.ofbiz.entity.transaction.GenericTransactionException; * Interface of pricat parser. */ public interface InterfacePricatParser { - static final String PARSE_EXCEL = "parse_excel"; - static final String CONFIRM = "confirm_action"; - static final String[] messageLabels = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"}; - public static final List<String> messages = Collections.unmodifiableList(Arrays.asList(messageLabels)); - public static final String tempFilesFolder = "runtime/pricat/"; - public static final String FileDateTimePattern = "yyyyMMddHHmmss"; - public static final String defaultColorName = "DefaultColor"; - public static final String defaultDimensionName = "DefaultDimension"; - public static final String defaultCategoryName = "DefaultCategory"; - public static final String EXCEL_TEMPLATE_TYPE = "excelTemplateType"; - public static final String FACILITY_ID = "facilityId"; - public static final String RESOURCE = "PricatUiLabels"; - public static final String PRICAT_FILE = "__PRICAT_FILE__"; - public static final String DEFAULT_PRICAT_TYPE = "ApacheOFBiz"; - public static final Map<String, String> PricatTypeLabels = UtilMisc.toMap(DEFAULT_PRICAT_TYPE, "ApacheOFBizPricatTemplate", "SamplePricat", "SamplePricatTemplate"); - public static final int HISTORY_MAX_FILENUMBER = UtilProperties.getPropertyAsInteger("pricat.properties", "pricat.history.max.filenumber", 20); - abstract void parsePricatExcel(); - public void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet); - public void initBasicConds(List<String> orgPartyIds); - public boolean existsCurrencyId(XSSFSheet sheet); - abstract void parseRowByRow(XSSFSheet sheet); - abstract boolean parseCellContentsAndStore(XSSFRow row, List<Object> cellContents) throws GenericTransactionException; - public Map<String, Object> updateSkuPrice(String skuId, String ownerPartyId, BigDecimal memberPrice); - - abstract String updateSku(XSSFRow row, String productId, String ownerPartyId, String facilityId, String barcode, BigDecimal inventory, + String PARSE_EXCEL = "parse_excel"; + String CONFIRM = "confirm_action"; + String[] messageLabels = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"}; + List<String> messages = Collections.unmodifiableList(Arrays.asList(messageLabels)); + String tempFilesFolder = "runtime/pricat/"; + String FileDateTimePattern = "yyyyMMddHHmmss"; + String defaultColorName = "DefaultColor"; + String defaultDimensionName = "DefaultDimension"; + String defaultCategoryName = "DefaultCategory"; + String EXCEL_TEMPLATE_TYPE = "excelTemplateType"; + String FACILITY_ID = "facilityId"; + String RESOURCE = "PricatUiLabels"; + String PRICAT_FILE = "__PRICAT_FILE__"; + String DEFAULT_PRICAT_TYPE = "ApacheOFBiz"; + Map<String, String> PricatTypeLabels = UtilMisc.toMap(DEFAULT_PRICAT_TYPE, "ApacheOFBizPricatTemplate", "SamplePricat", "SamplePricatTemplate"); + int HISTORY_MAX_FILENUMBER = UtilProperties.getPropertyAsInteger("pricat.properties", "pricat.history.max.filenumber", 20); + void parsePricatExcel(); + void writeCommentsToFile(XSSFWorkbook workbook, XSSFSheet sheet); + void initBasicConds(List<String> orgPartyIds); + boolean existsCurrencyId(XSSFSheet sheet); + void parseRowByRow(XSSFSheet sheet); + boolean parseCellContentsAndStore(XSSFRow row, List<Object> cellContents) throws GenericTransactionException; + Map<String, Object> updateSkuPrice(String skuId, String ownerPartyId, BigDecimal memberPrice); + + String updateSku(XSSFRow row, String productId, String ownerPartyId, String facilityId, String barcode, BigDecimal inventory, String colorId, String color, String dimensionId, String dimension, BigDecimal listPrice, BigDecimal averageCost); - public Map<String, Object> updateColorAndDimension(String productId, String ownerPartyId, String color, String dimension); + Map<String, Object> updateColorAndDimension(String productId, String ownerPartyId, String color, String dimension); - public Map<String, Object> getDimensionIds(String productId, String ownerPartyId, String dimension); + Map<String, Object> getDimensionIds(String productId, String ownerPartyId, String dimension); - public Map<String, Object> getColorIds(String productId, String ownerPartyId, String color); + Map<String, Object> getColorIds(String productId, String ownerPartyId, String color); - abstract String getProductId(XSSFRow row, String brandId, String modelName, String productName, String productCategoryId, String ownerPartyId, BigDecimal listPrice); + String getProductId(XSSFRow row, String brandId, String modelName, String productName, String productCategoryId, String ownerPartyId, BigDecimal listPrice); - public String getBrandId(String brandName, String ownerPartyId); + String getBrandId(String brandName, String ownerPartyId); - abstract Object getCellContent(List<Object> cellContents, String colName); + Object getCellContent(List<Object> cellContents, String colName); - abstract String getProductCategoryId(List<Object> cellContents, String ownerPartyId); + String getProductCategoryId(List<Object> cellContents, String ownerPartyId); - abstract boolean isFacilityOk(XSSFRow row, String facilityName, String facilityId); + boolean isFacilityOk(XSSFRow row, String facilityName, String facilityId); - abstract List<Object> getCellContents(XSSFRow row, List<Object[]> colNames, int size); + List<Object> getCellContents(XSSFRow row, List<Object[]> colNames, int size); - abstract boolean isTableHeaderMatched(XSSFSheet sheet); + boolean isTableHeaderMatched(XSSFSheet sheet); - abstract boolean isVersionSupported(XSSFSheet sheet); + boolean isVersionSupported(XSSFSheet sheet); - abstract boolean containsDataRows(XSSFSheet sheet); + boolean containsDataRows(XSSFSheet sheet); - public boolean isNumOfSheetsOK(XSSFWorkbook workbook); + boolean isNumOfSheetsOK(XSSFWorkbook workbook); - abstract void setFacilityId(String selectedFacilityId); + void setFacilityId(String selectedFacilityId); - public void endExcelImportHistory(String logFileName, String thruReasonId); + void endExcelImportHistory(String logFileName, String thruReasonId); - public boolean hasErrorMessages(); + boolean hasErrorMessages(); } diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java b/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java index 7aa5d30..bf483d7 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/PricatParseExcelHtmlThread.java @@ -65,17 +65,23 @@ import org.apache.ofbiz.service.LocalDispatcher; */ public class PricatParseExcelHtmlThread extends AbstractReportThread { - private static final String MODULE = PricatParseExcelHtmlThread.class.getName(); public static final String PARSE_EXCEL = "parse_excel"; public static final String CONFIRM = "confirm_action"; - public static final String[] messageLabels = new String[] {"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", "FORMAT_ERROR", "FORMAT_THROWABLE"}; - public static final List<String> messages = Collections.unmodifiableList(Arrays.asList(messageLabels)); - public static final String FileDateTimePattern = "yyyyMMddHHmmss"; - public static final String defaultColorName = "DefaultColor"; - public static final String defaultDimensionName = "DefaultDimension"; - public static final String defaultCategoryName = "DefaultCategory"; + public static final String[] MESSAGE_LABELS = new String[]{"FORMAT_DEFAULT", "FORMAT_WARNING", "FORMAT_HEADLINE", "FORMAT_NOTE", "FORMAT_OK", + "FORMAT_ERROR", "FORMAT_THROWABLE"}; + public static final List<String> MESSAGES = Collections.unmodifiableList(Arrays.asList(MESSAGE_LABELS)); + public static final String FILE_DATE_TIME_PATTERN = "yyyyMMddHHmmss"; + public static final String DEF_COLOR_NAME = "DefaultColor"; + public static final String DEF_DIM_NAME = "DefaultDimension"; + public static final String DEF_CAT_NAME = "DefaultCategory"; public static final String EXCEL_TEMPLATE_TYPE = "excelTemplateType"; public static final String FACILITY_ID = "facilityId"; + public static final String PRICAT_FILE = "__PRICAT_FILE__"; + public static final String DEFAULT_PRICAT_TYPE = "sample_pricat"; + public static final Map<String, String> TYPE_LABELS = UtilMisc.toMap("sample_pricat", "SamplePricatTemplate", + "ofbiz_pricat", "OFBizPricatTemplate"); + private static final String MODULE = PricatParseExcelHtmlThread.class.getName(); + private static final String RESOURCE = "PricatUiLabels"; private LocalDispatcher dispatcher; private Delegator delegator; private List<FileItem> fileItems; @@ -83,19 +89,14 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { private String userLoginId; private GenericValue userLogin; private Map<String, String[]> facilities = new HashMap<>(); - private static final String RESOURCE = "PricatUiLabels"; private HttpSession session; - public static final String PRICAT_FILE = "__PRICAT_FILE__"; - - public static final String DEFAULT_PRICAT_TYPE = "sample_pricat"; private String selectedPricatType = DEFAULT_PRICAT_TYPE; - public static final Map<String, String> PricatTypeLabels = UtilMisc.toMap("sample_pricat", "SamplePricatTemplate", - "ofbiz_pricat", "OFBizPricatTemplate"); - private InterfacePricatParser pricatParser; private String thruReasonId = "EXCEL_IMPORT_SUCCESS"; + /** * Constructor, creates a new html thread. + * * @param request * @param response * @param name @@ -158,7 +159,8 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { getReport().println(UtilProperties.getMessage(RESOURCE, "NoPricatParserFor", getLocale()), InterfaceReport.FORMAT_ERROR); } else { pricatParser.parsePricatExcel(); - getReport().println(UtilProperties.getMessage(RESOURCE, "PricatParseCompleted", getLocale()), InterfaceReport.FORMAT_HEADLINE); + getReport().println(UtilProperties.getMessage(RESOURCE, "PricatParseCompleted", getLocale()), + InterfaceReport.FORMAT_HEADLINE); } } } else { @@ -192,7 +194,8 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { // 1 get facilities belong to current userLogin facilities = getCurrentUserLoginFacilities(); if (UtilValidate.isEmpty(facilities)) { - getReport().println(UtilProperties.getMessage(RESOURCE, "CurrentUserLoginNoFacility", new Object[]{userLoginId}, getLocale()), InterfaceReport.FORMAT_ERROR); + getReport().println(UtilProperties.getMessage(RESOURCE, "CurrentUserLoginNoFacility", new Object[]{userLoginId}, getLocale()), + InterfaceReport.FORMAT_ERROR); return false; } else { getReport().println(" ... " + UtilProperties.getMessage(RESOURCE, "ok", getLocale()), InterfaceReport.FORMAT_OK); @@ -220,11 +223,11 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { } } getReport().print(UtilProperties.getMessage(RESOURCE, "ExcelTemplateTypeSelected", getLocale()), InterfaceReport.FORMAT_DEFAULT); - if (PricatTypeLabels.containsKey(selectedPricatType)) { - getReport().print(UtilProperties.getMessage(RESOURCE, PricatTypeLabels.get(selectedPricatType), getLocale()), InterfaceReport.FORMAT_DEFAULT); + if (TYPE_LABELS.containsKey(selectedPricatType)) { + getReport().print(UtilProperties.getMessage(RESOURCE, TYPE_LABELS.get(selectedPricatType), getLocale()), InterfaceReport.FORMAT_DEFAULT); getReport().println(" ... " + UtilProperties.getMessage(RESOURCE, "ok", getLocale()), InterfaceReport.FORMAT_OK); } else { - getReport().println(UtilProperties.getMessage(RESOURCE, PricatTypeLabels.get(selectedPricatType), getLocale()), InterfaceReport.FORMAT_ERROR); + getReport().println(UtilProperties.getMessage(RESOURCE, TYPE_LABELS.get(selectedPricatType), getLocale()), InterfaceReport.FORMAT_ERROR); return false; } @@ -259,7 +262,8 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { orgConditions.add(EntityCondition.makeCondition("twoRoleTypeIdFrom", EntityOperator.EQUALS, "INTERNAL_ORGANIZATIO")); orgConditions.add(EntityCondition.makeCondition("twoRoleTypeIdTo", EntityOperator.EQUALS, "EMPLOYEE")); orgConditions.add(EntityCondition.makeCondition("twoRoleTypeIdTo", EntityOperator.EQUALS, "EMPLOYEE")); - List<GenericValue> organizations = delegator.findList("PartyRelationshipToFrom", EntityCondition.makeCondition(orgConditions), null, null, null, false); + List<GenericValue> organizations = delegator.findList("PartyRelationshipToFrom", EntityCondition.makeCondition(orgConditions), null, + null, null, false); Timestamp now = UtilDateTime.nowTimestamp(); organizations = EntityUtil.filterByDate(organizations, now, "twoFromDate", "twoThruDate", true); organizations = EntityUtil.filterByDate(organizations, now, "oneFromDate", "oneThruDate", true); @@ -275,7 +279,8 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { if (UtilValidate.isEmpty(ownerPartyConditions)) { return facilities; } - List<GenericValue> facilityValues = delegator.findList("Facility", EntityCondition.makeCondition(ownerPartyConditions, EntityOperator.OR), null, null, null, false); + List<GenericValue> facilityValues = delegator.findList("Facility", EntityCondition.makeCondition(ownerPartyConditions, + EntityOperator.OR), null, null, null, false); if (UtilValidate.isNotEmpty(facilityValues)) { int i = 1; for (GenericValue facilityValue : facilityValues) { @@ -283,8 +288,9 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { String facilityId = facilityValue.getString("facilityId"); if (!facilities.containsKey(facilityId)) { String facilityName = facilityValue.getString("facilityName"); - facilities.put(facilityId, new String[] {facilityName, facilityValue.getString("ownerPartyId")}); - getReport().println(UtilProperties.getMessage(RESOURCE, "FacilityFoundForCurrentUserLogin", new Object[]{String.valueOf(i), facilityName, facilityId}, getLocale()), InterfaceReport.FORMAT_NOTE); + facilities.put(facilityId, new String[]{facilityName, facilityValue.getString("ownerPartyId")}); + getReport().println(UtilProperties.getMessage(RESOURCE, "FacilityFoundForCurrentUserLogin", + new Object[]{String.valueOf(i), facilityName, facilityId}, getLocale()), InterfaceReport.FORMAT_NOTE); i++; } } @@ -307,13 +313,16 @@ public class PricatParseExcelHtmlThread extends AbstractReportThread { public synchronized long addExcelImportHistory() { long latestId = 1; try { - GenericValue latestHistoryValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId).orderBy("sequenceNum DESC").queryFirst(); + GenericValue latestHistoryValue = EntityQuery.use(delegator).from("ExcelImportHistory").where("userLoginId", userLoginId).orderBy( + "sequenceNum DESC").queryFirst(); if (UtilValidate.isNotEmpty(latestHistoryValue)) { latestId = latestHistoryValue.getLong("sequenceNum") + 1; } - GenericValue newHistoryValue = delegator.makeValue("ExcelImportHistory", UtilMisc.toMap("sequenceNum", latestId, "userLoginId", userLoginId, - "fileName", pricatFile == null ? "" : pricatFile.getName(), "statusId", isAlive() ? "EXCEL_IMPORTING" : "EXCEL_IMPORTED", - "fromDate", UtilDateTime.nowTimestamp(), "threadName", getName(), "logFileName", InterfacePricatParser.tempFilesFolder + userLoginId + "/" + latestId + ".log")); + GenericValue newHistoryValue = delegator.makeValue("ExcelImportHistory", UtilMisc.toMap("sequenceNum", latestId, "userLoginId", + userLoginId, + "fileName", pricatFile == null ? "" : pricatFile.getName(), "statusId", isAlive() ? "EXCEL_IMPORTING" : "EXCEL_IMPORTED", + "fromDate", UtilDateTime.nowTimestamp(), "threadName", getName(), "logFileName", + InterfacePricatParser.tempFilesFolder + userLoginId + "/" + latestId + ".log")); newHistoryValue.create(); } catch (GenericEntityException e) { Debug.logError(e, MODULE); diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java b/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java index ded8c4f..89acdcc 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/sample/SamplePricatParser.java @@ -55,19 +55,96 @@ import org.apache.poi.xssf.usermodel.XSSFWorkbook; */ public class SamplePricatParser extends AbstractPricatParser { + public static final Map<String, List<Object[]>> COL_NAMES_LIST = UtilMisc.toMap("V1.1", genExcelHeaderNames("V1.1")); + public static final int HEADER_ROW_NO = 4; private static final String MODULE = SamplePricatParser.class.getName(); - - public static final Map<String, List<Object[]>> ColNamesList = UtilMisc.toMap("V1.1", genExcelHeaderNames("V1.1")); - - public static final int headerRowNo = 4; - private List<String> headerColNames = new ArrayList<>(); - public SamplePricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, Map<String, String[]> facilities, File pricatFile, GenericValue userLogin) { + public SamplePricatParser(LocalDispatcher dispatcher, Delegator delegator, Locale locale, InterfaceReport report, + Map<String, String[]> facilities, File pricatFile, GenericValue userLogin) { super(dispatcher, delegator, locale, report, facilities, pricatFile, userLogin); } /** + * The Object[] have 4 elements, they are: + * 1. Header Label Name. + * 2. Cell data type to return. + * 3. Boolean value to indicate whether the column is required. + * 4. Boolean value to indicate whether the column is a price when cell data type is BigDecimal, this element is optional. + * + * @param version + * @return List of Object[] + */ + private static List<Object[]> genExcelHeaderNames(String version) { + switch (version) { + case "V1.1": + default: + return genExcelHeaderNamesV1(); + } + } + + /** + * Get V1.1 pricat excel header names and attributes. + * + * @return list of Object[] + */ + private static List<Object[]> genExcelHeaderNamesV1() { + List<Object[]> listHeaderName = new ArrayList<>(); + listHeaderName.add(new Object[]{"Facility Name", + CellType.STRING, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"FacilityId", + CellType.STRING, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"Category L1", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Category L2", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Category L3", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Category L4", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Brand", + CellType.STRING, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"Style No", + CellType.STRING, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"Product Name", + CellType.STRING, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"Color", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Size", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Barcode", + CellType.STRING, + Boolean.FALSE}); + listHeaderName.add(new Object[]{"Stock Qty", + CellType.NUMERIC, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"Average Cost", + CellType.NUMERIC, + Boolean.TRUE, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"List Price", + CellType.NUMERIC, + Boolean.TRUE, + Boolean.TRUE}); + listHeaderName.add(new Object[]{"Member Price", + CellType.NUMERIC, + Boolean.FALSE, + Boolean.TRUE}); + return listHeaderName; + } + + /** * Parse pricat excel file in xlsx format. */ public void parsePricatExcel(boolean writeFile) { @@ -77,7 +154,8 @@ public class SamplePricatParser extends AbstractPricatParser { FileInputStream is = new FileInputStream(pricatFile); // 2. use POI to load this bytes - report.print(UtilProperties.getMessage(RESOURCE, "ParsePricatFileStatement", new Object[] { pricatFile.getName() }, locale), InterfaceReport.FORMAT_DEFAULT); + report.print(UtilProperties.getMessage(RESOURCE, "ParsePricatFileStatement", new Object[]{pricatFile.getName()}, locale), + InterfaceReport.FORMAT_DEFAULT); try { workbook = new XSSFWorkbook(is); report.println(UtilProperties.getMessage(RESOURCE, "ok", locale), InterfaceReport.FORMAT_OK); @@ -148,7 +226,7 @@ public class SamplePricatParser extends AbstractPricatParser { } } } - + /** exists currency id */ @Override public boolean existsCurrencyId(XSSFSheet sheet) { report.print(UtilProperties.getMessage(RESOURCE, "StartCheckCurrencyId", locale), InterfaceReport.FORMAT_NOTE); @@ -163,32 +241,32 @@ public class SamplePricatParser extends AbstractPricatParser { try { GenericValue currencyUom = EntityQuery.use(delegator).from("Uom").where("uomId", currencyId).queryOne(); if (!"CURRENCY_MEASURE".equals(currencyUom.getString("uomTypeId"))) { - String errorMessage = UtilProperties.getMessage(RESOURCE, "CurrencyIdNotCurrency", new Object[] {currencyId}, locale); + String errorMessage = UtilProperties.getMessage(RESOURCE, "CurrencyIdNotCurrency", new Object[]{currencyId}, locale); report.println(errorMessage, InterfaceReport.FORMAT_ERROR); errorMessages.put(new CellReference(currencyIdCell), errorMessage); return false; } } catch (GenericEntityException e) { - String errorMessage = UtilProperties.getMessage(RESOURCE, "CurrencyIdNotFound", new Object[] {currencyId}, locale); + String errorMessage = UtilProperties.getMessage(RESOURCE, "CurrencyIdNotFound", new Object[]{currencyId}, locale); report.println(errorMessage, InterfaceReport.FORMAT_ERROR); errorMessages.put(new CellReference(currencyIdCell), errorMessage); return false; } - report.print(UtilProperties.getMessage(RESOURCE, "CurrencyIdIs", new Object[] {currencyId}, locale), InterfaceReport.FORMAT_NOTE); + report.print(UtilProperties.getMessage(RESOURCE, "CurrencyIdIs", new Object[]{currencyId}, locale), InterfaceReport.FORMAT_NOTE); report.println(" ... " + UtilProperties.getMessage(RESOURCE, "ok", locale), InterfaceReport.FORMAT_OK); } return true; } - + /** parse row by row */ @Override public void parseRowByRow(XSSFSheet sheet) { int rows = sheet.getLastRowNum() + 1; - List<Object[]> colNames = ColNamesList.get(pricatFileVersion); + List<Object[]> colNames = COL_NAMES_LIST.get(pricatFileVersion); int colNumber = colNames.size(); int emptyRowStart = -1; int emptyRowEnd = -1; - for (int i = headerRowNo + 1; i < rows; i++) { + for (int i = HEADER_ROW_NO + 1; i < rows; i++) { XSSFRow row = sheet.getRow(i); if (UtilValidate.isEmpty(row) || isEmptyRow(row, colNumber, false)) { if (emptyRowStart == -1) { @@ -227,13 +305,12 @@ public class SamplePricatParser extends AbstractPricatParser { report.println(" ... " + UtilProperties.getMessage(RESOURCE, "skipped", locale), InterfaceReport.FORMAT_NOTE); } } - /** * Check data according to business logic. If data is ok, store it. * @param row * @param cellContents * @return - * @throws GenericTransactionException + * @throws GenericTransactionException */ @Override public boolean parseCellContentsAndStore(XSSFRow row, List<Object> cellContents) throws GenericTransactionException { @@ -243,18 +320,18 @@ public class SamplePricatParser extends AbstractPricatParser { switch (pricatFileVersion) { case "V1.1": default: - return parseCellContentsAndStoreV1_X(row, cellContents); + return parseCellContentsAndStoreV1(row, cellContents); } } - - private boolean parseCellContentsAndStoreV1_X(XSSFRow row, List<Object> cellContents) throws GenericTransactionException { + /** parse cell contents and store */ + private boolean parseCellContentsAndStoreV1(XSSFRow row, List<Object> cellContents) throws GenericTransactionException { if (UtilValidate.isEmpty(cellContents)) { return false; } // 1. check if facilityId is in the facilities belong to the user, or if the name is correct for the id String facilityName = (String) getCellContent(cellContents, "Facility Name"); String facilityId = (String) getCellContent(cellContents, "FacilityId"); - if (!isFacilityOk(row, facilityName, facilityId)) + if (!isFacilityOk(row, facilityName, facilityId)) return false; // 2. get productCategoryId @@ -307,7 +384,8 @@ public class SamplePricatParser extends AbstractPricatParser { String barcode = (String) getCellContent(cellContents, "Barcode"); BigDecimal inventory = (BigDecimal) getCellContent(cellContents, "Stock Qty"); BigDecimal averageCost = (BigDecimal) getCellContent(cellContents, "Average Cost"); - String skuId = updateSku(row, productId, ownerPartyId, facilityId, barcode, inventory, colorId, color, dimensionId, dimension, listPrice, averageCost); + String skuId = updateSku(row, productId, ownerPartyId, facilityId, barcode, inventory, colorId, color, dimensionId, dimension, listPrice, + averageCost); if (UtilValidate.isEmpty(skuId)) { return false; } @@ -321,16 +399,16 @@ public class SamplePricatParser extends AbstractPricatParser { return true; } - - + /** update sku */ @Override public String updateSku(XSSFRow row, String productId, String ownerPartyId, String facilityId, String barcode, BigDecimal inventory, - String colorId, String color, String dimensionId, String dimension, BigDecimal listPrice, BigDecimal averageCost) { + String colorId, String color, String dimensionId, String dimension, BigDecimal listPrice, BigDecimal averageCost) { return "sampleSkuId"; } - + /** get product id */ @Override - public String getProductId(XSSFRow row, String brandId, String modelName, String productName, String productCategoryId, String ownerPartyId, BigDecimal listPrice) { + public String getProductId(XSSFRow row, String brandId, String modelName, String productName, String productCategoryId, String ownerPartyId, + BigDecimal listPrice) { return "sampleProductId"; } @@ -357,7 +435,8 @@ public class SamplePricatParser extends AbstractPricatParser { String theFacilityId = (String) facilities.keySet().toArray()[0]; String name = facilities.get(theFacilityId)[0]; if (!name.equals(facilityName)) { - String errorMessage = UtilProperties.getMessage(RESOURCE, "FacilityNameNotMatchId", new Object[]{theFacilityId, name, facilityName}, locale); + String errorMessage = UtilProperties.getMessage(RESOURCE, "FacilityNameNotMatchId", new Object[]{theFacilityId, name, + facilityName}, locale); report.println(); report.print(errorMessage, InterfaceReport.FORMAT_ERROR); XSSFCell cell = row.getCell(0); @@ -376,7 +455,8 @@ public class SamplePricatParser extends AbstractPricatParser { } else { String name = facilities.get(facilityId)[0]; if (!name.equals(facilityName)) { - String errorMessage = UtilProperties.getMessage(RESOURCE, "FacilityNameNotMatchId", new Object[]{facilityId, name, facilityName}, locale); + String errorMessage = UtilProperties.getMessage(RESOURCE, "FacilityNameNotMatchId", new Object[]{facilityId, name, facilityName}, + locale); report.println(); report.print(errorMessage, InterfaceReport.FORMAT_ERROR); XSSFCell cell = row.getCell(0); @@ -389,30 +469,36 @@ public class SamplePricatParser extends AbstractPricatParser { @Override public boolean isTableHeaderMatched(XSSFSheet sheet) { - List<Object[]> columnNames = ColNamesList.get(pricatFileVersion); - short cols = sheet.getRow(headerRowNo).getLastCellNum(); - report.print(UtilProperties.getMessage(RESOURCE, "StartCheckHeaderColNum", new Object[] {pricatFileVersion}, locale), InterfaceReport.FORMAT_NOTE); + List<Object[]> columnNames = COL_NAMES_LIST.get(pricatFileVersion); + short cols = sheet.getRow(HEADER_ROW_NO).getLastCellNum(); + report.print(UtilProperties.getMessage(RESOURCE, "StartCheckHeaderColNum", new Object[]{pricatFileVersion}, locale), + InterfaceReport.FORMAT_NOTE); if (cols != columnNames.size()) { - report.print(UtilProperties.getMessage(RESOURCE, "HeaderColNumNotMatch", new Object[] {String.valueOf(cols), String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_WARNING); + report.print(UtilProperties.getMessage(RESOURCE, "HeaderColNumNotMatch", new Object[]{String.valueOf(cols), + String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_WARNING); if (cols < columnNames.size()) { - report.println(UtilProperties.getMessage(RESOURCE, "HeaderColNumShortThanRequired", new Object[] {String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_ERROR); + report.println(UtilProperties.getMessage(RESOURCE, "HeaderColNumShortThanRequired", + new Object[]{String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_ERROR); return false; } else { - report.println(UtilProperties.getMessage(RESOURCE, "UseHeaderColNum", new Object[] {String.valueOf(columnNames.size())}, locale), InterfaceReport.FORMAT_WARNING); + report.println(UtilProperties.getMessage(RESOURCE, "UseHeaderColNum", new Object[]{String.valueOf(columnNames.size())}, locale), + InterfaceReport.FORMAT_WARNING); cols = (short) columnNames.size(); } } else { report.println(UtilProperties.getMessage(RESOURCE, "ok", locale), InterfaceReport.FORMAT_OK); } - report.print(UtilProperties.getMessage(RESOURCE, "StartCheckHeaderColLabel", new Object[] {pricatFileVersion}, locale), InterfaceReport.FORMAT_NOTE); + report.print(UtilProperties.getMessage(RESOURCE, "StartCheckHeaderColLabel", new Object[]{pricatFileVersion}, locale), + InterfaceReport.FORMAT_NOTE); boolean foundLabelNotMatch = false; for (int i = 0; i < cols; i++) { - String coltext = sheet.getRow(headerRowNo).getCell(i).getStringCellValue().trim(); + String coltext = sheet.getRow(HEADER_ROW_NO).getCell(i).getStringCellValue().trim(); headerColNames.add(coltext); Object[] versionColumn = columnNames.get(i); if (!coltext.equals(versionColumn[0])) { - report.println(UtilProperties.getMessage(RESOURCE, "HeaderColLabelNotMatch", new Object[] {String.valueOf(headerRowNo + 1), String.valueOf(i + 1), coltext, versionColumn[0]}, locale), InterfaceReport.FORMAT_ERROR); + report.println(UtilProperties.getMessage(RESOURCE, "HeaderColLabelNotMatch", new Object[]{String.valueOf(HEADER_ROW_NO + 1), + String.valueOf(i + 1), coltext, versionColumn[0]}, locale), InterfaceReport.FORMAT_ERROR); foundLabelNotMatch = true; } else { report.print(" " + coltext, InterfaceReport.FORMAT_NOTE); @@ -433,12 +519,13 @@ public class SamplePricatParser extends AbstractPricatParser { public boolean isVersionSupported(XSSFSheet sheet) { report.print(UtilProperties.getMessage(RESOURCE, "StartCheckPricatVersion", locale), InterfaceReport.FORMAT_NOTE); pricatFileVersion = sheet.getRow(2).getCell(0).getStringCellValue().trim(); - if (ColNamesList.containsKey(pricatFileVersion)) { + if (COL_NAMES_LIST.containsKey(pricatFileVersion)) { report.print(" " + pricatFileVersion + " ... ", InterfaceReport.FORMAT_NOTE); report.println(UtilProperties.getMessage(RESOURCE, "ok", locale), InterfaceReport.FORMAT_OK); } else { report.println(UtilProperties.getMessage(RESOURCE, "error", locale), InterfaceReport.FORMAT_ERROR); - report.println(UtilProperties.getMessage(RESOURCE, "PricatVersionNotSupport", new Object[] {pricatFileVersion}, locale), InterfaceReport.FORMAT_ERROR); + report.println(UtilProperties.getMessage(RESOURCE, "PricatVersionNotSupport", new Object[]{pricatFileVersion}, locale), + InterfaceReport.FORMAT_ERROR); return false; } return true; @@ -447,92 +534,17 @@ public class SamplePricatParser extends AbstractPricatParser { @Override public boolean containsDataRows(XSSFSheet sheet) { int rows = sheet.getPhysicalNumberOfRows(); - if (rows > headerRowNo + 1) { - report.println(UtilProperties.getMessage(RESOURCE, "PricatTableRows", new Object[] {String.valueOf(headerRowNo + 1), String.valueOf(rows - headerRowNo - 1), sheet.getSheetName()}, locale), InterfaceReport.FORMAT_NOTE); + if (rows > HEADER_ROW_NO + 1) { + report.println(UtilProperties.getMessage(RESOURCE, "PricatTableRows", new Object[]{String.valueOf(HEADER_ROW_NO + 1), + String.valueOf(rows - HEADER_ROW_NO - 1), sheet.getSheetName()}, locale), InterfaceReport.FORMAT_NOTE); } else { - report.println(UtilProperties.getMessage(RESOURCE, "PricatNoDataRows", new Object[] {sheet.getSheetName()}, locale), InterfaceReport.FORMAT_ERROR); + report.println(UtilProperties.getMessage(RESOURCE, "PricatNoDataRows", new Object[]{sheet.getSheetName()}, locale), + InterfaceReport.FORMAT_ERROR); return false; } return true; } - /** - * The Object[] have 4 elements, they are: - * 1. Header Label Name. - * 2. Cell data type to return. - * 3. Boolean value to indicate whether the column is required. - * 4. Boolean value to indicate whether the column is a price when cell data type is BigDecimal, this element is optional. - * @param version - * @return List of Object[] - */ - private static List<Object[]> genExcelHeaderNames(String version) { - switch (version) { - case "V1.1": - default: - return genExcelHeaderNamesV1_1(); - } - } - - /** - * Get V1.1 pricat excel header names and attributes. - * @return list of Object[] - */ - private static List<Object[]> genExcelHeaderNamesV1_1() { - List<Object[]> listHeaderName = new ArrayList<>(); - listHeaderName.add(new Object[] {"Facility Name", - CellType.STRING, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"FacilityId", - CellType.STRING, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"Category L1", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Category L2", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Category L3", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Category L4", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Brand", - CellType.STRING, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"Style No", - CellType.STRING, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"Product Name", - CellType.STRING, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"Color", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Size", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Barcode", - CellType.STRING, - Boolean.FALSE}); - listHeaderName.add(new Object[] {"Stock Qty", - CellType.NUMERIC, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"Average Cost", - CellType.NUMERIC, - Boolean.TRUE, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"List Price", - CellType.NUMERIC, - Boolean.TRUE, - Boolean.TRUE}); - listHeaderName.add(new Object[] {"Member Price", - CellType.NUMERIC, - Boolean.FALSE, - Boolean.TRUE}); - return listHeaderName; - } - @Override public void parsePricatExcel() { parsePricatExcel(true); @@ -540,9 +552,10 @@ public class SamplePricatParser extends AbstractPricatParser { /** * Get data by version definition. + * * @param row - * @param colNames - * @param size + * @param colNames + * @param size * @return */ @Override @@ -561,9 +574,11 @@ public class SamplePricatParser extends AbstractPricatParser { } if (cell == null) { if ((Boolean) colNames.get(i)[2] && (facilities.keySet().size() > 1 || (facilities.keySet().size() == 1 && i >= 2))) { - report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING); + report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[]{colNames.get(i)[0]}, locale), + InterfaceReport.FORMAT_WARNING); cell = row.createCell(i); - errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale)); + errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", + new Object[]{colNames.get(i)[0]}, locale)); foundError = true; results.add(null); continue; @@ -585,16 +600,19 @@ public class SamplePricatParser extends AbstractPricatParser { // do nothing } } - report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE); + report.print(((i == 0) ? "" : ", ") + cellValue, InterfaceReport.FORMAT_NOTE); } else { - report.print(((i == 0)?"":", ") + cellValue, InterfaceReport.FORMAT_NOTE); + report.print(((i == 0) ? "" : ", ") + cellValue, InterfaceReport.FORMAT_NOTE); } } else { - report.print(((i == 0)?"":","), InterfaceReport.FORMAT_NOTE); + report.print(((i == 0) ? "" : ","), InterfaceReport.FORMAT_NOTE); } - if ((Boolean) colNames.get(i)[2] && UtilValidate.isEmpty(cellValue) && (facilities.keySet().size() > 1 || (facilities.keySet().size() == 1 && i >= 2))) { - report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale), InterfaceReport.FORMAT_WARNING); - errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[] {colNames.get(i)[0]}, locale)); + if ((Boolean) colNames.get(i)[2] && UtilValidate.isEmpty(cellValue) && (facilities.keySet().size() > 1 + || (facilities.keySet().size() == 1 && i >= 2))) { + report.print(UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", new Object[]{colNames.get(i)[0]}, locale), + InterfaceReport.FORMAT_WARNING); + errorMessages.put(new CellReference(cell), UtilProperties.getMessage(RESOURCE, "ErrorColCannotEmpty", + new Object[]{colNames.get(i)[0]}, locale)); foundError = true; results.add(null); continue; @@ -667,6 +685,6 @@ public class SamplePricatParser extends AbstractPricatParser { @Override protected int getHeaderRowNo() { - return headerRowNo; + return HEADER_ROW_NO; } } diff --git a/pricat/src/main/java/org/apache/ofbiz/pricat/util/OFBizPricatUtil.java b/pricat/src/main/java/org/apache/ofbiz/pricat/util/OFBizPricatUtil.java index 9c03596..cad8b2b 100644 --- a/pricat/src/main/java/org/apache/ofbiz/pricat/util/OFBizPricatUtil.java +++ b/pricat/src/main/java/org/apache/ofbiz/pricat/util/OFBizPricatUtil.java @@ -70,7 +70,7 @@ public final class OFBizPricatUtil { XSSFVMLDrawing vml = (XSSFVMLDrawing) VMLDrawingMethod.invoke(sheet, true); /** for POI 4.0 and later, use: CTShape ctshape = vml.findCommentShape(rowNum, colNum); - */ + */ CTShape ctshape = (CTShape) FindCommentShapeMethod.invoke(vml, rowNum, colNum); ctshape.setType("#_x0000_t202"); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { diff --git a/projectmgr/src/main/java/org/apache/ofbiz/project/Various.java b/projectmgr/src/main/java/org/apache/ofbiz/project/Various.java index c126404..5d09fba 100644 --- a/projectmgr/src/main/java/org/apache/ofbiz/project/Various.java +++ b/projectmgr/src/main/java/org/apache/ofbiz/project/Various.java @@ -42,7 +42,8 @@ public class Various { GenericValue nextTask = assoc.getRelatedOne("ToWorkEffort", false); Timestamp newStartDate = task.getTimestamp("estimatedCompletionDate"); // start of next task the next day if (nextTask.get("estimatedStartDate") == null || nextTask.getTimestamp("estimatedStartDate").before(newStartDate)) { - nextTask.put("estimatedStartDate", UtilDateTime.addDaysToTimestamp(task.getTimestamp("estimatedCompletionDate"), 1)); // start of next task the next day + nextTask.put("estimatedStartDate", UtilDateTime.addDaysToTimestamp(task.getTimestamp("estimatedCompletionDate"), 1)); + // start of next task the next day nextTask.put("estimatedCompletionDate", calculateCompletionDate(nextTask, task.getTimestamp("estimatedCompletionDate"))); nextTask.store(); } diff --git a/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumEvents.java b/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumEvents.java index 9cf3b54..a22aef9 100644 --- a/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumEvents.java +++ b/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumEvents.java @@ -46,7 +46,7 @@ import org.apache.ofbiz.entity.condition.EntityOperator; import org.apache.ofbiz.entity.util.EntityQuery; /** - * ScrumEvents - Check The Warning Message. + * ScrumEvents - Check The Warning Message. */ public class ScrumEvents { @@ -67,11 +67,15 @@ public class ScrumEvents { try { // should be scrum team or scrum master. - EntityConditionList<EntityExpr> exprOrs = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SCRUM_TEAM"), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SCRUM_MASTER")), EntityOperator.OR); - EntityConditionList<EntityCondition> exprAnds = EntityCondition.makeCondition(UtilMisc.toList(exprOrs, EntityCondition.makeCondition("partyId", EntityOperator.EQUALS, partyId)), EntityOperator.AND); + EntityConditionList<EntityExpr> exprOrs = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("roleTypeId", + EntityOperator.EQUALS, "SCRUM_TEAM"), EntityCondition.makeCondition("roleTypeId", EntityOperator.EQUALS, "SCRUM_MASTER")), + EntityOperator.OR); + EntityConditionList<EntityCondition> exprAnds = EntityCondition.makeCondition(UtilMisc.toList(exprOrs, EntityCondition.makeCondition( + "partyId", EntityOperator.EQUALS, partyId)), EntityOperator.AND); List<GenericValue> partyRoleList = EntityQuery.use(delegator).from("PartyRole").where(exprAnds).queryList(); if (UtilValidate.isNotEmpty(partyRoleList)) { - List<GenericValue> timesheetList = EntityQuery.use(delegator).from("Timesheet").where("partyId", partyId, "statusId", "TIMESHEET_IN_PROCESS").cache(true).queryList(); + List<GenericValue> timesheetList = EntityQuery.use(delegator).from("Timesheet").where("partyId", partyId, "statusId", + "TIMESHEET_IN_PROCESS").cache(true).queryList(); if (UtilValidate.isNotEmpty(timesheetList)) { for (GenericValue timesheetMap : timesheetList) { String timesheetId = timesheetMap.getString("timesheetId"); @@ -83,9 +87,11 @@ public class ScrumEvents { //compare week and compare date if ((timesheetDate.compareTo(weekStart) <= 0) && (realTimeDate.compareTo(nowStartDate) < 0)) { //check time entry - List<GenericValue> timeEntryList = timesheetMap.getRelated("TimeEntry", UtilMisc.toMap("partyId", partyId, "timesheetId", timesheetId, "fromDate", realTimeDate), null, false); + List<GenericValue> timeEntryList = timesheetMap.getRelated("TimeEntry", UtilMisc.toMap("partyId", partyId, + "timesheetId", timesheetId, "fromDate", realTimeDate), null, false); //check EmplLeave - List<GenericValue> emplLeaveList = EntityQuery.use(delegator).from("EmplLeave").where("partyId", partyId, "fromDate", realTimeDate).cache(true).queryList(); + List<GenericValue> emplLeaveList = EntityQuery.use(delegator).from("EmplLeave").where("partyId", partyId, "fromDate" + , realTimeDate).cache(true).queryList(); if (UtilValidate.isEmpty(timeEntryList) && UtilValidate.isEmpty(emplLeaveList)) { Map<String, Object> noEntryMap = new HashMap<>(); noEntryMap.put("timesheetId", timesheetId); @@ -114,7 +120,8 @@ public class ScrumEvents { } String warningData = warningDataBuffer.toString(); Debug.logInfo("The following time sheet no time entry: [" + warningData + "]", MODULE); - request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage("scrumUiLabels", "ScrumTimesheetWarningMessage", UtilMisc.toMap("warningMessage", warningData), UtilHttp.getLocale(request))); + request.setAttribute("_ERROR_MESSAGE_", UtilProperties.getMessage("scrumUiLabels", "ScrumTimesheetWarningMessage", UtilMisc.toMap( + "warningMessage", warningData), UtilHttp.getLocale(request))); } return "success"; } diff --git a/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumServices.java b/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumServices.java index ca8f614..8bff3f8 100644 --- a/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumServices.java +++ b/scrum/src/main/java/org/apache/ofbiz/scrum/ScrumServices.java @@ -43,6 +43,7 @@ import org.apache.ofbiz.service.DispatchContext; import org.apache.ofbiz.service.GenericServiceException; import org.apache.ofbiz.service.LocalDispatcher; import org.apache.ofbiz.service.ServiceUtil; + /** * Scrum Services */ @@ -50,6 +51,7 @@ public class ScrumServices { private static final String MODULE = ScrumServices.class.getName(); private static final String RESOURCE = "scrumUiLabels"; + public static Map<String, Object> linkToProduct(DispatchContext ctx, Map<String, ? extends Object> context) { Delegator delegator = ctx.getDelegator(); Locale locale = (Locale) context.get("locale"); @@ -59,7 +61,8 @@ public class ScrumServices { if (UtilValidate.isNotEmpty(communicationEventId)) { try { - GenericValue communicationEvent = EntityQuery.use(delegator).from("CommunicationEvent").where("communicationEventId", communicationEventId).queryOne(); + GenericValue communicationEvent = EntityQuery.use(delegator).from("CommunicationEvent").where("communicationEventId", + communicationEventId).queryOne(); if (UtilValidate.isNotEmpty(communicationEvent)) { String subject = communicationEvent.getString("subject"); if (UtilValidate.isNotEmpty(subject)) { @@ -74,24 +77,30 @@ public class ScrumServices { // Debug.logInfo("=======================Product id found in subject: >>" + custRequestId + "<<", MODULE); GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne(); if (product != null) { - GenericValue communicationEventProductMap = EntityQuery.use(delegator).from("CommunicationEventProduct").where("productId", productId, "communicationEventId", communicationEventId).queryOne(); + GenericValue communicationEventProductMap = EntityQuery.use(delegator).from("CommunicationEventProduct").where( + "productId", productId, "communicationEventId", communicationEventId).queryOne(); if (UtilValidate.isEmpty(communicationEventProductMap)) { - GenericValue communicationEventProduct = delegator.makeValue("CommunicationEventProduct", UtilMisc.toMap("productId", productId, "communicationEventId", communicationEventId)); + GenericValue communicationEventProduct = delegator.makeValue("CommunicationEventProduct", UtilMisc.toMap( + "productId", productId, "communicationEventId", communicationEventId)); communicationEventProduct.create(); } try { - GenericValue productRoleMap = EntityQuery.use(delegator).from("ProductRole").where("productId", productId, "partyId", communicationEvent.getString("partyIdFrom"), "roleTypeId", "PRODUCT_OWNER").queryFirst(); + GenericValue productRoleMap = EntityQuery.use(delegator).from("ProductRole").where("productId", productId, + "partyId", communicationEvent.getString("partyIdFrom"), "roleTypeId", "PRODUCT_OWNER").queryFirst(); GenericValue userLogin = (GenericValue) context.get("userLogin"); // also close the incoming communication event if (UtilValidate.isNotEmpty(productRoleMap)) { - Map<String, Object> result = dispatcher.runSync("setCommunicationEventStatus", UtilMisc.<String, Object>toMap("communicationEventId", communicationEvent.getString("communicationEventId"), "statusId", "COM_COMPLETE", "userLogin", userLogin)); + Map<String, Object> result = dispatcher.runSync("setCommunicationEventStatus", + UtilMisc.<String, Object>toMap("communicationEventId", communicationEvent.getString( + "communicationEventId"), "statusId", "COM_COMPLETE", "userLogin", userLogin)); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); } } } catch (GenericServiceException e1) { Debug.logError(e1, "Error calling updating commevent status", MODULE); - return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ScrumErrorCallingUpdatingCommeventStatus", locale) + e1.toString()); + return ServiceUtil.returnError(UtilProperties.getMessage(RESOURCE, "ScrumErrorCallingUpdatingCommeventStatus", + locale) + e1.toString()); } } else { Debug.logInfo("Product id " + productId + " found in subject but not in database", MODULE); @@ -117,7 +126,7 @@ public class ScrumServices { * <p> * Use for view Scrum Revision * - * @param ctx The DispatchContext that this service is operating in + * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters. */ @@ -162,7 +171,7 @@ public class ScrumServices { * <p> * Use for retrieve the missing data of the Revision * - * @param ctx The DispatchContext that this service is operating in + * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service, the output parameters. */ @@ -205,11 +214,13 @@ public class ScrumServices { taskId = taskInfo.substring(j - 4, j + 1); } } - String revisionLink = repositoryRoot.substring(repositoryRoot.lastIndexOf("svn/") + 4, repositoryRoot.length()) + "&revision=" + i; - Debug.logInfo("Revision Link ============== >>>>>>>>>>> "+ revisionLink, MODULE); + String revisionLink = repositoryRoot.substring(repositoryRoot.lastIndexOf("svn/") + 4, repositoryRoot.length()) + + "&revision=" + i; + Debug.logInfo("Revision Link ============== >>>>>>>>>>> " + revisionLink, MODULE); if (UtilValidate.isNotEmpty(taskId)) { String version = "R" + i; - List<GenericValue> workeffContentList = EntityQuery.use(delegator).from("WorkEffortAndContentDataResource").where("contentName", version.trim(), "drObjectInfo", revisionLink.trim()).queryList(); + List<GenericValue> workeffContentList = EntityQuery.use(delegator).from("WorkEffortAndContentDataResource").where( + "contentName", version.trim(), "drObjectInfo", revisionLink.trim()).queryList(); List<EntityCondition> exprsAnd = new LinkedList<>(); exprsAnd.add(EntityCondition.makeCondition("workEffortId", EntityOperator.EQUALS, taskId)); @@ -229,7 +240,7 @@ public class ScrumServices { inputMap.put("revisionLink", revisionLink); inputMap.put("revisionDescription", taskInfo); inputMap.put("userLogin", userLogin); - Debug.logInfo("inputMap ============== >>>>>>>>>>> "+ inputMap, MODULE); + Debug.logInfo("inputMap ============== >>>>>>>>>>> " + inputMap, MODULE); result = dispatcher.runSync("updateScrumRevision", inputMap); if (ServiceUtil.isError(result)) { return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result)); @@ -252,7 +263,7 @@ public class ScrumServices { * <p> * Use for remove duplicate scrum revision * - * @param ctx The DispatchContext that this service is operating in + * @param ctx The DispatchContext that this service is operating in * @param context Map containing the input parameters * @return Map with the result of the service. */ @@ -267,9 +278,10 @@ public class ScrumServices { exprsAnd.add(EntityCondition.makeCondition("workEffortContentTypeId", EntityOperator.EQUALS, "TASK_SUB_INFO")); exprsAnd.add(EntityCondition.makeCondition("contentTypeId", EntityOperator.EQUALS, "DOCUMENT")); exprsAnd.add(EntityCondition.makeCondition("drObjectInfo", EntityOperator.LIKE, revisionLink + "%")); - List<GenericValue> workEffortDataResourceList = EntityQuery.use(delegator).from("WorkEffortAndContentDataResource").where(exprsAnd).queryList(); + List<GenericValue> workEffortDataResourceList = + EntityQuery.use(delegator).from("WorkEffortAndContentDataResource").where(exprsAnd).queryList(); if (UtilValidate.isNotEmpty(workEffortDataResourceList)) { - Debug.logInfo("Total Content Size ============== >>>>>>>>>>> "+ workEffortDataResourceList.size(), MODULE); + Debug.logInfo("Total Content Size ============== >>>>>>>>>>> " + workEffortDataResourceList.size(), MODULE); Set<String> keys = new HashSet<>(); Set<GenericValue> exclusions = new HashSet<>(); for (GenericValue workEffort : workEffortDataResourceList) { @@ -281,12 +293,14 @@ public class ScrumServices { } } // remove the duplicate entry - Debug.logInfo("Remove size ============== >>>>>>>>>>> "+ exclusions.size(), MODULE); + Debug.logInfo("Remove size ============== >>>>>>>>>>> " + exclusions.size(), MODULE); if (UtilValidate.isNotEmpty(exclusions)) { for (GenericValue contentResourceMap : exclusions) { - Debug.logInfo("Remove contentId ============== >>>>>>>>>>> "+ contentResourceMap.getString("contentId"), MODULE); - GenericValue dataResourceMap = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", contentResourceMap.getString("dataResourceId")).queryOne(); - GenericValue contentMap = EntityQuery.use(delegator).from("Content").where("contentId", contentResourceMap.getString("contentId")).queryOne(); + Debug.logInfo("Remove contentId ============== >>>>>>>>>>> " + contentResourceMap.getString("contentId"), MODULE); + GenericValue dataResourceMap = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", + contentResourceMap.getString("dataResourceId")).queryOne(); + GenericValue contentMap = EntityQuery.use(delegator).from("Content").where("contentId", contentResourceMap.getString( + "contentId")).queryOne(); contentMap.removeRelated("WorkEffortContent"); contentMap.removeRelated("ContentRole"); contentMap.remove(); diff --git a/solr/src/main/java/org/apache/ofbiz/solr/CategoryUtil.java b/solr/src/main/java/org/apache/ofbiz/solr/CategoryUtil.java index a09e439..8aa7a01 100644 --- a/solr/src/main/java/org/apache/ofbiz/solr/CategoryUtil.java +++ b/solr/src/main/java/org/apache/ofbiz/solr/CategoryUtil.java @@ -46,7 +46,7 @@ public final class CategoryUtil { /** * Gets catalog IDs for specified product category. * <p> - * This method is a supplement to CatalogWorker methods. + * This method is a supplement to CatalogWorker methods. */ public static List<String> getCatalogIdsByCategoryId(Delegator delegator, String productCategoryId) { List<String> catalogIds = new ArrayList<>(); diff --git a/solr/src/main/java/org/apache/ofbiz/solr/control/OFBizSolrLoginWorker.java b/solr/src/main/java/org/apache/ofbiz/solr/control/OFBizSolrLoginWorker.java index ef2d0d6..552e048 100644 --- a/solr/src/main/java/org/apache/ofbiz/solr/control/OFBizSolrLoginWorker.java +++ b/solr/src/main/java/org/apache/ofbiz/solr/control/OFBizSolrLoginWorker.java @@ -29,7 +29,7 @@ import org.apache.ofbiz.webapp.control.LoginWorker; */ public final class OFBizSolrLoginWorker { - private final static String MODULE = OFBizSolrLoginWorker.class.getName(); + private static final String MODULE = OFBizSolrLoginWorker.class.getName(); protected OFBizSolrLoginWorker() { } /** diff --git a/solr/src/main/java/org/apache/ofbiz/solr/webapp/OFBizSolrContextFilter.java b/solr/src/main/java/org/apache/ofbiz/solr/webapp/OFBizSolrContextFilter.java index 3484d30..28573ae 100644 --- a/solr/src/main/java/org/apache/ofbiz/solr/webapp/OFBizSolrContextFilter.java +++ b/solr/src/main/java/org/apache/ofbiz/solr/webapp/OFBizSolrContextFilter.java @@ -60,6 +60,37 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { private static final String MODULE = OFBizSolrContextFilter.class.getName(); private static final String RESOURCE = "SolrUiLabels"; + private static void sendJsonHeaderMessage(HttpServletRequest httpRequest, HttpServletResponse httpResponse, + GenericValue userLogin, String notLoginMessage, String noPermissionMessage, Locale locale) + throws IOException { + httpResponse.setContentType("application/json"); + MapToJSON mapToJson = new MapToJSON(); + Map<String, Object> responseHeader = new HashMap<>(); + JSON json; + String message = ""; + + try (OutputStream os = httpResponse.getOutputStream()) { + if (UtilValidate.isEmpty(userLogin)) { + httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); + responseHeader.put("status", HttpServletResponse.SC_UNAUTHORIZED); + message = UtilProperties.getMessage(RESOURCE, notLoginMessage, locale); + responseHeader.put("message", message); + } else { + httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); + responseHeader.put("status", HttpServletResponse.SC_FORBIDDEN); + message = UtilProperties.getMessage(RESOURCE, noPermissionMessage, locale); + responseHeader.put("message", message); + } + json = mapToJson.convert(UtilMisc.toMap("responseHeader", (Object) responseHeader)); + os.write(json.toString().getBytes()); + os.flush(); + Debug.logInfo("[" + httpRequest.getRequestURI().substring(1) + "(Domain:" + httpRequest.getScheme() + "://" + httpRequest.getServerName() + + ")] Request error: " + message, MODULE); + } catch (ConversionException e) { + Debug.logError("Error while converting responseHeader map to JSON.", MODULE); + } + } + /** Init */ @Override public void init(FilterConfig config) throws ServletException { Properties props = System.getProperties(); @@ -68,7 +99,7 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { props.setProperty("solr/home", UtilProperties.getPropertyValue("solrconfig", "solr/home")); super.init(config); } - + /** Do filter */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; @@ -77,7 +108,7 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { // check if the request is from an authorized user String servletPath = httpRequest.getServletPath(); - if (UtilValidate.isNotEmpty(servletPath) && (servletPath.startsWith("/admin/") || servletPath.endsWith("/update") + if (UtilValidate.isNotEmpty(servletPath) && (servletPath.startsWith("/admin/") || servletPath.endsWith("/update") || servletPath.endsWith("/update/json") || servletPath.endsWith("/update/csv") || servletPath.endsWith("/update/extract") || servletPath.endsWith("/replication") || servletPath.endsWith("/file") || servletPath.endsWith("/file/"))) { HttpSession session = httpRequest.getSession(); @@ -98,7 +129,8 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { } else { message = UtilProperties.getMessage(RESOURCE, "SolrErrorNoManagePermission", locale); } - Debug.logInfo("[" + httpRequest.getRequestURI().substring(1) + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request error: " + message, MODULE); + Debug.logInfo("[" + httpRequest.getRequestURI().substring(1) + "(Domain:" + request.getScheme() + "://" + request.getServerName() + + ")] Request error: " + message, MODULE); } catch (ConversionException e) { Debug.logError("Error while converting Solr ofbizLogin map to JSON.", MODULE); } finally { @@ -107,7 +139,8 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { } } return; - } else if (servletPath.endsWith("/update") || servletPath.endsWith("/update/json") || servletPath.endsWith("/update/csv") || servletPath.endsWith("/update/extract")) { + } else if (servletPath.endsWith("/update") || servletPath.endsWith("/update/json") || servletPath.endsWith("/update/csv") + || servletPath.endsWith("/update/extract")) { // NOTE: the update requests are defined in an index's solrconfig.xml // get the Solr index name from the request if (UtilValidate.isEmpty(userLogin) || !LoginWorker.hasBasePermission(userLogin, httpRequest)) { @@ -117,13 +150,15 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { } else if (servletPath.endsWith("/replication")) { // get the Solr index name from the request if (UtilValidate.isEmpty(userLogin) || !LoginWorker.hasBasePermission(userLogin, httpRequest)) { - sendJsonHeaderMessage(httpRequest, httpResponse, userLogin, "SolrErrorReplicateLoginFirst", "SolrErrorNoReplicatePermission", locale); + sendJsonHeaderMessage(httpRequest, httpResponse, userLogin, "SolrErrorReplicateLoginFirst", "SolrErrorNoReplicatePermission", + locale); return; } } else if (servletPath.endsWith("/file") || servletPath.endsWith("/file/")) { // get the Solr index name from the request if (UtilValidate.isEmpty(userLogin) || !LoginWorker.hasBasePermission(userLogin, httpRequest)) { - sendJsonHeaderMessage(httpRequest, httpResponse, userLogin, "SolrErrorViewFileLoginFirst", "SolrErrorNoViewFilePermission", locale); + sendJsonHeaderMessage(httpRequest, httpResponse, userLogin, "SolrErrorViewFileLoginFirst", "SolrErrorNoViewFilePermission", + locale); return; } } @@ -134,20 +169,23 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { if (httpRequest.getRequestURI() != null) { rname = httpRequest.getRequestURI().substring(1); } - if (rname != null && (rname.endsWith(".css") || rname.endsWith(".js") || rname.endsWith(".ico") || rname.endsWith(".html") || rname.endsWith(".png") || rname.endsWith(".jpg") || rname.endsWith(".gif"))) { + if (rname != null && (rname.endsWith(".css") || rname.endsWith(".js") || rname.endsWith(".ico") || rname.endsWith(".html") + || rname.endsWith(".png") || rname.endsWith(".jpg") || rname.endsWith(".gif"))) { rname = null; } UtilTimer timer = null; if (Debug.timingOn() && rname != null) { timer = new UtilTimer(); timer.setLog(true); - timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Begun, encoding=[" + charset + "]", MODULE); + timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Begun, encoding=[" + + charset + "]", MODULE); } // NOTE: there's a chain.doFilter in SolrDispatchFilter's doFilter super.doFilter(request, response, chain); - if (Debug.timingOn() && rname != null) timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Done", MODULE); + if (Debug.timingOn() && rname != null) + timer.timerString("[" + rname + "(Domain:" + request.getScheme() + "://" + request.getServerName() + ")] Request Done", MODULE); } - + /** Destroy */ @Override public void destroy() { super.destroy(); @@ -155,6 +193,7 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { /** * Override this to change CoreContainer initialization + * * @return a CoreContainer to hold this server's cores */ @Override @@ -163,7 +202,7 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { try { nodeConfig = loadNodeConfig(solrHome, extraProperties); } catch (SolrException e) { -// nodeConfig = loadNodeConfig("plugins/solr/home", extraProperties); + // nodeConfig = loadNodeConfig("plugins/solr/home", extraProperties); Path path = Paths.get("plugins/solr/home"); nodeConfig = loadNodeConfig(path, extraProperties); } @@ -171,34 +210,5 @@ public class OFBizSolrContextFilter extends SolrDispatchFilter { cores.load(); return cores; } - private static void sendJsonHeaderMessage(HttpServletRequest httpRequest, HttpServletResponse httpResponse, - GenericValue userLogin, String notLoginMessage, String noPermissionMessage, Locale locale) - throws IOException { - httpResponse.setContentType("application/json"); - MapToJSON mapToJson = new MapToJSON(); - Map<String, Object> responseHeader = new HashMap<>(); - JSON json; - String message = ""; - - try (OutputStream os = httpResponse.getOutputStream()) { - if (UtilValidate.isEmpty(userLogin)) { - httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); - responseHeader.put("status", HttpServletResponse.SC_UNAUTHORIZED); - message = UtilProperties.getMessage(RESOURCE, notLoginMessage, locale); - responseHeader.put("message", message); - } else { - httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN); - responseHeader.put("status", HttpServletResponse.SC_FORBIDDEN); - message = UtilProperties.getMessage(RESOURCE, noPermissionMessage, locale); - responseHeader.put("message", message); - } - json = mapToJson.convert(UtilMisc.toMap("responseHeader", (Object) responseHeader)); - os.write(json.toString().getBytes()); - os.flush(); - Debug.logInfo("[" + httpRequest.getRequestURI().substring(1) + "(Domain:" + httpRequest.getScheme() + "://" + httpRequest.getServerName() + ")] Request error: " + message, MODULE); - } catch (ConversionException e) { - Debug.logError("Error while converting responseHeader map to JSON.", MODULE); - } - } } diff --git a/webpos/src/main/java/org/apache/ofbiz/webpos/WebPosEvents.java b/webpos/src/main/java/org/apache/ofbiz/webpos/WebPosEvents.java index 8517ea4..c80cf03 100755 --- a/webpos/src/main/java/org/apache/ofbiz/webpos/WebPosEvents.java +++ b/webpos/src/main/java/org/apache/ofbiz/webpos/WebPosEvents.java @@ -112,7 +112,8 @@ public class WebPosEvents { } if (UtilValidate.isNotEmpty(posTerminalId)) { - webPosSession = new WebPosSession(posTerminalId, null, userLogin, request.getLocale(), productStoreId, facilityId, currencyUomId, delegator, dispatcher, cart); + webPosSession = new WebPosSession(posTerminalId, null, userLogin, request.getLocale(), productStoreId, facilityId, currencyUomId, + delegator, dispatcher, cart); session.setAttribute("webPosSession", webPosSession); } else { Debug.logError("PosTerminalId is empty cannot create a webPosSession", MODULE); @@ -146,7 +147,8 @@ public class WebPosEvents { ShoppingCartEvents.clearCart(request, response); if (UtilValidate.isNotEmpty(webPosSession)) { - String autoSaveListId = ShoppingListEvents.getAutoSaveListId(webPosSession.getDelegator(), webPosSession.getDispatcher(), null, webPosSession.getUserLogin(), webPosSession.getProductStoreId()); + String autoSaveListId = ShoppingListEvents.getAutoSaveListId(webPosSession.getDelegator(), webPosSession.getDispatcher(), null, + webPosSession.getUserLogin(), webPosSession.getProductStoreId()); ShoppingListEvents.clearListInfo(webPosSession.getDelegator(), autoSaveListId); } return "success"; @@ -184,8 +186,8 @@ public class WebPosEvents { if (UtilValidate.isNotEmpty(featureSet)) { request.setAttribute("featureSet", featureSet); try { - variantTreeMap = dispatcher.runSync("getProductVariantTree", - UtilMisc.toMap("productId", productId, "featureOrder", featureSet, "productStoreId", productStoreId)); + variantTreeMap = dispatcher.runSync("getProductVariantTree", + UtilMisc.toMap("productId", productId, "featureOrder", featureSet, "productStoreId", productStoreId)); if (ServiceUtil.isError(variantTreeMap)) { String errorMessage = ServiceUtil.getErrorMessage(variantTreeMap); request.setAttribute("_ERROR_MESSAGE_", errorMessage); @@ -199,9 +201,10 @@ public class WebPosEvents { List<String> featureOrder = new LinkedList<>(featureSet); for (int i = 0; i < featureOrder.size(); i++) { String featureKey = featureOrder.get(i); - GenericValue featureValue = EntityQuery.use(delegator).from("ProductFeatureType").where("productFeatureTypeId", featureOrder.get(i)).cache().queryOne(); - if (featureValue != null && - UtilValidate.isNotEmpty(featureValue.get("description"))) { + GenericValue featureValue = EntityQuery.use(delegator).from("ProductFeatureType").where( + "productFeatureTypeId", featureOrder.get(i)).cache().queryOne(); + if (featureValue != null + && UtilValidate.isNotEmpty(featureValue.get("description"))) { featureTypes.put(featureKey, featureValue.get("description")); } else { featureTypes.put(featureKey, featureValue.get("productFeatureTypeId")); diff --git a/webpos/src/main/java/org/apache/ofbiz/webpos/search/WebPosSearch.java b/webpos/src/main/java/org/apache/ofbiz/webpos/search/WebPosSearch.java index fae3dfc..f69142c 100644 --- a/webpos/src/main/java/org/apache/ofbiz/webpos/search/WebPosSearch.java +++ b/webpos/src/main/java/org/apache/ofbiz/webpos/search/WebPosSearch.java @@ -57,12 +57,14 @@ public class WebPosSearch { // search by product name if (UtilValidate.isNotEmpty(searchByProductName)) { searchByProductName = searchByProductName.toUpperCase().trim(); - andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("productName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + searchByProductName + "%"))); + andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("productName"), EntityOperator.LIKE, + EntityFunction.UPPER("%" + searchByProductName + "%"))); } // search by description if (UtilValidate.isNotEmpty(searchByProductDescription)) { searchByProductDescription = searchByProductDescription.toUpperCase().trim(); - andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("description"), EntityOperator.LIKE, EntityFunction.UPPER("%" + searchByProductDescription + "%"))); + andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("description"), EntityOperator.LIKE, + EntityFunction.UPPER("%" + searchByProductDescription + "%"))); } // search by good identification if (UtilValidate.isNotEmpty(searchByProductIdValue)) { @@ -141,8 +143,10 @@ public class WebPosSearch { } andExprs.add(EntityCondition.makeCondition("partyTypeId", EntityOperator.EQUALS, "PERSON")); andExprs.add(EntityCondition.makeCondition("contactMechTypeId", EntityOperator.EQUALS, "POSTAL_ADDRESS")); - if (UtilValidate.isNotEmpty(shippingLocation) && "N".equalsIgnoreCase(shippingLocation) && UtilValidate.isNotEmpty(billingLocation) && "N".equalsIgnoreCase(billingLocation)) { - andExprs.add(EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.IN, UtilMisc.toList("SHIPPING_LOCATION", "BILLING_LOCATION"))); + if (UtilValidate.isNotEmpty(shippingLocation) && "N".equalsIgnoreCase(shippingLocation) && UtilValidate.isNotEmpty(billingLocation) + && "N".equalsIgnoreCase(billingLocation)) { + andExprs.add(EntityCondition.makeCondition("contactMechPurposeTypeId", EntityOperator.IN, UtilMisc.toList("SHIPPING_LOCATION", + "BILLING_LOCATION"))); } mainCond = EntityCondition.makeCondition(andExprs, EntityOperator.AND); orderBy.add("lastName"); @@ -150,12 +154,14 @@ public class WebPosSearch { // search by last name if (UtilValidate.isNotEmpty(searchByPartyLastName)) { searchByPartyLastName = searchByPartyLastName.toUpperCase().trim(); - andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("lastName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + searchByPartyLastName + "%"))); + andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("lastName"), EntityOperator.LIKE, + EntityFunction.UPPER("%" + searchByPartyLastName + "%"))); } // search by first name if (UtilValidate.isNotEmpty(searchByPartyFirstName)) { searchByPartyFirstName = searchByPartyFirstName.toUpperCase().trim(); - andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("firstName"), EntityOperator.LIKE, EntityFunction.UPPER("%" + searchByPartyFirstName + "%"))); + andExprs.add(EntityCondition.makeCondition(EntityFunction.UPPER_FIELD("firstName"), EntityOperator.LIKE, + EntityFunction.UPPER("%" + searchByPartyFirstName + "%"))); } // search by party identification if (UtilValidate.isNotEmpty(searchByPartyIdValue)) { @@ -175,4 +181,4 @@ public class WebPosSearch { result.put("partiesList", parties); return result; } -} \ No newline at end of file +} diff --git a/webpos/src/main/java/org/apache/ofbiz/webpos/transaction/WebPosTransaction.java b/webpos/src/main/java/org/apache/ofbiz/webpos/transaction/WebPosTransaction.java index 2fb033e..7d48161 100755 --- a/webpos/src/main/java/org/apache/ofbiz/webpos/transaction/WebPosTransaction.java +++ b/webpos/src/main/java/org/apache/ofbiz/webpos/transaction/WebPosTransaction.java @@ -24,6 +24,8 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import groovy.transform.AnnotationCollector; +import org.apache.commons.math3.analysis.solvers.AllowedSolution; import org.apache.ofbiz.base.util.Debug; import org.apache.ofbiz.base.util.GeneralException; import org.apache.ofbiz.base.util.UtilDateTime; @@ -96,7 +98,6 @@ public class WebPosTransaction { Debug.logInfo("Created WebPosTransaction [" + this.transactionId + "]", MODULE); } - public String getUserLoginId() { return webPosSession.getUserLoginId(); } @@ -309,7 +310,7 @@ public class WebPosTransaction { } public String getPaymentMethodTypeId(int index) { - return getCart().getPaymentInfo(index).paymentMethodTypeId; + return getCart().getPaymentInfo(index).getPaymentMethodTypeId(); } public int checkPaymentMethodType(String paymentMethodTypeId) { @@ -446,8 +447,7 @@ public class WebPosTransaction { public void setPaymentRefNum(int paymentIndex, String refNum, String authCode) { Debug.logInfo("setting payment index reference number " + paymentIndex + " / " + refNum + " / " + authCode, MODULE); ShoppingCart.CartPaymentInfo inf = getCart().getPaymentInfo(paymentIndex); - inf.refNum[0] = refNum; - inf.refNum[1] = authCode; + inf.setRefNum(refNum, authCode); } /* CVV2 code should be entered when a card can't be swiped */ @@ -455,8 +455,8 @@ public class WebPosTransaction { Debug.logInfo("setting payment security code " + paymentId, MODULE); int paymentIndex = getCart().getPaymentInfoIndex(paymentId, refNum); ShoppingCart.CartPaymentInfo inf = getCart().getPaymentInfo(paymentIndex); - inf.securityCode = securityCode; - inf.isSwiped = false; + inf.setSecurityCode(securityCode); + inf.setIsSwiped(false); } /* Track2 data should be sent to processor when a card is swiped. */ @@ -464,8 +464,8 @@ public class WebPosTransaction { Debug.logInfo("setting payment security code " + paymentId, MODULE); int paymentIndex = getCart().getPaymentInfoIndex(paymentId, refNum); ShoppingCart.CartPaymentInfo inf = getCart().getPaymentInfo(paymentIndex); - inf.securityCode = securityCode; - inf.isSwiped = true; + inf.setSecurityCode(securityCode); + inf.setIsSwiped(true); } /* Postal code should be entered when a card can't be swiped */ @@ -473,7 +473,7 @@ public class WebPosTransaction { Debug.logInfo("setting payment security code " + paymentId, MODULE); int paymentIndex = getCart().getPaymentInfoIndex(paymentId, refNum); ShoppingCart.CartPaymentInfo inf = getCart().getPaymentInfo(paymentIndex); - inf.postalCode = postalCode; + inf.setPostalCode(postalCode); } public BigDecimal getTaxTotal() { @@ -508,6 +508,7 @@ public class WebPosTransaction { return result; } + /** get cart */ public ShoppingCart getCart() { return webPosSession.getCart(); } |
Free forum by Nabble | Edit this page |