KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entity > util > EntityUtil


1 /*
2  * $Id: EntityUtil.java 5462 2005-08-05 18:35:48Z jonesde $
3  *
4  * Copyright (c) 2001-2005 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
25 package org.ofbiz.entity.util;
26
27 import java.sql.Timestamp JavaDoc;
28 import java.util.Collection JavaDoc;
29 import java.util.Collections JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.util.List JavaDoc;
32 import java.util.Map JavaDoc;
33 import java.util.Set JavaDoc;
34
35 import javolution.util.FastList;
36 import javolution.util.FastMap;
37 import javolution.util.FastSet;
38
39 import org.ofbiz.base.util.Debug;
40 import org.ofbiz.base.util.UtilDateTime;
41 import org.ofbiz.base.util.UtilMisc;
42 import org.ofbiz.entity.GenericDelegator;
43 import org.ofbiz.entity.GenericEntityException;
44 import org.ofbiz.entity.GenericValue;
45 import org.ofbiz.entity.condition.EntityCondition;
46 import org.ofbiz.entity.condition.EntityConditionList;
47 import org.ofbiz.entity.condition.EntityDateFilterCondition;
48 import org.ofbiz.entity.condition.EntityFieldMap;
49 import org.ofbiz.entity.condition.EntityOperator;
50 import org.ofbiz.entity.condition.OrderByList;
51 import org.ofbiz.entity.model.ModelField;
52
53 /**
54  * Helper methods when dealing with Entities, especially ones that follow certain conventions
55  *
56  *@author Eric Pabst
57  *@version $ Revision: $
58  *@since 1.0
59  */

