Search in sources :

Example 41 with EntityListIterator

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

the class JobManager method poll.

/**
 * Scans the JobSandbox entity and returns a list of jobs that are due to run.
 * Returns an empty list if there are no jobs due to run.
 * This method is called by the {@link JobPoller} polling thread.
 */
protected List<Job> poll(int limit) {
    assertIsRunning();
    // The rest of this method logs exceptions and does not throw them.
    // The idea is to keep the JobPoller working even when a database
    // connection is not available (possible on a saturated server).
    DispatchContext dctx = getDispatcher().getDispatchContext();
    if (dctx == null) {
        Debug.logWarning("Unable to locate DispatchContext object; not running job!", module);
        return Collections.emptyList();
    }
    // basic query
    List<EntityExpr> expressions = UtilMisc.toList(EntityCondition.makeCondition("runTime", EntityOperator.LESS_THAN_EQUAL_TO, UtilDateTime.nowTimestamp()), EntityCondition.makeCondition("startDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.EQUALS, null), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
    // limit to just defined pools
    List<String> pools = null;
    try {
        pools = getRunPools();
    } catch (GenericConfigException e) {
        Debug.logWarning(e, "Unable to get run pools - not running job: ", module);
        return Collections.emptyList();
    }
    List<EntityExpr> poolsExpr = UtilMisc.toList(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, null));
    if (!pools.isEmpty()) {
        for (String poolName : pools) {
            poolsExpr.add(EntityCondition.makeCondition("poolId", EntityOperator.EQUALS, poolName));
        }
    }
    List<Job> poll = new ArrayList<>(limit);
    // make the conditions
    EntityCondition baseCondition = EntityCondition.makeCondition(expressions);
    EntityCondition poolCondition = EntityCondition.makeCondition(poolsExpr, EntityOperator.OR);
    EntityCondition mainCondition = EntityCondition.makeCondition(UtilMisc.toList(baseCondition, poolCondition));
    boolean beganTransaction = false;
    try {
        beganTransaction = TransactionUtil.begin();
        if (!beganTransaction) {
            Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
            return poll;
        }
        try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("runTime").queryIterator()) {
            GenericValue jobValue = jobsIterator.next();
            while (jobValue != null) {
                // Claim ownership of this value. Using storeByCondition to avoid a race condition.
                List<EntityExpr> updateExpression = UtilMisc.toList(EntityCondition.makeCondition("jobId", EntityOperator.EQUALS, jobValue.get("jobId")), EntityCondition.makeCondition("runByInstanceId", EntityOperator.EQUALS, null));
                int rowsUpdated = delegator.storeByCondition("JobSandbox", UtilMisc.toMap("runByInstanceId", instanceId), EntityCondition.makeCondition(updateExpression));
                if (rowsUpdated == 1) {
                    poll.add(new PersistedServiceJob(dctx, jobValue, null));
                    if (poll.size() == limit) {
                        break;
                    }
                }
                jobValue = jobsIterator.next();
            }
        } catch (GenericEntityException e) {
            Debug.logWarning(e, module);
        }
        TransactionUtil.commit(beganTransaction);
    } catch (Throwable t) {
        String errMsg = "Exception thrown while polling JobSandbox: ";
        try {
            TransactionUtil.rollback(beganTransaction, errMsg, t);
        } catch (GenericEntityException e) {
            Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
        }
        Debug.logWarning(t, errMsg, module);
        return Collections.emptyList();
    }
    if (poll.isEmpty()) {
        // No jobs to run, see if there are any jobs to purge
        Calendar cal = Calendar.getInstance();
        try {
            int daysToKeep = ServiceConfigUtil.getServiceEngine().getThreadPool().getPurgeJobDays();
            cal.add(Calendar.DAY_OF_YEAR, -daysToKeep);
        } catch (GenericConfigException e) {
            Debug.logWarning(e, "Unable to get purge job days: ", module);
            return Collections.emptyList();
        }
        Timestamp purgeTime = new Timestamp(cal.getTimeInMillis());
        List<EntityExpr> finExp = UtilMisc.toList(EntityCondition.makeCondition("finishDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("finishDateTime", EntityOperator.LESS_THAN, purgeTime));
        List<EntityExpr> canExp = UtilMisc.toList(EntityCondition.makeCondition("cancelDateTime", EntityOperator.NOT_EQUAL, null), EntityCondition.makeCondition("cancelDateTime", EntityOperator.LESS_THAN, purgeTime));
        EntityCondition doneCond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition(canExp), EntityCondition.makeCondition(finExp)), EntityOperator.OR);
        mainCondition = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("runByInstanceId", instanceId), doneCond));
        beganTransaction = false;
        try {
            beganTransaction = TransactionUtil.begin();
            if (!beganTransaction) {
                Debug.logWarning("Unable to poll JobSandbox for jobs; unable to begin transaction.", module);
                return Collections.emptyList();
            }
            try (EntityListIterator jobsIterator = EntityQuery.use(delegator).from("JobSandbox").where(mainCondition).orderBy("jobId").queryIterator()) {
                GenericValue jobValue = jobsIterator.next();
                while (jobValue != null) {
                    poll.add(new PurgeJob(jobValue));
                    if (poll.size() == limit) {
                        break;
                    }
                    jobValue = jobsIterator.next();
                }
            } catch (GenericEntityException e) {
                Debug.logWarning(e, module);
            }
            TransactionUtil.commit(beganTransaction);
        } catch (Throwable t) {
            String errMsg = "Exception thrown while polling JobSandbox: ";
            try {
                TransactionUtil.rollback(beganTransaction, errMsg, t);
            } catch (GenericEntityException e) {
                Debug.logWarning(e, "Exception thrown while rolling back transaction: ", module);
            }
            Debug.logWarning(t, errMsg, module);
            return Collections.emptyList();
        }
    }
    return poll;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) Calendar(com.ibm.icu.util.Calendar) ArrayList(java.util.ArrayList) Timestamp(java.sql.Timestamp) DispatchContext(org.apache.ofbiz.service.DispatchContext) GenericConfigException(org.apache.ofbiz.base.config.GenericConfigException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) EntityExpr(org.apache.ofbiz.entity.condition.EntityExpr)

