Search in sources :

Example 56 with EntityListIterator

use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.

the class ProductUtilServices method attachProductFeaturesToCategory.

/**
 * Get all features associated with products and associate them with a feature group attached to the category for each feature type;
 * includes products associated with this category only, but will also associate all feature groups of sub-categories with this category, optionally calls this method for all sub-categories too
 */
public static void attachProductFeaturesToCategory(String productCategoryId, Set<String> productFeatureTypeIdsToInclude, Set<String> productFeatureTypeIdsToExclude, Delegator delegator, boolean doSubCategories, Timestamp nowTimestamp) throws GenericEntityException {
    if (nowTimestamp == null) {
        nowTimestamp = UtilDateTime.nowTimestamp();
    }
    // do sub-categories first so all feature groups will be in place
    List<GenericValue> subCategoryList = EntityQuery.use(delegator).from("ProductCategoryRollup").where("parentProductCategoryId", productCategoryId).queryList();
    if (doSubCategories) {
        for (GenericValue productCategoryRollup : subCategoryList) {
            attachProductFeaturesToCategory(productCategoryRollup.getString("productCategoryId"), productFeatureTypeIdsToInclude, productFeatureTypeIdsToExclude, delegator, true, nowTimestamp);
        }
    }
    // now get all features for this category and make associated feature groups
    Map<String, Set<String>> productFeatureIdByTypeIdSetMap = new HashMap<>();
    List<GenericValue> productCategoryMemberList = EntityQuery.use(delegator).from("ProductCategoryMember").where("productCategoryId", productCategoryId).queryList();
    for (GenericValue productCategoryMember : productCategoryMemberList) {
        String productId = productCategoryMember.getString("productId");
        EntityCondition condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productId", EntityOperator.EQUALS, productId), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp), EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
        try (EntityListIterator productFeatureAndApplEli = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where(condition).queryIterator()) {
            GenericValue productFeatureAndAppl = null;
            while ((productFeatureAndAppl = productFeatureAndApplEli.next()) != null) {
                String productFeatureId = productFeatureAndAppl.getString("productFeatureId");
                String productFeatureTypeId = productFeatureAndAppl.getString("productFeatureTypeId");
                if (UtilValidate.isNotEmpty(productFeatureTypeIdsToInclude) && !productFeatureTypeIdsToInclude.contains(productFeatureTypeId)) {
                    continue;
                }
                if (productFeatureTypeIdsToExclude != null && productFeatureTypeIdsToExclude.contains(productFeatureTypeId)) {
                    continue;
                }
                Set<String> productFeatureIdSet = productFeatureIdByTypeIdSetMap.get(productFeatureTypeId);
                if (productFeatureIdSet == null) {
                    productFeatureIdSet = new HashSet<>();
                    productFeatureIdByTypeIdSetMap.put(productFeatureTypeId, productFeatureIdSet);
                }
                productFeatureIdSet.add(productFeatureId);
            }
            for (Map.Entry<String, Set<String>> entry : productFeatureIdByTypeIdSetMap.entrySet()) {
                String productFeatureTypeId = entry.getKey();
                Set<String> productFeatureIdSet = entry.getValue();
                String productFeatureGroupId = productCategoryId + "_" + productFeatureTypeId;
                if (productFeatureGroupId.length() > 20) {
                    Debug.logWarning("Manufactured productFeatureGroupId was greater than 20 characters, means that we had some long productCategoryId and/or productFeatureTypeId values, at the category part should be unique since it is first, so if the feature type isn't unique it just means more than one type of feature will go into the category...", module);
                    productFeatureGroupId = productFeatureGroupId.substring(0, 20);
                }
                GenericValue productFeatureGroup = EntityQuery.use(delegator).from("ProductFeatureGroup").where("productFeatureGroupId", productFeatureGroupId).queryOne();
                if (productFeatureGroup == null) {
                    // auto-create the group
                    String description = "Feature Group for type [" + productFeatureTypeId + "] features in category [" + productCategoryId + "]";
                    productFeatureGroup = delegator.makeValue("ProductFeatureGroup", UtilMisc.toMap("productFeatureGroupId", productFeatureGroupId, "description", description));
                    productFeatureGroup.create();
                    GenericValue productFeatureCatGrpAppl = delegator.makeValue("ProductFeatureCatGrpAppl", UtilMisc.toMap("productFeatureGroupId", productFeatureGroupId, "productCategoryId", productCategoryId, "fromDate", nowTimestamp));
                    productFeatureCatGrpAppl.create();
                }
                // now put all of the features in the group, if there is not already a valid feature placement there...
                for (String productFeatureId : productFeatureIdSet) {
                    condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productFeatureId", EntityOperator.EQUALS, productFeatureId), EntityCondition.makeCondition("productFeatureGroupId", EntityOperator.EQUALS, productFeatureGroupId), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp), EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
                    if (EntityQuery.use(delegator).from("ProductFeatureGroupAppl").where(condition).queryCount() == 0) {
                        // if no valid ones, create one
                        GenericValue productFeatureGroupAppl = delegator.makeValue("ProductFeatureGroupAppl", UtilMisc.toMap("productFeatureGroupId", productFeatureGroupId, "productFeatureId", productFeatureId, "fromDate", nowTimestamp));
                        productFeatureGroupAppl.create();
                    }
                }
            }
            // now get all feature groups associated with sub-categories and associate them with this category
            for (GenericValue productCategoryRollup : subCategoryList) {
                String subProductCategoryId = productCategoryRollup.getString("productCategoryId");
                condition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, subProductCategoryId), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp), EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
                try (EntityListIterator productFeatureCatGrpApplEli = EntityQuery.use(delegator).from("ProductFeatureCatGrpAppl").where(condition).queryIterator()) {
                    GenericValue productFeatureCatGrpAppl = null;
                    while ((productFeatureCatGrpAppl = productFeatureCatGrpApplEli.next()) != null) {
                        String productFeatureGroupId = productFeatureCatGrpAppl.getString("productFeatureGroupId");
                        EntityCondition checkCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, productCategoryId), EntityCondition.makeCondition("productFeatureGroupId", EntityOperator.EQUALS, productFeatureGroupId), EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN_EQUAL_TO, nowTimestamp), EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN_EQUAL_TO, nowTimestamp))), EntityOperator.AND);
                        if (EntityQuery.use(delegator).from("ProductFeatureCatGrpAppl").where(checkCondition).queryCount() == 0) {
                            // if no valid ones, create one
                            GenericValue productFeatureGroupAppl = delegator.makeValue("ProductFeatureCatGrpAppl", UtilMisc.toMap("productFeatureGroupId", productFeatureGroupId, "productCategoryId", productCategoryId, "fromDate", nowTimestamp));
                            productFeatureGroupAppl.create();
                        }
                    }
                }
            }
        }
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap)

