Search in sources :

Example 31 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class ProductPromoWorker method checkCondition.

private static boolean checkCondition(GenericValue productPromoCond, ShoppingCart cart, Delegator delegator, LocalDispatcher dispatcher, Timestamp nowTimestamp) throws GenericEntityException {
    String condValue = productPromoCond.getString("condValue");
    String otherValue = productPromoCond.getString("otherValue");
    String inputParamEnumId = productPromoCond.getString("inputParamEnumId");
    String operatorEnumId = productPromoCond.getString("operatorEnumId");
    String shippingMethod = "";
    String carrierPartyId = "";
    if (otherValue != null && otherValue.contains("@")) {
        carrierPartyId = otherValue.substring(0, otherValue.indexOf('@'));
        shippingMethod = otherValue.substring(otherValue.indexOf('@') + 1);
        otherValue = "";
    }
    String partyId = cart.getPartyId();
    GenericValue userLogin = cart.getUserLogin();
    if (userLogin == null) {
        userLogin = cart.getAutoUserLogin();
    }
    if (Debug.verboseOn()) {
        Debug.logVerbose("Checking promotion condition: " + productPromoCond, module);
    }
    Integer compareBase = null;
    if ("PPIP_SERVICE".equals(inputParamEnumId)) {
        Map<String, Object> serviceCtx = UtilMisc.<String, Object>toMap("productPromoCond", productPromoCond, "shoppingCart", cart, "nowTimestamp", nowTimestamp);
        Map<String, Object> condResult;
        try {
            condResult = dispatcher.runSync(condValue, serviceCtx);
        } catch (GenericServiceException e) {
            Debug.logError(e, "Fatal error calling promo condition check service [" + condValue + "]", module);
            return false;
        }
        if (ServiceUtil.isError(condResult)) {
            Debug.logError("Error calling calling promo condition check service [" + condValue + "]", module);
            return false;
        }
        Boolean directResult = (Boolean) condResult.get("directResult");
        if (directResult != null) {
            return directResult.booleanValue();
        }
        compareBase = (Integer) condResult.get("compareBase");
        if (condResult.containsKey("operatorEnumId")) {
            operatorEnumId = (String) condResult.get("operatorEnumId");
        }
    } else if ("PPIP_PRODUCT_AMOUNT".equals(inputParamEnumId)) {
        // for this type of promo force the operatorEnumId = PPC_EQ, effectively ignore that setting because the comparison is implied in the code
        operatorEnumId = "PPC_EQ";
        // this type of condition requires items involved to not be involved in any other quantity consuming cond/action, and does not pro-rate the price, just uses the base price
        BigDecimal amountNeeded = BigDecimal.ZERO;
        if (UtilValidate.isNotEmpty(condValue)) {
            amountNeeded = new BigDecimal(condValue);
        }
        Set<String> productIds = ProductPromoWorker.getPromoRuleCondProductIds(productPromoCond, delegator, nowTimestamp);
        List<ShoppingCartItem> lineOrderedByBasePriceList = cart.getLineListOrderedByBasePrice(false);
        Iterator<ShoppingCartItem> lineOrderedByBasePriceIter = lineOrderedByBasePriceList.iterator();
        while (amountNeeded.compareTo(BigDecimal.ZERO) > 0 && lineOrderedByBasePriceIter.hasNext()) {
            ShoppingCartItem cartItem = lineOrderedByBasePriceIter.next();
            // only include if it is in the productId Set for this check and if it is not a Promo (GWP) item
            GenericValue product = cartItem.getProduct();
            String parentProductId = cartItem.getParentProductId();
            boolean passedItemConds = checkConditionsForItem(productPromoCond, cart, cartItem, delegator, dispatcher, nowTimestamp);
            if (passedItemConds && !cartItem.getIsPromo() && (productIds.contains(cartItem.getProductId()) || (parentProductId != null && productIds.contains(parentProductId))) && (product == null || !"N".equals(product.getString("includeInPromotions")))) {
                BigDecimal basePrice = cartItem.getBasePrice();
                // get a rough price, round it up to an integer
                BigDecimal quantityNeeded = amountNeeded.divide(basePrice, generalRounding).setScale(0, RoundingMode.CEILING);
                // reduce amount still needed to qualify for promo (amountNeeded)
                BigDecimal quantity = cartItem.addPromoQuantityCandidateUse(quantityNeeded, productPromoCond, false);
                // get pro-rated amount based on discount
                amountNeeded = amountNeeded.subtract(quantity.multiply(basePrice));
            }
        }
        // if amountNeeded > 0 then the promo condition failed, so remove candidate promo uses and increment the promoQuantityUsed to restore it
        if (amountNeeded.compareTo(BigDecimal.ZERO) > 0) {
            // failed, reset the entire rule, ie including all other conditions that might have been done before
            cart.resetPromoRuleUse(productPromoCond.getString("productPromoId"), productPromoCond.getString("productPromoRuleId"));
            compareBase = Integer.valueOf(-1);
        } else {
            // we got it, the conditions are in place...
            compareBase = Integer.valueOf(0);
        // NOTE: don't confirm promo rule use here, wait until actions are complete for the rule to do that
        }
    } else if ("PPIP_PRODUCT_TOTAL".equals(inputParamEnumId)) {
        // this type of condition allows items involved to be involved in other quantity consuming cond/action, and does pro-rate the price
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal amountNeeded = new BigDecimal(condValue);
            BigDecimal amountAvailable = BigDecimal.ZERO;
            Set<String> productIds = ProductPromoWorker.getPromoRuleCondProductIds(productPromoCond, delegator, nowTimestamp);
            List<ShoppingCartItem> lineOrderedByBasePriceList = cart.getLineListOrderedByBasePrice(false);
            for (ShoppingCartItem cartItem : lineOrderedByBasePriceList) {
                // only include if it is in the productId Set for this check and if it is not a Promo (GWP) item
                GenericValue product = cartItem.getProduct();
                String parentProductId = cartItem.getParentProductId();
                boolean passedItemConds = checkConditionsForItem(productPromoCond, cart, cartItem, delegator, dispatcher, nowTimestamp);
                if (passedItemConds && !cartItem.getIsPromo() && (productIds.contains(cartItem.getProductId()) || (parentProductId != null && productIds.contains(parentProductId))) && (product == null || !"N".equals(product.getString("includeInPromotions")))) {
                    // just count the entire sub-total of the item
                    amountAvailable = amountAvailable.add(cartItem.getItemSubTotal());
                }
            }
            compareBase = Integer.valueOf(amountAvailable.compareTo(amountNeeded));
        }
    } else if ("PPIP_PRODUCT_QUANT".equals(inputParamEnumId)) {
        if (operatorEnumId == null) {
            // if the operator is not specified in the condition, then assume as default PPC_EQ (for backward compatibility)
            operatorEnumId = "PPC_EQ";
        }
        BigDecimal quantityNeeded = BigDecimal.ONE;
        if (UtilValidate.isNotEmpty(condValue)) {
            quantityNeeded = new BigDecimal(condValue);
        }
        Set<String> productIds = ProductPromoWorker.getPromoRuleCondProductIds(productPromoCond, delegator, nowTimestamp);
        List<ShoppingCartItem> lineOrderedByBasePriceList = cart.getLineListOrderedByBasePrice(false);
        Iterator<ShoppingCartItem> lineOrderedByBasePriceIter = lineOrderedByBasePriceList.iterator();
        while (quantityNeeded.compareTo(BigDecimal.ZERO) > 0 && lineOrderedByBasePriceIter.hasNext()) {
            ShoppingCartItem cartItem = lineOrderedByBasePriceIter.next();
            // only include if it is in the productId Set for this check and if it is not a Promo (GWP) item
            GenericValue product = cartItem.getProduct();
            String parentProductId = cartItem.getParentProductId();
            boolean passedItemConds = checkConditionsForItem(productPromoCond, cart, cartItem, delegator, dispatcher, nowTimestamp);
            if (passedItemConds && !cartItem.getIsPromo() && (productIds.contains(cartItem.getProductId()) || (parentProductId != null && productIds.contains(parentProductId))) && (product == null || !"N".equals(product.getString("includeInPromotions")))) {
                // reduce quantity still needed to qualify for promo (quantityNeeded)
                quantityNeeded = quantityNeeded.subtract(cartItem.addPromoQuantityCandidateUse(quantityNeeded, productPromoCond, !"PPC_EQ".equals(operatorEnumId)));
            }
        }
        // if quantityNeeded > 0 then the promo condition failed, so remove candidate promo uses and increment the promoQuantityUsed to restore it
        if (quantityNeeded.compareTo(BigDecimal.ZERO) > 0) {
            // failed, reset the entire rule, ie including all other conditions that might have been done before
            cart.resetPromoRuleUse(productPromoCond.getString("productPromoId"), productPromoCond.getString("productPromoRuleId"));
            compareBase = Integer.valueOf(-1);
        } else {
            // we got it, the conditions are in place...
            compareBase = Integer.valueOf(0);
        // NOTE: don't confirm rpomo rule use here, wait until actions are complete for the rule to do that
        }
    } else if ("PPIP_NEW_ACCT".equals(inputParamEnumId)) {
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal acctDays = cart.getPartyDaysSinceCreated(nowTimestamp);
            if (acctDays == null) {
                // condition always fails if we don't know how many days since account created
                return false;
            }
            compareBase = acctDays.compareTo(new BigDecimal(condValue));
        }
    } else if ("PPIP_PARTY_ID".equals(inputParamEnumId)) {
        if (partyId != null && UtilValidate.isNotEmpty(condValue)) {
            compareBase = Integer.valueOf(partyId.compareTo(condValue));
        } else {
            compareBase = Integer.valueOf(1);
        }
    } else if ("PPIP_PARTY_GRP_MEM".equals(inputParamEnumId)) {
        if (UtilValidate.isEmpty(partyId) || UtilValidate.isEmpty(condValue)) {
            compareBase = Integer.valueOf(1);
        } else {
            String groupPartyId = condValue;
            if (partyId.equals(groupPartyId)) {
                compareBase = Integer.valueOf(0);
            } else {
                // look for PartyRelationship with partyRelationshipTypeId=GROUP_ROLLUP, the partyIdTo is the group member, so the partyIdFrom is the groupPartyId
                // and from/thru date within range
                List<GenericValue> partyRelationshipList = EntityQuery.use(delegator).from("PartyRelationship").where("partyIdFrom", groupPartyId, "partyIdTo", partyId, "partyRelationshipTypeId", "GROUP_ROLLUP").cache(true).filterByDate().queryList();
                if (UtilValidate.isNotEmpty(partyRelationshipList)) {
                    compareBase = Integer.valueOf(0);
                } else {
                    compareBase = Integer.valueOf(checkConditionPartyHierarchy(delegator, nowTimestamp, groupPartyId, partyId));
                }
            }
        }
    } else if ("PPIP_PARTY_CLASS".equals(inputParamEnumId)) {
        if (UtilValidate.isEmpty(partyId) || UtilValidate.isEmpty(condValue)) {
            compareBase = Integer.valueOf(1);
        } else {
            String partyClassificationGroupId = condValue;
            // find any PartyClassification
            // and from/thru date within range
            List<GenericValue> partyClassificationList = EntityQuery.use(delegator).from("PartyClassification").where("partyId", partyId, "partyClassificationGroupId", partyClassificationGroupId).cache(true).filterByDate().queryList();
            // then 0 (equals), otherwise 1 (not equals)
            if (UtilValidate.isNotEmpty(partyClassificationList)) {
                compareBase = Integer.valueOf(0);
            } else {
                compareBase = Integer.valueOf(1);
            }
        }
    } else if ("PPIP_ROLE_TYPE".equals(inputParamEnumId)) {
        if (partyId != null && UtilValidate.isNotEmpty(condValue)) {
            // if a PartyRole exists for this partyId and the specified roleTypeId
            GenericValue partyRole = EntityQuery.use(delegator).from("PartyRole").where("partyId", partyId, "roleTypeId", condValue).cache(true).queryOne();
            // then 0 (equals), otherwise 1 (not equals)
            if (partyRole != null) {
                compareBase = Integer.valueOf(0);
            } else {
                compareBase = Integer.valueOf(1);
            }
        } else {
            compareBase = Integer.valueOf(1);
        }
    } else if ("PPIP_GEO_ID".equals(inputParamEnumId)) {
        compareBase = Integer.valueOf(1);
        GenericValue shippingAddress = cart.getShippingAddress();
        if (UtilValidate.isNotEmpty(condValue) && shippingAddress != null) {
            if (condValue.equals(shippingAddress.getString("countryGeoId")) || condValue.equals(shippingAddress.getString("countyGeoId")) || condValue.equals(shippingAddress.getString("postalCodeGeoId")) || condValue.equals(shippingAddress.getString("stateProvinceGeoId"))) {
                compareBase = Integer.valueOf(0);
            } else {
                List<GenericValue> geoAssocList = EntityQuery.use(delegator).from("GeoAssoc").where("geoIdTo", condValue).queryList();
                for (GenericValue geo : geoAssocList) {
                    if (geo.get("geoId").equals(shippingAddress.getString("countryGeoId")) || geo.get("geoId").equals(shippingAddress.getString("countyGeoId")) || geo.get("geoId").equals(shippingAddress.getString("postalCodeGeoId")) || condValue.equals(shippingAddress.getString("stateProvinceGeoId"))) {
                        compareBase = Integer.valueOf(0);
                        break;
                    }
                }
            }
        }
    } else if ("PPIP_ORDER_TOTAL".equals(inputParamEnumId)) {
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal orderSubTotal = cart.getSubTotalForPromotions();
            if (Debug.verboseOn())
                Debug.logVerbose("Doing order total compare: orderSubTotal=" + orderSubTotal, module);
            compareBase = Integer.valueOf(orderSubTotal.compareTo(new BigDecimal(condValue)));
        }
    } else if ("PPIP_ORST_HIST".equals(inputParamEnumId)) {
        // description="Order sub-total X in last Y Months"
        if (partyId != null && userLogin != null && UtilValidate.isNotEmpty(condValue)) {
            // call the getOrderedSummaryInformation service to get the sub-total
            int monthsToInclude = 12;
            if (otherValue != null) {
                monthsToInclude = Integer.parseInt(otherValue);
            }
            Map<String, Object> serviceIn = UtilMisc.<String, Object>toMap("partyId", partyId, "roleTypeId", "PLACING_CUSTOMER", "orderTypeId", "SALES_ORDER", "statusId", "ORDER_COMPLETED", "monthsToInclude", Integer.valueOf(monthsToInclude), "userLogin", userLogin);
            try {
                Map<String, Object> result = dispatcher.runSync("getOrderedSummaryInformation", serviceIn);
                if (ServiceUtil.isError(result)) {
                    Debug.logError("Error calling getOrderedSummaryInformation service for the PPIP_ORST_HIST ProductPromo condition input value: " + ServiceUtil.getErrorMessage(result), module);
                    return false;
                } else {
                    BigDecimal orderSubTotal = (BigDecimal) result.get("totalSubRemainingAmount");
                    BigDecimal orderSubTotalAndCartSubTotal = orderSubTotal.add(cart.getSubTotal());
                    if (Debug.verboseOn())
                        Debug.logVerbose("Doing order history sub-total compare: orderSubTotal=" + orderSubTotal + ", for the last " + monthsToInclude + " months.", module);
                    compareBase = Integer.valueOf(orderSubTotalAndCartSubTotal.compareTo(new BigDecimal(condValue)));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error getting order history sub-total in the getOrderedSummaryInformation service, evaluating condition to false.", module);
                return false;
            }
        } else {
            return false;
        }
    } else if ("PPIP_ORST_YEAR".equals(inputParamEnumId)) {
        // description="Order sub-total X since beginning of current year"
        if (partyId != null && userLogin != null && UtilValidate.isNotEmpty(condValue)) {
            // call the getOrderedSummaryInformation service to get the sub-total
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTimestamp);
            int monthsToInclude = calendar.get(Calendar.MONTH) + 1;
            Map<String, Object> serviceIn = UtilMisc.<String, Object>toMap("partyId", partyId, "roleTypeId", "PLACING_CUSTOMER", "orderTypeId", "SALES_ORDER", "statusId", "ORDER_COMPLETED", "monthsToInclude", Integer.valueOf(monthsToInclude), "userLogin", userLogin);
            try {
                Map<String, Object> result = dispatcher.runSync("getOrderedSummaryInformation", serviceIn);
                if (ServiceUtil.isError(result)) {
                    Debug.logError("Error calling getOrderedSummaryInformation service for the PPIP_ORST_YEAR ProductPromo condition input value: " + ServiceUtil.getErrorMessage(result), module);
                    return false;
                } else {
                    BigDecimal orderSubTotal = (BigDecimal) result.get("totalSubRemainingAmount");
                    if (Debug.verboseOn())
                        Debug.logVerbose("Doing order history sub-total compare: orderSubTotal=" + orderSubTotal + ", for the last " + monthsToInclude + " months.", module);
                    compareBase = Integer.valueOf(orderSubTotal.compareTo(new BigDecimal((condValue))));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error getting order history sub-total in the getOrderedSummaryInformation service, evaluating condition to false.", module);
                return false;
            }
        }
    } else if ("PPIP_ORST_LAST_YEAR".equals(inputParamEnumId)) {
        // description="Order sub-total X since beginning of last year"
        if (partyId != null && userLogin != null && UtilValidate.isNotEmpty(condValue)) {
            // call the getOrderedSummaryInformation service to get the sub-total
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(nowTimestamp);
            int lastYear = calendar.get(Calendar.YEAR) - 1;
            Calendar fromDateCalendar = Calendar.getInstance();
            fromDateCalendar.set(lastYear, 0, 0, 0, 0);
            Timestamp fromDate = new Timestamp(fromDateCalendar.getTime().getTime());
            Calendar thruDateCalendar = Calendar.getInstance();
            thruDateCalendar.set(lastYear, 12, 0, 0, 0);
            Timestamp thruDate = new Timestamp(thruDateCalendar.getTime().getTime());
            Map<String, Object> serviceIn = UtilMisc.toMap("partyId", partyId, "roleTypeId", "PLACING_CUSTOMER", "orderTypeId", "SALES_ORDER", "statusId", "ORDER_COMPLETED", "fromDate", fromDate, "thruDate", thruDate, "userLogin", userLogin);
            try {
                Map<String, Object> result = dispatcher.runSync("getOrderedSummaryInformation", serviceIn);
                if (ServiceUtil.isError(result)) {
                    Debug.logError("Error calling getOrderedSummaryInformation service for the PPIP_ORST_LAST_YEAR ProductPromo condition input value: " + ServiceUtil.getErrorMessage(result), module);
                    return false;
                } else {
                    Double orderSubTotal = (Double) result.get("totalSubRemainingAmount");
                    if (Debug.verboseOn())
                        Debug.logVerbose("Doing order history sub-total compare: orderSubTotal=" + orderSubTotal + ", for last year.", module);
                    compareBase = Integer.valueOf(orderSubTotal.compareTo(Double.valueOf(condValue)));
                }
            } catch (GenericServiceException e) {
                Debug.logError(e, "Error getting order history sub-total in the getOrderedSummaryInformation service, evaluating condition to false.", module);
                return false;
            }
        } else {
            return false;
        }
    } else if ("PPIP_RECURRENCE".equals(inputParamEnumId)) {
        if (UtilValidate.isNotEmpty(condValue)) {
            compareBase = Integer.valueOf(1);
            GenericValue recurrenceInfo = EntityQuery.use(delegator).from("RecurrenceInfo").where("recurrenceInfoId", condValue).cache().queryOne();
            if (recurrenceInfo != null) {
                RecurrenceInfo recurrence = null;
                try {
                    recurrence = new RecurrenceInfo(recurrenceInfo);
                } catch (RecurrenceInfoException e) {
                    Debug.logError(e, module);
                }
                // check the current recurrence
                if (recurrence != null) {
                    if (recurrence.isValidCurrent()) {
                        compareBase = Integer.valueOf(0);
                    }
                }
            }
        }
    } else if ("PPIP_ORDER_SHIPTOTAL".equals(inputParamEnumId) && shippingMethod.equals(cart.getShipmentMethodTypeId()) && carrierPartyId.equals(cart.getCarrierPartyId())) {
        if (UtilValidate.isNotEmpty(condValue)) {
            BigDecimal orderTotalShipping = cart.getTotalShipping();
            if (Debug.verboseOn()) {
                Debug.logVerbose("Doing order total Shipping compare: ordertotalShipping=" + orderTotalShipping, module);
            }
            compareBase = orderTotalShipping.compareTo(new BigDecimal(condValue));
        }
    } else if ("PPIP_LPMUP_AMT".equals(inputParamEnumId)) {
        // does nothing on order level, only checked on item level, so ignore by always considering passed
        return true;
    } else if ("PPIP_LPMUP_PER".equals(inputParamEnumId)) {
        // does nothing on order level, only checked on item level, so ignore by always considering passed
        return true;
    } else {
        Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderAnUnSupportedProductPromoCondInputParameterLhs", UtilMisc.toMap("inputParamEnumId", productPromoCond.getString("inputParamEnumId")), cart.getLocale()), module);
        return false;
    }
    if (Debug.verboseOn())
        Debug.logVerbose("Condition compare done, compareBase=" + compareBase, module);
    if (compareBase != null) {
        int compare = compareBase.intValue();
        if ("PPC_EQ".equals(operatorEnumId)) {
            if (compare == 0)
                return true;
        } else if ("PPC_NEQ".equals(operatorEnumId)) {
            if (compare != 0)
                return true;
        } else if ("PPC_LT".equals(operatorEnumId)) {
            if (compare < 0)
                return true;
        } else if ("PPC_LTE".equals(operatorEnumId)) {
            if (compare <= 0)
                return true;
        } else if ("PPC_GT".equals(operatorEnumId)) {
            if (compare > 0)
                return true;
        } else if ("PPC_GTE".equals(operatorEnumId)) {
            if (compare >= 0)
                return true;
        } else {
            Debug.logWarning(UtilProperties.getMessage(resource_error, "OrderAnUnSupportedProductPromoCondCondition", UtilMisc.toMap("operatorEnumId", operatorEnumId), cart.getLocale()), module);
            return false;
        }
    }
    // default to not meeting the condition
    return false;
}
Also used : RecurrenceInfoException(org.apache.ofbiz.service.calendar.RecurrenceInfoException) GenericValue(org.apache.ofbiz.entity.GenericValue) HashSet(java.util.HashSet) Set(java.util.Set) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) Iterator(java.util.Iterator) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) HashMap(java.util.HashMap) Map(java.util.Map)

