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    *      https://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.Objects;
29  
30  /**
31   * Assists with the serialization process and performs additional functionality based
32   * on serialization.
33   *
34   * <ul>
35   * <li>Deep clone using serialization
36   * <li>Serialize managing finally and IOException
37   * <li>Deserialize managing finally and IOException
38   * </ul>
39   *
40   * <p>This class throws exceptions for invalid {@code null} inputs.
41   * Each method documents its behavior in more detail.</p>
42   *
43   * <p>#ThreadSafe#</p>
44   * @since 1.0
45   */
46  public class SerializationUtils {
47  
48      /**
49       * Custom specialization of the standard JDK {@link ObjectInputStream}
50       * that uses a custom  {@link ClassLoader} to resolve a class.
51       * If the specified {@link ClassLoader} is not able to resolve the class,
52       * the context classloader of the current thread will be used.
53       * This way, the standard deserialization work also in web-application
54       * containers and application servers, no matter in which of the
55       * {@link ClassLoader} the particular class that encapsulates
56       * serialization/deserialization lives.
57       *
58       * <p>For more in-depth information about the problem for which this
59       * class here is a workaround, see the JIRA issue LANG-626.</p>
60       */
61       static final class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
62  
63          private final ClassLoader classLoader;
64  
65          /**
66           * Constructs a new instance.
67           * @param in The {@link InputStream}.
68           * @param classLoader classloader to use
69           * @throws IOException if an I/O error occurs while reading stream header.
70           * @see java.io.ObjectInputStream
71           */
72          ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
73              super(in);
74              this.classLoader = classLoader;
75          }
76  
77          /**
78           * Overridden version that uses the parameterized {@link ClassLoader} or the {@link ClassLoader}
79           * of the current {@link Thread} to resolve the class.
80           * @param desc An instance of class {@link ObjectStreamClass}.
81           * @return A {@link Class} object corresponding to {@code desc}.
82           * @throws IOException Any of the usual Input/Output exceptions.
83           * @throws ClassNotFoundException If class of a serialized object cannot be found.
84           */
85          @Override
86          protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
87              final String name = desc.getName();
88              try {
89                  return Class.forName(name, false, classLoader);
90              } catch (final ClassNotFoundException ex) {
91                  try {
92                      return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
93                  } catch (final ClassNotFoundException cnfe) {
94                      final Class<?> cls = ClassUtils.getPrimitiveClass(name);
95                      if (cls != null) {
96                          return cls;
97                      }
98                      throw cnfe;
99                  }
100             }
101         }
102 
103     }
104 
105     /**
106      * Deep clones an {@link Object} using serialization.
107      *
108      * <p>This is many times slower than writing clone methods by hand
109      * on all objects in your object graph. However, for complex object
110      * graphs, or for those that don't support deep cloning this can
111      * be a simple alternative implementation. Of course all the objects
112      * must be {@link Serializable}.</p>
113      *
114      * @param <T> the type of the object involved
115      * @param object  the {@link Serializable} object to clone
116      * @return the cloned object
117      * @throws SerializationException (runtime) if the serialization fails
118      */
119     public static <T extends Serializable> T clone(final T object) {
120         if (object == null) {
121             return null;
122         }
123         final ByteArrayInputStream bais = new ByteArrayInputStream(serialize(object));
124         final Class<T> cls = ObjectUtils.getClass(object);
125         try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader())) {
126             // When we serialize and deserialize an object, it is reasonable to assume the deserialized object is of the
127             // same type as the original serialized object
128             return (T) in.readObject();
129 
130         } catch (final ClassNotFoundException | IOException ex) {
131             throw new SerializationException(String.format("%s while reading cloned object data", ex.getClass().getSimpleName()), ex);
132         }
133     }
134 
135     /**
136      * Deserializes a single {@link Object} from an array of bytes.
137      *
138      * <p>
139      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
140      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
141      * Note that in both cases, the ClassCastException is in the call site, not in this method.
142      * </p>
143      *
144      * @param <T>  the object type to be deserialized
145      * @param objectData
146      *            the serialized object, must not be null
147      * @return the deserialized object
148      * @throws NullPointerException if {@code objectData} is {@code null}
149      * @throws SerializationException (runtime) if the serialization fails
150      */
151     public static <T> T deserialize(final byte[] objectData) {
152         Objects.requireNonNull(objectData, "objectData");
153         return deserialize(new ByteArrayInputStream(objectData));
154     }
155 
156     /**
157      * Deserializes an {@link Object} from the specified stream.
158      *
159      * <p>
160      * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
161      * exception handling, in the application code.
162      * </p>
163      *
164      * <p>
165      * The stream passed in is not buffered internally within this method. This is the responsibility of your
166      * application if desired.
167      * </p>
168      *
169      * <p>
170      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
171      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
172      * Note that in both cases, the ClassCastException is in the call site, not in this method.
173      * </p>
174      *
175      * @param <T>  the object type to be deserialized
176      * @param inputStream
177      *            the serialized object input stream, must not be null
178      * @return the deserialized object
179      * @throws NullPointerException if {@code inputStream} is {@code null}
180      * @throws SerializationException (runtime) if the serialization fails
181      */
182     @SuppressWarnings("resource") // inputStream is managed by the caller
183     public static <T> T deserialize(final InputStream inputStream) {
184         Objects.requireNonNull(inputStream, "inputStream");
185         try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
186             @SuppressWarnings("unchecked")
187             final T obj = (T) in.readObject();
188             return obj;
189         } catch (final ClassNotFoundException | IOException | NegativeArraySizeException ex) {
190             throw new SerializationException(ex);
191         }
192     }
193 
194     /**
195      * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
196      * implement {@link Serializable}.
197      *
198      * @param <T>
199      *           the type of the object involved
200      * @param obj
201      *            the object to roundtrip
202      * @return the serialized and deserialized object
203      * @since 3.3
204      */
205     @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
206     public static <T extends Serializable> T roundtrip(final T obj) {
207         return (T) deserialize(serialize(obj));
208     }
209 
210     /**
211      * Serializes an {@link Object} to a byte array for
212      * storage/serialization.
213      *
214      * @param obj  the object to serialize to bytes
215      * @return a byte[] with the converted Serializable
216      * @throws SerializationException (runtime) if the serialization fails
217      */
218     public static byte[] serialize(final Serializable obj) {
219         final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
220         serialize(obj, baos);
221         return baos.toByteArray();
222     }
223 
224     /**
225      * Serializes an {@link Object} to the specified stream.
226      *
227      * <p>The stream will be closed once the object is written.
228      * This avoids the need for a finally clause, and maybe also exception
229      * handling, in the application code.</p>
230      *
231      * <p>The stream passed in is not buffered internally within this method.
232      * This is the responsibility of your application if desired.</p>
233      *
234      * @param obj  the object to serialize to bytes, may be null
235      * @param outputStream  the stream to write to, must not be null
236      * @throws NullPointerException if {@code outputStream} is {@code null}
237      * @throws SerializationException (runtime) if the serialization fails
238      */
239     @SuppressWarnings("resource") // outputStream is managed by the caller
240     public static void serialize(final Serializable obj, final OutputStream outputStream) {
241         Objects.requireNonNull(outputStream, "outputStream");
242         try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
243             out.writeObject(obj);
244         } catch (final IOException ex) {
245             throw new SerializationException(ex);
246         }
247     }
248 
249     /**
250      * SerializationUtils instances should NOT be constructed in standard programming.
251      * Instead, the class should be used as {@code SerializationUtils.clone(object)}.
252      *
253      * <p>This constructor is public to permit tools that require a JavaBean instance
254      * to operate.</p>
255      * @since 2.0
256      * @deprecated TODO Make private in 4.0.
257      */
258     @Deprecated
259     public SerializationUtils() {
260         // empty
261     }
262 
263 }