Example 57 with EntityListIterator

use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.

the class OrderServices method setEmptyGrandTotals.

/**
 * Service for setting the OrderHeader grandTotal for all OrderHeaders with no grandTotal
 */
public static Map<String, Object> setEmptyGrandTotals(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Boolean forceAll = (Boolean) context.get("forceAll");
    Locale locale = (Locale) context.get("locale");
    if (forceAll == null) {
        forceAll = Boolean.FALSE;
    }
    EntityCondition cond = null;
    if (!forceAll.booleanValue()) {
        List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("grandTotal", EntityOperator.EQUALS, null), EntityCondition.makeCondition("remainingSubTotal", EntityOperator.EQUALS, null));
        cond = EntityCondition.makeCondition(exprs, EntityOperator.OR);
    }
    try (EntityListIterator eli = EntityQuery.use(delegator).select("orderId").from("OrderHeader").where(cond).queryIterator()) {
        if (eli != null) {
            // reset each order
            GenericValue orderHeader = null;
            while ((orderHeader = eli.next()) != null) {
                String orderId = orderHeader.getString("orderId");
                Map<String, Object> resetResult = null;
                try {
                    resetResult = dispatcher.runSync("resetGrandTotal", UtilMisc.<String, Object>toMap("orderId", orderId, "userLogin", userLogin));
                    if (ServiceUtil.isError(resetResult)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(resetResult));
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e, "ERROR: Cannot reset order totals - " + orderId, module);
                }
                if (resetResult != null && ServiceUtil.isError(resetResult)) {
                    Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderErrorCannotResetOrderTotals", UtilMisc.toMap("orderId", orderId, "resetResult", ServiceUtil.getErrorMessage(resetResult)), locale), module);
                } else {
                    Debug.logInfo("No orders found for reset processing", module);
                }
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    return ServiceUtil.returnSuccess();
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 58 with EntityListIterator

use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.

the class OrderServices method createAlsoBoughtProductAssocs.

public static Map<String, Object> createAlsoBoughtProductAssocs(DispatchContext dctx, Map<String, ? extends Object> context) {
    final Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    // All orders with an entryDate > orderEntryFromDateTime will be processed
    Timestamp orderEntryFromDateTime = (Timestamp) context.get("orderEntryFromDateTime");
    // If true all orders ever created will be processed and any pre-existing ALSO_BOUGHT ProductAssocs will be expired
    boolean processAllOrders = context.get("processAllOrders") == null ? false : (Boolean) context.get("processAllOrders");
    if (orderEntryFromDateTime == null && !processAllOrders) {
        // No from date supplied, check to see when this service last ran and use the startDateTime
        // FIXME: This code is unreliable - the JobSandbox value might have been purged. Use another mechanism to persist orderEntryFromDateTime.
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toMap("statusId", "SERVICE_FINISHED", "serviceName", "createAlsoBoughtProductAssocs"));
        EntityFindOptions efo = new EntityFindOptions();
        efo.setMaxRows(1);
        try {
            GenericValue lastRunJobSandbox = EntityUtil.getFirst(delegator.findList("JobSandbox", cond, null, UtilMisc.toList("startDateTime DESC"), efo, false));
            if (lastRunJobSandbox != null) {
                orderEntryFromDateTime = lastRunJobSandbox.getTimestamp("startDateTime");
            }
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
        if (orderEntryFromDateTime == null) {
            // Still null, process all orders
            processAllOrders = true;
        }
    }
    if (processAllOrders) {
        // Expire any pre-existing ALSO_BOUGHT ProductAssocs in preparation for reprocessing
        EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productAssocTypeId", "ALSO_BOUGHT"), EntityCondition.makeConditionDate("fromDate", "thruDate")));
        try {
            delegator.storeByCondition("ProductAssoc", UtilMisc.toMap("thruDate", UtilDateTime.nowTimestamp()), cond);
        } catch (GenericEntityException e) {
            Debug.logError(e, module);
        }
    }
    List<EntityExpr> orderCondList = UtilMisc.toList(EntityCondition.makeCondition("orderTypeId", "SALES_ORDER"));
    if (!processAllOrders && orderEntryFromDateTime != null) {
        orderCondList.add(EntityCondition.makeCondition("entryDate", EntityOperator.GREATER_THAN, orderEntryFromDateTime));
    }
    final EntityCondition cond = EntityCondition.makeCondition(orderCondList);
    List<String> orderIds;
    try {
        orderIds = TransactionUtil.doNewTransaction(new Callable<List<String>>() {

            @Override
            public List<String> call() throws Exception {
                List<String> orderIds = new LinkedList<>();
                EntityQuery eq = EntityQuery.use(delegator).select("orderId").from("OrderHeader").where(cond).orderBy("entryDate ASC");
                try (EntityListIterator eli = eq.queryIterator()) {
                    GenericValue orderHeader;
                    while ((orderHeader = eli.next()) != null) {
                        orderIds.add(orderHeader.getString("orderId"));
                    }
                }
                return orderIds;
            }
        }, "getSalesOrderIds", 0, true);
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
        return ServiceUtil.returnError(e.getMessage());
    }
    for (String orderId : orderIds) {
        Map<String, Object> svcIn = new HashMap<>();
        svcIn.put("userLogin", context.get("userLogin"));
        svcIn.put("orderId", orderId);
        try {
            Map<String, Object> serviceResult = dispatcher.runSync("createAlsoBoughtProductAssocsForOrder", svcIn);
            if (ServiceUtil.isError(serviceResult)) {
                return ServiceUtil.returnError(ServiceUtil.getErrorMessage(serviceResult));
            }
        } catch (GenericServiceException e) {
            Debug.logError(e, module);
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) Callable(java.util.concurrent.Callable) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 59 with EntityListIterator

use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.

the class CommunicationEventServices method sendEmailToContactList.

public static Map<String, Object> sendEmailToContactList(DispatchContext ctx, Map<String, ? extends Object> context) {
    Delegator delegator = ctx.getDelegator();
    LocalDispatcher dispatcher = ctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    List<Object> errorMessages = new LinkedList<>();
    String errorCallingUpdateContactListPartyService = UtilProperties.getMessage(resource, "commeventservices.errorCallingUpdateContactListPartyService", locale);
    String errorCallingSendMailService = UtilProperties.getMessage(resource, "commeventservices.errorCallingSendMailService", locale);
    String errorInSendEmailToContactListService = UtilProperties.getMessage(resource, "commeventservices.errorInSendEmailToContactListService", locale);
    String skippingInvalidEmailAddress = UtilProperties.getMessage(resource, "commeventservices.skippingInvalidEmailAddress", locale);
    String contactListId = (String) context.get("contactListId");
    String communicationEventId = (String) context.get("communicationEventId");
    // Any exceptions thrown in this block will cause the service to return error
    try {
        GenericValue communicationEvent = EntityQuery.use(delegator).from("CommunicationEvent").where("communicationEventId", communicationEventId).queryOne();
        GenericValue contactList = EntityQuery.use(delegator).from("ContactList").where("contactListId", contactListId).queryOne();
        Map<String, Object> sendMailParams = new HashMap<>();
        sendMailParams.put("sendFrom", communicationEvent.getRelatedOne("FromContactMech", false).getString("infoString"));
        sendMailParams.put("subject", communicationEvent.getString("subject"));
        sendMailParams.put("contentType", communicationEvent.getString("contentMimeTypeId"));
        sendMailParams.put("userLogin", userLogin);
        // Find a list of distinct email addresses from active, ACCEPTED parties in the contact list
        // using a list iterator (because there can be a large number)
        List<EntityCondition> conditionList = UtilMisc.toList(EntityCondition.makeCondition("contactListId", EntityOperator.EQUALS, contactList.get("contactListId")), EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, "CLPT_ACCEPTED"), EntityCondition.makeCondition("preferredContactMechId", EntityOperator.NOT_EQUAL, null), EntityUtil.getFilterByDateExpr(), EntityUtil.getFilterByDateExpr("contactFromDate", "contactThruDate"));
        EntityQuery eq = EntityQuery.use(delegator).select("partyId", "preferredContactMechId", "fromDate", "infoString").from("ContactListPartyAndContactMech").where(EntityCondition.makeCondition(conditionList, EntityOperator.AND)).cursorScrollInsensitive().distinct();
        try (EntityListIterator eli = eq.queryIterator()) {
            // loop through the list iterator
            for (GenericValue contactListPartyAndContactMech; (contactListPartyAndContactMech = eli.next()) != null; ) {
                Debug.logInfo("Contact info: " + contactListPartyAndContactMech, module);
                // only be logged and not cause the service to return an error
                try {
                    String emailAddress = contactListPartyAndContactMech.getString("infoString");
                    if (UtilValidate.isEmpty(emailAddress)) {
                        continue;
                    }
                    emailAddress = emailAddress.trim();
                    if (!UtilValidate.isEmail(emailAddress)) {
                        // If validation fails, just log and skip the email address
                        Debug.logError(skippingInvalidEmailAddress + ": " + emailAddress, module);
                        errorMessages.add(skippingInvalidEmailAddress + ": " + emailAddress);
                        continue;
                    }
                    // Because we're retrieving infoString only above (so as not to pollute the distinctness), we
                    // need to retrieve the partyId it's related to. Since this could be multiple parties, get
                    // only the most recent valid one via ContactListPartyAndContactMech.
                    List<EntityCondition> clpConditionList = UtilMisc.makeListWritable(conditionList);
                    clpConditionList.add(EntityCondition.makeCondition("infoString", EntityOperator.EQUALS, emailAddress));
                    GenericValue lastContactListPartyACM = EntityQuery.use(delegator).from("ContactListPartyAndContactMech").where(EntityCondition.makeCondition(clpConditionList, EntityOperator.AND)).orderBy("-fromDate").cache(true).queryFirst();
                    if (lastContactListPartyACM == null) {
                        continue;
                    }
                    String partyId = lastContactListPartyACM.getString("partyId");
                    sendMailParams.put("sendTo", emailAddress);
                    sendMailParams.put("partyId", partyId);
                    // Retrieve a record for this contactMechId from ContactListCommStatus
                    Map<String, String> contactListCommStatusRecordMap = UtilMisc.toMap("contactListId", contactListId, "communicationEventId", communicationEventId, "contactMechId", lastContactListPartyACM.getString("preferredContactMechId"));
                    GenericValue contactListCommStatusRecord = EntityQuery.use(delegator).from("ContactListCommStatus").where(contactListCommStatusRecordMap).queryOne();
                    if (contactListCommStatusRecord == null) {
                        // No attempt has been made previously to send to this address, so create a record to reflect
                        // the beginning of the current attempt
                        Map<String, String> newContactListCommStatusRecordMap = UtilMisc.makeMapWritable(contactListCommStatusRecordMap);
                        newContactListCommStatusRecordMap.put("statusId", "COM_IN_PROGRESS");
                        newContactListCommStatusRecordMap.put("partyId", partyId);
                        contactListCommStatusRecord = delegator.create("ContactListCommStatus", newContactListCommStatusRecordMap);
                    } else if (contactListCommStatusRecord.get("statusId") != null && "COM_COMPLETE".equals(contactListCommStatusRecord.getString("statusId"))) {
                        // There was a successful earlier attempt, so skip this address
                        continue;
                    }
                    // Send e-mail
                    Debug.logInfo("Sending email to contact list [" + contactListId + "] party [" + partyId + "] : " + emailAddress, module);
                    // Make the attempt to send the email to the address
                    Map<String, Object> tmpResult = null;
                    // Retrieve a contact list party status
                    GenericValue contactListPartyStatus = EntityQuery.use(delegator).from("ContactListPartyStatus").where("contactListId", contactListId, "partyId", contactListPartyAndContactMech.getString("partyId"), "fromDate", contactListPartyAndContactMech.getTimestamp("fromDate"), "statusId", "CLPT_ACCEPTED").queryFirst();
                    if (contactListPartyStatus != null) {
                        // prepare body parameters
                        Map<String, Object> bodyParameters = new HashMap<>();
                        bodyParameters.put("contactListId", contactListId);
                        bodyParameters.put("partyId", contactListPartyAndContactMech.getString("partyId"));
                        bodyParameters.put("preferredContactMechId", contactListPartyAndContactMech.getString("preferredContactMechId"));
                        bodyParameters.put("emailAddress", emailAddress);
                        bodyParameters.put("fromDate", contactListPartyAndContactMech.getTimestamp("fromDate"));
                        bodyParameters.put("optInVerifyCode", contactListPartyStatus.getString("optInVerifyCode"));
                        bodyParameters.put("content", communicationEvent.getString("content"));
                        NotificationServices.setBaseUrl(delegator, contactList.getString("verifyEmailWebSiteId"), bodyParameters);
                        GenericValue webSite = EntityQuery.use(delegator).from("WebSite").where("webSiteId", contactList.getString("verifyEmailWebSiteId")).queryOne();
                        if (webSite != null) {
                            GenericValue productStore = webSite.getRelatedOne("ProductStore", false);
                            if (productStore != null) {
                                List<GenericValue> productStoreEmailSettings = productStore.getRelated("ProductStoreEmailSetting", UtilMisc.toMap("emailType", "CONT_EMAIL_TEMPLATE"), null, false);
                                GenericValue productStoreEmailSetting = EntityUtil.getFirst(productStoreEmailSettings);
                                if (productStoreEmailSetting != null) {
                                    // send e-mail using screen template
                                    sendMailParams.put("bodyScreenUri", productStoreEmailSetting.getString("bodyScreenLocation"));
                                    sendMailParams.put("bodyParameters", bodyParameters);
                                    sendMailParams.remove("body");
                                    tmpResult = dispatcher.runSync("sendMailFromScreen", sendMailParams, 360, true);
                                    if (ServiceUtil.isError(tmpResult)) {
                                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
                                    }
                                }
                            }
                        }
                    }
                    // If the e-mail does not be sent then send normal e-mail
                    if (UtilValidate.isEmpty(tmpResult)) {
                        sendMailParams.put("body", communicationEvent.getString("content"));
                        tmpResult = dispatcher.runSync("sendMail", sendMailParams, 360, true);
                        if (ServiceUtil.isError(tmpResult)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(tmpResult));
                        }
                    }
                    if (tmpResult == null || ServiceUtil.isError(tmpResult)) {
                        if (ServiceUtil.getErrorMessage(tmpResult).startsWith("[ADDRERR]")) {
                            // address error; mark the communication event as BOUNCED
                            contactListCommStatusRecord.set("statusId", "COM_BOUNCED");
                            try {
                                contactListCommStatusRecord.store();
                            } catch (GenericEntityException e) {
                                Debug.logError(e, module);
                                errorMessages.add(e.getMessage());
                            }
                            // deactivate from the contact list
                            try {
                                GenericValue contactListParty = contactListPartyAndContactMech.getRelatedOne("ContactListParty", false);
                                if (contactListParty != null) {
                                    contactListParty.set("statusId", "CLPT_INVALID");
                                    contactListParty.store();
                                }
                            } catch (GenericEntityException e) {
                                Debug.logError(e, module);
                                errorMessages.add(e.getMessage());
                            }
                            continue;
                        }
                        // If the send attempt fails, just log and skip the email address
                        Debug.logError(errorCallingSendMailService + ": " + ServiceUtil.getErrorMessage(tmpResult), module);
                        errorMessages.add(errorCallingSendMailService + ": " + ServiceUtil.getErrorMessage(tmpResult));
                        continue;
                    }
                    // attach the parent communication event to the new event created when sending
                    // the mail
                    String thisCommEventId = (String) tmpResult.get("communicationEventId");
                    GenericValue thisCommEvent = EntityQuery.use(delegator).from("CommunicationEvent").where("communicationEventId", thisCommEventId).queryOne();
                    if (thisCommEvent != null) {
                        thisCommEvent.set("contactListId", contactListId);
                        thisCommEvent.set("parentCommEventId", communicationEventId);
                        thisCommEvent.store();
                    }
                    String messageId = (String) tmpResult.get("messageId");
                    contactListCommStatusRecord.set("messageId", messageId);
                    if ("Y".equals(contactList.get("singleUse"))) {
                        // Expire the ContactListParty if the list is single use and sendEmail finishes successfully
                        tmpResult = dispatcher.runSync("updateContactListParty", UtilMisc.toMap("contactListId", lastContactListPartyACM.get("contactListId"), "partyId", partyId, "fromDate", lastContactListPartyACM.get("fromDate"), "thruDate", UtilDateTime.nowTimestamp(), "userLogin", userLogin));
                        if (ServiceUtil.isError(tmpResult)) {
                            // If the expiry fails, just log and skip the email address
                            Debug.logError(errorCallingUpdateContactListPartyService + ": " + ServiceUtil.getErrorMessage(tmpResult), module);
                            errorMessages.add(errorCallingUpdateContactListPartyService + ": " + ServiceUtil.getErrorMessage(tmpResult));
                            continue;
                        }
                    }
                    // All is successful, so update the ContactListCommStatus record
                    contactListCommStatusRecord.set("statusId", "COM_COMPLETE");
                    delegator.store(contactListCommStatusRecord);
                // Don't return a service error just because of failure for one address - just log the error and continue
                } catch (GenericEntityException nonFatalGEE) {
                    Debug.logError(nonFatalGEE, errorInSendEmailToContactListService, module);
                    errorMessages.add(errorInSendEmailToContactListService + ": " + nonFatalGEE.getMessage());
                } catch (GenericServiceException nonFatalGSE) {
                    Debug.logError(nonFatalGSE, errorInSendEmailToContactListService, module);
                    errorMessages.add(errorInSendEmailToContactListService + ": " + nonFatalGSE.getMessage());
                }
            }
        } catch (GenericEntityException fatalGEE) {
            return ServiceUtil.returnError(fatalGEE.getMessage());
        }
    } catch (GenericEntityException fatalGEE) {
        return ServiceUtil.returnError(fatalGEE.getMessage());
    }
    return errorMessages.size() == 0 ? ServiceUtil.returnSuccess() : ServiceUtil.returnError(errorMessages);
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 60 with EntityListIterator

use of org.apache.ofbiz.entity.util.EntityListIterator in project ofbiz-framework by apache.

the class OrderListState method getOrders.

/**
 * Get the OrderHeaders corresponding to the state.
 */
public List<GenericValue> getOrders(String facilityId, Timestamp filterDate, Delegator delegator) throws GenericEntityException {
    List<EntityCondition> allConditions = new LinkedList<>();
    if (facilityId != null) {
        allConditions.add(EntityCondition.makeCondition("originFacilityId", EntityOperator.EQUALS, facilityId));
    }
    if (filterDate != null) {
        List<EntityCondition> andExprs = new LinkedList<>();
        andExprs.add(EntityCondition.makeCondition("orderDate", EntityOperator.GREATER_THAN_EQUAL_TO, UtilDateTime.getDayStart(filterDate)));
        andExprs.add(EntityCondition.makeCondition("orderDate", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.getDayEnd(filterDate)));
        allConditions.add(EntityCondition.makeCondition(andExprs, EntityOperator.AND));
    }
    List<EntityCondition> statusConditions = new LinkedList<>();
    for (String status : orderStatusState.keySet()) {
        if (!hasStatus(status)) {
            continue;
        }
        statusConditions.add(EntityCondition.makeCondition("statusId", EntityOperator.EQUALS, parameterToOrderStatusId.get(status)));
    }
    List<EntityCondition> typeConditions = new LinkedList<>();
    for (String type : orderTypeState.keySet()) {
        if (!hasType(type)) {
            continue;
        }
        typeConditions.add(EntityCondition.makeCondition("orderTypeId", EntityOperator.EQUALS, parameterToOrderTypeId.get(type)));
    }
    EntityCondition statusConditionsList = EntityCondition.makeCondition(statusConditions, EntityOperator.OR);
    EntityCondition typeConditionsList = EntityCondition.makeCondition(typeConditions, EntityOperator.OR);
    if (statusConditions.size() > 0) {
        allConditions.add(statusConditionsList);
    }
    if (typeConditions.size() > 0) {
        allConditions.add(typeConditionsList);
    }
    EntityQuery eq = EntityQuery.use(delegator).from("OrderHeader").where(allConditions).orderBy("orderDate DESC").maxRows(viewSize * (viewIndex + 1)).cursorScrollInsensitive();
    try (EntityListIterator iterator = eq.queryIterator()) {
        // get subset corresponding to pagination state
        List<GenericValue> orders = iterator.getPartialList(viewSize * viewIndex, viewSize);
        orderListSize = iterator.getResultsSizeAfterPartialList();
        return orders;
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList)

Aggregations

EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)65 GenericValue (org.apache.ofbiz.entity.GenericValue)59 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)57 Delegator (org.apache.ofbiz.entity.Delegator)33 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)29 LinkedList (java.util.LinkedList)25 HashMap (java.util.HashMap)24 Timestamp (java.sql.Timestamp)23 Locale (java.util.Locale)21 EntityQuery (org.apache.ofbiz.entity.util.EntityQuery)19 GenericTransactionException (org.apache.ofbiz.entity.transaction.GenericTransactionException)18 Map (java.util.Map)16 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)13 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)12 DynamicViewEntity (org.apache.ofbiz.entity.model.DynamicViewEntity)8 ModelKeyMap (org.apache.ofbiz.entity.model.ModelKeyMap)8 GeneralException (org.apache.ofbiz.base.util.GeneralException)7 ModelEntity (org.apache.ofbiz.entity.model.ModelEntity)7 ArrayList (java.util.ArrayList)6 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)6