KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > util > SelectObserver


1 /* ====================================================================
2  *
3  * The ObjectStyle Group Software License, version 1.1
4  * ObjectStyle Group - http://objectstyle.org/
5  *
6  * Copyright (c) 2002-2005, Andrei (Andrus) Adamchik and individual authors
7  * of the software. All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  * notice, this list of conditions and the following disclaimer.
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  * notice, this list of conditions and the following disclaimer in
18  * the documentation and/or other materials provided with the
19  * distribution.
20  *
21  * 3. The end-user documentation included with the redistribution, if any,
22  * must include the following acknowlegement:
23  * "This product includes software developed by independent contributors
24  * and hosted on ObjectStyle Group web site (http://objectstyle.org/)."
25  * Alternately, this acknowlegement may appear in the software itself,
26  * if and wherever such third-party acknowlegements normally appear.
27  *
28  * 4. The names "ObjectStyle Group" and "Cayenne" must not be used to endorse
29  * or promote products derived from this software without prior written
30  * permission. For written permission, email
31  * "andrus at objectstyle dot org".
32  *
33  * 5. Products derived from this software may not be called "ObjectStyle"
34  * or "Cayenne", nor may "ObjectStyle" or "Cayenne" appear in their
35  * names without prior written permission.
36  *
37  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
38  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
39  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
40  * DISCLAIMED. IN NO EVENT SHALL THE OBJECTSTYLE GROUP OR
41  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
42  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
43  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
44  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
46  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
47  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
48  * SUCH DAMAGE.
49  * ====================================================================
50  *
51  * This software consists of voluntary contributions made by many
52  * individuals and hosted on ObjectStyle Group web site. For more
53  * information on the ObjectStyle Group, please see
54  * <http://objectstyle.org/>.
55  */

56
57 package org.objectstyle.cayenne.access.util;
58
59 import java.util.Collection JavaDoc;
60 import java.util.HashMap JavaDoc;
61 import java.util.List JavaDoc;
62 import java.util.Map JavaDoc;
63
64 import org.apache.log4j.Level;
65 import org.objectstyle.cayenne.CayenneRuntimeException;
66 import org.objectstyle.cayenne.ObjectFactory;
67 import org.objectstyle.cayenne.access.DataContext;
68 import org.objectstyle.cayenne.access.DataContextObjectFactory;
69 import org.objectstyle.cayenne.access.QueryLogger;
70 import org.objectstyle.cayenne.exp.Expression;
71 import org.objectstyle.cayenne.map.ObjEntity;
72 import org.objectstyle.cayenne.query.GenericSelectQuery;
73 import org.objectstyle.cayenne.query.QualifiedQuery;
74 import org.objectstyle.cayenne.query.Query;
75 import org.objectstyle.cayenne.util.Util;
76
77 /**
78  * OperationObserver that accumulates select query results provided by callback methods.
79  * Later the results can be retrieved via different <code>getResults</code> methods.
80  * Also supports instantiating DataObjects within a provided DataContext.
81  * <p>
82  * This class is used as a default OperationObserver by DataContext. Also it can serve as
83  * a helper for classes that work with DataNode directly, bypassing DataContext.
84  * </p>
85  * <p>
86  * If exceptions happen during the execution, they are immediately rethrown.
87  * </p>
88  * <p>
89  * <i>For more information see <a HREF="../../../../../../userguide/index.html"
90  * target="_top">Cayenne User Guide. </a> </i>
91  * </p>
92  *
93  * @author Andrei Adamchik
94  */