Example 32 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class ContactMechServices method createEmailAddressVerification.

/**
 * Creates an EmailAddressVerification
 */
public static Map<String, Object> createEmailAddressVerification(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    String emailAddress = (String) context.get("emailAddress");
    String verifyHash = null;
    String expireTime = EntityUtilProperties.getPropertyValue("security", "email_verification.expire.hours", delegator);
    Integer expTime = Integer.valueOf(expireTime);
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.HOUR, expTime.intValue());
    Date date = calendar.getTime();
    Timestamp expireDate = UtilDateTime.toTimestamp(date);
    SecureRandom secureRandom = new SecureRandom();
    synchronized (ContactMechServices.class) {
        while (true) {
            Long random = secureRandom.nextLong();
            verifyHash = HashCrypt.digestHash("MD5", Long.toString(random).getBytes(UtilIO.getUtf8()));
            List<GenericValue> emailAddVerifications = null;
            try {
                emailAddVerifications = EntityQuery.use(delegator).from("EmailAddressVerification").where("verifyHash", verifyHash).queryList();
            } catch (GenericEntityException e) {
                Debug.logError(e.getMessage(), module);
                return ServiceUtil.returnError(e.getMessage());
            }
            if (UtilValidate.isEmpty(emailAddVerifications)) {
                GenericValue emailAddressVerification = delegator.makeValue("EmailAddressVerification");
                emailAddressVerification.set("emailAddress", emailAddress);
                emailAddressVerification.set("verifyHash", verifyHash);
                emailAddressVerification.set("expireDate", expireDate);
                try {
                    delegator.create(emailAddressVerification);
                } catch (GenericEntityException e) {
                    Debug.logError(e.getMessage(), module);
                    return ServiceUtil.returnError(e.getMessage());
                }
                break;
            }
        }
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("verifyHash", verifyHash);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Calendar(com.ibm.icu.util.Calendar) SecureRandom(java.security.SecureRandom) Timestamp(java.sql.Timestamp) Date(java.util.Date) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException)

