001 package org.apache.ojb.otm.copy;
002
003 /* Copyright 2003-2005 The Apache Software Foundation
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * 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 */
017
018 import java.io.*;
019 import org.apache.ojb.broker.PersistenceBroker;
020
021 /**
022 * Does in-memory serialization to achieve a copy of the object graph.
023 *
024 * @author matthew.baird
025 * @see ObjectCopyStrategy
026 */
027 public final class SerializeObjectCopyStrategy implements ObjectCopyStrategy
028 {
029 /**
030 * This implementation will probably be slower than the metadata
031 * object copy, but this was easier to implement.
032 * @see org.apache.ojb.otm.copy.ObjectCopyStrategy#copy(Object)
033 */
034 public Object copy(final Object obj, PersistenceBroker broker)
035 throws ObjectCopyException
036 {
037 ObjectOutputStream oos = null;
038 ObjectInputStream ois = null;
039 try
040 {
041 final ByteArrayOutputStream bos = new ByteArrayOutputStream();
042 oos = new ObjectOutputStream(bos);
043 // serialize and pass the object
044 oos.writeObject(obj);
045 oos.flush();
046 final ByteArrayInputStream bin =
047 new ByteArrayInputStream(bos.toByteArray());
048 ois = new ObjectInputStream(bin);
049 // return the new object
050 return ois.readObject();
051 }
052 catch (Exception e)
053 {
054 throw new ObjectCopyException(e);
055 }
056 finally
057 {
058 try
059 {
060 if (oos != null)
061 {
062 oos.close();
063 }
064 if (ois != null)
065 {
066 ois.close();
067 }
068 }
069 catch (IOException ioe)
070 {
071 // ignore
072 }
073 }
074 }
075 }