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 behavior 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        try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais,
085                object.getClass().getClassLoader())) {
086            /*
087             * when we serialize and deserialize an object,
088             * it is reasonable to assume the deserialized object
089             * is of the same type as the original serialized object
090             */
091            @SuppressWarnings("unchecked") // see above
092            final T readObject = (T) in.readObject();
093            return readObject;
094
095        } catch (final ClassNotFoundException ex) {
096            throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
097        } catch (final IOException ex) {
098            throw new SerializationException("IOException while reading or closing cloned object data", ex);
099        }
100    }
101
102    /**
103     * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
104     * implement {@link Serializable}.
105     *
106     * @param <T>
107     *           the type of the object involved
108     * @param msg
109     *            the object to roundtrip
110     * @return the serialized and deserialized object
111     * @since 3.3
112     */
113    @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
114    public static <T extends Serializable> T roundtrip(final T msg) {
115        return (T) deserialize(serialize(msg));
116    }
117
118    // Serialize
119    //-----------------------------------------------------------------------
120    /**
121     * <p>Serializes an {@code Object} to the specified stream.</p>
122     *
123     * <p>The stream will be closed once the object is written.
124     * This avoids the need for a finally clause, and maybe also exception
125     * handling, in the application code.</p>
126     *
127     * <p>The stream passed in is not buffered internally within this method.
128     * This is the responsibility of your application if desired.</p>
129     *
130     * @param obj  the object to serialize to bytes, may be null
131     * @param outputStream  the stream to write to, must not be null
132     * @throws NullPointerException if {@code outputStream} is {@code null}
133     * @throws SerializationException (runtime) if the serialization fails
134     */
135    public static void serialize(final Serializable obj, final OutputStream outputStream) {
136        Validate.notNull(outputStream, "The OutputStream must not be null");
137        try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
138            out.writeObject(obj);
139        } catch (final IOException ex) {
140            throw new SerializationException(ex);
141        }
142    }
143
144    /**
145     * <p>Serializes an {@code Object} to a byte array for
146     * storage/serialization.</p>
147     *
148     * @param obj  the object to serialize to bytes
149     * @return a byte[] with the converted Serializable
150     * @throws SerializationException (runtime) if the serialization fails
151     */
152    public static byte[] serialize(final Serializable obj) {
153        final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
154        serialize(obj, baos);
155        return baos.toByteArray();
156    }
157
158    // Deserialize
159    //-----------------------------------------------------------------------
160    /**
161     * <p>
162     * Deserializes an {@code Object} from the specified stream.
163     * </p>
164     *
165     * <p>
166     * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
167     * exception handling, in the application code.
168     * </p>
169     *
170     * <p>
171     * The stream passed in is not buffered internally within this method. This is the responsibility of your
172     * application if desired.
173     * </p>
174     *
175     * <p>
176     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
177     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
178     * Note that in both cases, the ClassCastException is in the call site, not in this method.
179     * </p>
180     *
181     * @param <T>  the object type to be deserialized
182     * @param inputStream
183     *            the serialized object input stream, must not be null
184     * @return the deserialized object
185     * @throws NullPointerException if {@code inputStream} is {@code null}
186     * @throws SerializationException (runtime) if the serialization fails
187     */
188    public static <T> T deserialize(final InputStream inputStream) {
189        Validate.notNull(inputStream, "The InputStream must not be null");
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 ex) {
195            throw new SerializationException(ex);
196        }
197    }
198
199    /**
200     * <p>
201     * Deserializes a single {@code Object} from an array of bytes.
202     * </p>
203     *
204     * <p>
205     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
206     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
207     * Note that in both cases, the ClassCastException is in the call site, not in this method.
208     * </p>
209     *
210     * @param <T>  the object type to be deserialized
211     * @param objectData
212     *            the serialized object, must not be null
213     * @return the deserialized object
214     * @throws NullPointerException if {@code objectData} is {@code null}
215     * @throws SerializationException (runtime) if the serialization fails
216     */
217    public static <T> T deserialize(final byte[] objectData) {
218        Validate.notNull(objectData, "The byte[] must not be null");
219        return deserialize(new ByteArrayInputStream(objectData));
220    }
221
222    /**
223     * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
224     * that uses a custom  {@code ClassLoader} to resolve a class.
225     * If the specified {@code ClassLoader} is not able to resolve the class,
226     * the context classloader of the current thread will be used.
227     * This way, the standard deserialization work also in web-application
228     * containers and application servers, no matter in which of the
229     * {@code ClassLoader} the particular class that encapsulates
230     * serialization/deserialization lives. </p>
231     *
232     * <p>For more in-depth information about the problem for which this
233     * class here is a workaround, see the JIRA issue LANG-626. </p>
234     */
235     static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
236        private static final Map<String, Class<?>> primitiveTypes =
237                new HashMap<>();
238
239        static {
240            primitiveTypes.put("byte", byte.class);
241            primitiveTypes.put("short", short.class);
242            primitiveTypes.put("int", int.class);
243            primitiveTypes.put("long", long.class);
244            primitiveTypes.put("float", float.class);
245            primitiveTypes.put("double", double.class);
246            primitiveTypes.put("boolean", boolean.class);
247            primitiveTypes.put("char", char.class);
248            primitiveTypes.put("void", void.class);
249        }
250
251        private final ClassLoader classLoader;
252
253        /**
254         * Constructor.
255         * @param in The {@code InputStream}.
256         * @param classLoader classloader to use
257         * @throws IOException if an I/O error occurs while reading stream header.
258         * @see java.io.ObjectInputStream
259         */
260        ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
261            super(in);
262            this.classLoader = classLoader;
263        }
264
265        /**
266         * Overridden version that uses the parameterized {@code ClassLoader} or the {@code ClassLoader}
267         * of the current {@code Thread} to resolve the class.
268         * @param desc An instance of class {@code ObjectStreamClass}.
269         * @return A {@code Class} object corresponding to {@code desc}.
270         * @throws IOException Any of the usual Input/Output exceptions.
271         * @throws ClassNotFoundException If class of a serialized object cannot be found.
272         */
273        @Override
274        protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
275            final String name = desc.getName();
276            try {
277                return Class.forName(name, false, classLoader);
278            } catch (final ClassNotFoundException ex) {
279                try {
280                    return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
281                } catch (final ClassNotFoundException cnfe) {
282                    final Class<?> cls = primitiveTypes.get(name);
283                    if (cls != null) {
284                        return cls;
285                    }
286                    throw cnfe;
287                }
288            }
289        }
290
291    }
292
293}