KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > util > SerializationHelper


1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowledgement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowledgement may appear in the software itself,
24  * if and wherever such third-party acknowledgements normally appear.
25  *
26  * 4. The names "The Jakarta Project", "Commons", and "Apache Software
27  * Foundation" must not be used to endorse or promote products derived
28  * from this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Software Foundation.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of the Apache Software Foundation. For more
51  * information on the Apache Software Foundation, please see
52  * <http://www.apache.org/>.
53  */

54 package org.hibernate.util;
55
56 import java.io.ByteArrayInputStream JavaDoc;
57 import java.io.ByteArrayOutputStream JavaDoc;
58 import java.io.IOException JavaDoc;
59 import java.io.InputStream JavaDoc;
60 import java.io.ObjectOutputStream JavaDoc;
61 import java.io.OutputStream JavaDoc;
62 import java.io.Serializable JavaDoc;
63 import java.io.ObjectStreamClass JavaDoc;
64 import java.io.ObjectInputStream JavaDoc;
65
66 import org.hibernate.type.SerializationException;
67 import org.apache.commons.logging.Log;
68 import org.apache.commons.logging.LogFactory;
69
70 /**
71  * <p>Assists with the serialization process and performs additional functionality based
72  * on serialization.</p>
73  * <p>
74  * <ul>
75  * <li>Deep clone using serialization
76  * <li>Serialize managing finally and IOException
77  * <li>Deserialize managing finally and IOException
78  * </ul>
79  *
80  * <p>This class throws exceptions for invalid <code>null</code> inputs.
81  * Each method documents its behaviour in more detail.</p>
82  *
83  * @author <a HREF="mailto:nissim@nksystems.com">Nissim Karpenstein</a>
84  * @author <a HREF="mailto:janekdb@yahoo.co.uk">Janek Bogucki</a>
85  * @author <a HREF="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
86  * @author Stephen Colebourne
87  * @author Jeff Varszegi
88  * @author Gary Gregory
89  * @since 1.0
90  * @version $Id: SerializationHelper.java,v 1.2 2004/11/04 21:55:17 steveebersole Exp $
91  */