60 public class EntityUtil {
61
62     public static final String JavaDoc module = EntityUtil.class.getName();
63
64     public static GenericValue getFirst(List JavaDoc values) {
65         if ((values != null) && (values.size() > 0)) {
66             return (GenericValue) values.get(0);
67         } else {
68             return null;
69         }
70     }
71
72     public static GenericValue getOnly(List JavaDoc values) {
73         if (values != null) {
74             if (values.size() <= 0) {
75                 return null;
76             }
77             if (values.size() == 1) {
78                 return (GenericValue) values.get(0);
79             } else {
80                 throw new IllegalArgumentException JavaDoc("Passed List had more than one value.");
81             }
82         } else {
83             return null;
84         }
85     }
86
87     public static EntityCondition getFilterByDateExpr() {
88         return new EntityDateFilterCondition("fromDate", "thruDate");
89     }
90
91     public static EntityCondition getFilterByDateExpr(String JavaDoc fromDateName, String JavaDoc thruDateName) {
92         return new EntityDateFilterCondition(fromDateName, thruDateName);
93     }
94
95     public static EntityCondition getFilterByDateExpr(java.util.Date JavaDoc moment) {
96         return EntityDateFilterCondition.makeCondition(new java.sql.Timestamp JavaDoc(moment.getTime()), "fromDate", "thruDate");
97     }
98
99     public static EntityCondition getFilterByDateExpr(java.sql.Timestamp JavaDoc moment) {
100         return EntityDateFilterCondition.makeCondition(moment, "fromDate", "thruDate");
101     }
102
103     public static EntityCondition getFilterByDateExpr(java.sql.Timestamp JavaDoc moment, String JavaDoc fromDateName, String JavaDoc thruDateName) {
104         return EntityDateFilterCondition.makeCondition(moment, fromDateName, thruDateName);
105     }
106
107     /**
108      *returns the values that are currently active.
109      *
110      *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields
111      *@return List of GenericValue's that are currently active
112      */

113     public static List JavaDoc filterByDate(List JavaDoc datedValues) {
114         return filterByDate(datedValues, UtilDateTime.nowTimestamp(), null, null, true);
115     }
116
117     /**
118      *returns the values that are currently active.
119      *
120      *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields
121      *@param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we only have to see if the from and thru date fields are valid once
122      *@return List of GenericValue's that are currently active
123      */

124     public static List JavaDoc filterByDate(List JavaDoc datedValues, boolean allAreSame) {
125         return filterByDate(datedValues, UtilDateTime.nowTimestamp(), null, null, allAreSame);
126     }
127
128     /**
129      *returns the values that are active at the moment.
130      *
131      *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields
132      *@param moment the moment in question
133      *@return List of GenericValue's that are active at the moment
134      */

135     public static List JavaDoc filterByDate(List JavaDoc datedValues, java.util.Date JavaDoc moment) {
136         return filterByDate(datedValues, new java.sql.Timestamp JavaDoc(moment.getTime()), null, null, true);
137     }
138
139     /**
140      *returns the values that are active at the moment.
141      *
142      *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields
143      *@param moment the moment in question
144      *@return List of GenericValue's that are active at the moment
145      */

146     public static List JavaDoc filterByDate(List JavaDoc datedValues, java.sql.Timestamp JavaDoc moment) {
147         return filterByDate(datedValues, moment, null, null, true);
148     }
149
150     /**
151      *returns the values that are active at the moment.
152      *
153      *@param datedValues GenericValue's that have "fromDate" and "thruDate" fields
154      *@param moment the moment in question
155      *@param allAreSame Specifies whether all values in the List are of the same entity; this can help speed things up a fair amount since we only have to see if the from and thru date fields are valid once
156      *@return List of GenericValue's that are active at the moment
157      */

158     public static List JavaDoc filterByDate(List JavaDoc datedValues, java.sql.Timestamp JavaDoc moment, String JavaDoc fromDateName, String JavaDoc thruDateName, boolean allAreSame) {
159         if (datedValues == null) return null;
160         if (moment == null) return datedValues;
161         if (fromDateName == null) fromDateName = "fromDate";
162         if (thruDateName == null) thruDateName = "thruDate";
163
164         List JavaDoc result = FastList.newInstance();
165         Iterator JavaDoc iter = datedValues.iterator();
166
167         if (allAreSame) {
168             ModelField fromDateField = null;
169             ModelField thruDateField = null;
170
171             if (iter.hasNext()) {
172                 GenericValue datedValue = (GenericValue) iter.next();
173
174                 fromDateField = datedValue.getModelEntity().getField(fromDateName);
175                 if (fromDateField == null) throw new IllegalArgumentException JavaDoc("\"" + fromDateName + "\" is not a field of " + datedValue.getEntityName());
176                 thruDateField = datedValue.getModelEntity().getField(thruDateName);
177                 if (thruDateField == null) throw new IllegalArgumentException JavaDoc("\"" + thruDateName + "\" is not a field of " + datedValue.getEntityName());
178
179                 java.sql.Timestamp JavaDoc fromDate = (java.sql.Timestamp JavaDoc) datedValue.dangerousGetNoCheckButFast(fromDateField);
180                 java.sql.Timestamp JavaDoc thruDate = (java.sql.Timestamp JavaDoc) datedValue.dangerousGetNoCheckButFast(thruDateField);
181
182                 if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
183                     result.add(datedValue);
184                 }// else not active at moment
185
}
186             while (iter.hasNext()) {
187                 GenericValue datedValue = (GenericValue) iter.next();
188                 java.sql.Timestamp JavaDoc fromDate = (java.sql.Timestamp JavaDoc) datedValue.dangerousGetNoCheckButFast(fromDateField);
189                 java.sql.Timestamp JavaDoc thruDate = (java.sql.Timestamp JavaDoc) datedValue.dangerousGetNoCheckButFast(thruDateField);
190
191                 if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
192                     result.add(datedValue);
193                 }// else not active at moment
194
}
195         } else {
196             // if not all values are known to be of the same entity, must check each one...
197
while (iter.hasNext()) {
198                 GenericValue datedValue = (GenericValue) iter.next();
199                 java.sql.Timestamp JavaDoc fromDate = datedValue.getTimestamp(fromDateName);
200                 java.sql.Timestamp JavaDoc thruDate = datedValue.getTimestamp(thruDateName);
201
202                 if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
203                     result.add(datedValue);
204                 }// else not active at moment
205
}
206         }
207
208         return result;
209     }
210
211     public static boolean isValueActive(GenericValue datedValue, java.sql.Timestamp JavaDoc moment) {
212         return isValueActive(datedValue, moment, "fromDate", "thruDate");
213     }
214
215     public static boolean isValueActive(GenericValue datedValue, java.sql.Timestamp JavaDoc moment, String JavaDoc fromDateName, String JavaDoc thruDateName) {
216         java.sql.Timestamp JavaDoc fromDate = datedValue.getTimestamp(fromDateName);
217         java.sql.Timestamp JavaDoc thruDate = datedValue.getTimestamp(thruDateName);
218
219         if ((thruDate == null || thruDate.after(moment)) && (fromDate == null || fromDate.before(moment) || fromDate.equals(moment))) {
220             return true;
221         } else {
222             // else not active at moment
223
return false;
224         }
225     }
226
227     /**
228      *returns the values that match the values in fields
229      *
230      *@param values List of GenericValues
231      *@param fields the field-name/value pairs that must match
232      *@return List of GenericValue's that match the values in fields
233      */

