Search in sources :

Example 21 with EntityListIterator

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

the class EntityQueryTestSuite method testCursorScrollInSensitive.

/*
     * cursorScrollInSensitive(): ResultSet object's cursor is scrollable but generally not sensitive to changes to the data that underlies the ResultSet.
     * assert: Compared first record found by both the iterators.
     */
public void testCursorScrollInSensitive() throws GenericEntityException {
    List<GenericValue> testingTypes = new LinkedList<>();
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollInSensitive-1", "description", "cursorScrollInSensitive One"));
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollInSensitive-2", "description", "cursorScrollInSensitive Two"));
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollInSensitive-3", "description", "cursorScrollInSensitive Three"));
    delegator.storeAll(testingTypes);
    boolean transactionStarted = false;
    try {
        transactionStarted = TransactionUtil.begin();
        EntityListIterator eliByEntityEngine = null;
        EntityListIterator eliByEntityQuery = null;
        EntityFindOptions findOptions = new EntityFindOptions();
        findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_INSENSITIVE);
        eliByEntityEngine = delegator.find("TestingType", null, null, null, null, findOptions);
        eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").cursorScrollInsensitive().queryIterator();
        GenericValue nextRecordByDelegator = eliByEntityEngine.next();
        GenericValue nextRecordByEntityQuery = eliByEntityQuery.next();
        assertEquals("cursorScrollInSensitive(): Records by delegator method and by EntityQuery method matched", nextRecordByDelegator, nextRecordByEntityQuery);
        eliByEntityEngine.close();
        eliByEntityQuery.close();
        TransactionUtil.commit(transactionStarted);
    } catch (GenericEntityException e) {
        TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) LinkedList(java.util.LinkedList)

Example 22 with EntityListIterator

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

the class EntityQueryTestSuite method testCursorForwardOnly.

/*
     * cursorForwardOnly(): Indicate that the ResultSet object's cursor may move only forward
     * assert: Compared first record found by both the iterator.
     */
public void testCursorForwardOnly() throws GenericEntityException {
    List<GenericValue> testingTypes = new LinkedList<>();
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "cursorForwardOnly-1", "description", "cursorForwardOnly One"));
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "cursorForwardOnly-2", "description", "cursorForwardOnly Two"));
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "cursorForwardOnly-3", "description", "cursorForwardOnly Three"));
    delegator.storeAll(testingTypes);
    boolean transactionStarted = false;
    try {
        transactionStarted = TransactionUtil.begin();
        EntityListIterator eliByEntityEngine = null;
        EntityListIterator eliByEntityQuery = null;
        EntityFindOptions findOptions = new EntityFindOptions();
        findOptions.setResultSetType(EntityFindOptions.TYPE_FORWARD_ONLY);
        eliByEntityEngine = delegator.find("TestingType", null, null, null, null, findOptions);
        eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").cursorForwardOnly().queryIterator();
        GenericValue nextRecordByEntityEngine = eliByEntityEngine.next();
        GenericValue nextRecordByEntityQuery = eliByEntityQuery.next();
        assertEquals("cursorForwardOnly(): Value of first record pointed by both iterators matched", nextRecordByEntityEngine, nextRecordByEntityQuery);
        eliByEntityEngine.close();
        eliByEntityQuery.close();
        TransactionUtil.commit(transactionStarted);
    } catch (GenericEntityException e) {
        TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) LinkedList(java.util.LinkedList)

Example 23 with EntityListIterator

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

the class EntityQueryTestSuite method testCursorScrollSensitive.

/*
     * cursorScrollSensitive(): ResultSet object's cursor is scrollable but generally sensitive to changes to the data that underlies the ResultSet.
     * assert: Compared first record found by both the iterators.
     */
