KickJava   Java API By Example, From Geeks To Geeks.

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


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.Collections JavaDoc;
60 import java.util.Iterator JavaDoc;
61 import java.util.List JavaDoc;
62
63 import org.objectstyle.cayenne.CayenneRuntimeException;
64 import org.objectstyle.cayenne.DataObject;
65 import org.objectstyle.cayenne.DataRow;
66 import org.objectstyle.cayenne.PersistenceState;
67 import org.objectstyle.cayenne.map.DeleteRule;
68 import org.objectstyle.cayenne.map.ObjEntity;
69 import org.objectstyle.cayenne.map.ObjRelationship;
70
71 /**
72  * Helper class that implements DataObject deletion strategy.
73  *
74  * @since 1.2
75  * @author Andrei Adamchik
76  */

77 class DataContextDeleteAction {
78
79     DataContext dataContext;
80
81     DataContextDeleteAction(DataContext context) {
82         this.dataContext = context;
83     }
84
85     /**
86      * Deletes internal DataObject from its DataContext, processing delete rules.
87      */

88     boolean performDelete(DataObject object) throws DeleteDenyException {
89         int oldState = object.getPersistenceState();
90         if (oldState == PersistenceState.DELETED
91                 || oldState == PersistenceState.TRANSIENT) {
92
93             // Drop out... especially in case of DELETED we might be about to get
94
// into a horrible recursive loop due to CASCADE delete rules.
95
// Assume that everything must have been done correctly already
96
// and *don't* do it again
97
return false;
98         }
99
100         // must resolve HOLLOW objects before delete... needed
101
// to process relationships and optimistric locking...
102
object.resolveFault();
103
104         if (oldState == PersistenceState.NEW) {
105             deleteNew(object, oldState);
106         }
107         else {
108             deletePersistent(object, oldState);
109         }
110
111         return true;
112     }
113
114     private void deletePersistent(DataObject object, int oldState)
115             throws DeleteDenyException {
116
117         // duplicating some code from ObjectStore.retainSnapshot, as we have to do it
118
// in two phases, extracting snapshot here, but retaining it after the
119
// successful deletion only...
120
DataRow snapshot = dataContext.getObjectStore().getCachedSnapshot(object
121                 .getObjectId());
122         if (snapshot == null) {
123             snapshot = dataContext.currentSnapshot(object);
124         }
125
126         // We cannot delay setting state to deleted, as Cascade deletes might cause
127
// recursion, and the "deleted" state is the best way we have of noticing that and
128
// bailing out (see above)
129

130         object.setPersistenceState(PersistenceState.DELETED);
131         processDeleteRules(object, oldState);
132
133         // must retain snapshot for optimistic locking to work ...
134
dataContext.getObjectStore().retainSnapshot(object, snapshot);
135     }
136
137     private void deleteNew(DataObject object, int oldState) throws DeleteDenyException {
138         object.setPersistenceState(PersistenceState.TRANSIENT);
139         processDeleteRules(object, oldState);
140
141         // if an object was NEW, we must throw it out of the ObjectStore
142

143         dataContext.getObjectStore().objectsUnregistered(Collections
144                 .singletonList(object));
145         object.setDataContext(null);
146     }
147
148     private void processDeleteRules(DataObject object, int oldState)
149             throws DeleteDenyException {
150         ObjEntity entity = dataContext.getEntityResolver().lookupObjEntity(object);
151         Iterator JavaDoc it = entity.getRelationships().iterator();
152         while (it.hasNext()) {
153             ObjRelationship relationship = (ObjRelationship) it.next();
154
155             boolean processFlattened = relationship.isFlattened()
156                     && relationship.isToDependentEntity();
157
158             // first check for no action... bail out if no flattened processing is needed
159
if (relationship.getDeleteRule() == DeleteRule.NO_ACTION && !processFlattened) {
160                 continue;
161             }
162
163             List JavaDoc relatedObjects = Collections.EMPTY_LIST;
164             if (relationship.isToMany()) {
165
166                 List JavaDoc toMany = (List JavaDoc) object.readNestedProperty(relationship.getName());
167
168                 if (toMany.size() > 0) {
169                     // Get a copy of the list so that deleting objects doesn't
170
// result in concurrent modification exceptions
171
relatedObjects = new ArrayList JavaDoc(toMany);
172                 }
173             }
174             else {
175                 Object JavaDoc relatedObject = object.readNestedProperty(relationship.getName());
176
177                 if (relatedObject != null) {
178                     relatedObjects = Collections.singletonList(relatedObject);
179                 }
180             }
181
182             // no related object, bail out
183
if (relatedObjects.size() == 0) {
184                 continue;
185             }
186
187             // process DENY rule first...
188
if (relationship.getDeleteRule() == DeleteRule.DENY) {
189                 object.setPersistenceState(oldState);
190
191                 String JavaDoc message = relatedObjects.size() == 1
192                         ? "1 related object"
193                         : relatedObjects.size() + " related objects";
194                 throw new DeleteDenyException(object, relationship, message);
195             }
196
197             // process flattened with dependent join tables...
198
// joins must be removed even if they are non-existent or ignored in the
199
// object graph
200
if (processFlattened) {
201                 ObjectStore objectStore = dataContext.getObjectStore();
202                 Iterator JavaDoc iterator = relatedObjects.iterator();
203                 while (iterator.hasNext()) {
204                     DataObject relatedObject = (DataObject) iterator.next();
205                     objectStore.flattenedRelationshipUnset(object,
206                             relationship,
207                             relatedObject);
208                 }
209             }
210
211             // process remaining rules
212
switch (relationship.getDeleteRule()) {
213                 case DeleteRule.NO_ACTION:
214                     break;
215                 case DeleteRule.NULLIFY:
216                     ObjRelationship inverseRelationship = relationship
217                             .getReverseRelationship();
218
219                     if (inverseRelationship == null) {
220                         // nothing we can do here
221
break;
222                     }
223
224                     if (inverseRelationship.isToMany()) {
225                         Iterator JavaDoc iterator = relatedObjects.iterator();
226                         while (iterator.hasNext()) {
227                             DataObject relatedObject = (DataObject) iterator.next();
228                             relatedObject.removeToManyTarget(inverseRelationship
229                                     .getName(), object, true);
230                         }
231                     }
232                     else {
233                         // Inverse is to-one - find all related objects and
234
// nullify the reverse relationship
235
Iterator JavaDoc iterator = relatedObjects.iterator();
236                         while (iterator.hasNext()) {
237                             DataObject relatedObject = (DataObject) iterator.next();
238                             relatedObject.setToOneTarget(inverseRelationship.getName(),
239                                     null,
240                                     true);
241                         }
242                     }
243
244                     break;
245                 case DeleteRule.CASCADE:
246                     // Delete all related objects
247
Iterator JavaDoc iterator = relatedObjects.iterator();
248                     while (iterator.hasNext()) {
249                         DataObject relatedObject = (DataObject) iterator.next();
250                         new DataContextDeleteAction(this.dataContext)
251                                 .performDelete(relatedObject);
252                     }
253
254                     break;
255                 default:
256                     object.setPersistenceState(oldState);
257                     throw new CayenneRuntimeException("Invalid delete rule "
258                             + relationship.getDeleteRule());
259             }
260         }
261     }
262 }
Popular Tags