KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > product > category > CategoryWorker


1 /*
2  * $Id: CategoryWorker.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24 package org.ofbiz.product.category;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.HashMap JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.LinkedList JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33
34 import javax.servlet.ServletRequest JavaDoc;
35 import javax.servlet.http.HttpServletRequest JavaDoc;
36 import javax.servlet.http.HttpSession JavaDoc;
37 import javax.servlet.jsp.PageContext JavaDoc;
38
39 import org.ofbiz.base.util.*;
40 import org.ofbiz.entity.GenericDelegator;
41 import org.ofbiz.entity.GenericEntityException;
42 import org.ofbiz.entity.GenericValue;
43 import org.ofbiz.entity.condition.EntityExpr;
44 import org.ofbiz.entity.condition.EntityOperator;
45 import org.ofbiz.entity.condition.EntityConditionList;
46 import org.ofbiz.entity.condition.EntityCondition;
47 import org.ofbiz.entity.util.EntityUtil;
48 import org.ofbiz.product.product.ProductWorker;
49
50 /**
51  * CategoryWorker - Worker class to reduce code in JSPs.
52  *
53  * @author <a HREF="mailto:jaz@ofbiz.org">Andy Zeneski</a>
54  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
55  * @version $Rev: 5462 $
56  * @since 2.0
57  */

