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   */
47  public class SerializationUtils {
48  
49      /**
50       * <p>SerializationUtils instances should NOT be constructed in standard programming.
51       * Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
52       *
53       * <p>This constructor is public to permit tools that require a JavaBean instance
54       * to operate.</p>
55       * @since 2.0
56       */
57      public SerializationUtils() {
58          super();
59      }
60  
61      // Clone
62      //-----------------------------------------------------------------------
63      /**
64       * <p>Deep clone an {@code Object} using serialization.</p>
65       *
66       * <p>This is many times slower than writing clone methods by hand
67       * on all objects in your object graph. However, for complex object
68       * graphs, or for those that don't support deep cloning this can
69       * be a simple alternative implementation. Of course all the objects
70       * must be {@code Serializable}.</p>
71       *
72       * @param <T> the type of the object involved
73       * @param object  the {@code Serializable} object to clone
74       * @return the cloned object
75       * @throws SerializationException (runtime) if the serialization fails
76       */
77      public static <T extends Serializable> T clone(final T object) {
78          if (object == null) {
79              return null;
80          }
81          final byte[] objectData = serialize(object);
82          final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
83  
84          try (final ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais,
85                  object.getClass().getClassLoader())) {
86              /*
87               * when we serialize and deserialize an object,
88               * it is reasonable to assume the deserialized object
89               * is of the same type as the original serialized object
90               */
91              @SuppressWarnings("unchecked") // see above
92              final T readObject = (T) in.readObject();
93              return readObject;
94  
95          } catch (final ClassNotFoundException ex) {
96              throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
97          } catch (final IOException ex) {
98              throw new SerializationException("IOException while reading or closing cloned object data", ex);
99          }
100     }
101 
102     /**
103      * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
104      * implement {@link Serializable}.
105      *
106      * @param <T>
107      *           the type of the object involved
108      * @param msg
109      *            the object to roundtrip
110      * @return the serialized and deserialized object
111      * @since 3.3
112      */
113     @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
114     public static <T extends Serializable> T roundtrip(final T msg) {
115         return (T) SerializationUtils.deserialize(SerializationUtils.serialize(msg));
116     }
117 
118     // Serialize
119     //-----------------------------------------------------------------------
120     /**
121      * <p>Serializes an {@code Object} 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} is {@code null}
133      * @throws SerializationException (runtime) if the serialization fails
134      */
135     public static void serialize(final Serializable obj, final OutputStream outputStream) {
136         Validate.isTrue(outputStream != null, "The OutputStream must not be null");
137         try (ObjectOutputStream out = new ObjectOutputStream(outputStream)){
138             out.writeObject(obj);
139         } catch (final IOException ex) {
140             throw new SerializationException(ex);
141         }
142     }
143 
144     /**
145      * <p>Serializes an {@code Object} to a byte array for
146      * storage/serialization.</p>
147      *
148      * @param obj  the object to serialize to bytes
149      * @return a byte[] with the converted Serializable
150      * @throws SerializationException (runtime) if the serialization fails
151      */
152     public static byte[] serialize(final Serializable obj) {
153         final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
154         serialize(obj, baos);
155         return baos.toByteArray();
156     }
157 
158     // Deserialize
159     //-----------------------------------------------------------------------
160     /**
161      * <p>
162      * Deserializes an {@code Object} from the specified stream.
163      * </p>
164      *
165      * <p>
166      * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
167      * exception handling, in the application code.
168      * </p>
169      *
170      * <p>
171      * The stream passed in is not buffered internally within this method. This is the responsibility of your
172      * application if desired.
173      * </p>
174      *
175      * <p>
176      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
177      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
178      * Note that in both cases, the ClassCastException is in the call site, not in this method.
179      * </p>
180      *
181      * @param <T>  the object type to be deserialized
182      * @param inputStream
183      *            the serialized object input stream, must not be null
184      * @return the deserialized object
185      * @throws IllegalArgumentException
186      *             if {@code inputStream} is {@code null}
187      * @throws SerializationException
188      *             (runtime) if the serialization fails
189      */
190     public static <T> T deserialize(final InputStream inputStream) {
191         Validate.isTrue(inputStream != null, "The InputStream must not be null");
192         try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
193             @SuppressWarnings("unchecked")
194             final T obj = (T) in.readObject();
195             return obj;
196         } catch (final ClassNotFoundException | IOException ex) {
197             throw new SerializationException(ex);
198         }
199     }
200 
201     /**
202      * <p>
203      * Deserializes a single {@code Object} from an array of bytes.
204      * </p>
205      *
206      * <p>
207      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
208      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
209      * Note that in both cases, the ClassCastException is in the call site, not in this method.
210      * </p>
211      *
212      * @param <T>  the object type to be deserialized
213      * @param objectData
214      *            the serialized object, must not be null
215      * @return the deserialized object
216      * @throws IllegalArgumentException
217      *             if {@code objectData} is {@code null}
218      * @throws SerializationException
219      *             (runtime) if the serialization fails
220      */
221     public static <T> T deserialize(final byte[] objectData) {
222         Validate.isTrue(objectData != null, "The byte[] must not be null");
223         return SerializationUtils.deserialize(new ByteArrayInputStream(objectData));
224     }
225 
226     /**
227      * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
228      * that uses a custom  <code>ClassLoader</code> to resolve a class.
229      * If the specified <code>ClassLoader</code> is not able to resolve the class,
230      * the context classloader of the current thread will be used.
231      * This way, the standard deserialization work also in web-application
232      * containers and application servers, no matter in which of the
233      * <code>ClassLoader</code> the particular class that encapsulates
234      * serialization/deserialization lives. </p>
235      *
236      * <p>For more in-depth information about the problem for which this
237      * class here is a workaround, see the JIRA issue LANG-626. </p>
238      */
239      static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
240         private static final Map<String, Class<?>> primitiveTypes =
241                 new HashMap<>();
242 
243         static {
244             primitiveTypes.put("byte", byte.class);
245             primitiveTypes.put("short", short.class);
246             primitiveTypes.put("int", int.class);
247             primitiveTypes.put("long", long.class);
248             primitiveTypes.put("float", float.class);
249             primitiveTypes.put("double", double.class);
250             primitiveTypes.put("boolean", boolean.class);
251             primitiveTypes.put("char", char.class);
252             primitiveTypes.put("void", void.class);
253         }
254 
255         private final ClassLoader classLoader;
256 
257         /**
258          * Constructor.
259          * @param in The <code>InputStream</code>.
260          * @param classLoader classloader to use
261          * @throws IOException if an I/O error occurs while reading stream header.
262          * @see java.io.ObjectInputStream
263          */
264         ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
265             super(in);
266             this.classLoader = classLoader;
267         }
268 
269         /**
270          * Overridden version that uses the parameterized <code>ClassLoader</code> or the <code>ClassLoader</code>
271          * of the current <code>Thread</code> to resolve the class.
272          * @param desc An instance of class <code>ObjectStreamClass</code>.
273          * @return A <code>Class</code> object corresponding to <code>desc</code>.
274          * @throws IOException Any of the usual Input/Output exceptions.
275          * @throws ClassNotFoundException If class of a serialized object cannot be found.
276          */
277         @Override
278         protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
279             final String name = desc.getName();
280             try {
281                 return Class.forName(name, false, classLoader);
282             } catch (final ClassNotFoundException ex) {
283                 try {
284                     return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
285                 } catch (final ClassNotFoundException cnfe) {
286                     final Class<?> cls = primitiveTypes.get(name);
287                     if (cls != null) {
288                         return cls;
289                     }
290                     throw cnfe;
291                 }
292             }
293         }
294 
295     }
296 
297 }