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.HashMap; 29 import java.util.Map; 30 import java.util.Objects; 31 32 /** 33 * Assists with the serialization process and performs additional functionality based 34 * on serialization. 35 * 36 * <ul> 37 * <li>Deep clone using serialization 38 * <li>Serialize managing finally and IOException 39 * <li>Deserialize managing finally and IOException 40 * </ul> 41 * 42 * <p>This class throws exceptions for invalid {@code null} inputs. 43 * Each method documents its behavior in more detail.</p> 44 * 45 * <p>#ThreadSafe#</p> 46 * @since 1.0 47 */ 48 public class SerializationUtils { 49 50 /** 51 * Custom specialization of the standard JDK {@link java.io.ObjectInputStream} 52 * that uses a custom {@link ClassLoader} to resolve a class. 53 * If the specified {@link ClassLoader} is not able to resolve the class, 54 * the context classloader of the current thread will be used. 55 * This way, the standard deserialization work also in web-application 56 * containers and application servers, no matter in which of the 57 * {@link ClassLoader} the particular class that encapsulates 58 * serialization/deserialization lives. 59 * 60 * <p>For more in-depth information about the problem for which this 61 * class here is a workaround, see the JIRA issue LANG-626.</p> 62 */ 63 static class ClassLoaderAwareObjectInputStream extends ObjectInputStream { 64 private static final Map<String, Class<?>> primitiveTypes = 65 new HashMap<>(); 66 67 static { 68 primitiveTypes.put("byte", byte.class); 69 primitiveTypes.put("short", short.class); 70 primitiveTypes.put("int", int.class); 71 primitiveTypes.put("long", long.class); 72 primitiveTypes.put("float", float.class); 73 primitiveTypes.put("double", double.class); 74 primitiveTypes.put("boolean", boolean.class); 75 primitiveTypes.put("char", char.class); 76 primitiveTypes.put("void", void.class); 77 } 78 79 private final ClassLoader classLoader; 80 81 /** 82 * Constructor. 83 * @param in The {@link InputStream}. 84 * @param classLoader classloader to use 85 * @throws IOException if an I/O error occurs while reading stream header. 86 * @see java.io.ObjectInputStream 87 */ 88 ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException { 89 super(in); 90 this.classLoader = classLoader; 91 } 92 93 /** 94 * Overridden version that uses the parameterized {@link ClassLoader} or the {@link ClassLoader} 95 * of the current {@link Thread} to resolve the class. 96 * @param desc An instance of class {@link ObjectStreamClass}. 97 * @return A {@link Class} object corresponding to {@code desc}. 98 * @throws IOException Any of the usual Input/Output exceptions. 99 * @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 }