95 public class SelectObserver extends DefaultOperationObserver {
96
97     protected Map JavaDoc results = new HashMap JavaDoc();
98     protected int selectCount;
99
100     public SelectObserver() {
101         this(QueryLogger.DEFAULT_LOG_LEVEL);
102     }
103
104     public SelectObserver(Level logLevel) {
105         super.setLoggingLevel(logLevel);
106     }
107
108     /**
109      * Returns a count of select queries that returned results since the last time "clear"
110      * was called, or since this object was created.
111      */

112     public int getSelectCount() {
113         return selectCount;
114     }
115
116     /**
117      * Returns a list of result snapshots for the specified query, or null if this query
118      * has never produced any results.
119      */

120     public List JavaDoc getResults(Query q) {
121         return (List JavaDoc) results.get(q);
122     }
123
124     /**
125      * Returns query results accumulated during query execution with this object as an
126      * operation observer.
127      */

128     public Map JavaDoc getResults() {
129         return results;
130     }
131
132     /** Clears fetched objects stored in an internal list. */
133     public void clear() {
134         selectCount = 0;
135         results.clear();
136     }
137
138     /**
139      * Stores all objects in <code>dataRows</code> in an internal result list.
140      */

141     public void nextDataRows(Query query, List JavaDoc dataRows) {
142
143         if (dataRows != null) {
144             results.put(query, dataRows);
145         }
146
147         selectCount++;
148     }
149
150     /**
151      * @since 1.1
152      * @deprecated since 1.2 use ObjectFactory variety instead.
153      */

154     public List JavaDoc getResultsAsObjects(DataContext dataContext, Query rootQuery) {
155
156         if (!(rootQuery instanceof GenericSelectQuery)) {
157             throw new CayenneRuntimeException("Expected GenericSelectQuery, got: "
158                     + rootQuery);
159         }
160
161         GenericSelectQuery selectQuery = (GenericSelectQuery) rootQuery;
162
163         ObjectFactory factory = new DataContextObjectFactory(dataContext, selectQuery
164                 .isRefreshingObjects(), selectQuery.isResolvingInherited());
165         ObjEntity rootEntity = dataContext.getEntityResolver().lookupObjEntity(rootQuery);
166         return getResultsAsObjects(factory, rootEntity, selectQuery);
167     }
168
169     /**
170      * Returns results for a given query object as DataObjects. <code>rootQuery</code>
171      * argument is assumed to be the root query, and the rest are either independent
172      * queries or queries prefetching relationships for the root query.
173      * <p>
174      * If no results are found, an empty immutable list is returned. Most common case for
175      * this is when a delegate has blocked the query from execution.
176      * </p>
177      * <p>
178      * Side effect of this method call is that all data rows currently stored in this
179      * SelectObserver are loaded as objects to a given DataContext (thus resolving
180      * prefetched to-one relationships). Any to-many relationships for the root query are
181      * resolved as well.
182      * </p>
183      *
184      * @since 1.2
185      */

186     public List JavaDoc getResultsAsObjects(
187             ObjectFactory factory,
188             ObjEntity rootEntity,
189             GenericSelectQuery rootQuery) {
190
191         // sanity check
192
if (rootEntity == null) {
193             throw new CayenneRuntimeException(
194                     "Can't instantiate DataObjects from resutls. ObjEntity is undefined for query: "
195                             + rootQuery);
196         }
197
198         // prepare prefetch resolver ... it can be used in two different ways
199
// depending on whether we also have joint prefetches.
200
// TODO: this logic needs to be streamlined...
201
PrefetchResolver tree = new PrefetchResolver();
202         tree.buildTree(rootEntity, rootQuery, results);
203
204         Collection JavaDoc jointPrefetches = rootQuery.getJointPrefetches();
205         if (!jointPrefetches.isEmpty()) {
206
207             // certain qualifiers conflict with joint prefetches, so we
208
// might need to disable some prefetched to-many arrays from being
209
// resolved. This is somewhat of a hack in search of a better solution.
210
Expression qualifier = null;
211             if (rootQuery instanceof QualifiedQuery) {
212                 qualifier = ((QualifiedQuery) rootQuery).getQualifier();
213             }
214
215             FlatPrefetchTreeNode flatPrefetchTree = new FlatPrefetchTreeNode(
216                     rootEntity,
217                     jointPrefetches,
218                     qualifier);
219
220             FlatPrefetchResolver flatPrefetchResolver = new FlatPrefetchResolver(factory);
221
222             List JavaDoc objects = flatPrefetchResolver.resolveObjectTree(flatPrefetchTree,
223                     getResults(rootQuery));
224
225             // attach normal prefetches to the list of main objects that is already
226
// resolved...
227
tree.resolveObjectTree(factory, objects, true);
228             return objects;
229         }
230
231         return tree.resolveObjectTree(factory);
232     }
233
234     /**
235      * Overrides super implementation to rethrow an exception immediately.
236      */

237     public void nextQueryException(Query query, Exception JavaDoc ex) {
238         super.nextQueryException(query, ex);
239         throw new CayenneRuntimeException("Query exception.", Util.unwindException(ex));
240     }
241
242     /**
243      * Overrides superclass implementation to rethrow an exception immediately.
244      */

245     public void nextGlobalException(Exception JavaDoc ex) {
246         super.nextGlobalException(ex);
247         throw new CayenneRuntimeException("Global exception.", Util.unwindException(ex));
248     }
249 }
Popular Tags