Example 33 with Calendar

use of com.ibm.icu.util.Calendar in project ofbiz-framework by apache.

the class ShoppingListServices method autoDeleteAutoSaveShoppingList.

public static Map<String, Object> autoDeleteAutoSaveShoppingList(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    LocalDispatcher dispatcher = dctx.getDispatcher();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    List<GenericValue> shoppingList = null;
    Map<String, Object> result = new HashMap<String, Object>();
    try {
        shoppingList = EntityQuery.use(delegator).from("ShoppingList").where("partyId", null, "shoppingListTypeId", "SLT_SPEC_PURP").queryList();
    } catch (GenericEntityException e) {
        Debug.logError(e.getMessage(), module);
    }
    String maxDaysStr = EntityUtilProperties.getPropertyValue("order", "autosave.max.age", "30", delegator);
    int maxDays = 0;
    try {
        maxDays = Integer.parseInt(maxDaysStr);
    } catch (NumberFormatException e) {
        Debug.logError(e, "Unable to get maxDays", module);
    }
    for (GenericValue sl : shoppingList) {
        if (maxDays > 0) {
            Timestamp lastModified = sl.getTimestamp("lastAdminModified");
            if (lastModified == null) {
                lastModified = sl.getTimestamp("lastUpdatedStamp");
            }
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(lastModified.getTime());
            cal.add(Calendar.DAY_OF_YEAR, maxDays);
            Date expireDate = cal.getTime();
            Date nowDate = new Date();
            if (expireDate.equals(nowDate) || nowDate.after(expireDate)) {
                List<GenericValue> shoppingListItems = null;
                try {
                    shoppingListItems = sl.getRelated("ShoppingListItem", null, null, false);
                } catch (GenericEntityException e) {
                    Debug.logError(e.getMessage(), module);
                }
                for (GenericValue sli : shoppingListItems) {
                    try {
                        result = dispatcher.runSync("removeShoppingListItem", UtilMisc.toMap("shoppingListId", sl.getString("shoppingListId"), "shoppingListItemSeqId", sli.getString("shoppingListItemSeqId"), "userLogin", userLogin));
                        if (ServiceUtil.isError(result)) {
                            return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                        }
                    } catch (GenericServiceException e) {
                        Debug.logError(e.getMessage(), module);
                    }
                }
                try {
                    result = dispatcher.runSync("removeShoppingList", UtilMisc.toMap("shoppingListId", sl.getString("shoppingListId"), "userLogin", userLogin));
                    if (ServiceUtil.isError(result)) {
                        return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                    }
                } catch (GenericServiceException e) {
                    Debug.logError(e.getMessage(), module);
                }
            }
        }
    }
    return ServiceUtil.returnSuccess();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) HashMap(java.util.HashMap) Calendar(com.ibm.icu.util.Calendar) Timestamp(java.sql.Timestamp) Date(java.util.Date) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException)

