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