234     public static List JavaDoc filterByAnd(List JavaDoc values, Map JavaDoc fields) {
235         if (values == null) return null;
236
237         List JavaDoc result = null;
238         if (fields == null || fields.size() == 0) {
239             result = FastList.newInstance();
240             result.addAll(values);
241         } else {
242             result = FastList.newInstance();
243             Iterator JavaDoc iter = values.iterator();
244             while (iter.hasNext()) {
245                 GenericValue value = (GenericValue) iter.next();
246                 if (value.matchesFields(fields)) {
247                     result.add(value);
248                 }// else did not match
249
}
250         }
251         return result;
252     }
253
254     /**
255      *returns the values that match all of the exprs in list
256      *
257      *@param values List of GenericValues
258      *@param exprs the expressions that must validate to true
259      *@return List of GenericValue's that match the values in fields
260      */

261     public static List JavaDoc filterByAnd(List JavaDoc values, List JavaDoc exprs) {
262         if (values == null) return null;
263         if (exprs == null || exprs.size() == 0) {
264             // no constraints... oh well
265
return values;
266         }
267
268         List JavaDoc result = FastList.newInstance();
269         Iterator JavaDoc iter = values.iterator();
270         while (iter.hasNext()) {
271             GenericValue value = (GenericValue) iter.next();
272             Iterator JavaDoc exprIter = exprs.iterator();
273             boolean include = true;
274
275             while (exprIter.hasNext()) {
276                 EntityCondition condition = (EntityCondition) exprIter.next();
277                 include = condition.entityMatches(value);
278                 if (!include) break;
279             }
280             if (include) {
281                 result.add(value);
282             }
283         }
284         return result;
285     }
286
287     /**
288      *returns the values that match any of the exprs in list
289      *
290      *@param values List of GenericValues
291      *@param exprs the expressions that must validate to true
292      *@return List of GenericValue's that match the values in fields
293      */

294     public static List JavaDoc filterByOr(List JavaDoc values, List JavaDoc exprs) {
295         if (values == null) return null;
296         if (exprs == null || exprs.size() == 0) {
297             return values;
298         }
299
300         List JavaDoc result = FastList.newInstance();
301         Iterator JavaDoc iter = values.iterator();
302
303         while (iter.hasNext()) {
304             GenericValue value = (GenericValue) iter.next();
305             boolean include = false;
306
307             Iterator JavaDoc exprIter = exprs.iterator();
308             while (exprIter.hasNext()) {
309                 EntityCondition condition = (EntityCondition) exprIter.next();
310                 include = condition.entityMatches(value);
311                 if (include) break;
312             }
313             if (include) {
314                 result.add(value);
315             }
316         }
317         return result;
318     }
319
320     /**
321      *returns the values in the order specified
322      *
323      *@param values List of GenericValues
324      *@param orderBy The fields of the named entity to order the query by;
325      * optionally add a " ASC" for ascending or " DESC" for descending
326      *@return List of GenericValue's in the proper order
327      */