Example 34 with Calendar

use of com.ibm.icu.util.Calendar in project mycore by MyCoRe-Org.

the class MCRCalendar method getCalendarFromJulianDate.

/**
 * This method convert a JulianCalendar date to a general Calendar value.
 * The syntax for the julian input is: <br>
 * <ul>
 * <li> [[[t]t.][m]m.][yyy]y [v. Chr.|n. Chr.]</li>
 * <li> [[[t]t.][m]m.][yyy]y [AD|BC]</li>
 * <li> [-|AD|BC] [[[t]t.][m]m.][yyy]y</li>
 * <li> [[[t]t/][m]m/][yyy]y [AD|BC]</li>
 * <li> [-|AD|BC] [[[t]t/][m]m/][yyy]y</li>
 * <li> y[yyy][-m[m][-t[t]]] [v. Chr.|n. Chr.]</li>
 * <li> y[yyy][-m[m][-t[t]]] [AD|BC]</li>
 * <li> [-|AD|BC] y[yyy][-m[m][-t[t]]]</li>
 * </ul>
 *
 * @param date_string
 *            the date as string.
 * @param last
 *            the value is true if the date should be filled with the
 *            highest value of month or day like 12 or 31 else it fill the
 *            date with the lowest value 1 for month and day.
 *
 * @return the GregorianCalendar date value or null if an error was
 *         occurred.
 * @exception MCRException if parsing has an error
 */
