View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.lang3;
18  
19  import java.io.ByteArrayInputStream;
20  import java.io.ByteArrayOutputStream;
21  import java.io.IOException;
22  import java.io.InputStream;
23  import java.io.ObjectInputStream;
24  import java.io.ObjectOutputStream;
25  import java.io.ObjectStreamClass;
26  import java.io.OutputStream;
27  import java.io.Serializable;
28  import java.util.HashMap;
29  import java.util.Map;
30  
31  /**
32   * <p>Assists with the serialization process and performs additional functionality based
33   * on serialization.</p>
34   *
35   * <ul>
36   * <li>Deep clone using serialization
37   * <li>Serialize managing finally and IOException
38   * <li>Deserialize managing finally and IOException
39   * </ul>
40   *
41   * <p>This class throws exceptions for invalid {@code null} inputs.
42   * Each method documents its behaviour in more detail.</p>
43   *
44   * <p>#ThreadSafe#</p>
45   * @since 1.0
46   * @version $Id: SerializationUtils.java 1606461 2014-06-29 11:50:39Z ggregory $
47   */
48  public class SerializationUtils {
49  
50      /**
51       * <p>SerializationUtils instances should NOT be constructed in standard programming.
52       * Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
53       *
54       * <p>This constructor is public to permit tools that require a JavaBean instance
55       * to operate.</p>
56       * @since 2.0
57       */
58      public SerializationUtils() {
59          super();
60      }
61  
62      // Clone
63      //-----------------------------------------------------------------------
64      /**
65       * <p>Deep clone an {@code Object} using serialization.</p>
66       *
67       * <p>This is many times slower than writing clone methods by hand
68       * on all objects in your object graph. However, for complex object
69       * graphs, or for those that don't support deep cloning this can
70       * be a simple alternative implementation. Of course all the objects
71       * must be {@code Serializable}.</p>
72       *
73       * @param <T> the type of the object involved
74       * @param object  the {@code Serializable} object to clone
75       * @return the cloned object
76       * @throws SerializationException (runtime) if the serialization fails
77       */
78      public static <T extends Serializable> T clone(final T object) {
79          if (object == null) {
80              return null;
81          }
82          final byte[] objectData = serialize(object);
83          final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
84  
85          ClassLoaderAwareObjectInputStream in = null;
86          try {
87              // stream closed in the finally
88              in = new ClassLoaderAwareObjectInputStream(bais, object.getClass().getClassLoader());
89              /*
90               * when we serialize and deserialize an object,
91               * it is reasonable to assume the deserialized object
92               * is of the same type as the original serialized object
93               */
94              @SuppressWarnings("unchecked") // see above
95              final T readObject = (T) in.readObject();
96              return readObject;
97  
98          } catch (final ClassNotFoundException ex) {
99              throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
100         } catch (final IOException ex) {
101             throw new SerializationException("IOException while reading cloned object data", ex);
102         } finally {
103             try {
104                 if (in != null) {
105                     in.close();
106                 }
107             } catch (final IOException ex) {
108                 throw new SerializationException("IOException on closing cloned object data InputStream.", ex);
109             }
110         }
111     }
112 
113     /**
114      * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
115      * implement {@link Serializable}.
116      *
117      * @param <T>
118      *           the type of the object involved
119      * @param msg
120      *            the object to roundtrip
121      * @return the serialized and deseralized object
122      * @since 3.3
123      */
124     public static <T extends Serializable> T roundtrip(final T msg) {
125         return SerializationUtils.deserialize(SerializationUtils.serialize(msg));
126     }
127 
128     // Serialize
129     //-----------------------------------------------------------------------
130     /**
131      * <p>Serializes an {@code Object} to the specified stream.</p>
132      *
133      * <p>The stream will be closed once the object is written.
134      * This avoids the need for a finally clause, and maybe also exception
135      * handling, in the application code.</p>
136      *
137      * <p>The stream passed in is not buffered internally within this method.
138      * This is the responsibility of your application if desired.</p>
139      *
140      * @param obj  the object to serialize to bytes, may be null
141      * @param outputStream  the stream to write to, must not be null
142      * @throws IllegalArgumentException if {@code outputStream} is {@code null}
143      * @throws SerializationException (runtime) if the serialization fails
144      */
145     public static void serialize(final Serializable obj, final OutputStream outputStream) {
146         if (outputStream == null) {
147             throw new IllegalArgumentException("The OutputStream must not be null");
148         }
149         ObjectOutputStream out = null;
150         try {
151             // stream closed in the finally
152             out = new ObjectOutputStream(outputStream);
153             out.writeObject(obj);
154 
155         } catch (final IOException ex) {
156             throw new SerializationException(ex);
157         } finally {
158             try {
159                 if (out != null) {
160                     out.close();
161                 }
162             } catch (final IOException ex) { // NOPMD
163                 // ignore close exception
164             }
165         }
166     }
167 
168     /**
169      * <p>Serializes an {@code Object} to a byte array for
170      * storage/serialization.</p>
171      *
172      * @param obj  the object to serialize to bytes
173      * @return a byte[] with the converted Serializable
174      * @throws SerializationException (runtime) if the serialization fails
175      */
176     public static byte[] serialize(final Serializable obj) {
177         final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
178         serialize(obj, baos);
179         return baos.toByteArray();
180     }
181 
182     // Deserialize
183     //-----------------------------------------------------------------------
184     /**
185      * <p>
186      * Deserializes an {@code Object} from the specified stream.
187      * </p>
188      * 
189      * <p>
190      * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
191      * exception handling, in the application code.
192      * </p>
193      * 
194      * <p>
195      * The stream passed in is not buffered internally within this method. This is the responsibility of your
196      * application if desired.
197      * </p>
198      * 
199      * <p>
200      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
201      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
202      * Note that in both cases, the ClassCastException is in the call site, not in this method.
203      * </p>
204      *
205      * @param <T>  the object type to be deserialized
206      * @param inputStream
207      *            the serialized object input stream, must not be null
208      * @return the deserialized object
209      * @throws IllegalArgumentException
210      *             if {@code inputStream} is {@code null}
211      * @throws SerializationException
212      *             (runtime) if the serialization fails
213      */
214     public static <T> T deserialize(final InputStream inputStream) {
215         if (inputStream == null) {
216             throw new IllegalArgumentException("The InputStream must not be null");
217         }
218         ObjectInputStream in = null;
219         try {
220             // stream closed in the finally
221             in = new ObjectInputStream(inputStream);
222             @SuppressWarnings("unchecked") // may fail with CCE if serialised form is incorrect
223             final T obj = (T) in.readObject();
224             return obj;
225 
226         } catch (final ClassCastException ex) {
227             throw new SerializationException(ex);
228         } catch (final ClassNotFoundException ex) {
229             throw new SerializationException(ex);
230         } catch (final IOException ex) {
231             throw new SerializationException(ex);
232         } finally {
233             try {
234                 if (in != null) {
235                     in.close();
236                 }
237             } catch (final IOException ex) { // NOPMD
238                 // ignore close exception
239             }
240         }
241     }
242 
243     /**
244      * <p>
245      * Deserializes a single {@code Object} from an array of bytes.
246      * </p>
247      * 
248      * <p>
249      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
250      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
251      * Note that in both cases, the ClassCastException is in the call site, not in this method.
252      * </p>
253      * 
254      * @param <T>  the object type to be deserialized
255      * @param objectData
256      *            the serialized object, must not be null
257      * @return the deserialized object
258      * @throws IllegalArgumentException
259      *             if {@code objectData} is {@code null}
260      * @throws SerializationException
261      *             (runtime) if the serialization fails
262      */
263     public static <T> T deserialize(final byte[] objectData) {
264         if (objectData == null) {
265             throw new IllegalArgumentException("The byte[] must not be null");
266         }
267         return SerializationUtils.<T>deserialize(new ByteArrayInputStream(objectData));
268     }
269 
270     /**
271      * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
272      * that uses a custom  <code>ClassLoader</code> to resolve a class.
273      * If the specified <code>ClassLoader</code> is not able to resolve the class,
274      * the context classloader of the current thread will be used.
275      * This way, the standard deserialization work also in web-application
276      * containers and application servers, no matter in which of the
277      * <code>ClassLoader</code> the particular class that encapsulates
278      * serialization/deserialization lives. </p>
279      * 
280      * <p>For more in-depth information about the problem for which this
281      * class here is a workaround, see the JIRA issue LANG-626. </p>
282      */
283      static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
284         private static final Map<String, Class<?>> primitiveTypes = 
285                 new HashMap<String, Class<?>>();
286         private final ClassLoader classLoader;
287         
288         /**
289          * Constructor.
290          * @param in The <code>InputStream</code>.
291          * @param classLoader classloader to use
292          * @throws IOException if an I/O error occurs while reading stream header.
293          * @see java.io.ObjectInputStream
294          */
295         public ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
296             super(in);
297             this.classLoader = classLoader;
298 
299             primitiveTypes.put("byte", byte.class);
300             primitiveTypes.put("short", short.class);
301             primitiveTypes.put("int", int.class);
302             primitiveTypes.put("long", long.class);
303             primitiveTypes.put("float", float.class);
304             primitiveTypes.put("double", double.class);
305             primitiveTypes.put("boolean", boolean.class);
306             primitiveTypes.put("char", char.class);
307             primitiveTypes.put("void", void.class);
308         }
309 
310         /**
311          * Overriden version that uses the parametrized <code>ClassLoader</code> or the <code>ClassLoader</code>
312          * of the current <code>Thread</code> to resolve the class.
313          * @param desc An instance of class <code>ObjectStreamClass</code>.
314          * @return A <code>Class</code> object corresponding to <code>desc</code>.
315          * @throws IOException Any of the usual Input/Output exceptions.
316          * @throws ClassNotFoundException If class of a serialized object cannot be found.
317          */
318         @Override
319         protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
320             final String name = desc.getName();
321             try {
322                 return Class.forName(name, false, classLoader);
323             } catch (final ClassNotFoundException ex) {
324                 try {
325                     return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
326                 } catch (final ClassNotFoundException cnfe) {
327                     final Class<?> cls = primitiveTypes.get(name);
328                     if (cls != null) {
329                         return cls;
330                     }
331                     throw cnfe;
332                 }
333             }
334         }
335 
336     }
337 
338 }