001: /* ====================================================================
002: * The Apache Software License, Version 1.1
003: *
004: * Copyright (c) 2002-2003 The Apache Software Foundation. All rights
005: * reserved.
006: *
007: * Redistribution and use in source and binary forms, with or without
008: * modification, are permitted provided that the following conditions
009: * are met:
010: *
011: * 1. Redistributions of source code must retain the above copyright
012: * notice, this list of conditions and the following disclaimer.
013: *
014: * 2. Redistributions in binary form must reproduce the above copyright
015: * notice, this list of conditions and the following disclaimer in
016: * the documentation and/or other materials provided with the
017: * distribution.
018: *
019: * 3. The end-user documentation included with the redistribution, if
020: * any, must include the following acknowledgement:
021: * "This product includes software developed by the
022: * Apache Software Foundation (http://www.apache.org/)."
023: * Alternately, this acknowledgement may appear in the software itself,
024: * if and wherever such third-party acknowledgements normally appear.
025: *
026: * 4. The names "The Jakarta Project", "Commons", and "Apache Software
027: * Foundation" must not be used to endorse or promote products derived
028: * from this software without prior written permission. For written
029: * permission, please contact apache@apache.org.
030: *
031: * 5. Products derived from this software may not be called "Apache"
032: * nor may "Apache" appear in their names without prior written
033: * permission of the Apache Software Foundation.
034: *
035: * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
036: * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
037: * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
038: * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
039: * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
040: * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
041: * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
042: * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
043: * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
044: * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
045: * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
046: * SUCH DAMAGE.
047: * ====================================================================
048: *
049: * This software consists of voluntary contributions made by many
050: * individuals on behalf of the Apache Software Foundation. For more
051: * information on the Apache Software Foundation, please see
052: * <http://www.apache.org/>.
053: */
054: package org.hibernate.util;
055:
056: import java.io.ByteArrayInputStream;
057: import java.io.ByteArrayOutputStream;
058: import java.io.IOException;
059: import java.io.InputStream;
060: import java.io.ObjectOutputStream;
061: import java.io.OutputStream;
062: import java.io.Serializable;
063: import java.io.ObjectStreamClass;
064: import java.io.ObjectInputStream;
065:
066: import org.hibernate.type.SerializationException;
067: import org.hibernate.Hibernate;
068: import org.apache.commons.logging.Log;
069: import org.apache.commons.logging.LogFactory;
070:
071: /**
072: * <p>Assists with the serialization process and performs additional functionality based
073: * on serialization.</p>
074: * <p>
075: * <ul>
076: * <li>Deep clone using serialization
077: * <li>Serialize managing finally and IOException
078: * <li>Deserialize managing finally and IOException
079: * </ul>
080: *
081: * <p>This class throws exceptions for invalid <code>null</code> inputs.
082: * Each method documents its behaviour in more detail.</p>
083: *
084: * @author <a href="mailto:nissim@nksystems.com">Nissim Karpenstein</a>
085: * @author <a href="mailto:janekdb@yahoo.co.uk">Janek Bogucki</a>
086: * @author <a href="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
087: * @author Stephen Colebourne
088: * @author Jeff Varszegi
089: * @author Gary Gregory
090: * @since 1.0
091: * @version $Id: SerializationHelper.java 9180 2006-01-30 23:51:27Z steveebersole $
092: */
093: public final class SerializationHelper {
094:
095: private static final Log log = LogFactory
096: .getLog(SerializationHelper.class);
097:
098: private SerializationHelper() {
099: }
100:
101: // Clone
102: //-----------------------------------------------------------------------
103: /**
104: * <p>Deep clone an <code>Object</code> using serialization.</p>
105: *
106: * <p>This is many times slower than writing clone methods by hand
107: * on all objects in your object graph. However, for complex object
108: * graphs, or for those that don't support deep cloning this can
109: * be a simple alternative implementation. Of course all the objects
110: * must be <code>Serializable</code>.</p>
111: *
112: * @param object the <code>Serializable</code> object to clone
113: * @return the cloned object
114: * @throws SerializationException (runtime) if the serialization fails
115: */
116: public static Object clone(Serializable object)
117: throws SerializationException {
118: log.trace("Starting clone through serialization");
119: return deserialize(serialize(object));
120: }
121:
122: // Serialize
123: //-----------------------------------------------------------------------
124: /**
125: * <p>Serializes an <code>Object</code> to the specified stream.</p>
126: *
127: * <p>The stream will be closed once the object is written.
128: * This avoids the need for a finally clause, and maybe also exception
129: * handling, in the application code.</p>
130: *
131: * <p>The stream passed in is not buffered internally within this method.
132: * This is the responsibility of your application if desired.</p>
133: *
134: * @param obj the object to serialize to bytes, may be null
135: * @param outputStream the stream to write to, must not be null
136: * @throws IllegalArgumentException if <code>outputStream</code> is <code>null</code>
137: * @throws SerializationException (runtime) if the serialization fails
138: */
139: public static void serialize(Serializable obj,
140: OutputStream outputStream) throws SerializationException {
141: if (outputStream == null) {
142: throw new IllegalArgumentException(
143: "The OutputStream must not be null");
144: }
145:
146: if (log.isTraceEnabled()) {
147: if (Hibernate.isInitialized(obj)) {
148: log.trace("Starting serialization of object [" + obj
149: + "]");
150: } else {
151: log
152: .trace("Starting serialization of [uninitialized proxy]");
153: }
154: }
155:
156: ObjectOutputStream out = null;
157: try {
158: // stream closed in the finally
159: out = new ObjectOutputStream(outputStream);
160: out.writeObject(obj);
161:
162: } catch (IOException ex) {
163: throw new SerializationException("could not serialize", ex);
164: } finally {
165: try {
166: if (out != null)
167: out.close();
168: } catch (IOException ignored) {
169: }
170: }
171: }
172:
173: /**
174: * <p>Serializes an <code>Object</code> to a byte array for
175: * storage/serialization.</p>
176: *
177: * @param obj the object to serialize to bytes
178: * @return a byte[] with the converted Serializable
179: * @throws SerializationException (runtime) if the serialization fails
180: */
181: public static byte[] serialize(Serializable obj)
182: throws SerializationException {
183: ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
184: serialize(obj, baos);
185: return baos.toByteArray();
186: }
187:
188: // Deserialize
189: //-----------------------------------------------------------------------
190: /**
191: * <p>Deserializes an <code>Object</code> from the specified stream.</p>
192: *
193: * <p>The stream will be closed once the object is written. This
194: * avoids the need for a finally clause, and maybe also exception
195: * handling, in the application code.</p>
196: *
197: * <p>The stream passed in is not buffered internally within this method.
198: * This is the responsibility of your application if desired.</p>
199: *
200: * @param inputStream the serialized object input stream, must not be null
201: * @return the deserialized object
202: * @throws IllegalArgumentException if <code>inputStream</code> is <code>null</code>
203: * @throws SerializationException (runtime) if the serialization fails
204: */
205: public static Object deserialize(InputStream inputStream)
206: throws SerializationException {
207: if (inputStream == null) {
208: throw new IllegalArgumentException(
209: "The InputStream must not be null");
210: }
211:
212: log.trace("Starting deserialization of object");
213:
214: CustomObjectInputStream in = null;
215: try {
216: // stream closed in the finally
217: in = new CustomObjectInputStream(inputStream);
218: return in.readObject();
219:
220: } catch (ClassNotFoundException ex) {
221: throw new SerializationException("could not deserialize",
222: ex);
223: } catch (IOException ex) {
224: throw new SerializationException("could not deserialize",
225: ex);
226: } finally {
227: try {
228: if (in != null)
229: in.close();
230: } catch (IOException ex) {
231: }
232: }
233: }
234:
235: /**
236: * <p>Deserializes a single <code>Object</code> from an array of bytes.</p>
237: *
238: * @param objectData the serialized object, must not be null
239: * @return the deserialized object
240: * @throws IllegalArgumentException if <code>objectData</code> is <code>null</code>
241: * @throws SerializationException (runtime) if the serialization fails
242: */
243: public static Object deserialize(byte[] objectData)
244: throws SerializationException {
245: if (objectData == null) {
246: throw new IllegalArgumentException(
247: "The byte[] must not be null");
248: }
249: ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
250: return deserialize(bais);
251: }
252:
253: /**
254: * Custom ObjectInputStream implementation to more appropriately handle classloading
255: * within app servers (mainly jboss - hence this class inspired by jboss's class of
256: * the same purpose).
257: */
258: private static final class CustomObjectInputStream extends
259: ObjectInputStream {
260:
261: public CustomObjectInputStream(InputStream in)
262: throws IOException {
263: super (in);
264: }
265:
266: protected Class resolveClass(ObjectStreamClass v)
267: throws IOException, ClassNotFoundException {
268: String className = v.getName();
269: Class resolvedClass = null;
270:
271: log.trace("Attempting to locate class [" + className + "]");
272:
273: ClassLoader loader = Thread.currentThread()
274: .getContextClassLoader();
275: try {
276: resolvedClass = loader.loadClass(className);
277: log
278: .trace("Class resolved through context class loader");
279: } catch (ClassNotFoundException e) {
280: log.trace("Asking super to resolve");
281: resolvedClass = super.resolveClass(v);
282: }
283:
284: return resolvedClass;
285: }
286: }
287: }
|