001/*
002 * Copyright 2002-2014 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.util;
018
019import java.io.ByteArrayInputStream;
020import java.io.ByteArrayOutputStream;
021import java.io.IOException;
022import java.io.ObjectInputStream;
023import java.io.ObjectOutputStream;
024
025/**
026 * Static utilities for serialization and deserialization.
027 *
028 * @author Dave Syer
029 * @since 3.0.5
030 */
031public abstract class SerializationUtils {
032
033        /**
034         * Serialize the given object to a byte array.
035         * @param object the object to serialize
036         * @return an array of bytes representing the object in a portable fashion
037         */
038        public static byte[] serialize(Object object) {
039                if (object == null) {
040                        return null;
041                }
042                ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
043                try {
044                        ObjectOutputStream oos = new ObjectOutputStream(baos);
045                        oos.writeObject(object);
046                        oos.flush();
047                }
048                catch (IOException ex) {
049                        throw new IllegalArgumentException("Failed to serialize object of type: " + object.getClass(), ex);
050                }
051                return baos.toByteArray();
052        }
053
054        /**
055         * Deserialize the byte array into an object.
056         * @param bytes a serialized object
057         * @return the result of deserializing the bytes
058         */
059        public static Object deserialize(byte[] bytes) {
060                if (bytes == null) {
061                        return null;
062                }
063                try {
064                        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
065                        return ois.readObject();
066                }
067                catch (IOException ex) {
068                        throw new IllegalArgumentException("Failed to deserialize object", ex);
069                }
070                catch (ClassNotFoundException ex) {
071                        throw new IllegalStateException("Failed to deserialize object type", ex);
072                }
073        }
074
075}