public void testCursorScrollSensitive() throws GenericEntityException {
    List<GenericValue> testingTypes = new LinkedList<>();
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollSensitive-1", "description", "cursorScrollSensitive One"));
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollSensitive-2", "description", "cursorScrollSensitive Two"));
    testingTypes.add(delegator.makeValue("TestingType", "testingTypeId", "scrollSensitive-3", "description", "cursorScrollSensitive Three"));
    delegator.storeAll(testingTypes);
    boolean transactionStarted = false;
    try {
        transactionStarted = TransactionUtil.begin();
        EntityListIterator eliByEntityEngine = null;
        EntityListIterator eliByEntityQuery = null;
        EntityFindOptions findOptions = new EntityFindOptions();
        findOptions.setResultSetType(EntityFindOptions.TYPE_SCROLL_SENSITIVE);
        eliByEntityEngine = delegator.find("TestingType", null, null, null, null, findOptions);
        eliByEntityQuery = EntityQuery.use(delegator).from("TestingType").cursorScrollSensitive().queryIterator();
        GenericValue nextRecordByDelegator = eliByEntityEngine.next();
        GenericValue nextRecordByEntityQuery = eliByEntityQuery.next();
        assertEquals("cursorScrollSensitive(): Records by delegator method and by EntityQuery method matched", nextRecordByDelegator, nextRecordByEntityQuery);
        eliByEntityEngine.close();
        eliByEntityQuery.close();
        TransactionUtil.commit(transactionStarted);
    } catch (GenericEntityException e) {
        TransactionUtil.rollback(transactionStarted, "Transaction is Rolled Back", e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) LinkedList(java.util.LinkedList)

Example 24 with EntityListIterator

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

the class ListFinder method runFind.

@Override
public void runFind(Map<String, Object> context, Delegator delegator) throws GeneralException {
    String entityName = this.entityNameExdr.expandString(context);
    String useCacheStr = this.useCacheStrExdr.expandString(context);
    String filterByDateStr = this.filterByDateStrExdr.expandString(context);
    String distinctStr = this.distinctStrExdr.expandString(context);
    String delegatorName = this.delegatorNameExdr.expandString(context);
    ModelEntity modelEntity = delegator.getModelEntity(entityName);
    String resultSetTypeString = this.resultSetTypeExdr.expandString(context);
    if (modelEntity == null) {
        throw new IllegalArgumentException("In find entity by " + label + " could not find definition for entity with name [" + entityName + "].");
    }
    boolean useCache = "true".equals(useCacheStr);
    boolean filterByDate = "true".equals(filterByDateStr);
    boolean distinct = "true".equals(distinctStr);
    int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
    if ("forward".equals(resultSetTypeString)) {
        resultSetType = ResultSet.TYPE_FORWARD_ONLY;
    }
    if (UtilValidate.isNotEmpty(delegatorName)) {
        delegator = DelegatorFactory.getDelegator(delegatorName);
    }
    EntityCondition whereEntityCondition = getWhereEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
    EntityCondition havingEntityCondition = getHavingEntityCondition(context, modelEntity, delegator.getModelFieldTypeReader(modelEntity));
    if (useCache) {
        // if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination
        if (outputHandler instanceof UseIterator) {
            Debug.logWarning("In find entity by " + label + " cannot have use-cache set to true " + label + " select use-iterator for the output type. Using cache and ignoring use-iterator setting.", module);
            outputHandler = new GetAll();
        }
        if (distinct) {
            throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true " + label + " set distinct to true.");
        }
        if (havingEntityCondition != null) {
            throw new IllegalArgumentException("In find entity by " + label + " cannot have use-cache set to true and specify a having-condition-list (can only use a where condition with condition-expr or condition-list).");
        }
    }
    // get the list of fieldsToSelect from selectFieldExpanderList
    Set<String> fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
    // if fieldsToSelect != null and useCacheBool is true, throw an error
    if (fieldsToSelect != null && useCache) {
        throw new IllegalArgumentException("Error in entity query by " + label + " definition, cannot specify select-field elements when use-cache is set to true");
    }
    // get the list of orderByFields from orderByExpanderList
    List<String> orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
    try {
        // if filterByDate, do a date filter on the results based on the now-timestamp
        if (filterByDate && !useCache) {
            EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr();
            if (whereEntityCondition != null) {
                whereEntityCondition = EntityCondition.makeCondition(UtilMisc.toList(whereEntityCondition, filterByDateCondition));
            } else {
                whereEntityCondition = filterByDateCondition;
            }
        }
        if (useCache) {
            List<GenericValue> results = delegator.findList(entityName, whereEntityCondition, fieldsToSelect, orderByFields, null, true);
            if (filterByDate) {
                results = EntityUtil.filterByDate(results);
            }
            this.outputHandler.handleOutput(results, context, listAcsr);
        } else {
            boolean useTransaction = true;
            if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) {
                Exception newE = new Exception("Stack Trace");
                Debug.logError(newE, "ERROR: Cannot do a by " + label + " find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
                useTransaction = false;
            }
            EntityFindOptions options = new EntityFindOptions();
            options.setDistinct(distinct);
            options.setResultSetType(resultSetType);
            if (outputHandler instanceof LimitRange) {
                LimitRange limitRange = (LimitRange) outputHandler;
                int start = limitRange.getStart(context);
                int size = limitRange.getSize(context);
                options.setMaxRows(start + size);
            } else if (outputHandler instanceof LimitView) {
                LimitView limitView = (LimitView) outputHandler;
                int index = limitView.getIndex(context);
                int size = limitView.getSize(context);
                options.setMaxRows(size * (index + 1));
            }
            boolean beganTransaction = false;
            try {
                if (useTransaction) {
                    beganTransaction = TransactionUtil.begin();
                }
                EntityListIterator eli = delegator.find(entityName, whereEntityCondition, havingEntityCondition, fieldsToSelect, orderByFields, options);
                this.outputHandler.handleOutput(eli, context, listAcsr);
            // NOTE: the eli EntityListIterator is not closed here. It SHOULD be closed later after the returned list will be used (eg see EntityAnd.getChildren() in ModelTree.java)
            } catch (GenericEntityException e) {
                String errMsg = "Failure in by " + label + " find operation, rolling back transaction";
                Debug.logError(e, errMsg, module);
                try {
                    // only rollback the transaction if we started one...
                    TransactionUtil.rollback(beganTransaction, errMsg, e);
                } catch (GenericEntityException e2) {
                    Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
                }
                // after rolling back, rethrow the exception
                throw e;
            } finally {
                // only commit the transaction if we started one... this will throw an exception if it fails
                TransactionUtil.commit(beganTransaction);
            }
        }
    } catch (GenericEntityException e) {
        String errMsg = "Error doing find by " + label + ": " + e.toString();
        Debug.logError(e, module);
        throw new GeneralException(errMsg, e);
    }
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GeneralException(org.apache.ofbiz.base.util.GeneralException) GetAll(org.apache.ofbiz.entity.finder.EntityFinderUtil.GetAll) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LimitView(org.apache.ofbiz.entity.finder.EntityFinderUtil.LimitView) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GeneralException(org.apache.ofbiz.base.util.GeneralException) LimitRange(org.apache.ofbiz.entity.finder.EntityFinderUtil.LimitRange) UseIterator(org.apache.ofbiz.entity.finder.EntityFinderUtil.UseIterator) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 25 with EntityListIterator

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

the class OrderServices method runSubscriptionAutoReorders.

public static Map<String, Object> runSubscriptionAutoReorders(DispatchContext dctx, Map<String, ? extends Object> context) {
    LocalDispatcher dispatcher = dctx.getDispatcher();
    Delegator delegator = dctx.getDelegator();
    GenericValue userLogin = (GenericValue) context.get("userLogin");
    Locale locale = (Locale) context.get("locale");
    int count = 0;
    Map<String, Object> result = null;
    boolean beganTransaction = false;
    List<EntityExpr> exprs = UtilMisc.toList(EntityCondition.makeCondition("automaticExtend", EntityOperator.EQUALS, "Y"), EntityCondition.makeCondition("orderId", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("productId", EntityOperator.NOT_EQUAL, null));
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, "[Delegator] Could not begin transaction: " + e1.toString(), module);
    }
    try (EntityListIterator eli = EntityQuery.use(delegator).from("Subscription").where(exprs).queryIterator()) {
        if (eli != null) {
            GenericValue subscription;
            while (((subscription = eli.next()) != null)) {
                Calendar endDate = Calendar.getInstance();
                endDate.setTime(UtilDateTime.nowTimestamp());
                // Check if today date + cancel period (if provided) is earlier than the thrudate
                int field = Calendar.MONTH;
                if (subscription.get("canclAutmExtTime") != null && subscription.get("canclAutmExtTimeUomId") != null) {
                    if ("TF_day".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.DAY_OF_YEAR;
                    } else if ("TF_wk".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.WEEK_OF_YEAR;
                    } else if ("TF_mon".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.MONTH;
                    } else if ("TF_yr".equals(subscription.getString("canclAutmExtTimeUomId"))) {
                        field = Calendar.YEAR;
                    } else {
                        Debug.logWarning("Don't know anything about canclAutmExtTimeUomId [" + subscription.getString("canclAutmExtTimeUomId") + "], defaulting to month", module);
                    }
                    endDate.add(field, Integer.parseInt(subscription.getString("canclAutmExtTime")));
                }
                Calendar endDateSubscription = Calendar.getInstance();
                endDateSubscription.setTime(subscription.getTimestamp("thruDate"));
                if (endDate.before(endDateSubscription)) {
                    // nor expired yet.....
                    continue;
                }
                result = dispatcher.runSync("loadCartFromOrder", UtilMisc.toMap("orderId", subscription.get("orderId"), "userLogin", userLogin));
                if (ServiceUtil.isError(result)) {
                    return ServiceUtil.returnError(ServiceUtil.getErrorMessage(result));
                }
                ShoppingCart cart = (ShoppingCart) result.get("shoppingCart");
                // remove former orderId from cart (would cause duplicate entry).
                // orderId is set by order-creation services (including store-specific prefixes, e.g.)
                cart.setOrderId(null);
                // only keep the orderitem with the related product.
                List<ShoppingCartItem> cartItems = cart.items();
                for (ShoppingCartItem shoppingCartItem : cartItems) {
                    if (!subscription.get("productId").equals(shoppingCartItem.getProductId())) {
                        cart.removeCartItem(shoppingCartItem, dispatcher);
                    }
                }
                CheckOutHelper helper = new CheckOutHelper(dispatcher, delegator, cart);
                // store the order
                Map<String, Object> createResp = helper.createOrder(userLogin);
                if (createResp != null && ServiceUtil.isError(createResp)) {
                    Debug.logError("Cannot create order for shopping list - " + subscription, module);
                } else {
                    String orderId = (String) createResp.get("orderId");
                    // authorize the payments
                    Map<String, Object> payRes = null;
                    try {
                        payRes = helper.processPayment(ProductStoreWorker.getProductStore(cart.getProductStoreId(), delegator), userLogin);
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                    if (payRes != null && ServiceUtil.isError(payRes)) {
                        Debug.logError("Payment processing problems with shopping list - " + subscription, module);
                    }
                    // remove the automatic extension flag
                    subscription.put("automaticExtend", "N");
                    subscription.store();
                    // send notification
                    if (orderId != null) {
                        dispatcher.runAsync("sendOrderPayRetryNotification", UtilMisc.toMap("orderId", orderId));
                    }
                    count++;
                }
            }
        }
    } catch (GenericServiceException e) {
        Debug.logError("Could call service to create cart", module);
        return ServiceUtil.returnError(e.toString());
    } catch (CartItemModifyException e) {
        Debug.logError("Could not modify cart: " + e.toString(), module);
        return ServiceUtil.returnError(e.toString());
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error creating subscription auto-reorders", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        Debug.logError(e, "Error while creating new shopping list based automatic reorder" + e.toString(), module);
        return ServiceUtil.returnError(UtilProperties.getMessage(resource, "OrderShoppingListCreationError", UtilMisc.toMap("errorString", e.toString()), locale));
    } finally {
        try {
            // only commit the transaction if we started one... this will throw an exception if it fails
            TransactionUtil.commit(beganTransaction);
        } catch (GenericEntityException e) {
            Debug.logError(e, "Could not commit transaction for creating new shopping list based automatic reorder", module);
        }
    }
    return ServiceUtil.returnSuccess(UtilProperties.getMessage(resource, "OrderRunSubscriptionAutoReorders", UtilMisc.toMap("count", count), locale));
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) Calendar(com.ibm.icu.util.Calendar) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) CartItemModifyException(org.apache.ofbiz.order.shoppingcart.CartItemModifyException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) ShoppingCartItem(org.apache.ofbiz.order.shoppingcart.ShoppingCartItem) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

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