SerializationUtils.java

  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. import java.io.ByteArrayInputStream;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.ObjectInputStream;
  23. import java.io.ObjectOutputStream;
  24. import java.io.ObjectStreamClass;
  25. import java.io.OutputStream;
  26. import java.io.Serializable;
  27. import java.util.Objects;

  28. /**
  29.  * Assists with the serialization process and performs additional functionality based
  30.  * on serialization.
  31.  *
  32.  * <ul>
  33.  * <li>Deep clone using serialization
  34.  * <li>Serialize managing finally and IOException
  35.  * <li>Deserialize managing finally and IOException
  36.  * </ul>
  37.  *
  38.  * <p>This class throws exceptions for invalid {@code null} inputs.
  39.  * Each method documents its behavior in more detail.</p>
  40.  *
  41.  * <p>#ThreadSafe#</p>
  42.  * @since 1.0
  43.  */
  44. public class SerializationUtils {

  45.     /**
  46.      * Custom specialization of the standard JDK {@link ObjectInputStream}
  47.      * that uses a custom  {@link ClassLoader} to resolve a class.
  48.      * If the specified {@link ClassLoader} is not able to resolve the class,
  49.      * the context classloader of the current thread will be used.
  50.      * This way, the standard deserialization work also in web-application
  51.      * containers and application servers, no matter in which of the
  52.      * {@link ClassLoader} the particular class that encapsulates
  53.      * serialization/deserialization lives.
  54.      *
  55.      * <p>For more in-depth information about the problem for which this
  56.      * class here is a workaround, see the JIRA issue LANG-626.</p>
  57.      */
  58.      static final class ClassLoaderAwareObjectInputStream extends ObjectInputStream {

  59.         private final ClassLoader classLoader;

  60.         /**
  61.          * Constructs a new instance.
  62.          * @param in The {@link InputStream}.
  63.          * @param classLoader classloader to use
  64.          * @throws IOException if an I/O error occurs while reading stream header.
  65.          * @see java.io.ObjectInputStream
  66.          */
  67.         ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
  68.             super(in);
  69.             this.classLoader = classLoader;
  70.         }

  71.         /**
  72.          * Overridden version that uses the parameterized {@link ClassLoader} or the {@link ClassLoader}
  73.          * of the current {@link Thread} to resolve the class.
  74.          * @param desc An instance of class {@link ObjectStreamClass}.
  75.          * @return A {@link Class} object corresponding to {@code desc}.
  76.          * @throws IOException Any of the usual Input/Output exceptions.
  77.          * @throws ClassNotFoundException If class of a serialized object cannot be found.
  78.          */
  79.         @Override
  80.         protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
  81.             final String name = desc.getName();
  82.             try {
  83.                 return Class.forName(name, false, classLoader);
  84.             } catch (final ClassNotFoundException ex) {
  85.                 try {
  86.                     return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
  87.                 } catch (final ClassNotFoundException cnfe) {
  88.                     final Class<?> cls = ClassUtils.getPrimitiveClass(name);
  89.                     if (cls != null) {
  90.                         return cls;
  91.                     }
  92.                     throw cnfe;
  93.                 }
  94.             }
  95.         }

  96.     }

  97.     /**
  98.      * Deep clone an {@link Object} using serialization.
  99.      *
  100.      * <p>This is many times slower than writing clone methods by hand
  101.      * on all objects in your object graph. However, for complex object
  102.      * graphs, or for those that don't support deep cloning this can
  103.      * be a simple alternative implementation. Of course all the objects
  104.      * must be {@link Serializable}.</p>
  105.      *
  106.      * @param <T> the type of the object involved
  107.      * @param object  the {@link Serializable} object to clone
  108.      * @return the cloned object
  109.      * @throws SerializationException (runtime) if the serialization fails
  110.      */
  111.     public static <T extends Serializable> T clone(final T object) {
  112.         if (object == null) {
  113.             return null;
  114.         }
  115.         final byte[] objectData = serialize(object);
  116.         final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);

  117.         final Class<T> cls = ObjectUtils.getClass(object);
  118.         try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader())) {
  119.             /*
  120.              * when we serialize and deserialize an object, it is reasonable to assume the deserialized object is of the
  121.              * same type as the original serialized object
  122.              */
  123.             return cls.cast(in.readObject());

  124.         } catch (final ClassNotFoundException | IOException ex) {
  125.             throw new SerializationException(
  126.                 String.format("%s while reading cloned object data", ex.getClass().getSimpleName()), ex);
  127.         }
  128.     }

  129.     /**
  130.      * Deserializes a single {@link Object} from an array of bytes.
  131.      *
  132.      * <p>
  133.      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
  134.      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
  135.      * Note that in both cases, the ClassCastException is in the call site, not in this method.
  136.      * </p>
  137.      *
  138.      * @param <T>  the object type to be deserialized
  139.      * @param objectData
  140.      *            the serialized object, must not be null
  141.      * @return the deserialized object
  142.      * @throws NullPointerException if {@code objectData} is {@code null}
  143.      * @throws SerializationException (runtime) if the serialization fails
  144.      */
  145.     public static <T> T deserialize(final byte[] objectData) {
  146.         Objects.requireNonNull(objectData, "objectData");
  147.         return deserialize(new ByteArrayInputStream(objectData));
  148.     }

  149.     /**
  150.      * Deserializes an {@link Object} from the specified stream.
  151.      *
  152.      * <p>
  153.      * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
  154.      * exception handling, in the application code.
  155.      * </p>
  156.      *
  157.      * <p>
  158.      * The stream passed in is not buffered internally within this method. This is the responsibility of your
  159.      * application if desired.
  160.      * </p>
  161.      *
  162.      * <p>
  163.      * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
  164.      * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
  165.      * Note that in both cases, the ClassCastException is in the call site, not in this method.
  166.      * </p>
  167.      *
  168.      * @param <T>  the object type to be deserialized
  169.      * @param inputStream
  170.      *            the serialized object input stream, must not be null
  171.      * @return the deserialized object
  172.      * @throws NullPointerException if {@code inputStream} is {@code null}
  173.      * @throws SerializationException (runtime) if the serialization fails
  174.      */
  175.     @SuppressWarnings("resource") // inputStream is managed by the caller
  176.     public static <T> T deserialize(final InputStream inputStream) {
  177.         Objects.requireNonNull(inputStream, "inputStream");
  178.         try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
  179.             @SuppressWarnings("unchecked")
  180.             final T obj = (T) in.readObject();
  181.             return obj;
  182.         } catch (final ClassNotFoundException | IOException | NegativeArraySizeException ex) {
  183.             throw new SerializationException(ex);
  184.         }
  185.     }

  186.     /**
  187.      * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
  188.      * implement {@link Serializable}.
  189.      *
  190.      * @param <T>
  191.      *           the type of the object involved
  192.      * @param obj
  193.      *            the object to roundtrip
  194.      * @return the serialized and deserialized object
  195.      * @since 3.3
  196.      */
  197.     @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
  198.     public static <T extends Serializable> T roundtrip(final T obj) {
  199.         return (T) deserialize(serialize(obj));
  200.     }

  201.     /**
  202.      * Serializes an {@link Object} to a byte array for
  203.      * storage/serialization.
  204.      *
  205.      * @param obj  the object to serialize to bytes
  206.      * @return a byte[] with the converted Serializable
  207.      * @throws SerializationException (runtime) if the serialization fails
  208.      */
  209.     public static byte[] serialize(final Serializable obj) {
  210.         final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
  211.         serialize(obj, baos);
  212.         return baos.toByteArray();
  213.     }

  214.     /**
  215.      * Serializes an {@link Object} to the specified stream.
  216.      *
  217.      * <p>The stream will be closed once the object is written.
  218.      * This avoids the need for a finally clause, and maybe also exception
  219.      * handling, in the application code.</p>
  220.      *
  221.      * <p>The stream passed in is not buffered internally within this method.
  222.      * This is the responsibility of your application if desired.</p>
  223.      *
  224.      * @param obj  the object to serialize to bytes, may be null
  225.      * @param outputStream  the stream to write to, must not be null
  226.      * @throws NullPointerException if {@code outputStream} is {@code null}
  227.      * @throws SerializationException (runtime) if the serialization fails
  228.      */
  229.     @SuppressWarnings("resource") // outputStream is managed by the caller
  230.     public static void serialize(final Serializable obj, final OutputStream outputStream) {
  231.         Objects.requireNonNull(outputStream, "outputStream");
  232.         try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
  233.             out.writeObject(obj);
  234.         } catch (final IOException ex) {
  235.             throw new SerializationException(ex);
  236.         }
  237.     }

  238.     /**
  239.      * SerializationUtils instances should NOT be constructed in standard programming.
  240.      * Instead, the class should be used as {@code SerializationUtils.clone(object)}.
  241.      *
  242.      * <p>This constructor is public to permit tools that require a JavaBean instance
  243.      * to operate.</p>
  244.      * @since 2.0
  245.      *
  246.      * @deprecated TODO Make private in 4.0.
  247.      */
  248.     @Deprecated
  249.     public SerializationUtils() {
  250.         // empty
  251.     }

  252. }