    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      https://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 * Unless required by applicable law or agreed to in writing, software
    012 * distributed under the License is distributed on an "AS IS" BASIS,
    013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 * See the License for the specific language governing permissions and
    015 * limitations under the License.
    016 */
    017package org.apache.commons.lang3;
    018
    019import java.io.ByteArrayInputStream;
    020import java.io.ByteArrayOutputStream;
    021import java.io.IOException;
    022import java.io.InputStream;
    023import java.io.ObjectInputStream;
    024import java.io.ObjectOutputStream;
    025import java.io.ObjectStreamClass;
    026import java.io.OutputStream;
    027import java.io.Serializable;
    028import java.util.Objects;
    029
    030/**
    031 * Assists with the serialization process and performs additional functionality based
    032 * on serialization.
    033 *
    034 * <ul>
    035 * <li>Deep clone using serialization
    036 * <li>Serialize managing finally and IOException
    037 * <li>Deserialize managing finally and IOException
    038 * </ul>
    039 *
    040 * <p>This class throws exceptions for invalid {@code null} inputs.
    041 * Each method documents its behavior in more detail.</p>
    042 *
    043 * <p>#ThreadSafe#</p>
    044 * @since 1.0
    045 */
    046public class SerializationUtils {
    047
    048    /**
    049     * Custom specialization of the standard JDK {@link ObjectInputStream}
    050     * that uses a custom  {@link ClassLoader} to resolve a class.
    051     * If the specified {@link ClassLoader} is not able to resolve the class,
    052     * the context classloader of the current thread will be used.
    053     * This way, the standard deserialization work also in web-application
    054     * containers and application servers, no matter in which of the
    055     * {@link ClassLoader} the particular class that encapsulates
    056     * serialization/deserialization lives.
    057     *
    058     * <p>For more in-depth information about the problem for which this
    059     * class here is a workaround, see the JIRA issue LANG-626.</p>
    060     */
    061     static final class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
    062
    063        private final ClassLoader classLoader;
    064
    065        /**
    066         * Constructs a new instance.
    067         * @param in The {@link InputStream}.
    068         * @param classLoader classloader to use
    069         * @throws IOException if an I/O error occurs while reading stream header.
    070         * @see java.io.ObjectInputStream
    071         */
    072        ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
    073            super(in);
    074            this.classLoader = classLoader;
    075        }
    076
    077        /**
    078         * Overridden version that uses the parameterized {@link ClassLoader} or the {@link ClassLoader}
    079         * of the current {@link Thread} to resolve the class.
    080         * @param desc An instance of class {@link ObjectStreamClass}.
    081         * @return A {@link Class} object corresponding to {@code desc}.
    082         * @throws IOException Any of the usual Input/Output exceptions.
    083         * @throws ClassNotFoundException If class of a serialized object cannot be found.
    084         */
    085        @Override
    086        protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
    087            final String name = desc.getName();
    088            try {
    089                return Class.forName(name, false, classLoader);
    090            } catch (final ClassNotFoundException ex) {
    091                try {
    092                    return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
    093                } catch (final ClassNotFoundException cnfe) {
    094                    final Class<?> cls = ClassUtils.getPrimitiveClass(name);
    095                    if (cls != null) {
    096                        return cls;
    097                    }
    098                    throw cnfe;
    099                }
    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}