KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > ofbiz > entity > finder > ByAndFinder


1 /*
2  * $Id: ByAndFinder.java 6197 2005-11-26 06:07:08Z jonesde $
3  *
4  * Copyright (c) 2004 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.entity.finder;
25
26 import java.util.HashMap JavaDoc;
27 import java.util.Iterator JavaDoc;
28 import java.util.LinkedList JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Set JavaDoc;
32
33 import org.ofbiz.base.util.Debug;
34 import org.ofbiz.base.util.GeneralException;
35 import org.ofbiz.base.util.UtilXml;
36 import org.ofbiz.base.util.UtilMisc;
37 import org.ofbiz.base.util.collections.FlexibleMapAccessor;
38 import org.ofbiz.base.util.string.FlexibleStringExpander;
39 import org.ofbiz.entity.GenericDelegator;
40 import org.ofbiz.entity.GenericEntityException;
41 import org.ofbiz.entity.condition.EntityFieldMap;
42 import org.ofbiz.entity.condition.EntityOperator;
43 import org.ofbiz.entity.condition.EntityCondition;
44 import org.ofbiz.entity.condition.EntityConditionList;
45 import org.ofbiz.entity.condition.EntityJoinOperator;
46 import org.ofbiz.entity.finder.EntityFinderUtil.GetAll;
47 import org.ofbiz.entity.finder.EntityFinderUtil.LimitRange;
48 import org.ofbiz.entity.finder.EntityFinderUtil.LimitView;
49 import org.ofbiz.entity.finder.EntityFinderUtil.OutputHandler;
50 import org.ofbiz.entity.finder.EntityFinderUtil.UseIterator;
51 import org.ofbiz.entity.model.ModelEntity;
52 import org.ofbiz.entity.transaction.TransactionUtil;
53 import org.ofbiz.entity.util.EntityFindOptions;
54 import org.ofbiz.entity.util.EntityListIterator;
55 import org.ofbiz.entity.util.EntityUtil;
56 import org.w3c.dom.Element JavaDoc;
57
58 import java.io.Serializable JavaDoc;
59 import java.sql.ResultSet JavaDoc;
60
61 /**
62  * Uses the delegator to find entity values by a and
63  *
64  * @author <a HREF="mailto:jonesde@ofbiz.org">David E. Jones</a>
65  * @version $Rev: 6197 $
66  * @since 3.1
67  */

