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