Search in sources :

Example 46 with GenericValue

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

the class ProductSearchSession method processSearchParameters.

public static void processSearchParameters(Map<String, Object> parameters, HttpServletRequest request) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Boolean alreadyRun = (Boolean) request.getAttribute("processSearchParametersAlreadyRun");
    if (Boolean.TRUE.equals(alreadyRun)) {
        return;
    }
    request.setAttribute("processSearchParametersAlreadyRun", Boolean.TRUE);
    HttpSession session = request.getSession();
    boolean constraintsChanged = false;
    GenericValue productStore = ProductStoreWorker.getProductStore(request);
    // clear search? by default yes, but if the clearSearch parameter is N then don't
    String clearSearchString = (String) parameters.get("clearSearch");
    if (!"N".equals(clearSearchString)) {
        searchClear(session);
        constraintsChanged = true;
    } else {
        String removeConstraint = (String) parameters.get("removeConstraint");
        if (UtilValidate.isNotEmpty(removeConstraint)) {
            try {
                searchRemoveConstraint(Integer.parseInt(removeConstraint), session);
                constraintsChanged = true;
            } catch (Exception e) {
                Debug.logError(e, "Error removing constraint [" + removeConstraint + "]", module);
            }
        }
    }
    String prioritizeCategoryId = null;
    if (UtilValidate.isNotEmpty(parameters.get("PRIORITIZE_CATEGORY_ID"))) {
        prioritizeCategoryId = (String) parameters.get("PRIORITIZE_CATEGORY_ID");
    } else if (UtilValidate.isNotEmpty(parameters.get("S_TPC"))) {
        prioritizeCategoryId = (String) parameters.get("S_TPC");
    }
    if (UtilValidate.isNotEmpty(prioritizeCategoryId)) {
        ProductSearchOptions.setTopProductCategoryId(prioritizeCategoryId, session);
        constraintsChanged = true;
    }
    // if there is another category, add a constraint for it
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_CATEGORY_ID"))) {
        String searchCategoryId = (String) parameters.get("SEARCH_CATEGORY_ID");
        String searchSubCategories = (String) parameters.get("SEARCH_SUB_CATEGORIES");
        String searchCategoryExc = (String) parameters.get("SEARCH_CATEGORY_EXC");
        Boolean exclude = UtilValidate.isEmpty(searchCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchCategoryExc));
        searchAddConstraint(new ProductSearch.CategoryConstraint(searchCategoryId, !"N".equals(searchSubCategories), exclude), session);
        constraintsChanged = true;
    }
    for (int catNum = 1; catNum < 10; catNum++) {
        if (UtilValidate.isNotEmpty(parameters.get("SEARCH_CATEGORY_ID" + catNum))) {
            String searchCategoryId = (String) parameters.get("SEARCH_CATEGORY_ID" + catNum);
            String searchSubCategories = (String) parameters.get("SEARCH_SUB_CATEGORIES" + catNum);
            String searchCategoryExc = (String) parameters.get("SEARCH_CATEGORY_EXC" + catNum);
            Boolean exclude = UtilValidate.isEmpty(searchCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchCategoryExc));
            searchAddConstraint(new ProductSearch.CategoryConstraint(searchCategoryId, !"N".equals(searchSubCategories), exclude), session);
            constraintsChanged = true;
        }
    }
    // a shorter variation for categories
    for (int catNum = 1; catNum < 10; catNum++) {
        if (UtilValidate.isNotEmpty(parameters.get("S_CAT" + catNum))) {
            String searchCategoryId = (String) parameters.get("S_CAT" + catNum);
            String searchSubCategories = (String) parameters.get("S_CSB" + catNum);
            String searchCategoryExc = (String) parameters.get("S_CEX" + catNum);
            Boolean exclude = UtilValidate.isEmpty(searchCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchCategoryExc));
            searchAddConstraint(new ProductSearch.CategoryConstraint(searchCategoryId, !"N".equals(searchSubCategories), exclude), session);
            constraintsChanged = true;
        }
    }
    // if there is any category selected try to use catalog and add a constraint for it
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_CATALOG_ID"))) {
        String searchCatalogId = (String) parameters.get("SEARCH_CATALOG_ID");
        if (searchCatalogId != null && !searchCatalogId.equalsIgnoreCase("")) {
            String topCategory = CatalogWorker.getCatalogTopCategoryId(request, searchCatalogId);
            if (UtilValidate.isEmpty(topCategory)) {
                topCategory = CatalogWorker.getCatalogTopEbayCategoryId(request, searchCatalogId);
            }
            List<GenericValue> categories = CategoryWorker.getRelatedCategoriesRet(request, "topLevelList", topCategory, true, false, true);
            searchAddConstraint(new ProductSearch.CatalogConstraint(searchCatalogId, categories), session);
            constraintsChanged = true;
        }
    }
    // if keywords were specified, add a constraint for them
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_STRING"))) {
        String keywordString = (String) parameters.get("SEARCH_STRING");
        String searchOperator = (String) parameters.get("SEARCH_OPERATOR");
        // defaults to true/Y, ie anything but N is true/Y
        boolean anyPrefixSuffix = !"N".equals(parameters.get("SEARCH_ANYPRESUF"));
        searchAddConstraint(new ProductSearch.KeywordConstraint(keywordString, anyPrefixSuffix, anyPrefixSuffix, null, "AND".equals(searchOperator)), session);
        constraintsChanged = true;
    }
    // if productName were specified, add a constraint for them
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_PRODUCT_NAME"))) {
        String productName = (String) parameters.get("SEARCH_PRODUCT_NAME");
        searchAddConstraint(new ProductSearch.ProductFieldConstraint(productName, "productName"), session);
        constraintsChanged = true;
    }
    // if internalName were specified, add a constraint for them
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_INTERNAL_PROD_NAME"))) {
        String internalName = (String) parameters.get("SEARCH_INTERNAL_PROD_NAME");
        searchAddConstraint(new ProductSearch.ProductFieldConstraint(internalName, "internalName"), session);
        constraintsChanged = true;
    }
    for (int kwNum = 1; kwNum < 10; kwNum++) {
        if (UtilValidate.isNotEmpty(parameters.get("SEARCH_STRING" + kwNum))) {
            String keywordString = (String) parameters.get("SEARCH_STRING" + kwNum);
            String searchOperator = (String) parameters.get("SEARCH_OPERATOR" + kwNum);
            // defaults to true/Y, ie anything but N is true/Y
            boolean anyPrefixSuffix = !"N".equals(parameters.get("SEARCH_ANYPRESUF" + kwNum));
            searchAddConstraint(new ProductSearch.KeywordConstraint(keywordString, anyPrefixSuffix, anyPrefixSuffix, null, "AND".equals(searchOperator)), session);
            constraintsChanged = true;
        }
    }
    for (Entry<String, Object> entry : parameters.entrySet()) {
        String parameterName = entry.getKey();
        if (parameterName.startsWith("SEARCH_FEAT") && !parameterName.startsWith("SEARCH_FEAT_EXC")) {
            String productFeatureId = (String) parameters.get(parameterName);
            if (UtilValidate.isNotEmpty(productFeatureId)) {
                String paramNameExt = parameterName.substring("SEARCH_FEAT".length());
                String searchCategoryExc = (String) parameters.get("SEARCH_FEAT_EXC" + paramNameExt);
                Boolean exclude = UtilValidate.isEmpty(searchCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchCategoryExc));
                // Debug.logInfo("parameterName=" + parameterName + ", paramNameExt=" + paramNameExt + ", searchCategoryExc=" + searchCategoryExc + ", exclude=" + exclude, module);
                searchAddConstraint(new ProductSearch.FeatureConstraint(productFeatureId, exclude), session);
                constraintsChanged = true;
            }
        }
        // a shorter feature variation
        if (parameterName.startsWith("S_PFI")) {
            String productFeatureId = (String) parameters.get(parameterName);
            if (UtilValidate.isNotEmpty(productFeatureId)) {
                String paramNameExt = parameterName.substring("S_PFI".length());
                String searchCategoryExc = (String) parameters.get("S_PFX" + paramNameExt);
                Boolean exclude = UtilValidate.isEmpty(searchCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchCategoryExc));
                searchAddConstraint(new ProductSearch.FeatureConstraint(productFeatureId, exclude), session);
                constraintsChanged = true;
            }
        }
        // if product features category were selected add a constraint for each
        if (parameterName.startsWith("SEARCH_PROD_FEAT_CAT") && !parameterName.startsWith("SEARCH_PROD_FEAT_CAT_EXC")) {
            String productFeatureCategoryId = (String) parameters.get(parameterName);
            if (UtilValidate.isNotEmpty(productFeatureCategoryId)) {
                String paramNameExt = parameterName.substring("SEARCH_PROD_FEAT_CAT".length());
                String searchProdFeatureCategoryExc = (String) parameters.get("SEARCH_PROD_FEAT_CAT_EXC" + paramNameExt);
                Boolean exclude = UtilValidate.isEmpty(searchProdFeatureCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchProdFeatureCategoryExc));
                searchAddConstraint(new ProductSearch.FeatureCategoryConstraint(productFeatureCategoryId, exclude), session);
                constraintsChanged = true;
            }
        }
        // a shorter variation for feature category
        if (parameterName.startsWith("S_FCI")) {
            String productFeatureCategoryId = (String) parameters.get(parameterName);
            if (UtilValidate.isNotEmpty(productFeatureCategoryId)) {
                String paramNameExt = parameterName.substring("S_FCI".length());
                String searchProdFeatureCategoryExc = (String) parameters.get("S_FCX" + paramNameExt);
                Boolean exclude = UtilValidate.isEmpty(searchProdFeatureCategoryExc) ? null : Boolean.valueOf(!"N".equals(searchProdFeatureCategoryExc));
                searchAddConstraint(new ProductSearch.FeatureCategoryConstraint(productFeatureCategoryId, exclude), session);
                constraintsChanged = true;
            }
        }
        // if product features group were selected add a constraint for each
        if (parameterName.startsWith("SEARCH_PROD_FEAT_GRP") && !parameterName.startsWith("SEARCH_PROD_FEAT_GRP_EXC")) {
            String productFeatureGroupId = (String) parameters.get(parameterName);
            if (UtilValidate.isNotEmpty(productFeatureGroupId)) {
                String paramNameExt = parameterName.substring("SEARCH_PROD_FEAT_GRP".length());
                String searchProdFeatureGroupExc = (String) parameters.get("SEARCH_PROD_FEAT_GRP_EXC" + paramNameExt);
                Boolean exclude = UtilValidate.isEmpty(searchProdFeatureGroupExc) ? null : Boolean.valueOf(!"N".equals(searchProdFeatureGroupExc));
                searchAddConstraint(new ProductSearch.FeatureGroupConstraint(productFeatureGroupId, exclude), session);
                constraintsChanged = true;
            }
        }
        // a shorter variation for feature group
        if (parameterName.startsWith("S_FGI")) {
            String productFeatureGroupId = (String) parameters.get(parameterName);
            if (UtilValidate.isNotEmpty(productFeatureGroupId)) {
                String paramNameExt = parameterName.substring("S_FGI".length());
                String searchProdFeatureGroupExc = (String) parameters.get("S_FGX" + paramNameExt);
                Boolean exclude = UtilValidate.isEmpty(searchProdFeatureGroupExc) ? null : Boolean.valueOf(!"N".equals(searchProdFeatureGroupExc));
                searchAddConstraint(new ProductSearch.FeatureGroupConstraint(productFeatureGroupId, exclude), session);
                constraintsChanged = true;
            }
        }
    }
    // if features were selected add a constraint for each
    Map<String, String> featureIdByType = ParametricSearch.makeFeatureIdByTypeMap(parameters);
    if (featureIdByType.size() > 0) {
        constraintsChanged = true;
        searchAddFeatureIdConstraints(featureIdByType.values(), null, request);
    }
    // add a supplier to the search
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_SUPPLIER_ID")) || UtilValidate.isNotEmpty(parameters.get("S_SUP"))) {
        String supplierPartyId = (String) parameters.get("SEARCH_SUPPLIER_ID");
        if (UtilValidate.isEmpty(supplierPartyId)) {
            supplierPartyId = (String) parameters.get("S_SUP");
        }
        searchAddConstraint(new ProductSearch.SupplierConstraint(supplierPartyId), session);
        constraintsChanged = true;
    }
    // add a list price range to the search
    if (UtilValidate.isNotEmpty(parameters.get("LIST_PRICE_LOW")) || UtilValidate.isNotEmpty(parameters.get("LIST_PRICE_HIGH"))) {
        BigDecimal listPriceLow = null;
        BigDecimal listPriceHigh = null;
        String listPriceCurrency = UtilHttp.getCurrencyUom(request);
        if (UtilValidate.isNotEmpty(parameters.get("LIST_PRICE_LOW"))) {
            try {
                listPriceLow = new BigDecimal((String) parameters.get("LIST_PRICE_LOW"));
            } catch (NumberFormatException e) {
                Debug.logError("Error parsing LIST_PRICE_LOW parameter [" + (String) parameters.get("LIST_PRICE_LOW") + "]: " + e.toString(), module);
            }
        }
        if (UtilValidate.isNotEmpty(parameters.get("LIST_PRICE_HIGH"))) {
            try {
                listPriceHigh = new BigDecimal((String) parameters.get("LIST_PRICE_HIGH"));
            } catch (NumberFormatException e) {
                Debug.logError("Error parsing LIST_PRICE_HIGH parameter [" + (String) parameters.get("LIST_PRICE_HIGH") + "]: " + e.toString(), module);
            }
        }
        searchAddConstraint(new ProductSearch.ListPriceRangeConstraint(listPriceLow, listPriceHigh, listPriceCurrency), session);
        constraintsChanged = true;
    }
    if (UtilValidate.isNotEmpty(parameters.get("LIST_PRICE_RANGE")) || UtilValidate.isNotEmpty(parameters.get("S_LPR"))) {
        String listPriceRangeStr = (String) parameters.get("LIST_PRICE_RANGE");
        if (UtilValidate.isEmpty(listPriceRangeStr)) {
            listPriceRangeStr = (String) parameters.get("S_LPR");
        }
        int underscoreIndex = listPriceRangeStr.indexOf('_');
        String listPriceLowStr;
        String listPriceHighStr;
        if (underscoreIndex >= 0) {
            listPriceLowStr = listPriceRangeStr.substring(0, listPriceRangeStr.indexOf('_'));
            listPriceHighStr = listPriceRangeStr.substring(listPriceRangeStr.indexOf('_') + 1);
        } else {
            // no underscore: assume it is a low range with no high range, ie the ending underscore was left off
            listPriceLowStr = listPriceRangeStr;
            listPriceHighStr = null;
        }
        BigDecimal listPriceLow = null;
        BigDecimal listPriceHigh = null;
        String listPriceCurrency = UtilHttp.getCurrencyUom(request);
        if (UtilValidate.isNotEmpty(listPriceLowStr)) {
            try {
                listPriceLow = new BigDecimal(listPriceLowStr);
            } catch (NumberFormatException e) {
                Debug.logError("Error parsing low part of LIST_PRICE_RANGE parameter [" + listPriceLowStr + "]: " + e.toString(), module);
            }
        }
        if (UtilValidate.isNotEmpty(listPriceHighStr)) {
            try {
                listPriceHigh = new BigDecimal(listPriceHighStr);
            } catch (NumberFormatException e) {
                Debug.logError("Error parsing high part of LIST_PRICE_RANGE parameter [" + listPriceHighStr + "]: " + e.toString(), module);
            }
        }
        searchAddConstraint(new ProductSearch.ListPriceRangeConstraint(listPriceLow, listPriceHigh, listPriceCurrency), session);
        constraintsChanged = true;
    }
    // check the ProductStore to see if we should add the ExcludeVariantsConstraint
    if (productStore != null && !"N".equals(productStore.getString("prodSearchExcludeVariants"))) {
        searchAddConstraint(new ProductSearch.ExcludeVariantsConstraint(), session);
    // not consider this a change for now, shouldn't change often: constraintsChanged = true;
    }
    if ("true".equalsIgnoreCase((String) parameters.get("AVAILABILITY_FILTER"))) {
        searchAddConstraint(new ProductSearch.AvailabilityDateConstraint(), session);
        constraintsChanged = true;
    }
    if (UtilValidate.isNotEmpty(parameters.get("SEARCH_GOOD_IDENTIFICATION_TYPE")) || UtilValidate.isNotEmpty(parameters.get("SEARCH_GOOD_IDENTIFICATION_VALUE"))) {
        String include = (String) parameters.get("SEARCH_GOOD_IDENTIFICATION_INCL");
        if (UtilValidate.isEmpty(include)) {
            include = "Y";
        }
        Boolean inc = Boolean.TRUE;
        if ("N".equalsIgnoreCase(include)) {
            inc = Boolean.FALSE;
        }
        searchAddConstraint(new ProductSearch.GoodIdentificationConstraint((String) parameters.get("SEARCH_GOOD_IDENTIFICATION_TYPE"), (String) parameters.get("SEARCH_GOOD_IDENTIFICATION_VALUE"), inc), session);
        constraintsChanged = true;
    }
    String prodCatalogId = CatalogWorker.getCurrentCatalogId(request);
    String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, prodCatalogId);
    if (UtilValidate.isNotEmpty(viewProductCategoryId)) {
        ProductSearchConstraint viewAllowConstraint = new CategoryConstraint(viewProductCategoryId, true, null);
        searchAddConstraint(viewAllowConstraint, session);
    // not consider this a change for now, shouldn't change often: constraintsChanged = true;
    }
    // set the sort order
    String sortOrder = (String) parameters.get("sortOrder");
    if (UtilValidate.isEmpty(sortOrder)) {
        sortOrder = (String) parameters.get("S_O");
    }
    String sortAscending = (String) parameters.get("sortAscending");
    if (UtilValidate.isEmpty(sortAscending)) {
        sortAscending = (String) parameters.get("S_A");
    }
    boolean ascending = !"N".equals(sortAscending);
    if (sortOrder != null) {
        if ("SortKeywordRelevancy".equals(sortOrder) || "SKR".equals(sortOrder)) {
            searchSetSortOrder(new ProductSearch.SortKeywordRelevancy(), session);
        } else if (sortOrder.startsWith("SortProductField:")) {
            String fieldName = sortOrder.substring("SortProductField:".length());
            searchSetSortOrder(new ProductSearch.SortProductField(fieldName, ascending), session);
        } else if (sortOrder.startsWith("SPF:")) {
            String fieldName = sortOrder.substring("SPF:".length());
            searchSetSortOrder(new ProductSearch.SortProductField(fieldName, ascending), session);
        } else if (sortOrder.startsWith("SortProductPrice:")) {
            String priceTypeId = sortOrder.substring("SortProductPrice:".length());
            searchSetSortOrder(new ProductSearch.SortProductPrice(priceTypeId, ascending), session);
        } else if (sortOrder.startsWith("SPP:")) {
            String priceTypeId = sortOrder.substring("SPP:".length());
            searchSetSortOrder(new ProductSearch.SortProductPrice(priceTypeId, ascending), session);
        } else if (sortOrder.startsWith("SortProductFeature:")) {
            String featureId = sortOrder.substring("SortProductFeature:".length());
            searchSetSortOrder(new ProductSearch.SortProductFeature(featureId, ascending), session);
        } else if (sortOrder.startsWith("SPFT:")) {
            String priceTypeId = sortOrder.substring("SPFT:".length());
            searchSetSortOrder(new ProductSearch.SortProductPrice(priceTypeId, ascending), session);
        }
    }
    ProductSearchOptions productSearchOptions = getProductSearchOptions(session);
    if (constraintsChanged) {
        // query changed, clear out the VIEW_INDEX & VIEW_SIZE
        productSearchOptions.clearViewInfo();
    }
    productSearchOptions.setViewIndex((String) parameters.get("VIEW_INDEX"));
    productSearchOptions.setViewSize((String) parameters.get("VIEW_SIZE"));
    productSearchOptions.setPaging((String) parameters.get("PAGING"));
}
Also used : KeywordConstraint(org.apache.ofbiz.product.product.ProductSearch.KeywordConstraint) GenericValue(org.apache.ofbiz.entity.GenericValue) HttpSession(javax.servlet.http.HttpSession) FeatureConstraint(org.apache.ofbiz.product.product.ProductSearch.FeatureConstraint) IOException(java.io.IOException) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) CategoryConstraint(org.apache.ofbiz.product.product.ProductSearch.CategoryConstraint) 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) BigDecimal(java.math.BigDecimal) Delegator(org.apache.ofbiz.entity.Delegator) SortKeywordRelevancy(org.apache.ofbiz.product.product.ProductSearch.SortKeywordRelevancy) CategoryConstraint(org.apache.ofbiz.product.product.ProductSearch.CategoryConstraint) ProductSearchConstraint(org.apache.ofbiz.product.product.ProductSearch.ProductSearchConstraint)

