01: /*
02: * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
03: */
04: package com.tc.objectserver.persistence.sleepycat;
05:
06: import com.sleepycat.je.DatabaseEntry;
07: import com.tc.io.serializer.TCObjectInputStream;
08: import com.tc.io.serializer.TCObjectOutputStream;
09: import com.tc.io.serializer.api.Serializer;
10: import com.tc.io.serializer.impl.StringUTFSerializer;
11: import com.tc.objectserver.core.api.ManagedObject;
12: import com.tc.objectserver.managedobject.ManagedObjectSerializer;
13:
14: import java.io.ByteArrayInputStream;
15: import java.io.ByteArrayOutputStream;
16: import java.io.IOException;
17:
18: public class CustomSerializationAdapter implements SerializationAdapter {
19:
20: private final ByteArrayOutputStream baout;
21: private final TCObjectOutputStream out;
22: private final ManagedObjectSerializer moSerializer;
23: private final StringUTFSerializer stringSerializer;
24:
25: private final Object serializerLock = new Object();
26:
27: public CustomSerializationAdapter(
28: ManagedObjectSerializer moSerializer,
29: StringUTFSerializer stringSerializer) {
30: this .moSerializer = moSerializer;
31: this .stringSerializer = stringSerializer;
32: baout = new ByteArrayOutputStream(4096);
33: out = new TCObjectOutputStream(baout);
34: }
35:
36: public void serializeManagedObject(DatabaseEntry entry,
37: ManagedObject managedObject) throws IOException {
38: synchronized (serializerLock) {
39: serialize(entry, managedObject, moSerializer);
40: }
41: }
42:
43: public synchronized void serializeString(DatabaseEntry entry,
44: String string) throws IOException {
45: synchronized (serializerLock) {
46: serialize(entry, string, stringSerializer);
47: }
48: }
49:
50: private void serialize(DatabaseEntry entry, Object o,
51: Serializer serializer) throws IOException {
52: serializer.serializeTo(o, out);
53: out.flush();
54: entry.setData(baout.toByteArray());
55: baout.reset();
56: }
57:
58: public synchronized ManagedObject deserializeManagedObject(
59: DatabaseEntry data) throws IOException,
60: ClassNotFoundException {
61: return (ManagedObject) deserialize(data, moSerializer);
62: }
63:
64: public String deserializeString(DatabaseEntry data)
65: throws IOException, ClassNotFoundException {
66: return (String) deserialize(data, stringSerializer);
67: }
68:
69: private Object deserialize(DatabaseEntry entry,
70: Serializer serializer) throws IOException,
71: ClassNotFoundException {
72: ByteArrayInputStream bain = new ByteArrayInputStream(entry
73: .getData());
74: TCObjectInputStream in = new TCObjectInputStream(bain);
75: return serializer.deserializeFrom(in);
76: }
77: }
|