KickJava   Java API By Example, From Geeks To Geeks.

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


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 package org.objectstyle.cayenne.access.util;
57
58 import java.util.ArrayList JavaDoc;
59 import java.util.HashMap JavaDoc;
60 import java.util.HashSet JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.List JavaDoc;
63 import java.util.Map JavaDoc;
64 import java.util.Set JavaDoc;
65
66 import org.objectstyle.cayenne.CayenneException;
67 import org.objectstyle.cayenne.access.ResultIterator;
68 import org.objectstyle.cayenne.map.DbAttribute;
69 import org.objectstyle.cayenne.map.DbEntity;
70
71 /**
72  * A ResultIterator that does in-memory filtering of rows to return only distinct rows.
73  * Distinct comparison is done by comparing ObjectIds created from each row. Internally
74  * DistinctResultIterator wraps another ResultIterator that provides the actual rows. The
75  * current limitation is that once switched to reading ids instead of rows (i.e. when
76  * "nextObjectId()" is called for the first time), it can't be used to read data rows
77  * again. This is pretty sensible for most things in Cayenne.
78  *
79  * @since 1.2 Prior to 1.2 this was a non-public class in access package.
80  * @author Andrei Adamchik
81  */

82 public class DistinctResultIterator implements ResultIterator {
83
84     protected ResultIterator wrappedIterator;
85     protected Set JavaDoc fetchedIds;
86     protected Map JavaDoc nextDataRow;
87     protected DbEntity defaultEntity;
88     protected boolean readingIds;
89
90     /**
91      * Creates new DistinctResultIterator wrapping another ResultIterator.
92      *
93      * @param wrappedIterator
94      * @param defaultEntity an entity needed to build ObjectIds for distinct comparison.
95      */

96     public DistinctResultIterator(ResultIterator wrappedIterator, DbEntity defaultEntity)
97             throws CayenneException {
98         if (wrappedIterator == null) {
99             throw new CayenneException("Null wrapped iterator.");
100         }
101
102         if (defaultEntity == null) {
103             throw new CayenneException("Null defaultEntity.");
104         }
105
106         this.wrappedIterator = wrappedIterator;
107         this.defaultEntity = defaultEntity;
108         this.fetchedIds = new HashSet JavaDoc();
109
110         checkNextRow();
111     }
112
113     /**
114      * CLoses underlying ResultIterator.
115      */

116     public void close() throws CayenneException {
117         wrappedIterator.close();
118     }
119
120     /**
121      * Returns all data rows.
122      */

123     public List JavaDoc dataRows(boolean close) throws CayenneException {
124         List JavaDoc list = new ArrayList JavaDoc();
125
126         try {
127             while (this.hasNextRow()) {
128                 list.add(this.nextDataRow());
129             }
130             return list;
131         }
132         finally {
133             if (close) {
134                 this.close();
135             }
136         }
137     }
138
139     public int getDataRowWidth() {
140         return wrappedIterator.getDataRowWidth();
141     }
142
143     public boolean hasNextRow() throws CayenneException {
144         return nextDataRow != null;
145     }
146
147     public Map JavaDoc nextDataRow() throws CayenneException {
148         if (!hasNextRow()) {
149             throw new CayenneException(
150                     "An attempt to read uninitialized row or past the end of the iterator.");
151         }
152
153         Map JavaDoc row = nextDataRow;
154         checkNextRow();
155         return row;
156     }
157
158     /**
159      * Returns a Map for the next ObjectId. After calling this method, calls to
160      * "nextDataRow()" will result in exceptions.
161      */

162     public Map JavaDoc nextObjectId(DbEntity entity) throws CayenneException {
163         if (!hasNextRow()) {
164             throw new CayenneException(
165                     "An attempt to read uninitialized row or past the end of the iterator.");
166         }
167
168         Map JavaDoc row = nextDataRow;
169
170         // if we were previously reading full rows, we need to strip extra keys...
171
if (!readingIds) {
172             Iterator JavaDoc it = row.entrySet().iterator();
173             while (it.hasNext()) {
174                 Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
175                 String JavaDoc name = (String JavaDoc) entry.getKey();
176                 DbAttribute attribute = (DbAttribute) entity.getAttribute(name);
177                 if (attribute == null || !attribute.isPrimaryKey()) {
178                     it.remove();
179                 }
180             }
181         }
182
183         checkNextId(entity);
184         return row;
185     }
186
187     public void skipDataRow() throws CayenneException {
188         if (!hasNextRow()) {
189             throw new CayenneException(
190                     "An attempt to read uninitialized row or past the end of the iterator.");
191         }
192
193         if (readingIds) {
194             checkNextId(defaultEntity);
195         }
196         else {
197             checkNextRow();
198         }
199     }
200
201     void checkNextRow() throws CayenneException {
202         if (readingIds) {
203             throw new CayenneException(
204                     "Can't go back from reading ObjectIds to reading rows.");
205         }
206
207         nextDataRow = null;
208         while (wrappedIterator.hasNextRow()) {
209             Map JavaDoc next = wrappedIterator.nextDataRow();
210
211             // create id map...
212
// TODO: this can be optimized by creating an array with id keys
213
// to avoid iterating over default entity attributes...
214

215             Map JavaDoc id = new HashMap JavaDoc();
216             Iterator JavaDoc it = defaultEntity.getPrimaryKey().iterator();
217             while (it.hasNext()) {
218                 DbAttribute pk = (DbAttribute) it.next();
219                 id.put(pk.getName(), next.get(pk.getName()));
220             }
221
222             if (fetchedIds.add(id)) {
223                 this.nextDataRow = next;
224                 break;
225             }
226         }
227     }
228
229     void checkNextId(DbEntity entity) throws CayenneException {
230         if (entity == null) {
231             throw new CayenneException("Null DbEntity, can't create id.");
232         }
233
234         this.readingIds = true;
235         this.nextDataRow = null;
236
237         while (wrappedIterator.hasNextRow()) {
238             Map JavaDoc next = wrappedIterator.nextObjectId(entity);
239
240             if (fetchedIds.add(next)) {
241                 this.nextDataRow = next;
242                 break;
243             }
244         }
245     }
246 }
Popular Tags