protected static Calendar getCalendarFromJulianDate(String date_string, boolean last) throws MCRException {
    try {
        int[] fields = checkDateStringForJulianCalendar(date_string, last);
        Calendar calendar = new GregorianCalendar();
        calendar.set(fields[0], fields[1], fields[2]);
        if (fields[3] == -1) {
            calendar.set(Calendar.ERA, GregorianCalendar.BC);
        } else {
            calendar.set(Calendar.ERA, GregorianCalendar.AD);
        }
        // correct data
        int julian_day = calendar.get(Calendar.JULIAN_DAY);
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 6 && fields[3] == 1) {
            julian_day = 2299162;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 7 && fields[3] == 1) {
            julian_day = 2299163;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 8 && fields[3] == 1) {
            julian_day = 2299164;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 9 && fields[3] == 1) {
            julian_day = 2299165;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 10 && fields[3] == 1) {
            julian_day = 2299166;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 11 && fields[3] == 1) {
            julian_day = 2299167;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 12 && fields[3] == 1) {
            julian_day = 2299168;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 13 && fields[3] == 1) {
            julian_day = 2299169;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 14 && fields[3] == 1) {
            julian_day = 2299170;
        }
        if (fields[0] == 1582 && fields[1] == 9 && fields[2] == 15 && fields[3] == 1) {
            julian_day = 2299171;
        }
        if ((fields[0] > 1582 || (fields[0] == 1582 && fields[1] > 9) || (fields[0] == 1582 && fields[1] == 9 && fields[2] > 15)) && fields[3] == 1) {
            julian_day += 10;
        }
        if ((fields[0] > 1700 || (fields[0] == 1700 && fields[1] >= 2)) && fields[3] == 1) {
            julian_day += 1;
        }
        if ((fields[0] > 1800 || (fields[0] == 1800 && fields[1] >= 2)) && fields[3] == 1) {
            julian_day += 1;
        }
        if ((fields[0] > 1900 || (fields[0] == 1900 && fields[1] >= 2)) && fields[3] == 1) {
            julian_day += 1;
        }
        if ((fields[0] > 2100 || (fields[0] == 2100 && fields[1] >= 2)) && fields[3] == 1) {
            julian_day += 1;
        }
        calendar.set(Calendar.JULIAN_DAY, julian_day);
        return calendar;
    } catch (Exception e) {
        throw new MCRException("The ancient julian date is false.", e);
    }
}
Also used : EthiopicCalendar(com.ibm.icu.util.EthiopicCalendar) JapaneseCalendar(com.ibm.icu.util.JapaneseCalendar) Calendar(com.ibm.icu.util.Calendar) IslamicCalendar(com.ibm.icu.util.IslamicCalendar) BuddhistCalendar(com.ibm.icu.util.BuddhistCalendar) CopticCalendar(com.ibm.icu.util.CopticCalendar) HebrewCalendar(com.ibm.icu.util.HebrewCalendar) GregorianCalendar(com.ibm.icu.util.GregorianCalendar) GregorianCalendar(com.ibm.icu.util.GregorianCalendar)

