KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectstyle > cayenne > client > ClientObjectContext


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.client;
57
58 import java.util.Collection JavaDoc;
59 import java.util.Iterator JavaDoc;
60 import java.util.List JavaDoc;
61
62 import org.objectstyle.cayenne.CayenneRuntimeException;
63 import org.objectstyle.cayenne.ObjectContext;
64 import org.objectstyle.cayenne.PersistenceState;
65 import org.objectstyle.cayenne.Persistent;
66 import org.objectstyle.cayenne.QueryResponse;
67 import org.objectstyle.cayenne.distribution.BootstrapMessage;
68 import org.objectstyle.cayenne.distribution.CayenneConnector;
69 import org.objectstyle.cayenne.distribution.CommitMessage;
70 import org.objectstyle.cayenne.distribution.GenericQueryMessage;
71 import org.objectstyle.cayenne.distribution.GlobalID;
72 import org.objectstyle.cayenne.distribution.SelectMessage;
73 import org.objectstyle.cayenne.distribution.UpdateMessage;
74 import org.objectstyle.cayenne.graph.CompoundDiff;
75 import org.objectstyle.cayenne.graph.GraphDiff;
76 import org.objectstyle.cayenne.graph.GraphManager;
77 import org.objectstyle.cayenne.graph.OperationRecorder;
78 import org.objectstyle.cayenne.query.QueryExecutionPlan;
79
80 /**
81  * An client tier ObjectContext implementation in a 3+ tier Cayenne application. Instead
82  * of using regular Cayenne stack for database updates ClientObjectContext uses a
83  * connector object to communicate with server-side peer.
84  *
85  * @since 1.2
86  * @author Andrus Adamchik
87  */

