01: package org.apache.ojb.otm.copy;
02:
03: /* Copyright 2003-2005 The Apache Software Foundation
04: *
05: * Licensed under the Apache License, Version 2.0 (the "License");
06: * you may not use this file except in compliance with the License.
07: * You may obtain a copy of the License at
08: *
09: * http://www.apache.org/licenses/LICENSE-2.0
10: *
11: * Unless required by applicable law or agreed to in writing, software
12: * distributed under the License is distributed on an "AS IS" BASIS,
13: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14: * See the License for the specific language governing permissions and
15: * limitations under the License.
16: */
17:
18: import java.io.*;
19: import org.apache.ojb.broker.PersistenceBroker;
20:
21: /**
22: * Does in-memory serialization to achieve a copy of the object graph.
23: *
24: * @author matthew.baird
25: * @see ObjectCopyStrategy
26: */
27: public final class SerializeObjectCopyStrategy implements
28: ObjectCopyStrategy {
29: /**
30: * This implementation will probably be slower than the metadata
31: * object copy, but this was easier to implement.
32: * @see org.apache.ojb.otm.copy.ObjectCopyStrategy#copy(Object)
33: */
34: public Object copy(final Object obj, PersistenceBroker broker)
35: throws ObjectCopyException {
36: ObjectOutputStream oos = null;
37: ObjectInputStream ois = null;
38: try {
39: final ByteArrayOutputStream bos = new ByteArrayOutputStream();
40: oos = new ObjectOutputStream(bos);
41: // serialize and pass the object
42: oos.writeObject(obj);
43: oos.flush();
44: final ByteArrayInputStream bin = new ByteArrayInputStream(
45: bos.toByteArray());
46: ois = new ObjectInputStream(bin);
47: // return the new object
48: return ois.readObject();
49: } catch (Exception e) {
50: throw new ObjectCopyException(e);
51: } finally {
52: try {
53: if (oos != null) {
54: oos.close();
55: }
56: if (ois != null) {
57: ois.close();
58: }
59: } catch (IOException ioe) {
60: // ignore
61: }
62: }
63: }
64: }
|