328     public static List JavaDoc orderBy(Collection JavaDoc values, List JavaDoc orderBy) {
329         if (values == null) return null;
330         if (values.size() == 0) return FastList.newInstance();
331         if (orderBy == null || orderBy.size() == 0) {
332             List JavaDoc newList = FastList.newInstance();
333             newList.addAll(values);
334             return newList;
335         }
336
337         List JavaDoc result = FastList.newInstance();
338         result.addAll(values);
339         if (Debug.verboseOn()) Debug.logVerbose("Sorting " + values.size() + " values, orderBy=" + orderBy.toString(), module);
340         Collections.sort(result, new OrderByList(orderBy));
341         return result;
342     }
343
344     public static List JavaDoc getRelated(String JavaDoc relationName, List JavaDoc values) throws GenericEntityException {
345         if (values == null) return null;
346
347         List JavaDoc result = FastList.newInstance();
348         Iterator JavaDoc iter = values.iterator();
349         while (iter.hasNext()) {
350             result.addAll(((GenericValue) iter.next()).getRelated(relationName));
351         }
352         return result;
353     }
354
355     public static List JavaDoc getRelatedCache(String JavaDoc relationName, List JavaDoc values) throws GenericEntityException {
356         if (values == null) return null;
357
358         List JavaDoc result = FastList.newInstance();
359         Iterator JavaDoc iter = values.iterator();
360         while (iter.hasNext()) {
361             result.addAll(((GenericValue) iter.next()).getRelatedCache(relationName));
362         }
363         return result;
364     }
365
366     public static List JavaDoc getRelatedByAnd(String JavaDoc relationName, Map JavaDoc fields, List JavaDoc values) throws GenericEntityException {
367         if (values == null) return null;
368
369         List JavaDoc result = FastList.newInstance();
370         Iterator JavaDoc iter = values.iterator();
371         while (iter.hasNext()) {
372             result.addAll(((GenericValue) iter.next()).getRelatedByAnd(relationName, fields));
373         }
374         return result;
375     }
376
377     public static List JavaDoc filterByCondition(List JavaDoc values, EntityCondition condition) {
378         if (values == null) return null;
379
380         List JavaDoc result = FastList.newInstance();
381         Iterator JavaDoc iter = values.iterator();
382         while (iter.hasNext()) {
383             GenericValue value = (GenericValue) iter.next();
384             if (condition.entityMatches(value)) {
385                 result.add(value);
386             }
387         }
388         return result;
389     }
390
391     public static List JavaDoc filterOutByCondition(List JavaDoc values, EntityCondition condition) {
392         if (values == null) return null;
393
394         List JavaDoc result = FastList.newInstance();
395         Iterator JavaDoc iter = values.iterator();
396         while (iter.hasNext()) {
397             GenericValue value = (GenericValue) iter.next();
398             if (!condition.entityMatches(value)) {
399                 result.add(value);
400             }
401         }
402         return result;
403     }
404
405     public static List JavaDoc findDatedInclusionEntity(GenericDelegator delegator, String JavaDoc entityName, Map JavaDoc search) throws GenericEntityException {
406         return findDatedInclusionEntity(delegator, entityName, search, UtilDateTime.nowTimestamp());
407     }
408
409     public static List JavaDoc findDatedInclusionEntity(GenericDelegator delegator, String JavaDoc entityName, Map JavaDoc search, Timestamp JavaDoc now) throws GenericEntityException {
410         EntityCondition searchCondition = new EntityConditionList(UtilMisc.toList(
411             new EntityFieldMap(search, EntityOperator.AND),
412             EntityUtil.getFilterByDateExpr(now)
413         ), EntityOperator.AND);
414         return delegator.findByCondition(entityName,searchCondition,null,UtilMisc.toList("-fromDate"));
415     }
416
417     public static GenericValue newDatedInclusionEntity(GenericDelegator delegator, String JavaDoc entityName, Map JavaDoc search) throws GenericEntityException {
418         return newDatedInclusionEntity(delegator, entityName, search, UtilDateTime.nowTimestamp());
419     }
420
421     public static GenericValue newDatedInclusionEntity(GenericDelegator delegator, String JavaDoc entityName, Map JavaDoc search, Timestamp JavaDoc now) throws GenericEntityException {
422         List JavaDoc entities = findDatedInclusionEntity(delegator, entityName, search, now);
423         if (entities != null && entities.size() > 0) {
424             search = null;
425             for (int i = 0; i < entities.size(); i++) {
426                 GenericValue entity = (GenericValue)entities.get(i);
427                 if (now.equals(entity.get("fromDate"))) {
428                     search = FastMap.newInstance();
429                     search.putAll(entity.getPrimaryKey());
430                     entity.remove("thruDate");
431                 } else {
432                     entity.set("thruDate",now);
433                 }
434                 entity.store();
435             }
436             if (search == null) {
437                 search = FastMap.newInstance();
438                 search.putAll(EntityUtil.getFirst(entities));
439             }
440         } else {
441             /* why is this being done? leaving out for now...
442             search = new HashMap(search);
443             */

444         }
445         if (now.equals(search.get("fromDate"))) {
446             return EntityUtil.getOnly(delegator.findByAnd(entityName, search));
447         } else {
448             search.put("fromDate",now);
449             search.remove("thruDate");
450             return delegator.makeValue(entityName, search);
451         }
452     }
453
454     public static void delDatedInclusionEntity(GenericDelegator delegator, String JavaDoc entityName, Map JavaDoc search) throws GenericEntityException {
455         delDatedInclusionEntity(delegator, entityName, search, UtilDateTime.nowTimestamp());
456     }
457
458     public static void delDatedInclusionEntity(GenericDelegator delegator, String JavaDoc entityName, Map JavaDoc search, Timestamp JavaDoc now) throws GenericEntityException {
459         List JavaDoc entities = findDatedInclusionEntity(delegator, entityName, search, now);
460         for (int i = 0; entities != null && i < entities.size(); i++) {
461             GenericValue entity = (GenericValue)entities.get(i);
462             entity.set("thruDate",now);
463             entity.store();
464         }
465     }
466     
467     public static List JavaDoc getFieldListFromEntityList(List JavaDoc genericValueList, String JavaDoc fieldName, boolean distinct) {
468         if (genericValueList == null || fieldName == null) {
469             return null;
470         }
471         List JavaDoc fieldList = FastList.newInstance();
472         Set JavaDoc distinctSet = null;
473         if (distinct) {
474             distinctSet = FastSet.newInstance();
475         }
476         
477         Iterator JavaDoc genericValueIter = genericValueList.iterator();
478         while (genericValueIter.hasNext()) {
479             GenericValue value = (GenericValue) genericValueIter.next();
480             Object JavaDoc fieldValue = value.get(fieldName);
481             if (distinct) {
482                 if (!distinctSet.contains(fieldValue)) {
483                     fieldList.add(fieldValue);
484                     distinctSet.add(fieldValue);
485                 }
486             } else {
487                 fieldList.add(fieldValue);
488             }
489         }
490         
491         return fieldList;
492     }
493     
494     public static List JavaDoc getFieldListFromEntityListIterator(EntityListIterator genericValueEli, String JavaDoc fieldName, boolean distinct) {
495         if (genericValueEli == null || fieldName == null) {
496             return null;
497         }
498         List JavaDoc fieldList = FastList.newInstance();
499         Set JavaDoc distinctSet = null;
500         if (distinct) {
501             distinctSet = FastSet.newInstance();
502         }
503         
504         GenericValue value = null;
505         while ((value = (GenericValue) genericValueEli.next()) != null) {
506             Object JavaDoc fieldValue = value.get(fieldName);
507             if (distinct) {
508                 if (!distinctSet.contains(fieldValue)) {
509                     fieldList.add(fieldValue);
510                     distinctSet.add(fieldValue);
511                 }
512             } else {
513                 fieldList.add(fieldValue);
514             }
515         }
516         
517         return fieldList;
518     }
519 }
520
Popular Tags