58 public class CategoryWorker {
59
60     public static final String JavaDoc module = CategoryWorker.class.getName();
61
62     public static String JavaDoc getCatalogTopCategory(PageContext JavaDoc pageContext, String JavaDoc defaultTopCategory) {
63         return getCatalogTopCategory(pageContext.getRequest(), defaultTopCategory);
64     }
65
66     public static String JavaDoc getCatalogTopCategory(ServletRequest JavaDoc request, String JavaDoc defaultTopCategory) {
67         HttpServletRequest JavaDoc httpRequest = (HttpServletRequest JavaDoc) request;
68         Map JavaDoc requestParameters = UtilHttp.getParameterMap(httpRequest);
69         String JavaDoc topCatName = null;
70         boolean fromSession = false;
71
72         // first see if a new category was specified as a parameter
73
topCatName = (String JavaDoc) requestParameters.get("CATALOG_TOP_CATEGORY");
74         // if no parameter, try from session
75
if (topCatName == null) {
76             topCatName = (String JavaDoc) httpRequest.getSession().getAttribute("CATALOG_TOP_CATEGORY");
77             if (topCatName != null)
78                 fromSession = true;
79         }
80         // if nothing else, just use a default top category name
81
if (topCatName == null)
82             topCatName = defaultTopCategory;
83         if (topCatName == null)
84             topCatName = "CATALOG1";
85
86         if (!fromSession) {
87             if (Debug.infoOn()) Debug.logInfo("[CategoryWorker.getCatalogTopCategory] Setting new top category: " + topCatName, module);
88             httpRequest.getSession().setAttribute("CATALOG_TOP_CATEGORY", topCatName);
89         }
90         return topCatName;
91     }
92
93     public static void getCategoriesWithNoParent(PageContext JavaDoc pageContext, String JavaDoc attributeName) {
94         getCategoriesWithNoParent(pageContext.getRequest(), attributeName);
95     }
96
97     public static void getCategoriesWithNoParent(ServletRequest JavaDoc request, String JavaDoc attributeName) {
98         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
99         Collection JavaDoc results = new LinkedList JavaDoc();
100
101         try {
102             Collection JavaDoc allCategories = delegator.findAll("ProductCategory");
103
104             if (allCategories == null)
105                 return;
106             Iterator JavaDoc aciter = allCategories.iterator();
107
108             while (aciter.hasNext()) {
109                 GenericValue curCat = (GenericValue) aciter.next();
110                 Collection JavaDoc parentCats = curCat.getRelatedCache("CurrentProductCategoryRollup");
111
112                 if (parentCats == null || parentCats.size() <= 0)
113                     results.add(curCat);
114             }
115         } catch (GenericEntityException e) {
116             Debug.logWarning(e, module);
117         }
118         request.setAttribute(attributeName, results);
119     }
120
121     public static void getRelatedCategories(PageContext JavaDoc pageContext, String JavaDoc attributeName, boolean limitView) {
122             getRelatedCategories(pageContext.getRequest(), attributeName, limitView);
123     }
124
125     public static void getRelatedCategories(ServletRequest JavaDoc request, String JavaDoc attributeName, boolean limitView) {
126         Map JavaDoc requestParameters = UtilHttp.getParameterMap((HttpServletRequest JavaDoc) request);
127         String JavaDoc requestId = null;
128
129         requestId = UtilFormatOut.checkNull((String JavaDoc)requestParameters.get("catalog_id"), (String JavaDoc)requestParameters.get("CATALOG_ID"),
130                 (String JavaDoc)requestParameters.get("category_id"), (String JavaDoc)requestParameters.get("CATEGORY_ID"));
131
132         if (requestId.equals(""))
133             return;
134         if (Debug.infoOn()) Debug.logInfo("[CatalogHelper.getRelatedCategories] RequestID: " + requestId, module);
135         getRelatedCategories(request, attributeName, requestId, limitView);
136     }
137
138     public static void getRelatedCategories(PageContext JavaDoc pageContext, String JavaDoc attributeName, String JavaDoc parentId, boolean limitView) {
139         getRelatedCategories(pageContext.getRequest(), attributeName, parentId, limitView);
140     }
141
142     public static void getRelatedCategories(ServletRequest JavaDoc request, String JavaDoc attributeName, String JavaDoc parentId, boolean limitView) {
143         getRelatedCategories(request, attributeName, parentId, limitView, false);
144     }
145
146     public static void getRelatedCategories(ServletRequest JavaDoc request, String JavaDoc attributeName, String JavaDoc parentId, boolean limitView, boolean excludeEmpty) {
147         ArrayList JavaDoc categories = getRelatedCategoriesRet(request, attributeName, parentId, limitView, excludeEmpty);
148
149         if (categories.size() > 0)
150             request.setAttribute(attributeName, categories);
151     }
152
153     public static ArrayList JavaDoc getRelatedCategoriesRet(PageContext JavaDoc pageContext, String JavaDoc attributeName, String JavaDoc parentId, boolean limitView) {
154         return getRelatedCategoriesRet(pageContext.getRequest(), attributeName, parentId, limitView);
155     }
156
157     public static ArrayList JavaDoc getRelatedCategoriesRet(ServletRequest JavaDoc request, String JavaDoc attributeName, String JavaDoc parentId, boolean limitView) {
158         return getRelatedCategoriesRet(request, attributeName, parentId, limitView, false);
159     }
160
161     public static ArrayList JavaDoc getRelatedCategoriesRet(ServletRequest JavaDoc request, String JavaDoc attributeName, String JavaDoc parentId, boolean limitView, boolean excludeEmpty) {
162         ArrayList JavaDoc categories = new ArrayList JavaDoc();
163
164         if (Debug.verboseOn()) Debug.logVerbose("[CatalogHelper.getRelatedCategories] ParentID: " + parentId, module);
165
166         GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
167         List JavaDoc rollups = null;
168
169         try {
170             rollups = delegator.findByAndCache("ProductCategoryRollup",
171                         UtilMisc.toMap("parentProductCategoryId", parentId),
172                         UtilMisc.toList("sequenceNum"));
173             if (limitView) {
174                 rollups = EntityUtil.filterByDate(rollups, true);
175             }
176         } catch (GenericEntityException e) {
177             Debug.logWarning(e.getMessage(), module);
178             rollups = null;
179         }
180         if (rollups != null && rollups.size() > 0) {
181             // Debug.log("Rollup size: " + rollups.size(), module);
182
Iterator JavaDoc ri = rollups.iterator();
183
184             while (ri.hasNext()) {
185                 GenericValue parent = (GenericValue) ri.next();
186                 // Debug.log("Adding child of: " + parent.getString("parentProductCategoryId"), module);
187
GenericValue cv = null;
188
189                 try {
190                     cv = parent.getRelatedOneCache("CurrentProductCategory");
191                 } catch (GenericEntityException e) {
192                     Debug.logWarning(e.getMessage(), module);
193                     cv = null;
194                 }
195                 if (cv != null) {
196                     if (excludeEmpty) {
197                         if (!isCategoryEmpty(cv)) {
198                             //Debug.log("Child : " + cv.getString("productCategoryId") + " is not empty.", module);
199
categories.add(cv);
200                         }
201                     } else {
202                         categories.add(cv);
203                     }
204                 }
205             }
206         }
207         return categories;
208     }
209
210     public static boolean isCategoryEmpty(GenericValue category) {
211         boolean empty = true;
212         long members = categoryMemberCount(category);
213         //Debug.log("Category : " + category.get("productCategoryId") + " has " + members + " members", module);
214
if (members > 0) {
215             empty = false;
216         }
217
218         if (empty) {
219             long rollups = categoryRollupCount(category);
220             //Debug.log("Category : " + category.get("productCategoryId") + " has " + rollups + " rollups", module);
221
if (rollups > 0) {
222                 empty = false;
223             }
224         }
225
226         return empty;
227     }
228
229     public static long categoryMemberCount(GenericValue category) {
230         if (category == null) return 0;
231         GenericDelegator delegator = category.getDelegator();
232         long count = 0;
233         try {
234             count = delegator.findCountByCondition("ProductCategoryMember", buildCountCondition("productCategoryId", category.getString("productCategoryId")), null);
235         } catch (GenericEntityException e) {
236             Debug.logError(e, module);
237         }
238         return count;
239     }
240
241     public static long categoryRollupCount(GenericValue category) {
242         if (category == null) return 0;
243         GenericDelegator delegator = category.getDelegator();
244         long count = 0;
245         try {
246             count = delegator.findCountByCondition("ProductCategoryRollup", buildCountCondition("parentProductCategoryId", category.getString("productCategoryId")), null);
247         } catch (GenericEntityException e) {
248             Debug.logError(e, module);
249         }
250         return count;
251     }
252
253     private static EntityCondition buildCountCondition(String JavaDoc fieldName, String JavaDoc fieldValue) {
254         List JavaDoc orCondList = new ArrayList JavaDoc();
255         orCondList.add(new EntityExpr("thruDate", EntityOperator.GREATER_THAN, UtilDateTime.nowTimestamp()));
256         orCondList.add(new EntityExpr("thruDate", EntityOperator.EQUALS, null));
257         EntityCondition orCond = new EntityConditionList(orCondList, EntityOperator.OR);
258
259         List JavaDoc andCondList = new ArrayList JavaDoc();
260         andCondList.add(new EntityExpr("fromDate", EntityOperator.LESS_THAN, UtilDateTime.nowTimestamp()));
261         andCondList.add(new EntityExpr(fieldName, EntityOperator.EQUALS, fieldValue));
262         andCondList.add(orCond);
263         EntityCondition andCond = new EntityConditionList(andCondList, EntityOperator.AND);
264
265         return andCond;
266     }
267
268     public static void setTrail(PageContext JavaDoc pageContext, String JavaDoc currentCategory) {
269         setTrail(pageContext.getRequest(), currentCategory);
270     }
271
272     public static void setTrail(ServletRequest JavaDoc request, String JavaDoc currentCategory) {
273         Map JavaDoc requestParameters = UtilHttp.getParameterMap((HttpServletRequest JavaDoc) request);
274         String JavaDoc previousCategory = (String JavaDoc) requestParameters.get("pcategory");
275
276         if (Debug.verboseOn()) Debug.logVerbose("[CatalogHelper.setTrail] Start: previousCategory=" + previousCategory +
277                 " currentCategory=" + currentCategory, module);
278
279         // if there is no current category, just return and do nothing to that the last settings will stay
280
if (currentCategory == null || currentCategory.length() <= 0)
281             return;
282
283         // always get the last crumb list
284
List JavaDoc crumb = getTrail(request);
285
286         if (crumb == null)
287             crumb = new ArrayList JavaDoc();
288
289         // if no previous category was specified, check to see if currentCategory is in the list
290
if (previousCategory == null || previousCategory.length() <= 0) {
291             if (crumb.contains(currentCategory)) {
292                 // if cur category is in crumb, remove everything after it and return
293
int cindex = crumb.lastIndexOf(currentCategory);
294
295                 if (cindex < (crumb.size() - 1)) {
296                     for (int i = crumb.size() - 1; i > cindex; i--) {
297                         String JavaDoc deadCat = (String JavaDoc) crumb.remove(i);
298
299                         if (Debug.infoOn()) Debug.logInfo("[CatalogHelper.setTrail] Removed after current category index: " + i +
300                                 " catname: " + deadCat, module);
301                     }
302                 }
303                 return;
304             } else {
305                 // current category is not in the list, and no previous category was specified, go back to the beginning
306
previousCategory = "TOP";
307                 crumb.clear();
308                 crumb.add(previousCategory);
309                 if (Debug.infoOn()) Debug.logInfo("[CatalogHelper.setTrail] Starting new list, added previousCategory: " + previousCategory, module);
310             }
311         }
312
313         if (!crumb.contains(previousCategory)) {
314             // previous category was NOT in the list, ERROR, start over
315
if (Debug.infoOn()) Debug.logInfo("[CatalogHelper.setTrail] ERROR: previousCategory (" + previousCategory +
316                     ") was not in the crumb list, position is lost, starting over with TOP", module);
317             previousCategory = "TOP";
318             crumb.clear();
319             crumb.add(previousCategory);
320         } else {
321             // remove all categories after the previous category, preparing for adding the current category
322
int index = crumb.indexOf(previousCategory);
323
324             if (index < (crumb.size() - 1)) {
325                 for (int i = crumb.size() - 1; i > index; i--) {
326                     String JavaDoc deadCat = (String JavaDoc) crumb.remove(i);
327
328                     if (Debug.infoOn()) Debug.logInfo("[CatalogHelper.setTrail] Removed after previous category index: " + i +
329                             " catname: " + deadCat, module);
330                 }
331             }
332         }
333
334         // add the current category to the end of the list
335
crumb.add(currentCategory);
336         if (Debug.verboseOn()) Debug.logVerbose("[CatalogHelper.setTrail] Continuing list: Added currentCategory: " + currentCategory, module);
337         setTrail(request, crumb);
338     }
339
340     public static List JavaDoc getTrail(PageContext JavaDoc pageContext) {
341         return getTrail(pageContext.getRequest());
342     }
343
344     public static List JavaDoc getTrail(ServletRequest JavaDoc request) {
345         HttpSession JavaDoc session = ((HttpServletRequest JavaDoc) request).getSession();
346         ArrayList JavaDoc crumb = (ArrayList JavaDoc) session.getAttribute("_BREAD_CRUMB_TRAIL_");
347         return crumb;
348     }
349
350     public static List JavaDoc setTrail(PageContext JavaDoc pageContext, List JavaDoc crumb) {
351         return setTrail(pageContext.getRequest(), crumb);
352     }
353
354     public static List JavaDoc setTrail(ServletRequest JavaDoc request, List JavaDoc crumb) {
355         HttpSession JavaDoc session = ((HttpServletRequest JavaDoc) request).getSession();
356         session.setAttribute("_BREAD_CRUMB_TRAIL_", crumb);
357         return crumb;
358     }
359
360     public static boolean checkTrailItem(PageContext JavaDoc pageContext, String JavaDoc category) {
361         return checkTrailItem(pageContext.getRequest(), category);
362     }
363
364     public static boolean checkTrailItem(ServletRequest JavaDoc request, String JavaDoc category) {
365         List JavaDoc crumb = getTrail(request);
366
367         if (crumb != null && crumb.contains(category))
368             return true;
369         else
370             return false;
371     }
372
373     public static String JavaDoc lastTrailItem(PageContext JavaDoc pageContext) {
374         return lastTrailItem(pageContext.getRequest());
375     }
376
377     public static String JavaDoc lastTrailItem(ServletRequest JavaDoc request) {
378         List JavaDoc crumb = getTrail(request);
379
380         if (crumb != null && crumb.size() > 0) {
381             return (String JavaDoc) crumb.get(crumb.size() - 1);
382         } else {
383             return null;
384         }
385     }
386
387     public static boolean isProductInCategory(GenericDelegator delegator, String JavaDoc productId, String JavaDoc productCategoryId) throws GenericEntityException {
388         if (productCategoryId == null) return false;
389         if (productId == null || productId.length() == 0) return false;
390
391         List JavaDoc productCategoryMembers = EntityUtil.filterByDate(delegator.findByAndCache("ProductCategoryMember",
392                 UtilMisc.toMap("productCategoryId", productCategoryId, "productId", productId)), true);
393         if (productCategoryMembers == null || productCategoryMembers.size() == 0) {
394             //before giving up see if this is a variant product, and if so look up the virtual product and check it...
395
GenericValue product = delegator.findByPrimaryKey("Product", UtilMisc.toMap("productId", productId));
396             List JavaDoc productAssocs = ProductWorker.getVariantVirtualAssocs(product);
397             //this does take into account that a product could be a variant of multiple products, but this shouldn't ever really happen...
398
if (productAssocs != null && productAssocs.size() > 0) {
399                 Iterator JavaDoc pasIter = productAssocs.iterator();
400                 while (pasIter.hasNext()) {
401                     GenericValue productAssoc = (GenericValue) pasIter.next();
402                     if (isProductInCategory(delegator, productAssoc.getString("productId"), productCategoryId)) {
403                         return true;
404                     }
405                 }
406             }
407
408             return false;
409         } else {
410             return true;
411         }
412     }
413
414     public static List JavaDoc filterProductsInCategory(GenericDelegator delegator, List JavaDoc valueObjects, String JavaDoc productCategoryId) throws GenericEntityException {
415         return filterProductsInCategory(delegator, valueObjects, productCategoryId, "productId");
416     }
417
418     public static List JavaDoc filterProductsInCategory(GenericDelegator delegator, List JavaDoc valueObjects, String JavaDoc productCategoryId, String JavaDoc productIdFieldName) throws GenericEntityException {
419         if (productCategoryId == null) return new LinkedList JavaDoc();
420         if (valueObjects == null) return null;
421
422         List JavaDoc newList = new ArrayList JavaDoc(valueObjects.size());
423         Iterator JavaDoc valIter = valueObjects.iterator();
424         while (valIter.hasNext()) {
425             GenericValue curValue = (GenericValue) valIter.next();
426             String JavaDoc productId = curValue.getString(productIdFieldName);
427             if (isProductInCategory(delegator, productId, productCategoryId)) {
428                 newList.add(curValue);
429             }
430         }
431         return newList;
432     }
433     
434     public static HashMap JavaDoc getCategoryContentWrappers(HashMap JavaDoc catContentWrappers, Iterator JavaDoc catIterator, HttpServletRequest JavaDoc request) throws GenericEntityException {
435         while(catIterator.hasNext()) {
436             GenericValue cat = (GenericValue) catIterator.next();
437             CategoryContentWrapper catContentWrapper = new CategoryContentWrapper(cat, request);
438             String JavaDoc id = (String JavaDoc) cat.get("productCategoryId");
439             catContentWrappers.put(id, catContentWrapper);
440             ArrayList JavaDoc subCat = new ArrayList JavaDoc();
441             subCat = getRelatedCategoriesRet(request, "subCatList", id, true);
442             if(subCat != null) {
443                 Iterator JavaDoc subCatIterator = UtilMisc.toIterator(subCat);
444                 if(subCatIterator != null) {
445                     getCategoryContentWrappers(catContentWrappers, subCatIterator, request );
446                 }
447             }
448         }
449         return catContentWrappers;
450     }
451 }
452
Popular Tags