Classes in this File | Line Coverage | Branch Coverage | Complexity | ||||
SerializeObjectCopyStrategy |
|
| 7.0;7 |
1 | package org.apache.ojb.otm.copy; | |
2 | ||
3 | /* Copyright 2003-2005 The Apache Software Foundation | |
4 | * | |
5 | * Licensed under the Apache License, Version 2.0 (the "License"); | |
6 | * you may not use this file except in compliance with the License. | |
7 | * You may obtain a copy of the License at | |
8 | * | |
9 | * 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 ObjectCopyStrategy | |
28 | { | |
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 | { | |
37 | ObjectOutputStream oos = null; | |
38 | ObjectInputStream ois = null; | |
39 | try | |
40 | { | |
41 | final ByteArrayOutputStream bos = new ByteArrayOutputStream(); | |
42 | oos = new ObjectOutputStream(bos); | |
43 | // serialize and pass the object | |
44 | oos.writeObject(obj); | |
45 | oos.flush(); | |
46 | final ByteArrayInputStream bin = | |
47 | new ByteArrayInputStream(bos.toByteArray()); | |
48 | ois = new ObjectInputStream(bin); | |
49 | // return the new object | |
50 | return ois.readObject(); | |
51 | } | |
52 | catch (Exception e) | |
53 | { | |
54 | throw new ObjectCopyException(e); | |
55 | } | |
56 | finally | |
57 | { | |
58 | try | |
59 | { | |
60 | if (oos != null) | |
61 | { | |
62 | oos.close(); | |
63 | } | |
64 | if (ois != null) | |
65 | { | |
66 | ois.close(); | |
67 | } | |
68 | } | |
69 | catch (IOException ioe) | |
70 | { | |
71 | // ignore | |
72 | } | |
73 | } | |
74 | } | |
75 | } |