88 public class ClientObjectContext implements ObjectContext {
89
90     // if we are to pass ClientObjectContext around, connector should be left alone and
91
// reinjected later if needed
92
protected transient CayenneConnector connector;
93
94     protected ClientEntityResolver entityResolver;
95     protected GraphManager graphManager;
96     protected OperationRecorder changeRecorder;
97     protected ClientStateRecorder stateRecorder;
98
99     /**
100      * Creates a new ClientObjectContext, initializaing it with a connector instance that
101      * should be used to connect to a remote Cayenne service.
102      */

103     public ClientObjectContext(CayenneConnector connector) {
104         this.connector = connector;
105
106         // assemble objects that track graph changes
107
this.graphManager = new GraphManager();
108
109         this.changeRecorder = new OperationRecorder();
110         this.stateRecorder = new ClientStateRecorder();
111
112         graphManager.addLocalChangeHandler(changeRecorder);
113         graphManager.addLocalChangeHandler(stateRecorder);
114         graphManager.setRemoteChangeHandler(new ClientObjectContextMergeHandler(
115                 stateRecorder,
116                 graphManager));
117     }
118
119     public ClientEntityResolver getEntityResolver() {
120         // load entity resolver on demand
121
if (entityResolver == null) {
122             synchronized (this) {
123                 if (entityResolver == null) {
124                     entityResolver = new BootstrapMessage().sendBootstrap(connector);
125                 }
126             }
127         }
128
129         return entityResolver;
130     }
131
132     public void setEntityResolver(ClientEntityResolver entityResolver) {
133         this.entityResolver = entityResolver;
134     }
135
136     /**
137      * Returns connector used to access remote Cayenne service.
138      */

139     public CayenneConnector getConnector() {
140         return connector;
141     }
142
143     /**
144      * Commits changes to uncommitted objects. First checks if there are changes in this
145      * context and if any changes are detected, sends a commit message to remote Cayenne
146      * service via an internal instance of CayenneConnector.
147      */

148     public GraphDiff commit() {
149
150         if (!changeRecorder.isEmpty()) {
151             GraphDiff commitDiff = new CommitMessage(changeRecorder.getDiffs())
152                     .sendCommit(connector);
153
154             graphManager.mergeRemoteChange(commitDiff);
155             stateRecorder.processCommit(graphManager);
156             changeRecorder.clear();
157
158             return commitDiff;
159         }
160         else {
161             return new CompoundDiff();
162         }
163     }
164
165     /**
166      * Deletes an object locally, scheduling it for future deletion from the external data
167      * store.
168      */

169     public void deleteObject(Persistent object) {
170         if (object.getPersistenceState() == PersistenceState.TRANSIENT) {
171             return;
172         }
173
174         if (object.getPersistenceState() == PersistenceState.DELETED) {
175             return;
176         }
177
178         if (object.getPersistenceState() == PersistenceState.NEW) {
179             // kick it out of context
180
object.setPersistenceState(PersistenceState.TRANSIENT);
181             graphManager.unregisterNode(object.getOid());
182             return;
183         }
184
185         // TODO: no delete rules (yet)
186

187         object.setPersistenceState(PersistenceState.DELETED);
188         graphManager.nodeRemoved(object.getOid());
189     }
190
191     /**
192      * Creates and registers a new Persistent object instance.
193      */

194     public Persistent newObject(Class JavaDoc persistentClass) {
195         if (persistentClass == null) {
196             throw new NullPointerException JavaDoc("Persistent class can't be null.");
197         }
198
199         Persistent object = null;
200         try {
201             object = (Persistent) persistentClass.newInstance();
202         }
203         catch (Exception JavaDoc ex) {
204             throw new CayenneRuntimeException(
205                     "Error instantiating persistent object of class " + persistentClass,
206                     ex);
207         }
208
209         object.setOid(new GlobalID(getEntityResolver().lookupEntity(persistentClass)));
210         object.setPersistenceState(PersistenceState.NEW);
211         object.setObjectContext(this);
212
213         graphManager.registerNode(object.getOid(), object);
214         graphManager.nodeCreated(object.getOid());
215
216         return object;
217     }
218
219     public int[] performUpdateQuery(QueryExecutionPlan query) {
220         return new UpdateMessage(query).send(connector);
221     }
222
223     public List JavaDoc performSelectQuery(QueryExecutionPlan query) {
224         List JavaDoc objects = new SelectMessage(query).send(connector);
225
226         // register objects with graphManager
227
Iterator JavaDoc it = objects.iterator();
228         while (it.hasNext()) {
229             Persistent o = (Persistent) it.next();
230
231             // sanity check
232
if (o.getOid() == null) {
233                 throw new CayenneClientException(
234                         "Server returned an object without an id: " + o);
235             }
236
237             o.setPersistenceState(PersistenceState.COMMITTED);
238             o.setObjectContext(this);
239             graphManager.registerNode(o.getOid(), o);
240         }
241
242         return objects;
243     }
244
245     public QueryResponse performGenericQuery(QueryExecutionPlan query) {
246         return new GenericQueryMessage(query).send(connector);
247     }
248
249     public void objectWillRead(Persistent dataObject, String JavaDoc property) {
250         if (dataObject.getPersistenceState() == PersistenceState.HOLLOW) {
251             // must resolve...
252
throw new CayenneClientException("Resolving an object is Unimplemented");
253         }
254     }
255
256     public void objectWillWrite(
257             Persistent object,
258             String JavaDoc property,
259             Object JavaDoc oldValue,
260             Object JavaDoc newValue) {
261
262         // change state...
263
if (object.getPersistenceState() == PersistenceState.COMMITTED) {
264             object.setPersistenceState(PersistenceState.MODIFIED);
265         }
266
267         graphManager.nodePropertyChanged(object.getOid(), property, oldValue, newValue);
268     }
269
270     public Collection JavaDoc uncommittedObjects() {
271         // TODO: sync on graphManager?
272
return stateRecorder.dirtyNodes(graphManager);
273     }
274
275     public Collection JavaDoc deletedObjects() {
276         // TODO: sync on graphManager?
277
return stateRecorder.dirtyNodes(graphManager, PersistenceState.DELETED);
278     }
279
280     public Collection JavaDoc modifiedObjects() {
281         // TODO: sync on graphManager?
282
return stateRecorder.dirtyNodes(graphManager, PersistenceState.MODIFIED);
283     }
284
285     public Collection JavaDoc newObjects() {
286         // TODO: sync on graphManager?
287
return stateRecorder.dirtyNodes(graphManager, PersistenceState.NEW);
288     }
289 }
Popular Tags