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.HashMap;
029import java.util.Map;
030import java.util.Objects;
031
032/**
033 * Assists with the serialization process and performs additional functionality based
034 * on serialization.
035 *
036 * <ul>
037 * <li>Deep clone using serialization
038 * <li>Serialize managing finally and IOException
039 * <li>Deserialize managing finally and IOException
040 * </ul>
041 *
042 * <p>This class throws exceptions for invalid {@code null} inputs.
043 * Each method documents its behavior in more detail.</p>
044 *
045 * <p>#ThreadSafe#</p>
046 * @since 1.0
047 */
048public class SerializationUtils {
049
050    /**
051     * Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
052     * that uses a custom  {@link ClassLoader} to resolve a class.
053     * If the specified {@link ClassLoader} is not able to resolve the class,
054     * the context classloader of the current thread will be used.
055     * This way, the standard deserialization work also in web-application
056     * containers and application servers, no matter in which of the
057     * {@link ClassLoader} the particular class that encapsulates
058     * serialization/deserialization lives.
059     *
060     * <p>For more in-depth information about the problem for which this
061     * class here is a workaround, see the JIRA issue LANG-626.</p>
062     */
063     static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
064        private static final Map<String, Class<?>> primitiveTypes =
065                new HashMap<>();
066
067        static {
068            primitiveTypes.put("byte", byte.class);
069            primitiveTypes.put("short", short.class);
070            primitiveTypes.put("int", int.class);
071            primitiveTypes.put("long", long.class);
072            primitiveTypes.put("float", float.class);
073            primitiveTypes.put("double", double.class);
074            primitiveTypes.put("boolean", boolean.class);
075            primitiveTypes.put("char", char.class);
076            primitiveTypes.put("void", void.class);
077        }
078
079        private final ClassLoader classLoader;
080
081        /**
082         * Constructor.
083         * @param in The {@link InputStream}.
084         * @param classLoader classloader to use
085         * @throws IOException if an I/O error occurs while reading stream header.
086         * @see java.io.ObjectInputStream
087         */
088        ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
089            super(in);
090            this.classLoader = classLoader;
091        }
092
093        /**
094         * Overridden version that uses the parameterized {@link ClassLoader} or the {@link ClassLoader}
095         * of the current {@link Thread} to resolve the class.
096         * @param desc An instance of class {@link ObjectStreamClass}.
097         * @return A {@link Class} object corresponding to {@code desc}.
098         * @throws IOException Any of the usual Input/Output exceptions.
099         * @throws ClassNotFoundException If class of a serialized object cannot be found.
100         */
101        @Override
102        protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
103            final String name = desc.getName();
104            try {
105                return Class.forName(name, false, classLoader);
106            } catch (final ClassNotFoundException ex) {
107                try {
108                    return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
109                } catch (final ClassNotFoundException cnfe) {
110                    final Class<?> cls = primitiveTypes.get(name);
111                    if (cls != null) {
112                        return cls;
113                    }
114                    throw cnfe;
115                }
116            }
117        }
118
119    }
120
121    /**
122     * Deep clone an {@link Object} using serialization.
123     *
124     * <p>This is many times slower than writing clone methods by hand
125     * on all objects in your object graph. However, for complex object
126     * graphs, or for those that don't support deep cloning this can
127     * be a simple alternative implementation. Of course all the objects
128     * must be {@link Serializable}.</p>
129     *
130     * @param <T> the type of the object involved
131     * @param object  the {@link Serializable} object to clone
132     * @return the cloned object
133     * @throws SerializationException (runtime) if the serialization fails
134     */
135    public static <T extends Serializable> T clone(final T object) {
136        if (object == null) {
137            return null;
138        }
139        final byte[] objectData = serialize(object);
140        final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);
141
142        final Class<T> cls = ObjectUtils.getClass(object);
143        try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais, cls.getClassLoader())) {
144            /*
145             * when we serialize and deserialize an object, it is reasonable to assume the deserialized object is of the
146             * same type as the original serialized object
147             */
148            return cls.cast(in.readObject());
149
150        } catch (final ClassNotFoundException | IOException ex) {
151            throw new SerializationException(
152                String.format("%s while reading cloned object data", ex.getClass().getSimpleName()), ex);
153        }
154    }
155
156    /**
157     * Deserializes a single {@link Object} from an array of bytes.
158     *
159     * <p>
160     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
161     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
162     * Note that in both cases, the ClassCastException is in the call site, not in this method.
163     * </p>
164     *
165     * @param <T>  the object type to be deserialized
166     * @param objectData
167     *            the serialized object, must not be null
168     * @return the deserialized object
169     * @throws NullPointerException if {@code objectData} is {@code null}
170     * @throws SerializationException (runtime) if the serialization fails
171     */
172    public static <T> T deserialize(final byte[] objectData) {
173        Objects.requireNonNull(objectData, "objectData");
174        return deserialize(new ByteArrayInputStream(objectData));
175    }
176
177    /**
178     * Deserializes an {@link Object} from the specified stream.
179     *
180     * <p>
181     * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
182     * exception handling, in the application code.
183     * </p>
184     *
185     * <p>
186     * The stream passed in is not buffered internally within this method. This is the responsibility of your
187     * application if desired.
188     * </p>
189     *
190     * <p>
191     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
192     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
193     * Note that in both cases, the ClassCastException is in the call site, not in this method.
194     * </p>
195     *
196     * @param <T>  the object type to be deserialized
197     * @param inputStream
198     *            the serialized object input stream, must not be null
199     * @return the deserialized object
200     * @throws NullPointerException if {@code inputStream} is {@code null}
201     * @throws SerializationException (runtime) if the serialization fails
202     */
203    @SuppressWarnings("resource") // inputStream is managed by the caller
204    public static <T> T deserialize(final InputStream inputStream) {
205        Objects.requireNonNull(inputStream, "inputStream");
206        try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
207            @SuppressWarnings("unchecked")
208            final T obj = (T) in.readObject();
209            return obj;
210        } catch (final ClassNotFoundException | IOException ex) {
211            throw new SerializationException(ex);
212        }
213    }
214
215    /**
216     * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
217     * implement {@link Serializable}.
218     *
219     * @param <T>
220     *           the type of the object involved
221     * @param obj
222     *            the object to roundtrip
223     * @return the serialized and deserialized object
224     * @since 3.3
225     */
226    @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
227    public static <T extends Serializable> T roundtrip(final T obj) {
228        return (T) deserialize(serialize(obj));
229    }
230
231    /**
232     * Serializes an {@link Object} to a byte array for
233     * storage/serialization.
234     *
235     * @param obj  the object to serialize to bytes
236     * @return a byte[] with the converted Serializable
237     * @throws SerializationException (runtime) if the serialization fails
238     */
239    public static byte[] serialize(final Serializable obj) {
240        final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
241        serialize(obj, baos);
242        return baos.toByteArray();
243    }
244
245    /**
246     * Serializes an {@link Object} to the specified stream.
247     *
248     * <p>The stream will be closed once the object is written.
249     * This avoids the need for a finally clause, and maybe also exception
250     * handling, in the application code.</p>
251     *
252     * <p>The stream passed in is not buffered internally within this method.
253     * This is the responsibility of your application if desired.</p>
254     *
255     * @param obj  the object to serialize to bytes, may be null
256     * @param outputStream  the stream to write to, must not be null
257     * @throws NullPointerException if {@code outputStream} is {@code null}
258     * @throws SerializationException (runtime) if the serialization fails
259     */
260    @SuppressWarnings("resource") // outputStream is managed by the caller
261    public static void serialize(final Serializable obj, final OutputStream outputStream) {
262        Objects.requireNonNull(outputStream, "outputStream");
263        try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
264            out.writeObject(obj);
265        } catch (final IOException ex) {
266            throw new SerializationException(ex);
267        }
268    }
269
270    /**
271     * SerializationUtils instances should NOT be constructed in standard programming.
272     * Instead, the class should be used as {@code SerializationUtils.clone(object)}.
273     *
274     * <p>This constructor is public to permit tools that require a JavaBean instance
275     * to operate.</p>
276     * @since 2.0
277     */
278    public SerializationUtils() {
279    }
280
281}