92 public final class SerializationHelper {
93
94     private static final Log log = LogFactory.getLog(SerializationHelper.class);
95
96     private SerializationHelper() {}
97
98     // Clone
99
//-----------------------------------------------------------------------
100
/**
101      * <p>Deep clone an <code>Object</code> using serialization.</p>
102      *
103      * <p>This is many times slower than writing clone methods by hand
104      * on all objects in your object graph. However, for complex object
105      * graphs, or for those that don't support deep cloning this can
106      * be a simple alternative implementation. Of course all the objects
107      * must be <code>Serializable</code>.</p>
108      *
109      * @param object the <code>Serializable</code> object to clone
110      * @return the cloned object
111      * @throws SerializationException (runtime) if the serialization fails
112      */

113     public static Object JavaDoc clone(Serializable JavaDoc object) throws SerializationException {
114         log.trace("Starting clone through serialization");
115         return deserialize( serialize(object) );
116     }
117
118     // Serialize
119
//-----------------------------------------------------------------------
120
/**
121      * <p>Serializes an <code>Object</code> to the specified stream.</p>
122      *
123      * <p>The stream will be closed once the object is written.
124      * This avoids the need for a finally clause, and maybe also exception
125      * handling, in the application code.</p>
126      *
127      * <p>The stream passed in is not buffered internally within this method.
128      * This is the responsibility of your application if desired.</p>
129      *
130      * @param obj the object to serialize to bytes, may be null
131      * @param outputStream the stream to write to, must not be null
132      * @throws IllegalArgumentException if <code>outputStream</code> is <code>null</code>
133      * @throws SerializationException (runtime) if the serialization fails
134      */

135     public static void serialize(Serializable JavaDoc obj, OutputStream JavaDoc outputStream) throws SerializationException {
136         if (outputStream == null) {
137             throw new IllegalArgumentException JavaDoc("The OutputStream must not be null");
138         }
139
140         if ( log.isTraceEnabled() ) {
141             log.trace("Starting serialization of object [" + obj + "]");
142         }
143
144         ObjectOutputStream JavaDoc out = null;
145         try {
146             // stream closed in the finally
147
out = new ObjectOutputStream JavaDoc(outputStream);
148             out.writeObject(obj);
149
150         }
151         catch (IOException JavaDoc ex) {
152             throw new SerializationException("could not serialize", ex);
153         }
154         finally {
155             try {
156                 if (out != null) out.close();
157             }
158             catch (IOException JavaDoc ignored) {}
159         }
160     }
161
162     /**
163      * <p>Serializes an <code>Object</code> to a byte array for
164      * storage/serialization.</p>
165      *
166      * @param obj the object to serialize to bytes
167      * @return a byte[] with the converted Serializable
168      * @throws SerializationException (runtime) if the serialization fails
169      */

170     public static byte[] serialize(Serializable JavaDoc obj) throws SerializationException {
171         ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc(512);
172         serialize(obj, baos);
173         return baos.toByteArray();
174     }
175
176     // Deserialize
177
//-----------------------------------------------------------------------
178
/**
179      * <p>Deserializes an <code>Object</code> from the specified stream.</p>
180      *
181      * <p>The stream will be closed once the object is written. This
182      * avoids the need for a finally clause, and maybe also exception
183      * handling, in the application code.</p>
184      *
185      * <p>The stream passed in is not buffered internally within this method.
186      * This is the responsibility of your application if desired.</p>
187      *
188      * @param inputStream the serialized object input stream, must not be null
189      * @return the deserialized object
190      * @throws IllegalArgumentException if <code>inputStream</code> is <code>null</code>
191      * @throws SerializationException (runtime) if the serialization fails
192      */

193     public static Object JavaDoc deserialize(InputStream JavaDoc inputStream) throws SerializationException {
194         if (inputStream == null) {
195             throw new IllegalArgumentException JavaDoc("The InputStream must not be null");
196         }
197
198         log.trace("Starting deserialization of object");
199
200         CustomObjectInputStream in = null;
201         try {
202             // stream closed in the finally
203
in = new CustomObjectInputStream(inputStream);
204             return in.readObject();
205
206         }
207         catch (ClassNotFoundException JavaDoc ex) {
208             throw new SerializationException("could not deserialize", ex);
209         }
210         catch (IOException JavaDoc ex) {
211             throw new SerializationException("could not deserialize", ex);
212         }
213         finally {
214             try {
215                 if (in != null) in.close();
216             }
217             catch (IOException JavaDoc ex) {}
218         }
219     }
220
221     /**
222      * <p>Deserializes a single <code>Object</code> from an array of bytes.</p>
223      *
224      * @param objectData the serialized object, must not be null
225      * @return the deserialized object
226      * @throws IllegalArgumentException if <code>objectData</code> is <code>null</code>
227      * @throws SerializationException (runtime) if the serialization fails
228      */

229     public static Object JavaDoc deserialize(byte[] objectData) throws SerializationException {
230         if (objectData == null) {
231             throw new IllegalArgumentException JavaDoc("The byte[] must not be null");
232         }
233         ByteArrayInputStream JavaDoc bais = new ByteArrayInputStream JavaDoc(objectData);
234         return deserialize(bais);
235     }
236
237
238     /**
239      * Custom ObjectInputStream implementation to more appropriately handle classloading
240      * within app servers (mainly jboss - hence this class inspired by jboss's class of
241      * the same purpose).
242      */

243     private static final class CustomObjectInputStream extends ObjectInputStream JavaDoc {
244
245         public CustomObjectInputStream(InputStream JavaDoc in) throws IOException JavaDoc {
246             super(in);
247         }
248
249         protected Class JavaDoc resolveClass(ObjectStreamClass JavaDoc v) throws IOException JavaDoc, ClassNotFoundException JavaDoc {
250             String JavaDoc className = v.getName();
251             Class JavaDoc resolvedClass = null;
252
253             log.trace("Attempting to locate class [" + className + "]");
254
255             ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
256             try {
257                 resolvedClass = loader.loadClass(className);
258                 log.trace("Class resolved through context class loader");
259             }
260             catch(ClassNotFoundException JavaDoc e) {
261                 log.trace("Asking super to resolve");
262                 resolvedClass = super.resolveClass(v);
263             }
264
265             return resolvedClass;
266         }
267     }
268 }
269
Popular Tags