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