KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > access > CommitObserver


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;
57
58 import java.util.ArrayList JavaDoc;
59 import java.util.Arrays JavaDoc;
60 import java.util.Collection JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.List JavaDoc;
63
64 import org.objectstyle.cayenne.CayenneException;
65 import org.objectstyle.cayenne.CayenneRuntimeException;
66 import org.objectstyle.cayenne.DataRow;
67 import org.objectstyle.cayenne.ObjectId;
68 import org.objectstyle.cayenne.access.event.DataContextEvent;
69 import org.objectstyle.cayenne.access.event.DataContextTransactionEventListener;
70 import org.objectstyle.cayenne.access.event.DataObjectTransactionEventListener;
71 import org.objectstyle.cayenne.access.util.DefaultOperationObserver;
72 import org.objectstyle.cayenne.event.EventManager;
73 import org.objectstyle.cayenne.map.DbAttribute;
74 import org.objectstyle.cayenne.query.InsertBatchQuery;
75 import org.objectstyle.cayenne.query.Query;
76 import org.objectstyle.cayenne.util.Util;
77
78 /**
79  * Used as an observer for DataContext commit operations.
80  *
81  * @since 1.2
82  * @author Andrei Adamchik
83  */

84 class CommitObserver extends DefaultOperationObserver implements
85         DataContextTransactionEventListener {
86
87     List JavaDoc updObjects;
88     List JavaDoc delObjects;
89     List JavaDoc insObjects;
90     List JavaDoc objectsToNotify;
91
92     DataContext context;
93
94     CommitObserver(DataContext context, List JavaDoc insObjects, List JavaDoc updObjects, List JavaDoc delObjects) {
95         this.context = context;
96         this.insObjects = insObjects;
97         this.updObjects = updObjects;
98         this.delObjects = delObjects;
99         this.objectsToNotify = new ArrayList JavaDoc();
100
101         // Build a list of objects that need to be notified about posted
102
// DataContext events. When notifying about a successful completion
103
// of a transaction we cannot build this list anymore, since all
104
// the work will be done by then.
105
Iterator JavaDoc collIter = (Arrays.asList(new List JavaDoc[] {
106                 delObjects, updObjects, insObjects
107         })).iterator();
108         while (collIter.hasNext()) {
109             Iterator JavaDoc objIter = ((Collection JavaDoc) collIter.next()).iterator();
110             while (objIter.hasNext()) {
111                 Object JavaDoc element = objIter.next();
112                 if (element instanceof DataObjectTransactionEventListener) {
113                     this.objectsToNotify.add(element);
114                 }
115             }
116         }
117     }
118
119     public void nextQueryException(Query query, Exception JavaDoc ex) {
120         super.nextQueryException(query, ex);
121         throw new CayenneRuntimeException("Raising from query exception.", Util
122                 .unwindException(ex));
123     }
124
125     public void nextGlobalException(Exception JavaDoc ex) {
126         super.nextGlobalException(ex);
127         throw new CayenneRuntimeException(
128                 "Raising from underlyingQueryEngine exception.",
129                 Util.unwindException(ex));
130     }
131
132     void registerForDataContextEvents() {
133         EventManager mgr = EventManager.getDefaultManager();
134         mgr.addListener(
135                 this,
136                 "dataContextWillCommit",
137                 DataContextEvent.class,
138                 DataContext.WILL_COMMIT,
139                 this.context);
140         mgr.addListener(
141                 this,
142                 "dataContextDidCommit",
143                 DataContextEvent.class,
144                 DataContext.DID_COMMIT,
145                 this.context);
146         mgr.addListener(
147                 this,
148                 "dataContextDidRollback",
149                 DataContextEvent.class,
150                 DataContext.DID_ROLLBACK,
151                 this.context);
152     }
153
154     void unregisterFromDataContextEvents() {
155         EventManager mgr = EventManager.getDefaultManager();
156         mgr.removeListener(this, DataContext.WILL_COMMIT);
157         mgr.removeListener(this, DataContext.DID_COMMIT);
158         mgr.removeListener(this, DataContext.DID_ROLLBACK);
159     }
160
161     public void dataContextWillCommit(DataContextEvent event) {
162         Iterator JavaDoc iter = objectsToNotify.iterator();
163         while (iter.hasNext()) {
164             ((DataObjectTransactionEventListener) iter.next()).willCommit(event);
165         }
166     }
167
168     public void dataContextDidCommit(DataContextEvent event) {
169         Iterator JavaDoc iter = objectsToNotify.iterator();
170         while (iter.hasNext()) {
171             ((DataObjectTransactionEventListener) iter.next()).didCommit(event);
172         }
173     }
174
175     public void dataContextDidRollback(DataContextEvent event) {
176         // do nothing for now
177
}
178
179     /**
180      * @since 1.2
181      */

182     public void nextGeneratedDataRows(Query query, ResultIterator keysIterator) {
183
184         // read and close the iterator before doing anything else
185
List JavaDoc keys;
186         try {
187             keys = keysIterator.dataRows(true);
188         }
189         catch (CayenneException ex) {
190             throw new CayenneRuntimeException("Error reading primary key", Util
191                     .unwindException(ex));
192         }
193
194         if (!(query instanceof InsertBatchQuery)) {
195             throw new CayenneRuntimeException(
196                     "Generated keys only supported for InsertBatchQuery, instead got "
197                             + query);
198         }
199
200         InsertBatchQuery batch = (InsertBatchQuery) query;
201
202         ObjectId id = batch.getObjectId();
203         if (id == null || !id.isTemporary()) {
204             // why would this happen?
205
return;
206         }
207
208         if (keys.size() != 1) {
209             throw new CayenneRuntimeException(
210                     "One and only one PK row is expected, instead got " + keys.size());
211         }
212
213         DataRow key = (DataRow) keys.get(0);
214
215         // empty key?
216
if (key.size() == 0) {
217             throw new CayenneRuntimeException("Empty key generated.");
218         }
219
220         // determine DbAttribute name...
221

222         // As of now (01/2005) all tested drivers don't provide decent descriptors of
223
// identity result sets, so a data row will contain garbage labels. Also most
224
// DBs only support one autogenerated key per table... So here we will have to
225
// infer the key name and currently will only support a single column...
226
if (key.size() > 1) {
227             throw new CayenneRuntimeException(
228                     "Only a single column autogenerated PK is supported. "
229                             + "Generated key: "
230                             + key);
231         }
232
233         Iterator JavaDoc it = batch.getDbEntity().getGeneratedAttributes().iterator();
234         while (it.hasNext()) {
235             DbAttribute attribute = (DbAttribute) it.next();
236
237             // batch can have generated attributes that are not PKs, e.g. columns with
238
// DB DEFAULT values. Ignore those.
239
if (attribute.isPrimaryKey()) {
240                 Object JavaDoc value = key.values().iterator().next();
241
242                 // I guess we should override any existing value,
243
// as generated key is the latest thing that exists in the DB.
244
id.getReplacementIdMap().put(attribute.getName(), value);
245                 break;
246             }
247         }
248     }
249 }
Popular Tags