Example 42 with EntityListIterator

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

the class ProductSearchSession method getCountForProductCategory.

/**
 * This method returns count of products in a given category (including all sub categories), the constraint being
 * applied on current ProductSearchConstraint list in session.
 * @param productCategoryId productCategoryId for which the count should be returned.
 * @param session Current session.
 * @param delegator The delegator object.
 * @return The long value of count of products.
 */
public static long getCountForProductCategory(String productCategoryId, HttpSession session, Delegator delegator) {
    String visitId = VisitHandler.getVisitId(session);
    ProductSearchContext productSearchContext = new ProductSearchContext(delegator, visitId);
    List<ProductSearchConstraint> productSearchConstraintList = ProductSearchOptions.getConstraintList(session);
    if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
        productSearchContext.addProductSearchConstraints(productSearchConstraintList);
    }
    productSearchContext.finishKeywordConstraints();
    productSearchContext.finishCategoryAndFeatureConstraints();
    DynamicViewEntity dynamicViewEntity = productSearchContext.dynamicViewEntity;
    List<EntityCondition> entityConditionList = productSearchContext.entityConditionList;
    List<String> fieldsToSelect = new LinkedList<>();
    dynamicViewEntity.addMemberEntity("PCMC", "ProductCategoryMember");
    dynamicViewEntity.addAlias("PCMC", "pcmcProductCategoryId", "productCategoryId", null, null, null, null);
    dynamicViewEntity.addAlias("PCMC", "pcmcFromDate", "fromDate", null, null, null, null);
    dynamicViewEntity.addAlias("PCMC", "pcmcThruDate", "thruDate", null, null, null, null);
    dynamicViewEntity.addAlias("PCMC", "categoryCount", "productId", null, null, null, "count-distinct");
    dynamicViewEntity.addViewLink("PROD", "PCMC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("productId"));
    fieldsToSelect.add("categoryCount");
    entityConditionList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("pcmcThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("pcmcThruDate", EntityOperator.GREATER_THAN, productSearchContext.nowTimestamp)));
    entityConditionList.add(EntityCondition.makeCondition("pcmcFromDate", EntityOperator.LESS_THAN, productSearchContext.nowTimestamp));
    Set<String> productCategoryIdSet = new HashSet<>();
    ProductSearch.getAllSubCategoryIds(productCategoryId, productCategoryIdSet, delegator, productSearchContext.nowTimestamp);
    entityConditionList.add(EntityCondition.makeCondition("pcmcProductCategoryId", EntityOperator.IN, productCategoryIdSet));
    Long categoryCount = Long.valueOf(0);
    EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet(fieldsToSelect)).from(dynamicViewEntity).where(entityConditionList).orderBy(productSearchContext.orderByList).cursorScrollInsensitive();
    try (EntityListIterator eli = eq.queryIterator()) {
        GenericValue searchResult = null;
        while ((searchResult = eli.next()) != null) {
            categoryCount = searchResult.getLong("categoryCount");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error in product search", module);
    }
    return categoryCount;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ProductSearchContext(org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint) HashSet(java.util.HashSet)

Example 43 with EntityListIterator

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

the class ProductSearchSession method listCountByFeatureForType.

/**
 * This method returns a list of productId counts grouped by productFeatureId's of input productFeatureTypeId,
 * the constraint being applied on current ProductSearchConstraint list in session.
 * @param productFeatureTypeId The productFeatureTypeId, productFeatureId's of which should be considered.
 * @param session Current session.
 * @param delegator The delegator object.
 * @return List of Maps containing productFeatureId, productFeatureTypeId, description, featureCount.
 */
public static List<Map<String, String>> listCountByFeatureForType(String productFeatureTypeId, HttpSession session, Delegator delegator) {
    String visitId = VisitHandler.getVisitId(session);
    ProductSearchContext productSearchContext = new ProductSearchContext(delegator, visitId);
    List<ProductSearchConstraint> productSearchConstraintList = ProductSearchOptions.getConstraintList(session);
    if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
        productSearchContext.addProductSearchConstraints(productSearchConstraintList);
    }
    productSearchContext.finishKeywordConstraints();
    productSearchContext.finishCategoryAndFeatureConstraints();
    DynamicViewEntity dynamicViewEntity = productSearchContext.dynamicViewEntity;
    List<EntityCondition> entityConditionList = productSearchContext.entityConditionList;
    dynamicViewEntity.addMemberEntity("PFAC", "ProductFeatureAppl");
    dynamicViewEntity.addAlias("PFAC", "pfacProductFeatureId", "productFeatureId", null, null, Boolean.TRUE, null);
    dynamicViewEntity.addAlias("PFAC", "pfacFromDate", "fromDate", null, null, null, null);
    dynamicViewEntity.addAlias("PFAC", "pfacThruDate", "thruDate", null, null, null, null);
    dynamicViewEntity.addAlias("PFAC", "featureCount", "productId", null, null, null, "count-distinct");
    dynamicViewEntity.addViewLink("PROD", "PFAC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("productId"));
    entityConditionList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("pfacThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("pfacThruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp())));
    entityConditionList.add(EntityCondition.makeCondition("pfacFromDate", EntityOperator.LESS_THAN, UtilDateTime.nowTimestamp()));
    dynamicViewEntity.addMemberEntity("PFC", "ProductFeature");
    dynamicViewEntity.addAlias("PFC", "pfcProductFeatureTypeId", "productFeatureTypeId", null, null, Boolean.TRUE, null);
    dynamicViewEntity.addAlias("PFC", "pfcDescription", "description", null, null, Boolean.TRUE, null);
    dynamicViewEntity.addViewLink("PFAC", "PFC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("productFeatureId"));
    entityConditionList.add(EntityCondition.makeCondition("pfcProductFeatureTypeId", EntityOperator.EQUALS, productFeatureTypeId));
    List<Map<String, String>> featureCountList = null;
    EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet("pfacProductFeatureId", "featureCount", "pfcDescription", "pfcProductFeatureTypeId")).from(dynamicViewEntity).where(entityConditionList).orderBy(productSearchContext.orderByList).cursorScrollInsensitive();
    try (EntityListIterator eli = eq.queryIterator()) {
        featureCountList = new LinkedList<>();
        GenericValue searchResult = null;
        while ((searchResult = eli.next()) != null) {
            featureCountList.add(UtilMisc.<String, String>toMap("productFeatureId", (String) searchResult.get("pfacProductFeatureId"), "productFeatureTypeId", (String) searchResult.get("pfcProductFeatureTypeId"), "description", (String) searchResult.get("pfcDescription"), "featureCount", Long.toString((Long) searchResult.get("featureCount"))));
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error in product search", module);
        return null;
    }
    return featureCountList;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ProductSearchContext(org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) HashMap(java.util.HashMap) Map(java.util.Map) ModelKeyMap(org.apache.ofbiz.entity.model.ModelKeyMap) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)

Example 44 with EntityListIterator

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

the class ProductSearchSession method getProductSearchResult.

@SuppressWarnings("unchecked")
public static Map<String, Object> getProductSearchResult(HttpServletRequest request, Delegator delegator, String prodCatalogId) {
    // ========== Create View Indexes
    int viewIndex = 0;
    int viewSize = 20;
    int highIndex = 0;
    int lowIndex = 0;
    int listSize = 0;
    String paging = "Y";
    int previousViewSize = 20;
    Map<String, Object> requestParams = UtilHttp.getCombinedMap(request);
    List<String> keywordTypeIds = new LinkedList<>();
    if (requestParams.get("keywordTypeId") instanceof String) {
        keywordTypeIds.add((String) requestParams.get("keywordTypeId"));
    } else if (requestParams.get("keywordTypeId") instanceof List) {
        keywordTypeIds = (List<String>) requestParams.get("keywordTypeId");
    }
    String statusId = (String) requestParams.get("statusId");
    HttpSession session = request.getSession();
    ProductSearchOptions productSearchOptions = getProductSearchOptions(session);
    String addOnTopProdCategoryId = productSearchOptions.getTopProductCategoryId();
    Integer viewIndexInteger = productSearchOptions.getViewIndex();
    if (viewIndexInteger != null) {
        viewIndex = viewIndexInteger.intValue();
    }
    Integer viewSizeInteger = productSearchOptions.getViewSize();
    if (viewSizeInteger != null) {
        viewSize = viewSizeInteger.intValue();
    }
    Integer previousViewSizeInteger = productSearchOptions.getPreviousViewSize();
    if (previousViewSizeInteger != null) {
        previousViewSize = previousViewSizeInteger.intValue();
    }
    String pag = productSearchOptions.getPaging();
    paging = pag;
    lowIndex = viewIndex * viewSize;
    highIndex = (viewIndex + 1) * viewSize;
    // ========== Do the actual search
    List<String> productIds = new LinkedList<>();
    String visitId = VisitHandler.getVisitId(session);
    List<ProductSearchConstraint> productSearchConstraintList = ProductSearchOptions.getConstraintList(session);
    String noConditionFind = (String) requestParams.get("noConditionFind");
    if (UtilValidate.isEmpty(noConditionFind)) {
        noConditionFind = EntityUtilProperties.getPropertyValue("widget", "widget.defaultNoConditionFind", delegator);
    }
    // if noConditionFind to Y then find without conditions otherwise search according to constraints.
    if ("Y".equals(noConditionFind) || UtilValidate.isNotEmpty(productSearchConstraintList)) {
        // if the search options have changed since the last search, put at the beginning of the options history list
        checkSaveSearchOptionsHistory(session);
        int addOnTopTotalListSize = 0;
        int addOnTopListSize = 0;
        List<GenericValue> addOnTopProductCategoryMembers;
        if (UtilValidate.isNotEmpty(addOnTopProdCategoryId)) {
            // always include the members of the addOnTopProdCategoryId
            Timestamp now = UtilDateTime.nowTimestamp();
            List<EntityCondition> addOnTopProdCondList = new LinkedList<>();
            addOnTopProdCondList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("thruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("thruDate", EntityOperator.GREATER_THAN, now)));
            addOnTopProdCondList.add(EntityCondition.makeCondition("fromDate", EntityOperator.LESS_THAN, now));
            addOnTopProdCondList.add(EntityCondition.makeCondition("productCategoryId", EntityOperator.EQUALS, addOnTopProdCategoryId));
            EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet("productId", "sequenceNum")).from("ProductCategoryMember").where(addOnTopProdCondList).orderBy("sequenceNum").cursorScrollInsensitive().distinct().maxRows(highIndex);
            try (EntityListIterator pli = eq.queryIterator()) {
                addOnTopProductCategoryMembers = pli.getPartialList(lowIndex, viewSize);
                addOnTopListSize = addOnTopProductCategoryMembers.size();
                for (GenericValue alwaysAddProductCategoryMember : addOnTopProductCategoryMembers) {
                    productIds.add(alwaysAddProductCategoryMember.getString("productId"));
                }
                addOnTopTotalListSize = pli.getResultsSizeAfterPartialList();
                listSize = listSize + addOnTopTotalListSize;
            } catch (GenericEntityException e) {
                Debug.logError(e, module);
            }
        }
        // setup resultOffset and maxResults, noting that resultOffset is 1 based, not zero based as these numbers
        int resultOffsetInt = lowIndex - addOnTopTotalListSize + 1;
        if (resultOffsetInt < 1) {
            resultOffsetInt = 1;
        }
        int maxResultsInt = viewSize - addOnTopListSize;
        Integer resultOffset = Integer.valueOf(resultOffsetInt);
        Integer maxResults = Integer.valueOf(maxResultsInt);
        ResultSortOrder resultSortOrder = ProductSearchOptions.getResultSortOrder(request);
        ProductSearchContext productSearchContext = new ProductSearchContext(delegator, visitId);
        if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
            productSearchContext.addProductSearchConstraints(productSearchConstraintList);
        }
        productSearchContext.setResultSortOrder(resultSortOrder);
        productSearchContext.setResultOffset(resultOffset);
        productSearchContext.setMaxResults(maxResults);
        if (UtilValidate.isNotEmpty(keywordTypeIds)) {
            productSearchContext.keywordTypeIds = keywordTypeIds;
        } else {
            productSearchContext.keywordTypeIds = UtilMisc.toList("KWT_KEYWORD");
        }
        if (UtilValidate.isNotEmpty(statusId)) {
            productSearchContext.statusId = statusId;
        }
        List<String> foundProductIds = productSearchContext.doSearch();
        if (maxResultsInt > 0) {
            productIds.addAll(foundProductIds);
        }
        Integer totalResults = productSearchContext.getTotalResults();
        if (totalResults != null) {
            listSize = listSize + totalResults.intValue();
        }
    }
    if (listSize < highIndex) {
        highIndex = listSize;
    }
    // ========== Setup other display info
    List<String> searchConstraintStrings = searchGetConstraintStrings(false, session, delegator);
    String searchSortOrderString = searchGetSortOrderString(false, request);
    // ========== populate the result Map
    Map<String, Object> result = new HashMap<>();
    result.put("productIds", productIds);
    result.put("viewIndex", Integer.valueOf(viewIndex));
    result.put("viewSize", Integer.valueOf(viewSize));
    result.put("listSize", Integer.valueOf(listSize));
    result.put("lowIndex", Integer.valueOf(lowIndex));
    result.put("highIndex", Integer.valueOf(highIndex));
    result.put("paging", paging);
    result.put("previousViewSize", previousViewSize);
    result.put("searchConstraintStrings", searchConstraintStrings);
    result.put("searchSortOrderString", searchSortOrderString);
    result.put("noConditionFind", noConditionFind);
    return result;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) ResultSortOrder(org.apache.ofbiz.product.product.ProductSearch.ResultSortOrder) HashMap(java.util.HashMap) HttpSession(javax.servlet.http.HttpSession) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) Timestamp(java.sql.Timestamp) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint) FeatureConstraint(org.apache.ofbiz.product.product.ProductSearch.FeatureConstraint) CategoryConstraint(org.apache.ofbiz.product.product.ProductSearch.CategoryConstraint) KeywordConstraint(org.apache.ofbiz.product.product.ProductSearch.KeywordConstraint) LinkedList(java.util.LinkedList) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ProductSearchContext(org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)