Example 35 with Calendar

use of com.ibm.icu.util.Calendar in project mycore by MyCoRe-Org.

the class MCRCalendar method getHistoryDateAsCalendar.

/**
 * This method check a ancient date string for the given calendar. For
 * syntax of the date string see javadocs of calendar methods.
 *
 * @param date_string
 *            the date as string.
 * @param last
 *            the value is true if the date should be filled with the
 *            highest value of month or day like 12 or 31 else it fill the
 *            date with the lowest value 1 for month and day.
 * @param calendar_string
 *            the calendar name as String, kind of the calendars are
 *            ('gregorian', 'julian', 'islamic', 'buddhist', 'coptic',
 *            'ethiopic', 'persic', 'japanese', 'armenian' or 'egyptian' )
 *
 * @return the ICU Calendar instance of the concrete calendar type or null if an error was occurred.
 * @exception MCRException if parsing has an error
 */
public static Calendar getHistoryDateAsCalendar(String date_string, boolean last, String calendar_string) throws MCRException {
    Calendar out = null;
    // check date_string
    LOGGER.debug("Input of getHistoryDateAsCalendar: {}  {}  {}", date_string, calendar_string, Boolean.toString(last));
    if (date_string == null || date_string.trim().length() == 0) {
        throw new MCRException("The ancient date string is null or empty");
    }
    date_string = date_string.trim();
    if (calendar_string == null || calendar_string.trim().length() == 0) {
        throw new MCRException("The calendar string is null or empty");
    }
    if (date_string.equals("4713-01-01 BC")) {
        LOGGER.debug("Date string contains MIN_JULIAN_DAY_NUMBER");
        out = new GregorianCalendar();
        out.set(Calendar.JULIAN_DAY, MCRCalendar.MIN_JULIAN_DAY_NUMBER);
        return out;
    }
    if (date_string.equals("4000-01-28 AD")) {
        LOGGER.debug("Date string contains MAX_JULIAN_DAY_NUMBER");
        out = new GregorianCalendar();
        out.set(Calendar.JULIAN_DAY, MCRCalendar.MAX_JULIAN_DAY_NUMBER);
        return out;
    }
    // Check calendar string
    if (!CALENDARS_LIST.contains(calendar_string)) {
        throw new MCRException("The calendar string " + calendar_string + " is not supported");
    }
    // select for calendar
    if (calendar_string.equals(TAG_GREGORIAN)) {
        out = getCalendarFromGregorianDate(date_string, last);
    }
    if (calendar_string.equals(TAG_JULIAN)) {
        out = getCalendarFromJulianDate(date_string, last);
    }
    if (calendar_string.equals(TAG_ISLAMIC)) {
        out = getCalendarFromIslamicDate(date_string, last);
    }
    if (calendar_string.equals(TAG_COPTIC)) {
        out = getCalendarFromCopticDate(date_string, last);
    }
    if (calendar_string.equals(TAG_ETHIOPIC)) {
        out = getCalendarFromEthiopicDate(date_string, last);
    }
    if (calendar_string.equals(TAG_BUDDHIST)) {
        out = getCalendarFromBuddhistDate(date_string, last);
    }
    if (calendar_string.equals(TAG_PERSIC)) {
        out = getCalendarFromPersicDate(date_string, last);
    }
    if (calendar_string.equals(TAG_ARMENIAN)) {
        out = getCalendarFromArmenianDate(date_string, last);
    }
    if (calendar_string.equals(TAG_EGYPTIAN)) {
        out = getCalendarFromEgyptianDate(date_string, last);
    }
    if (calendar_string.equals(TAG_JAPANESE)) {
        out = getCalendarFromJapaneseDate(date_string, last);
    }
    if (calendar_string.equals(TAG_HEBREW)) {
        out = getCalendarFromHebrewDate(date_string, last);
    }
    LOGGER.debug("Output of getHistoryDateAsCalendar: {}", getCalendarDateToFormattedString(out));
    return out;
}
Also used : EthiopicCalendar(com.ibm.icu.util.EthiopicCalendar) JapaneseCalendar(com.ibm.icu.util.JapaneseCalendar) Calendar(com.ibm.icu.util.Calendar) IslamicCalendar(com.ibm.icu.util.IslamicCalendar) BuddhistCalendar(com.ibm.icu.util.BuddhistCalendar) CopticCalendar(com.ibm.icu.util.CopticCalendar) HebrewCalendar(com.ibm.icu.util.HebrewCalendar) GregorianCalendar(com.ibm.icu.util.GregorianCalendar) GregorianCalendar(com.ibm.icu.util.GregorianCalendar)

Aggregations

Calendar (com.ibm.icu.util.Calendar)75 Timestamp (java.sql.Timestamp)37 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)24 GenericValue (org.apache.ofbiz.entity.GenericValue)24 Delegator (org.apache.ofbiz.entity.Delegator)17 Date (java.util.Date)14 HashMap (java.util.HashMap)12 Locale (java.util.Locale)12 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)11 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)11 GregorianCalendar (com.ibm.icu.util.GregorianCalendar)10 ArrayList (java.util.ArrayList)8 SimpleDateFormat (java.text.SimpleDateFormat)6 LinkedList (java.util.LinkedList)6 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)6 Map (java.util.Map)5 TimeDuration (org.apache.ofbiz.base.util.TimeDuration)5 BigDecimal (java.math.BigDecimal)4 Time (java.sql.Time)4 UtilDateTime (org.apache.ofbiz.base.util.UtilDateTime)4