001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.kernel.util;
016    
017    import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayInputStream;
018    import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
019    
020    import java.io.IOException;
021    import java.io.ObjectInputStream;
022    import java.io.ObjectOutputStream;
023    
024    /**
025     * @author Alexander Chow
026     */
027    public class SerializableUtil {
028    
029            public static Object deserialize(byte[] bytes)
030                    throws ClassNotFoundException, IOException {
031    
032                    ObjectInputStream ois = null;
033    
034                    try {
035                            ois = new ObjectInputStream(new UnsyncByteArrayInputStream(bytes));
036    
037                            Object obj = ois.readObject();
038    
039                            ois.close();
040    
041                            ois = null;
042    
043                            return obj;
044                    }
045                    finally {
046                            if (ois != null) {
047                                    ois.close();
048                            }
049                    }
050            }
051    
052            public static byte[] serialize(Object obj) throws IOException {
053                    ObjectOutputStream oos = null;
054    
055                    try {
056                            UnsyncByteArrayOutputStream ubaos =
057                                    new UnsyncByteArrayOutputStream();
058    
059                            oos = new ObjectOutputStream(ubaos);
060    
061                            oos.writeObject(obj);
062    
063                            oos.close();
064    
065                            oos = null;
066    
067                            return ubaos.toByteArray();
068                    }
069                    finally {
070                            if (oos != null) {
071                                    oos.close();
072                            }
073                    }
074            }
075    
076    }