Source code
Description: source: package: org.apache.commons.lang3, class: SerializationUtils

    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 *      http://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 clone 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 byte[] objectData = serialize(object);
    124        final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
    125
    126        final Class<T> cls = ObjectUtils.getClass(object);
    127        try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader())) {
    128            /*
    129             * when we serialize and deserialize an object, it is reasonable to assume the deserialized object is of the
    130             * same type as the original serialized object
    131             */
    132            return cls.cast(in.readObject());
    133
    134        } catch (final ClassNotFoundException | IOException ex) {
    135            throw new SerializationException(
    136                String.format("%s while reading cloned object data", ex.getClass().getSimpleName()), ex);
    137        }
    138    }
    139
    140    /**
    141     * Deserializes a single {@link Object} from an array of bytes.
    142     *
    143     * <p>
    144     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
    145     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
    146     * Note that in both cases, the ClassCastException is in the call site, not in this method.
    147     * </p>
    148     *
    149     * @param <T>  the object type to be deserialized
    150     * @param objectData
    151     *            the serialized object, must not be null
    152     * @return the deserialized object
    153     * @throws NullPointerException if {@code objectData} is {@code null}
    154     * @throws SerializationException (runtime) if the serialization fails
    155     */
    156    public static <T> T deserialize(final byte[] objectData) {
    157        Objects.requireNonNull(objectData, "objectData");
    158        return deserialize(new ByteArrayInputStream(objectData));
    159    }
    160
    161    /**
    162     * Deserializes an {@link Object} from the specified stream.
    163     *
    164     * <p>
    165     * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
    166     * exception handling, in the application code.
    167     * </p>
    168     *
    169     * <p>
    170     * The stream passed in is not buffered internally within this method. This is the responsibility of your
    171     * application if desired.
    172     * </p>
    173     *
    174     * <p>
    175     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
    176     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
    177     * Note that in both cases, the ClassCastException is in the call site, not in this method.
    178     * </p>
    179     *
    180     * @param <T>  the object type to be deserialized
    181     * @param inputStream
    182     *            the serialized object input stream, must not be null
    183     * @return the deserialized object
    184     * @throws NullPointerException if {@code inputStream} is {@code null}
    185     * @throws SerializationException (runtime) if the serialization fails
    186     */
    187    @SuppressWarnings("resource") // inputStream is managed by the caller
    188    public static <T> T deserialize(final InputStream inputStream) {
    189        Objects.requireNonNull(inputStream, "inputStream");
    190        try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
    191            @SuppressWarnings("unchecked")
    192            final T obj = (T) in.readObject();
    193            return obj;
    194        } catch (final ClassNotFoundException | IOException | NegativeArraySizeException ex) {
    195            throw new SerializationException(ex);
    196        }
    197    }
    198
    199    /**
    200     * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
    201     * implement {@link Serializable}.
    202     *
    203     * @param <T>
    204     *           the type of the object involved
    205     * @param obj
    206     *            the object to roundtrip
    207     * @return the serialized and deserialized object
    208     * @since 3.3
    209     */
    210    @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
    211    public static <T extends Serializable> T roundtrip(final T obj) {
    212        return (T) deserialize(serialize(obj));
    213    }
    214
    215    /**
    216     * Serializes an {@link Object} to a byte array for
    217     * storage/serialization.
    218     *
    219     * @param obj  the object to serialize to bytes
    220     * @return a byte[] with the converted Serializable
    221     * @throws SerializationException (runtime) if the serialization fails
    222     */
    223    public static byte[] serialize(final Serializable obj) {
    224        final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
    225        serialize(obj, baos);
    226        return baos.toByteArray();
    227    }
    228
    229    /**
    230     * Serializes an {@link Object} to the specified stream.
    231     *
    232     * <p>The stream will be closed once the object is written.
    233     * This avoids the need for a finally clause, and maybe also exception
    234     * handling, in the application code.</p>
    235     *
    236     * <p>The stream passed in is not buffered internally within this method.
    237     * This is the responsibility of your application if desired.</p>
    238     *
    239     * @param obj  the object to serialize to bytes, may be null
    240     * @param outputStream  the stream to write to, must not be null
    241     * @throws NullPointerException if {@code outputStream} is {@code null}
    242     * @throws SerializationException (runtime) if the serialization fails
    243     */
    244    @SuppressWarnings("resource") // outputStream is managed by the caller
    245    public static void serialize(final Serializable obj, final OutputStream outputStream) {
    246        Objects.requireNonNull(outputStream, "outputStream");
    247        try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
    248            out.writeObject(obj);
    249        } catch (final IOException ex) {
    250            throw new SerializationException(ex);
    251        }
    252    }
    253
    254    /**
    255     * SerializationUtils instances should NOT be constructed in standard programming.
    256     * Instead, the class should be used as {@code SerializationUtils.clone(object)}.
    257     *
    258     * <p>This constructor is public to permit tools that require a JavaBean instance
    259     * to operate.</p>
    260     * @since 2.0
    261     *
    262     * @deprecated TODO Make private in 4.0.
    263     */
    264    @Deprecated
    265    public SerializationUtils() {
    266        // empty
    267    }
    268
    269}