KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > beans > Encoder


1 /*
2  * @(#)Encoder.java 1.20 04/05/05
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
6  */

7 package java.beans;
8
9 import java.io.*;
10 import java.util.*;
11
12
13 /**
14  * An <code>Encoder</code> is a class which can be used to create
15  * files or streams that encode the state of a collection of
16  * JavaBeans in terms of their public APIs. The <code>Encoder</code>,
17  * in conjunction with its persistence delegates, is responsible for
18  * breaking the object graph down into a series of <code>Statements</code>s
19  * and <code>Expression</code>s which can be used to create it.
20  * A subclass typically provides a syntax for these expressions
21  * using some human readable form - like Java source code or XML.
22  *
23  * @since 1.4
24  *
25  * @version 1.3 11/15/00
26  * @author Philip Milne
27  */

28         
29 public class Encoder {
30     private Map bindings = new IdentityHashMap();
31     private ExceptionListener JavaDoc exceptionListener;
32     boolean executeStatements = true;
33     private Map attributes;
34
35     /**
36      * Write the specified object to the output stream.
37      * The serialized form will denote a series of
38      * expressions, the combined effect of which will create
39      * an equivalent object when the input stream is read.
40      * By default, the object is assumed to be a <em>JavaBean</em>
41      * with a nullary constructor, whose state is defined by
42      * the matching pairs of "setter" and "getter" methods
43      * returned by the Introspector.
44      *
45      * @param o The object to be written to the stream.
46      *
47      * @see XMLDecoder#readObject
48      */

49     protected void writeObject(Object JavaDoc o) {
50         if (o == this) {
51             return;
52         }
53         PersistenceDelegate JavaDoc info = getPersistenceDelegate(o == null ? null : o.getClass());
54         info.writeObject(o, this);
55     }
56     
57     /**
58      * Sets the exception handler for this stream to <code>exceptionListener</code>.
59      * The exception handler is notified when this stream catches recoverable
60      * exceptions.
61      *
62      * @param exceptionListener The exception handler for this stream;
63      * if <code>null</code> the default exception listener will be used.
64      *
65      * @see #getExceptionListener
66      */

67     public void setExceptionListener(ExceptionListener JavaDoc exceptionListener) {
68         this.exceptionListener = exceptionListener;
69     }
70     
71     /**
72      * Gets the exception handler for this stream.
73      *
74      * @return The exception handler for this stream;
75      * Will return the default exception listener if this has not explicitly been set.
76      *
77      * @see #setExceptionListener
78      */

79     public ExceptionListener JavaDoc getExceptionListener() {
80         return (exceptionListener != null) ? exceptionListener : Statement.defaultExceptionListener;
81     }
82     
83     Object JavaDoc getValue(Expression JavaDoc exp) {
84         try {
85             return (exp == null) ? null : exp.getValue();
86         }
87         catch (Exception JavaDoc e) {
88             getExceptionListener().exceptionThrown(e);
89             throw new RuntimeException JavaDoc("failed to evaluate: " + exp.toString());
90         }
91     }
92
93     /**
94      * Returns the persistence delegate for the given type.
95      * The persistence delegate is calculated
96      * by applying the following of rules in order:
97      * <ul>
98      * <li>
99      * If the type is an array, an internal persistence
100      * delegate is returned which will instantiate an
101      * array of the appropriate type and length, initializing
102      * each of its elements as if they are properties.
103      * <li>
104      * If the type is a proxy, an internal persistence
105      * delegate is returned which will instantiate a
106      * new proxy instance using the static
107      * "newProxyInstance" method defined in the
108      * Proxy class.
109      * <li>
110      * If the BeanInfo for this type has a <code>BeanDescriptor</code>
111      * which defined a "persistenceDelegate" property, this
112      * value is returned.
113      * <li>
114      * In all other cases the default persistence delegate
115      * is returned. The default persistence delegate assumes
116      * the type is a <em>JavaBean</em>, implying that it has a nullary constructor
117      * and that its state may be characterized by the matching pairs
118      * of "setter" and "getter" methods returned by the Introspector.
119      * </ul>
120      *
121      * @param type The type of the object.
122      * @return The persistence delegate for this type of object.
123      *
124      * @see #setPersistenceDelegate
125      * @see java.beans.Introspector#getBeanInfo
126      * @see java.beans.BeanInfo#getBeanDescriptor
127      */

128     public PersistenceDelegate JavaDoc getPersistenceDelegate(Class JavaDoc<?> type) {
129         return MetaData.getPersistenceDelegate(type);
130     }
131     
132     /**
133      * Sets the persistence delegate associated with this <code>type</code> to
134      * <code>persistenceDelegate</code>.
135      *
136      * @param type The class of objects that <code>persistenceDelegate</code> applies to.
137      * @param persistenceDelegate The persistence delegate for instances of <code>type</code>.
138      *
139      * @see #getPersistenceDelegate
140      * @see java.beans.Introspector#getBeanInfo
141      * @see java.beans.BeanInfo#getBeanDescriptor
142      */

143     public void setPersistenceDelegate(Class JavaDoc<?> type,
144                        PersistenceDelegate JavaDoc persistenceDelegate)
145     {
146         MetaData.setPersistenceDelegate(type, persistenceDelegate);
147     }
148     
149     /**
150      * Removes the entry for this instance, returning the old entry.
151      *
152      * @param oldInstance The entry that should be removed.
153      * @return The entry that was removed.
154      *
155      * @see #get
156      */

157     public Object JavaDoc remove(Object JavaDoc oldInstance) {
158         Expression JavaDoc exp = (Expression JavaDoc)bindings.remove(oldInstance);
159         return getValue(exp);
160     }
161     
162     /**
163      * Returns a tentative value for <code>oldInstance</code> in
164      * the environment created by this stream. A persistence
165      * delegate can use its <code>mutatesTo</code> method to
166      * determine whether this value may be initialized to
167      * form the equivalent object at the output or whether
168      * a new object must be instantiated afresh. If the
169      * stream has not yet seen this value, null is returned.
170      *
171      * @param oldInstance The instance to be looked up.
172      * @return The object, null if the object has not been seen before.
173      */

174     public Object JavaDoc get(Object JavaDoc oldInstance) {
175         if (oldInstance == null || oldInstance == this ||
176         oldInstance.getClass() == String JavaDoc.class) {
177             return oldInstance;
178         }
179         Expression JavaDoc exp = (Expression JavaDoc)bindings.get(oldInstance);
180         return getValue(exp);
181     }
182     
183     private Object JavaDoc writeObject1(Object JavaDoc oldInstance) {
184         Object JavaDoc o = get(oldInstance);
185         if (o == null) {
186             writeObject(oldInstance);
187             o = get(oldInstance);
188         }
189         return o;
190     }
191     
192     private Statement JavaDoc cloneStatement(Statement JavaDoc oldExp) {
193         Object JavaDoc oldTarget = oldExp.getTarget();
194         Object JavaDoc newTarget = writeObject1(oldTarget);
195                 
196         Object JavaDoc[] oldArgs = oldExp.getArguments();
197         Object JavaDoc[] newArgs = new Object JavaDoc[oldArgs.length];
198         for (int i = 0; i < oldArgs.length; i++) {
199             newArgs[i] = writeObject1(oldArgs[i]);
200         }
201         if (oldExp.getClass() == Statement JavaDoc.class) {
202             return new Statement JavaDoc(newTarget, oldExp.getMethodName(), newArgs);
203         }
204         else {
205             return new Expression JavaDoc(newTarget, oldExp.getMethodName(), newArgs);
206         }
207     }
208     
209     /**
210      * Writes statement <code>oldStm</code> to the stream.
211      * The <code>oldStm</code> should be written entirely
212      * in terms of the callers environment, i.e. the
213      * target and all arguments should be part of the
214      * object graph being written. These expressions
215      * represent a series of "what happened" expressions
216      * which tell the output stream how to produce an
217      * object graph like the original.
218      * <p>
219      * The implementation of this method will produce
220      * a second expression to represent the same expression in
221      * an environment that will exist when the stream is read.
222      * This is achieved simply by calling <code>writeObject</code>
223      * on the target and all the arguments and building a new
224      * expression with the results.
225      *
226      * @param oldStm The expression to be written to the stream.
227      */

228     public void writeStatement(Statement JavaDoc oldStm) {
229         // System.out.println("writeStatement: " + oldExp);
230
Statement JavaDoc newStm = cloneStatement(oldStm);
231         if (oldStm.getTarget() != this && executeStatements) {
232         try {
233         newStm.execute();
234         } catch (Exception JavaDoc e) {
235         getExceptionListener().exceptionThrown(new Exception JavaDoc("Encoder: discarding statement "
236                                      + newStm, e));
237         }
238         }
239     }
240     
241     /**
242      * The implementation first checks to see if an
243      * expression with this value has already been written.
244      * If not, the expression is cloned, using
245      * the same procedure as <code>writeStatement</code>,
246      * and the value of this expression is reconciled
247      * with the value of the cloned expression
248      * by calling <code>writeObject</code>.
249      *
250      * @param oldExp The expression to be written to the stream.
251      */

252     public void writeExpression(Expression JavaDoc oldExp) {
253         // System.out.println("Encoder::writeExpression: " + oldExp);
254
Object JavaDoc oldValue = getValue(oldExp);
255         if (get(oldValue) != null) {
256             return;
257         }
258         bindings.put(oldValue, (Expression JavaDoc)cloneStatement(oldExp));
259         writeObject(oldValue);
260     }
261     
262     void clear() {
263         bindings.clear();
264     }
265
266     // Package private method for setting an attributes table for the encoder
267
void setAttribute(Object JavaDoc key, Object JavaDoc value) {
268     if (attributes == null) {
269         attributes = new HashMap();
270     }
271     attributes.put(key, value);
272     }
273
274     Object JavaDoc getAttribute(Object JavaDoc key) {
275     if (attributes == null) {
276         return null;
277     }
278     return attributes.get(key);
279     }
280 }
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
Popular Tags