| 1 | /* |
| 2 | * Licensed to the Apache Software Foundation (ASF) under one or more |
| 3 | * contributor license agreements. See the NOTICE file distributed with |
| 4 | * this work for additional information regarding copyright ownership. |
| 5 | * The ASF licenses this file to You under the Apache License, Version 2.0 |
| 6 | * (the "License"); you may not use this file except in compliance with |
| 7 | * the License. You may obtain a copy of the License at |
| 8 | * |
| 9 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | * |
| 11 | * Unless required by applicable law or agreed to in writing, software |
| 12 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 14 | * See the License for the specific language governing permissions and |
| 15 | * limitations under the License. |
| 16 | */ |
| 17 | package org.apache.commons.lang3; |
| 18 | |
| 19 | import java.io.ByteArrayInputStream; |
| 20 | import java.io.ByteArrayOutputStream; |
| 21 | import java.io.IOException; |
| 22 | import java.io.InputStream; |
| 23 | import java.io.ObjectInputStream; |
| 24 | import java.io.ObjectOutputStream; |
| 25 | import java.io.ObjectStreamClass; |
| 26 | import java.io.OutputStream; |
| 27 | import java.io.Serializable; |
| 28 | import java.util.Objects; |
| 29 | |
| 30 | /** |
| 31 | * Assists with the serialization process and performs additional functionality based |
| 32 | * on serialization. |
| 33 | * |
| 34 | * <ul> |
| 35 | * <li>Deep clone using serialization |
| 36 | * <li>Serialize managing finally and IOException |
| 37 | * <li>Deserialize managing finally and IOException |
| 38 | * </ul> |
| 39 | * |
| 40 | * <p>This class throws exceptions for invalid {@code null} inputs. |
| 41 | * Each method documents its behavior in more detail.</p> |
| 42 | * |
| 43 | * <p>#ThreadSafe#</p> |
| 44 | * @since 1.0 |
| 45 | */ |
| 46 | public class SerializationUtils { |
| 47 | |
| 48 | /** |
| 49 | * Custom specialization of the standard JDK {@link ObjectInputStream} |
| 50 | * that uses a custom {@link ClassLoader} to resolve a class. |
| 51 | * If the specified {@link ClassLoader} is not able to resolve the class, |
| 52 | * the context classloader of the current thread will be used. |
| 53 | * This way, the standard deserialization work also in web-application |
| 54 | * containers and application servers, no matter in which of the |
| 55 | * {@link ClassLoader} the particular class that encapsulates |
| 56 | * serialization/deserialization lives. |
| 57 | * |
| 58 | * <p>For more in-depth information about the problem for which this |
| 59 | * class here is a workaround, see the JIRA issue LANG-626.</p> |
| 60 | */ |
| 61 | static final class ClassLoaderAwareObjectInputStream extends ObjectInputStream { |
| 62 | |
| 63 | private final ClassLoader classLoader; |
| 64 | |
| 65 | /** |
| 66 | * Constructs a new instance. |
| 67 | * @param in The {@link InputStream}. |
| 68 | * @param classLoader classloader to use |
| 69 | * @throws IOException if an I/O error occurs while reading stream header. |
| 70 | * @see java.io.ObjectInputStream |
| 71 | */ |
| 72 | ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException { |
| 73 | super(in); |
| 74 | this.classLoader = classLoader; |
| 75 | } |
| 76 | |
| 77 | /** |
| 78 | * Overridden version that uses the parameterized {@link ClassLoader} or the {@link ClassLoader} |
| 79 | * of the current {@link Thread} to resolve the class. |
| 80 | * @param desc An instance of class {@link ObjectStreamClass}. |
| 81 | * @return A {@link Class} object corresponding to {@code desc}. |
| 82 | * @throws IOException Any of the usual Input/Output exceptions. |
| 83 | * @throws ClassNotFoundException If class of a serialized object cannot be found. |
| 84 | */ |
| 85 | @Override |
| 86 | protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException { |
| 87 | final String name = desc.getName(); |
| 88 | try { |
| 89 | return Class.forName(name, false, classLoader); |
| 90 | } catch (final ClassNotFoundException ex) { |
| 91 | try { |
| 92 | return Class.forName(name, false, Thread.currentThread().getContextClassLoader()); |
| 93 | } catch (final ClassNotFoundException cnfe) { |
| 94 | final Class<?> cls = ClassUtils.getPrimitiveClass(name); |
| 95 | if (cls != null) { |
| 96 | return cls; |
| 97 | } |
| 98 | throw cnfe; |
| 99 | } |
| 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 | } |