Example 47 with GenericValue

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

the class ProductSearchEvents method searchAddToCategory.

/**
 *  Adds the results of a search to the specified catogory
 *@param request The HTTPRequest object for the current request
 *@param response The HTTPResponse object for the current request
 *@return String specifying the exit status of this event
 */
public static String searchAddToCategory(HttpServletRequest request, HttpServletResponse response) {
    Delegator delegator = (Delegator) request.getAttribute("delegator");
    String productCategoryId = request.getParameter("SE_SEARCH_CATEGORY_ID");
    String fromDateStr = request.getParameter("fromDate");
    Timestamp fromDate = null;
    String errMsg = null;
    try {
        fromDate = Timestamp.valueOf(fromDateStr);
    } catch (RuntimeException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errDateFormat", e.toString());
        errMsg = UtilProperties.getMessage(resource, "productsearchevents.fromDate_not_formatted_properly", messageMap, UtilHttp.getLocale(request));
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    try {
        boolean beganTransaction = TransactionUtil.begin(DEFAULT_TX_TIMEOUT);
        try (EntityListIterator eli = getProductSearchResults(request)) {
            if (eli == null) {
                errMsg = UtilProperties.getMessage(resource, "productsearchevents.no_results_found_probably_error_constraints", UtilHttp.getLocale(request));
                request.setAttribute("_ERROR_MESSAGE_", errMsg);
                return "error";
            }
            GenericValue searchResultView = null;
            int numAdded = 0;
            while ((searchResultView = eli.next()) != null) {
                String productId = searchResultView.getString("mainProductId");
                GenericValue pcm = delegator.makeValue("ProductCategoryMember");
                pcm.set("productCategoryId", productCategoryId);
                pcm.set("productId", productId);
                pcm.set("fromDate", fromDate);
                pcm.create();
                numAdded++;
            }
            Map<String, String> messageMap = UtilMisc.toMap("numAdded", Integer.toString(numAdded));
            errMsg = UtilProperties.getMessage(resource, "productsearchevents.added_x_product_category_members", messageMap, UtilHttp.getLocale(request));
            request.setAttribute("_EVENT_MESSAGE_", errMsg);
        } catch (GenericEntityException e) {
            Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
            errMsg = UtilProperties.getMessage(resource, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
            Debug.logError(e, errMsg, module);
            request.setAttribute("_ERROR_MESSAGE_", errMsg);
            TransactionUtil.rollback(beganTransaction, errMsg, e);
            return "error";
        } finally {
            TransactionUtil.commit(beganTransaction);
        }
    } catch (GenericTransactionException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errSearchResult", e.toString());
        errMsg = UtilProperties.getMessage(resource, "productsearchevents.error_getting_search_results", messageMap, UtilHttp.getLocale(request));
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }
    return "success";
}
Also used : GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) GenericTransactionException(org.apache.ofbiz.entity.transaction.GenericTransactionException) EntityListIterator(org.apache.ofbiz.entity.util.EntityListIterator) Timestamp(java.sql.Timestamp) HashMap(java.util.HashMap) Map(java.util.Map)

Example 48 with GenericValue

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

the class ProductServices method quickAddVariant.

public static Map<String, Object> quickAddVariant(DispatchContext dctx, Map<String, ? extends Object> context) {
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> result = new HashMap<>();
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    String productId = (String) context.get("productId");
    String variantProductId = (String) context.get("productVariantId");
    String productFeatureIds = (String) context.get("productFeatureIds");
    Long prodAssocSeqNum = (Long) context.get("sequenceNum");
    try {
        // read the product, duplicate it with the given id
        GenericValue product = EntityQuery.use(delegator).from("Product").where("productId", productId).queryOne();
        if (product == null) {
            Map<String, String> messageMap = UtilMisc.toMap("productId", productId);
            errMsg = UtilProperties.getMessage(resourceError, "productservices.product_not_found_with_ID", messageMap, locale);
            result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
            result.put(ModelService.ERROR_MESSAGE, errMsg);
            return result;
        }
        // check if product exists
        GenericValue variantProduct = EntityQuery.use(delegator).from("Product").where("productId", variantProductId).queryOne();
        boolean variantProductExists = (variantProduct != null);
        if (variantProduct == null) {
            // if product does not exist
            variantProduct = GenericValue.create(product);
            variantProduct.set("productId", variantProductId);
            variantProduct.set("isVirtual", "N");
            variantProduct.set("isVariant", "Y");
            variantProduct.set("primaryProductCategoryId", null);
            // create new
            variantProduct.create();
        } else {
            // if product does exist
            variantProduct.set("isVirtual", "N");
            variantProduct.set("isVariant", "Y");
            variantProduct.set("primaryProductCategoryId", null);
            // update entry
            variantProduct.store();
        }
        if (variantProductExists) {
            // Since the variant product is already a variant, first of all we remove the old features
            // and the associations of type PRODUCT_VARIANT: a given product can be a variant of only one product.
            delegator.removeByAnd("ProductAssoc", UtilMisc.toMap("productIdTo", variantProductId, "productAssocTypeId", "PRODUCT_VARIANT"));
            delegator.removeByAnd("ProductFeatureAppl", UtilMisc.toMap("productId", variantProductId, "productFeatureApplTypeId", "STANDARD_FEATURE"));
        }
        // add an association from productId to variantProductId of the PRODUCT_VARIANT
        Map<String, Object> productAssocMap = UtilMisc.toMap("productId", productId, "productIdTo", variantProductId, "productAssocTypeId", "PRODUCT_VARIANT", "fromDate", UtilDateTime.nowTimestamp());
        if (prodAssocSeqNum != null) {
            productAssocMap.put("sequenceNum", prodAssocSeqNum);
        }
        GenericValue productAssoc = delegator.makeValue("ProductAssoc", productAssocMap);
        productAssoc.create();
        // add the selected standard features to the new product given the productFeatureIds
        java.util.StringTokenizer st = new java.util.StringTokenizer(productFeatureIds, "|");
        while (st.hasMoreTokens()) {
            String productFeatureId = st.nextToken();
            GenericValue productFeature = EntityQuery.use(delegator).from("ProductFeature").where("productFeatureId", productFeatureId).queryOne();
            GenericValue productFeatureAppl = delegator.makeValue("ProductFeatureAppl", UtilMisc.toMap("productId", variantProductId, "productFeatureId", productFeatureId, "productFeatureApplTypeId", "STANDARD_FEATURE", "fromDate", UtilDateTime.nowTimestamp()));
            // set the default seq num if it's there...
            if (productFeature != null) {
                productFeatureAppl.set("sequenceNum", productFeature.get("defaultSequenceNum"));
            }
            productFeatureAppl.create();
        }
    } catch (GenericEntityException e) {
        Debug.logError(e, "Entity error creating quick add variant data", module);
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productservices.entity_error_quick_add_variant_data", messageMap, locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
        return result;
    }
    result.put("productVariantId", variantProductId);
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 49 with GenericValue

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

the class ProductServices method prodFindAssociatedByType.

/**
 * Finds associated products by product ID and association ID.
 */
public static Map<String, Object> prodFindAssociatedByType(DispatchContext dctx, Map<String, ? extends Object> context) {
    // String type -- Type of association (ie PRODUCT_UPGRADE, PRODUCT_COMPLEMENT, PRODUCT_VARIANT)
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> result = new HashMap<>();
    String productId = (String) context.get("productId");
    String productIdTo = (String) context.get("productIdTo");
    String type = (String) context.get("type");
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    Boolean cvaBool = (Boolean) context.get("checkViewAllow");
    boolean checkViewAllow = (cvaBool == null ? false : cvaBool);
    String prodCatalogId = (String) context.get("prodCatalogId");
    Boolean bidirectional = (Boolean) context.get("bidirectional");
    bidirectional = bidirectional == null ? Boolean.FALSE : bidirectional;
    Boolean sortDescending = (Boolean) context.get("sortDescending");
    sortDescending = sortDescending == null ? Boolean.FALSE : sortDescending;
    if (productId == null && productIdTo == null) {
        errMsg = UtilProperties.getMessage(resourceError, "productservices.both_productId_and_productIdTo_cannot_be_null", locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
        return result;
    }
    if (productId != null && productIdTo != null) {
        errMsg = UtilProperties.getMessage(resourceError, "productservices.both_productId_and_productIdTo_cannot_be_defined", locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
        return result;
    }
    productId = productId == null ? productIdTo : productId;
    GenericValue product = null;
    try {
        product = EntityQuery.use(delegator).from("Product").where("productId", productId).cache().queryOne();
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.getMessage());
        errMsg = UtilProperties.getMessage(resourceError, "productservices.problems_reading_product_entity", messageMap, locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
        return result;
    }
    if (product == null) {
        errMsg = UtilProperties.getMessage(resourceError, "productservices.problems_getting_product_entity", locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
        return result;
    }
    try {
        List<GenericValue> productAssocs = null;
        List<String> orderBy = new LinkedList<>();
        if (sortDescending) {
            orderBy.add("sequenceNum DESC");
        } else {
            orderBy.add("sequenceNum");
        }
        if (bidirectional) {
            EntityCondition cond = EntityCondition.makeCondition(UtilMisc.toList(EntityCondition.makeCondition("productId", productId), EntityCondition.makeCondition("productIdTo", productId)), EntityJoinOperator.OR);
            productAssocs = EntityQuery.use(delegator).from("ProductAssoc").where(EntityCondition.makeCondition(cond, EntityCondition.makeCondition("productAssocTypeId", type))).orderBy(orderBy).cache(true).queryList();
        } else {
            if (productIdTo == null) {
                productAssocs = product.getRelated("MainProductAssoc", UtilMisc.toMap("productAssocTypeId", type), orderBy, true);
            } else {
                productAssocs = product.getRelated("AssocProductAssoc", UtilMisc.toMap("productAssocTypeId", type), orderBy, true);
            }
        }
        // filter the list by date
        productAssocs = EntityUtil.filterByDate(productAssocs);
        // first check to see if there is a view allow category and if these products are in it...
        if (checkViewAllow && prodCatalogId != null && UtilValidate.isNotEmpty(productAssocs)) {
            String viewProductCategoryId = CatalogWorker.getCatalogViewAllowCategoryId(delegator, prodCatalogId);
            if (viewProductCategoryId != null) {
                if (productIdTo == null) {
                    productAssocs = CategoryWorker.filterProductsInCategory(delegator, productAssocs, viewProductCategoryId, "productIdTo");
                } else {
                    productAssocs = CategoryWorker.filterProductsInCategory(delegator, productAssocs, viewProductCategoryId, "productId");
                }
            }
        }
        result.put("assocProducts", productAssocs);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.getMessage());
        errMsg = UtilProperties.getMessage(resourceError, "productservices.problems_product_association_relation_error", messageMap, locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
        return result;
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) EntityCondition(org.apache.ofbiz.entity.condition.EntityCondition) LinkedList(java.util.LinkedList) Delegator(org.apache.ofbiz.entity.Delegator) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 50 with GenericValue

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

the class ProductServices method prodGetFeatures.

/**
 * Gets the product features of a product.
 */
public static Map<String, Object> prodGetFeatures(DispatchContext dctx, Map<String, ? extends Object> context) {
    // String type          -- Type of feature (STANDARD_FEATURE, SELECTABLE_FEATURE)
    // String distinct      -- Distinct feature (SIZE, COLOR)
    Delegator delegator = dctx.getDelegator();
    Map<String, Object> result = new HashMap<>();
    String productId = (String) context.get("productId");
    String distinct = (String) context.get("distinct");
    String type = (String) context.get("type");
    Locale locale = (Locale) context.get("locale");
    String errMsg = null;
    List<GenericValue> features = null;
    try {
        Map<String, String> fields = UtilMisc.toMap("productId", productId);
        if (distinct != null) {
            fields.put("productFeatureTypeId", distinct);
        }
        if (type != null) {
            fields.put("productFeatureApplTypeId", type);
        }
        features = EntityQuery.use(delegator).from("ProductFeatureAndAppl").where(fields).orderBy("sequenceNum", "productFeatureTypeId").cache(true).queryList();
        result.put("productFeatures", features);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS);
    } catch (GenericEntityException e) {
        Map<String, String> messageMap = UtilMisc.toMap("errMessage", e.toString());
        errMsg = UtilProperties.getMessage(resourceError, "productservices.problem_reading_product_feature_entity", messageMap, locale);
        result.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_ERROR);
        result.put(ModelService.ERROR_MESSAGE, errMsg);
    }
    return result;
}
Also used : Locale(java.util.Locale) GenericValue(org.apache.ofbiz.entity.GenericValue) Delegator(org.apache.ofbiz.entity.Delegator) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) GenericEntityException(org.apache.ofbiz.entity.GenericEntityException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Aggregations

GenericValue (org.apache.ofbiz.entity.GenericValue)1422 GenericEntityException (org.apache.ofbiz.entity.GenericEntityException)871 Delegator (org.apache.ofbiz.entity.Delegator)721 Locale (java.util.Locale)505 HashMap (java.util.HashMap)463 GenericServiceException (org.apache.ofbiz.service.GenericServiceException)370 LocalDispatcher (org.apache.ofbiz.service.LocalDispatcher)356 BigDecimal (java.math.BigDecimal)338 LinkedList (java.util.LinkedList)312 Timestamp (java.sql.Timestamp)202 GeneralException (org.apache.ofbiz.base.util.GeneralException)168 Map (java.util.Map)155 IOException (java.io.IOException)116 EntityCondition (org.apache.ofbiz.entity.condition.EntityCondition)97 HttpSession (javax.servlet.http.HttpSession)89 ArrayList (java.util.ArrayList)69 Security (org.apache.ofbiz.security.Security)69 EntityListIterator (org.apache.ofbiz.entity.util.EntityListIterator)59 List (java.util.List)56 EntityExpr (org.apache.ofbiz.entity.condition.EntityExpr)52