Search in sources :

Example 61 with EntityListIterator

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

the class ShoppingListServices method createListReorders.

public static Map<String, Object> createListReorders(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");
    boolean beganTransaction = false;
    EntityQuery eq = EntityQuery.use(delegator).from("ShoppingList").where("shoppingListTypeId", "SLT_AUTO_REODR", "isActive", "Y").orderBy("-lastOrderedDate");
    try {
        beganTransaction = TransactionUtil.begin();
    } catch (GenericTransactionException e1) {
        Debug.logError(e1, "[Delegator] Could not begin transaction: " + e1.toString(), module);
    }
    try (EntityListIterator eli = eq.queryIterator()) {
        if (eli != null) {
            GenericValue shoppingList;
            while (((shoppingList = eli.next()) != null)) {
                Timestamp lastOrder = shoppingList.getTimestamp("lastOrderedDate");
                RecurrenceInfo recurrence = null;
                GenericValue recurrenceInfo = shoppingList.getRelatedOne("RecurrenceInfo", false);
                Timestamp startDateTime = recurrenceInfo.getTimestamp("startDateTime");
                try {
                    recurrence = new RecurrenceInfo(recurrenceInfo);
                } catch (RecurrenceInfoException e) {
                    Debug.logError(e, module);
                }
                // check the next recurrence
                if (recurrence != null) {
                    long next = lastOrder == null ? recurrence.next(startDateTime.getTime()) : recurrence.next(lastOrder.getTime());
                    Timestamp now = UtilDateTime.nowTimestamp();
                    Timestamp nextOrder = UtilDateTime.getDayStart(UtilDateTime.getTimestamp(next));
                    if (nextOrder.after(now)) {
                        continue;
                    }
                } else {
                    continue;
                }
                ShoppingCart listCart = makeShoppingListCart(dispatcher, shoppingList, locale);
                CheckOutHelper helper = new CheckOutHelper(dispatcher, delegator, listCart);
                // store the order
                Map<String, Object> createResp = helper.createOrder(userLogin);
                if (createResp == null || (createResp != null && ServiceUtil.isError(createResp))) {
                    Debug.logError("Cannot create order for shopping list - " + shoppingList, module);
                } else {
                    String orderId = (String) createResp.get("orderId");
                    // authorize the payments
                    Map<String, Object> payRes = null;
                    try {
                        payRes = helper.processPayment(ProductStoreWorker.getProductStore(listCart.getProductStoreId(), delegator), userLogin);
                    } catch (GeneralException e) {
                        Debug.logError(e, module);
                    }
                    if (payRes != null && ServiceUtil.isError(payRes)) {
                        Debug.logError("Payment processing problems with shopping list - " + shoppingList, module);
                    }
                    shoppingList.set("lastOrderedDate", UtilDateTime.nowTimestamp());
                    shoppingList.store();
                    // send notification
                    try {
                        dispatcher.runAsync("sendOrderPayRetryNotification", UtilMisc.toMap("orderId", orderId));
                    } catch (GenericServiceException e) {
                        Debug.logError(e, module);
                    }
                    // increment the recurrence
                    recurrence.incrementCurrentCount();
                }
            }
        }
        return ServiceUtil.returnSuccess();
    } catch (GenericEntityException e) {
        try {
            // only rollback the transaction if we started one...
            TransactionUtil.rollback(beganTransaction, "Error creating shopping list auto-reorders", e);
        } catch (GenericEntityException e2) {
            Debug.logError(e2, "[Delegator] Could not rollback transaction: " + e2.toString(), module);
        }
        String errMsg = UtilProperties.getMessage(resource_error, "OrderErrorWhileCreatingNewShoppingListBasedAutomaticReorder", UtilMisc.toMap("errorString", e.toString()), locale);
        Debug.logError(e, errMsg, module);
        return ServiceUtil.returnError(errMsg);
    } 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);
        }
    }
}
Also used : Locale(java.util.Locale) RecurrenceInfoException(org.apache.ofbiz.service.calendar.RecurrenceInfoException) GenericValue(org.apache.ofbiz.entity.GenericValue) LocalDispatcher(org.apache.ofbiz.service.LocalDispatcher) GeneralException(org.apache.ofbiz.base.util.GeneralException) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) CheckOutHelper(org.apache.ofbiz.order.shoppingcart.CheckOutHelper) Delegator(org.apache.ofbiz.entity.Delegator) ShoppingCart(org.apache.ofbiz.order.shoppingcart.ShoppingCart) RecurrenceInfo(org.apache.ofbiz.service.calendar.RecurrenceInfo) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) GenericServiceException(org.apache.ofbiz.service.GenericServiceException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 62 with EntityListIterator

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

the class WorkEffortServices method removeDuplicateWorkEfforts.

public static Map<String, Object> removeDuplicateWorkEfforts(DispatchContext ctx, Map<String, ? extends Object> context) {
    List<GenericValue> resultList = null;
    try (EntityListIterator eli = (EntityListIterator) context.get("workEffortIterator")) {
        if (eli != null) {
            Set<String> keys = new HashSet<>();
            resultList = new LinkedList<>();
            GenericValue workEffort = eli.next();
            while (workEffort != null) {
                String workEffortId = workEffort.getString("workEffortId");
                if (!keys.contains(workEffortId)) {
                    resultList.add(workEffort);
                    keys.add(workEffortId);
                }
                workEffort = eli.next();
            }
        } else {
            List<GenericValue> workEfforts = UtilGenerics.checkList(context.get("workEfforts"));
            if (workEfforts != null) {
                resultList = WorkEffortWorker.removeDuplicateWorkEfforts(workEfforts);
            }
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, module);
    }
    Map<String, Object> result = ServiceUtil.returnSuccess();
    result.put("workEfforts", resultList);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashSet(java.util.HashSet)

Example 63 with EntityListIterator

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

the class LoginServices method createUserLoginPasswordHistory.

public static void createUserLoginPasswordHistory(Delegator delegator, String userLoginId, String currentPassword) throws GenericEntityException {
    int passwordChangeHistoryLimit = 0;
    try {
        passwordChangeHistoryLimit = EntityUtilProperties.getPropertyAsInteger("security", "password.change.history.limit", 0).intValue();
    } catch (NumberFormatException nfe) {
        // No valid value is found so don't bother to save any password history
        passwordChangeHistoryLimit = 0;
    }
    if (passwordChangeHistoryLimit == 0 || passwordChangeHistoryLimit < 0) {
        // Not saving password history, so return from here.
        return;
    }
    EntityQuery eq = EntityQuery.use(delegator).from("UserLoginPasswordHistory").where("userLoginId", userLoginId).orderBy("-fromDate").cursorScrollInsensitive();
    Timestamp nowTimestamp = UtilDateTime.nowTimestamp();
    try (EntityListIterator eli = eq.queryIterator()) {
        GenericValue pwdHist;
        if ((pwdHist = eli.next()) != null) {
            // updating password so set end date on previous password in history
            pwdHist.set("thruDate", nowTimestamp);
            pwdHist.store();
            // check if we have hit the limit on number of password changes to be saved. If we did then delete the oldest password from history.
            eli.last();
            int rowIndex = eli.currentIndex();
            if (rowIndex == passwordChangeHistoryLimit) {
                eli.afterLast();
                pwdHist = eli.previous();
                pwdHist.remove();
            }
        }
    }
    // save this password in history
    GenericValue userLoginPwdHistToCreate = delegator.makeValue("UserLoginPasswordHistory", UtilMisc.toMap("userLoginId", userLoginId, "fromDate", nowTimestamp));
    boolean useEncryption = "true".equals(EntityUtilProperties.getPropertyValue("security", "password.encrypt", delegator));
    userLoginPwdHistToCreate.set("currentPassword", useEncryption ? HashCrypt.cryptUTF8(getHashType(), null, currentPassword) : currentPassword);
    userLoginPwdHistToCreate.create();
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp)

Example 64 with EntityListIterator

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

the class GenericDelegator method findList.

/* (non-Javadoc)
     * @see org.apache.ofbiz.entity.Delegator#findList(java.lang.String, org.apache.ofbiz.entity.condition.EntityCondition, java.util.Set, java.util.List, org.apache.ofbiz.entity.util.EntityFindOptions, boolean)
     */
@Override
public List<GenericValue> findList(String entityName, EntityCondition entityCondition, Set<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions, boolean useCache) throws GenericEntityException {
    EntityEcaRuleRunner<?> ecaRunner = null;
    GenericValue dummyValue = null;
    if (useCache) {
        ecaRunner = this.getEcaRuleRunner(entityName);
        ModelEntity modelEntity = getModelReader().getModelEntity(entityName);
        dummyValue = GenericValue.create(modelEntity);
        ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_CHECK, EntityEcaHandler.OP_FIND, dummyValue, false);
        List<GenericValue> cacheList = this.cache.get(entityName, entityCondition, orderBy);
        if (cacheList != null) {
            return cacheList;
        }
    }
    boolean beganTransaction = false;
    try {
        if (alwaysUseTransaction) {
            beganTransaction = TransactionUtil.begin();
        }
        List<GenericValue> list = null;
        try (EntityListIterator eli = this.find(entityName, entityCondition, null, fieldsToSelect, orderBy, findOptions)) {
            list = eli.getCompleteList();
        }
        if (useCache) {
            ecaRunner.evalRules(EntityEcaHandler.EV_CACHE_PUT, EntityEcaHandler.OP_FIND, dummyValue, false);
            this.cache.put(entityName, entityCondition, orderBy, list);
        }
        TransactionUtil.commit(beganTransaction);
        return list;
    } catch (GenericEntityException e) {
        String errMsg = "Failure in findByCondition operation for entity [" + entityName + "]: " + e.toString() + ". Rolling back transaction.";
        Debug.logError(e, errMsg, module);
        TransactionUtil.rollback(beganTransaction, errMsg, e);
        throw new GenericEntityException(e);
    }
}
Also used : ModelEntity(org.apache.ofbiz.entity.model.ModelEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator)

Example 65 with EntityListIterator

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

the class GenericDAO method selectListIteratorByCondition.

/* ====================================================================== */
/* ====================================================================== */
/**
 * Finds GenericValues by the conditions specified in the EntityCondition object, the the EntityCondition javadoc for more details.
 *@param modelEntity The ModelEntity of the Entity as defined in the entity XML file
 *@param whereEntityCondition The EntityCondition object that specifies how to constrain this query before any groupings are done (if this is a view entity with group-by aliases)
 *@param havingEntityCondition The EntityCondition object that specifies how to constrain this query after any groupings are done (if this is a view entity with group-by aliases)
 *@param fieldsToSelect The fields of the named entity to get from the database; if empty or null all fields will be retreived
 *@param orderBy The fields of the named entity to order the query by; optionally add a " ASC" for ascending or " DESC" for descending
 *@param findOptions An instance of EntityFindOptions that specifies advanced query options. See the EntityFindOptions JavaDoc for more details.
 *@return EntityListIterator representing the result of the query: NOTE THAT THIS MUST BE CLOSED WHEN YOU ARE
 *      DONE WITH IT (preferably in a finally block),
 *      AND DON'T LEAVE IT OPEN TOO LONG BECAUSE IT WILL MAINTAIN A DATABASE CONNECTION.
 */
public EntityListIterator selectListIteratorByCondition(Delegator delegator, ModelEntity modelEntity, EntityCondition whereEntityCondition, EntityCondition havingEntityCondition, Collection<String> fieldsToSelect, List<String> orderBy, EntityFindOptions findOptions) throws GenericEntityException {
    if (modelEntity == null) {
        return null;
    }
    ModelViewEntity modelViewEntity = null;
    if (modelEntity instanceof ModelViewEntity) {
        modelViewEntity = (ModelViewEntity) modelEntity;
    }
    // if no find options passed, use default
    if (findOptions == null)
        findOptions = new EntityFindOptions();
    boolean verboseOn = Debug.verboseOn();
    if (verboseOn) {
        // put this inside an if statement so that we don't have to generate the string when not used...
        if (Debug.verboseOn())
            Debug.logVerbose("Doing selectListIteratorByCondition with whereEntityCondition: " + whereEntityCondition, module);
    }
    // make two ArrayLists of fields, one for fields to select and the other for where clause fields (to find by)
    List<ModelField> selectFields = new LinkedList<ModelField>();
    if (UtilValidate.isNotEmpty(fieldsToSelect)) {
        Set<String> tempKeys = new HashSet<String>();
        tempKeys.addAll(fieldsToSelect);
        Set<String> fieldSetsToInclude = new HashSet<String>();
        Set<String> addedFields = new HashSet<String>();
        for (String fieldToSelect : fieldsToSelect) {
            if (tempKeys.contains(fieldToSelect)) {
                ModelField curField = modelEntity.getField(fieldToSelect);
                if (curField != null) {
                    fieldSetsToInclude.add(curField.getFieldSet());
                    selectFields.add(curField);
                    tempKeys.remove(fieldToSelect);
                    addedFields.add(fieldToSelect);
                }
            }
        }
        if (tempKeys.size() > 0) {
            throw new GenericModelException("In selectListIteratorByCondition invalid field names specified: " + tempKeys.toString());
        }
        fieldSetsToInclude.remove("");
        if (verboseOn) {
            Debug.logInfo("[" + modelEntity.getEntityName() + "]: field-sets to include: " + fieldSetsToInclude, module);
        }
        if (UtilValidate.isNotEmpty(fieldSetsToInclude)) {
            Iterator<ModelField> fieldIter = modelEntity.getFieldsIterator();
            Set<String> extraFields = new HashSet<String>();
            Set<String> reasonSets = new HashSet<String>();
            while (fieldIter.hasNext()) {
                ModelField curField = fieldIter.next();
                String fieldSet = curField.getFieldSet();
                if (UtilValidate.isEmpty(fieldSet)) {
                    continue;
                }
                if (!fieldSetsToInclude.contains(fieldSet)) {
                    continue;
                }
                String fieldName = curField.getName();
                if (addedFields.contains(fieldName)) {
                    continue;
                }
                reasonSets.add(fieldSet);
                extraFields.add(fieldName);
                addedFields.add(fieldName);
                selectFields.add(curField);
            }
            if (verboseOn) {
                Debug.logInfo("[" + modelEntity.getEntityName() + "]: auto-added select fields: " + extraFields, module);
                Debug.logInfo("[" + modelEntity.getEntityName() + "]: auto-added field-sets: " + reasonSets, module);
            }
        }
    } else {
        selectFields = modelEntity.getFieldsUnmodifiable();
    }
    StringBuilder sqlBuffer = new StringBuilder("SELECT ");
    if (findOptions.getDistinct()) {
        sqlBuffer.append("DISTINCT ");
    }
    if (selectFields.size() > 0) {
        modelEntity.colNameString(selectFields, sqlBuffer, "", ", ", "", datasource.getAliasViewColumns());
    } else {
        sqlBuffer.append("*");
    }
    // populate the info from entity-condition in the view-entity, if it is one and there is one
    List<EntityCondition> viewWhereConditions = null;
    List<EntityCondition> viewHavingConditions = null;
    List<String> viewOrderByList = null;
    if (modelViewEntity != null) {
        viewWhereConditions = new LinkedList<EntityCondition>();
        viewHavingConditions = new LinkedList<EntityCondition>();
        viewOrderByList = new LinkedList<String>();
        modelViewEntity.populateViewEntityConditionInformation(modelFieldTypeReader, viewWhereConditions, viewHavingConditions, viewOrderByList, null);
    }
    // FROM clause and when necessary the JOIN or LEFT JOIN clause(s) as well
    sqlBuffer.append(SqlJdbcUtil.makeFromClause(modelEntity, modelFieldTypeReader, datasource));
    // WHERE clause
    List<EntityConditionParam> whereEntityConditionParams = new LinkedList<EntityConditionParam>();
    makeConditionWhereString(sqlBuffer, " WHERE ", modelEntity, whereEntityCondition, viewWhereConditions, whereEntityConditionParams);
    // GROUP BY clause for view-entity
    if (modelViewEntity != null) {
        modelViewEntity.colNameString(modelViewEntity.getGroupBysCopy(selectFields), sqlBuffer, " GROUP BY ", ", ", "", false);
    }
    // HAVING clause
    List<EntityConditionParam> havingEntityConditionParams = new LinkedList<EntityConditionParam>();
    makeConditionHavingString(sqlBuffer, " HAVING ", modelEntity, havingEntityCondition, viewHavingConditions, havingEntityConditionParams);
    // ORDER BY clause
    List<String> orderByExpanded = new LinkedList<String>();
    // add the manually specified ones, then the ones in the view entity's entity-condition
    if (orderBy != null) {
        orderByExpanded.addAll(orderBy);
    }
    if (viewOrderByList != null) {
        // add to end of other order by so that those in method call will override those in view
        orderByExpanded.addAll(viewOrderByList);
    }
    sqlBuffer.append(SqlJdbcUtil.makeOrderByClause(modelEntity, orderByExpanded, datasource));
    // OFFSET clause
    makeOffsetString(sqlBuffer, findOptions);
    // make the final SQL String
    String sql = sqlBuffer.toString();
    SQLProcessor sqlP = new SQLProcessor(delegator, helperInfo);
    sqlP.prepareStatement(sql, findOptions.getSpecifyTypeAndConcur(), findOptions.getResultSetType(), findOptions.getResultSetConcurrency(), findOptions.getFetchSize(), findOptions.getMaxRows());
    if (verboseOn) {
        // put this inside an if statement so that we don't have to generate the string when not used...
        if (Debug.verboseOn())
            Debug.logVerbose("Setting the whereEntityConditionParams: " + whereEntityConditionParams, module);
    }
    // set all of the values from the Where EntityCondition
    for (EntityConditionParam whereEntityConditionParam : whereEntityConditionParams) {
        SqlJdbcUtil.setValue(sqlP, whereEntityConditionParam.getModelField(), modelEntity.getEntityName(), whereEntityConditionParam.getFieldValue(), modelFieldTypeReader);
    }
    if (verboseOn) {
        // put this inside an if statement so that we don't have to generate the string when not used...
        if (Debug.verboseOn())
            Debug.logVerbose("Setting the havingEntityConditionParams: " + havingEntityConditionParams, module);
    }
    // set all of the values from the Having EntityCondition
    for (EntityConditionParam havingEntityConditionParam : havingEntityConditionParams) {
        SqlJdbcUtil.setValue(sqlP, havingEntityConditionParam.getModelField(), modelEntity.getEntityName(), havingEntityConditionParam.getFieldValue(), modelFieldTypeReader);
    }
    long queryStartTime = 0;
    if (Debug.timingOn()) {
        queryStartTime = System.currentTimeMillis();
    }
    sqlP.executeQuery();
    if (Debug.timingOn()) {
        long queryEndTime = System.currentTimeMillis();
        long queryTotalTime = queryEndTime - queryStartTime;
        if (queryTotalTime > 150) {
            Debug.logTiming("Ran query in " + queryTotalTime + " milli-seconds: " + " EntityName: " + modelEntity.getEntityName() + " Sql: " + sql + " where clause:" + whereEntityConditionParams, module);
        }
    }
    return new EntityListIterator(sqlP, modelEntity, selectFields, modelFieldTypeReader, this, whereEntityCondition, havingEntityCondition, findOptions.getDistinct());
}
Also used : GenericModelException(org.apache.ofbiz.entity.GenericModelException) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) SQLProcessor(org.apache.ofbiz.entity.jdbc.SQLProcessor) ModelField(org.apache.ofbiz.entity.model.ModelField) EntityFindOptions(org.apache.ofbiz.entity.util.EntityFindOptions) ModelViewEntity(org.apache.ofbiz.entity.model.ModelViewEntity) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashSet(java.util.HashSet) EntityConditionParam(org.apache.ofbiz.entity.condition.EntityConditionParam)

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