68 public class ByAndFinder implements Serializable JavaDoc {
69     
70     public static final String JavaDoc module = ByAndFinder.class.getName();
71     
72     protected FlexibleStringExpander entityNameExdr;
73     protected FlexibleStringExpander useCacheStrExdr;
74     protected FlexibleStringExpander filterByDateStrExdr;
75     protected FlexibleStringExpander distinctStrExdr;
76     protected FlexibleStringExpander delegatorNameExdr;
77     protected FlexibleMapAccessor listAcsr;
78     protected FlexibleStringExpander resultSetTypeExdr;
79     
80     protected Map JavaDoc fieldMap;
81     protected List JavaDoc selectFieldExpanderList;
82     protected List JavaDoc orderByExpanderList;
83     protected OutputHandler outputHandler;
84
85     public ByAndFinder(Element JavaDoc element) {
86         this.entityNameExdr = new FlexibleStringExpander(element.getAttribute("entity-name"));
87         this.useCacheStrExdr = new FlexibleStringExpander(element.getAttribute("use-cache"));
88         this.filterByDateStrExdr = new FlexibleStringExpander(element.getAttribute("filter-by-date"));
89         this.distinctStrExdr = new FlexibleStringExpander(element.getAttribute("distinct"));
90         this.delegatorNameExdr = new FlexibleStringExpander(element.getAttribute("delegator-name"));
91         this.listAcsr = new FlexibleMapAccessor(element.getAttribute("list-name"));
92         this.resultSetTypeExdr = new FlexibleStringExpander(element.getAttribute("result-set-type"));
93         
94         // process field-map
95
this.fieldMap = EntityFinderUtil.makeFieldMap(element);
96
97         // process select-field
98
selectFieldExpanderList = EntityFinderUtil.makeSelectFieldExpanderList(element);
99         
100         // process order-by
101
List JavaDoc orderByElementList = UtilXml.childElementList(element, "order-by");
102         if (orderByElementList.size() > 0) {
103             orderByExpanderList = new LinkedList JavaDoc();
104             Iterator JavaDoc orderByElementIter = orderByElementList.iterator();
105             while (orderByElementIter.hasNext()) {
106                 Element JavaDoc orderByElement = (Element JavaDoc) orderByElementIter.next();
107                 orderByExpanderList.add(new FlexibleStringExpander(orderByElement.getAttribute("field-name")));
108             }
109         }
110
111         // process limit-range | limit-view | use-iterator
112
Element JavaDoc limitRangeElement = UtilXml.firstChildElement(element, "limit-range");
113         Element JavaDoc limitViewElement = UtilXml.firstChildElement(element, "limit-view");
114         Element JavaDoc useIteratorElement = UtilXml.firstChildElement(element, "use-iterator");
115         if ((limitRangeElement != null && limitViewElement != null) || (limitRangeElement != null && useIteratorElement != null) || (limitViewElement != null && useIteratorElement != null)) {
116             throw new IllegalArgumentException JavaDoc("In entity find by and element, cannot have more than one of the following: limit-range, limit-view, and use-iterator");
117         }
118         if (limitRangeElement != null) {
119             outputHandler = new LimitRange(limitRangeElement);
120         } else if (limitViewElement != null) {
121             outputHandler = new LimitView(limitViewElement);
122         } else if (useIteratorElement != null) {
123             outputHandler = new UseIterator(useIteratorElement);
124         } else {
125             // default to get all
126
outputHandler = new GetAll();
127         }
128     }
129
130     public void runFind(Map JavaDoc context, GenericDelegator delegator) throws GeneralException {
131         String JavaDoc entityName = this.entityNameExdr.expandString(context);
132         String JavaDoc useCacheStr = this.useCacheStrExdr.expandString(context);
133         String JavaDoc filterByDateStr = this.filterByDateStrExdr.expandString(context);
134         String JavaDoc distinctStr = this.distinctStrExdr.expandString(context);
135         String JavaDoc delegatorName = this.delegatorNameExdr.expandString(context);
136         ModelEntity modelEntity = delegator.getModelEntity(entityName);
137         String JavaDoc resultSetTypeString = this.resultSetTypeExdr.expandString(context);
138         
139         if (modelEntity == null) {
140             throw new IllegalArgumentException JavaDoc("In find entity by and could not find definition for entity with name [" + entityName + "].");
141         }
142         
143         boolean useCache = "true".equals(useCacheStr);
144         boolean filterByDate = "true".equals(filterByDateStr);
145         boolean distinct = "true".equals(distinctStr);
146         int resultSetType = ResultSet.TYPE_SCROLL_INSENSITIVE;
147         if ("forward".equals(resultSetTypeString))
148             resultSetType = ResultSet.TYPE_FORWARD_ONLY;
149         
150         if (delegatorName != null && delegatorName.length() > 0) {
151             delegator = GenericDelegator.getGenericDelegator(delegatorName);
152         }
153
154         if (useCache) {
155             // if useCache == true && outputHandler instanceof UseIterator, throw exception; not a valid combination
156
if (outputHandler instanceof UseIterator) {
157                 throw new IllegalArgumentException JavaDoc("In find entity by and cannot have use-cache set to true and select use-iterator for the output type.");
158             }
159             if (distinct) {
160                 throw new IllegalArgumentException JavaDoc("In find entity by and cannot have use-cache set to true and set distinct to true.");
161             }
162         }
163
164         // create the by and map
165
Map JavaDoc entityContext = new HashMap JavaDoc();
166         EntityFinderUtil.expandFieldMapToContext(this.fieldMap, context, entityContext);
167         // then convert the types...
168
modelEntity.convertFieldMapInPlace(entityContext, delegator);
169         
170         
171         // get the list of fieldsToSelect from selectFieldExpanderList
172
Set JavaDoc fieldsToSelect = EntityFinderUtil.makeFieldsToSelect(selectFieldExpanderList, context);
173
174         // get the list of orderByFields from orderByExpanderList
175
List JavaDoc orderByFields = EntityFinderUtil.makeOrderByFieldList(this.orderByExpanderList, context);
176         
177         try {
178             // if filterByDate, do a date filter on the results based on the now-timestamp
179
EntityCondition whereEntityCondition = new EntityFieldMap(entityContext, EntityOperator.AND);
180             if (filterByDate) {
181                 EntityCondition filterByDateCondition = EntityUtil.getFilterByDateExpr();
182                 if (whereEntityCondition != null) {
183                     whereEntityCondition = new EntityConditionList(UtilMisc.toList(whereEntityCondition, filterByDateCondition), EntityJoinOperator.AND);
184                 } else {
185                     whereEntityCondition = filterByDateCondition;
186                 }
187             }
188             
189             if (useCache) {
190                 List JavaDoc results = delegator.findByConditionCache(entityName, whereEntityCondition, fieldsToSelect, orderByFields);
191                 this.outputHandler.handleOutput(results, context, listAcsr);
192             } else {
193                 boolean useTransaction = true;
194                 if (this.outputHandler instanceof UseIterator && !TransactionUtil.isTransactionInPlace()) {
195                     Exception JavaDoc newE = new Exception JavaDoc("Stack Trace");
196                     Debug.logError(newE, "ERROR: Cannot do a by and find that returns an EntityListIterator with no transaction in place. Wrap this call in a transaction.", module);
197                     useTransaction = false;
198                 }
199                 
200                 EntityFindOptions options = new EntityFindOptions();
201                 options.setDistinct(distinct);
202                 options.setResultSetType(resultSetType);
203                 boolean beganTransaction = false;
204                 try {
205                     if (useTransaction) {
206                         beganTransaction = TransactionUtil.begin();
207                     }
208
209                     EntityListIterator eli = delegator.findListIteratorByCondition(entityName, whereEntityCondition, null, fieldsToSelect, orderByFields, options);
210                     this.outputHandler.handleOutput(eli, context, listAcsr);
211                 } catch (GenericEntityException e) {
212                     String JavaDoc errMsg = "Failure in by and find operation, rolling back transaction";
213                     Debug.logError(e, errMsg, module);
214                     try {
215                         // only rollback the transaction if we started one...
216
TransactionUtil.rollback(beganTransaction, errMsg, e);
217                     } catch (GenericEntityException e2) {
218                         Debug.logError(e2, "Could not rollback transaction: " + e2.toString(), module);
219                     }
220                     // after rolling back, rethrow the exception
221
throw e;
222                 } finally {
223                     // only commit the transaction if we started one... this will throw an exception if it fails
224
TransactionUtil.commit(beganTransaction);
225                 }
226             }
227         } catch (GenericEntityException e) {
228             String JavaDoc errMsg = "Error doing find by and: " + e.toString();
229             Debug.logError(e, module);
230             throw new GeneralException(errMsg, e);
231         }
232     }
233 }
234
235
Popular Tags