001/*
002 * (C) Copyright 2007 Nuxeo SAS (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     Nuxeo - initial API and implementation
016 *
017 * $Id: DeepCopy.java 19474 2007-05-27 10:18:21Z sfermigier $
018 */
019
020package org.nuxeo.ecm.platform.ui.web.util;
021
022import java.io.ByteArrayInputStream;
023import java.io.ByteArrayOutputStream;
024import java.io.IOException;
025import java.io.ObjectInputStream;
026import java.io.ObjectOutputStream;
027
028/**
029 * Deep copy utils.
030 * <p>
031 * Most classes implementing the {@link Cloneable} interface only perform a shallow copy of an object. This class
032 * performs deep cloning serializing and deserializing an object. Therefore only serializable objects can be copied
033 * using this util.
034 *
035 * @author <a href="mailto:at@nuxeo.com">Anahide Tchertchian</a>
036 */
037// XXX AT: needs optimizing, see
038// http://javatechniques.com/blog/faster-deep-copies-of-java-objects/
039public final class DeepCopy {
040
041    // Utility class.
042    private DeepCopy() {
043    }
044
045    public static Object deepCopy(Object object) {
046        Object copy;
047        try {
048            // Write the object out to a byte array
049            ByteArrayOutputStream bos = new ByteArrayOutputStream();
050            ObjectOutputStream out = new ObjectOutputStream(bos);
051            out.writeObject(object);
052            out.flush();
053            out.close();
054
055            // Make an input stream from the byte array and read
056            // a copy of the object back in.
057            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
058            copy = in.readObject();
059        } catch (IOException e) {
060            throw new RuntimeException(e);
061        } catch (ClassNotFoundException cnfe) {
062            throw new RuntimeException(cnfe);
063        }
064        return copy;
065    }
066
067}