Example 45 with EntityListIterator

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

the class ProductSearchSession method getCountForListPriceRange.

/**
 * This method returns count of products within a given price range, the constraint being
 * applied on current ProductSearchConstraint list in session.
 * @param priceLow The low price.
 * @param priceHigh The high price.
 * @param session Current session.
 * @param delegator The delegator object.
 * @return The long value of count of products.
 */
public static long getCountForListPriceRange(BigDecimal priceLow, BigDecimal priceHigh, HttpSession session, Delegator delegator) {
    String visitId = VisitHandler.getVisitId(session);
    ProductSearchContext productSearchContext = new ProductSearchContext(delegator, visitId);
    List<ProductSearchConstraint> productSearchConstraintList = ProductSearchOptions.getConstraintList(session);
    if (UtilValidate.isNotEmpty(productSearchConstraintList)) {
        productSearchContext.addProductSearchConstraints(productSearchConstraintList);
    }
    productSearchContext.finishKeywordConstraints();
    productSearchContext.finishCategoryAndFeatureConstraints();
    DynamicViewEntity dynamicViewEntity = productSearchContext.dynamicViewEntity;
    List<EntityCondition> entityConditionList = productSearchContext.entityConditionList;
    List<String> fieldsToSelect = new LinkedList<>();
    dynamicViewEntity.addMemberEntity("PPC", "ProductPrice");
    dynamicViewEntity.addAlias("PPC", "ppcProductPriceTypeId", "productPriceTypeId", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "ppcFromDate", "fromDate", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "ppcThruDate", "thruDate", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "ppcPrice", "price", null, null, null, null);
    dynamicViewEntity.addAlias("PPC", "priceRangeCount", "productId", null, null, null, "count-distinct");
    dynamicViewEntity.addViewLink("PROD", "PPC", Boolean.FALSE, ModelKeyMap.makeKeyMapList("productId"));
    fieldsToSelect.add("priceRangeCount");
    entityConditionList.add(EntityCondition.makeCondition(EntityCondition.makeCondition("ppcThruDate", EntityOperator.EQUALS, null), EntityOperator.OR, EntityCondition.makeCondition("ppcThruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp())));
    entityConditionList.add(EntityCondition.makeCondition("ppcFromDate", EntityOperator.LESS_THAN, UtilDateTime.nowTimestamp()));
    entityConditionList.add(EntityCondition.makeCondition("ppcPrice", EntityOperator.GREATER_THAN_EQUAL_TO, priceLow));
    entityConditionList.add(EntityCondition.makeCondition("ppcPrice", EntityOperator.LESS_THAN_EQUAL_TO, priceHigh));
    entityConditionList.add(EntityCondition.makeCondition("ppcProductPriceTypeId", EntityOperator.EQUALS, "LIST_PRICE"));
    Long priceRangeCount = Long.valueOf(0);
    EntityQuery eq = EntityQuery.use(delegator).select(UtilMisc.toSet(fieldsToSelect)).from(dynamicViewEntity).where(entityConditionList).orderBy(productSearchContext.orderByList).cursorScrollInsensitive();
    try (EntityListIterator eli = eq.queryIterator()) {
        GenericValue searchResult = null;
        while ((searchResult = eli.next()) != null) {
            priceRangeCount = searchResult.getLong("priceRangeCount");
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Error in product search", module);
    }
    return priceRangeCount;
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) EntityQuery(org.apache.ofbiz.entity.util.EntityQuery) LinkedList(java.util.LinkedList) DynamicViewEntity(org.apache.ofbiz.entity.model.DynamicViewEntity) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) ProductSearchContext(org.apache.ofbiz.product.product.ProductSearch.ProductSearchContext) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)

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