01: package org.apache.ojb.broker.accesslayer.conversions;
02:
03: /* Copyright 2002-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.ByteArrayInputStream;
19: import java.io.ByteArrayOutputStream;
20: import java.io.ObjectInputStream;
21: import java.io.ObjectOutputStream;
22: import java.util.zip.GZIPInputStream;
23: import java.util.zip.GZIPOutputStream;
24:
25: /**
26: * This implementation of the FieldConversion interface converts
27: * between java.lang.Objects values and byte[] values in the rdbms.
28: * This conversion is useful to store serialized objects in database
29: * columns.
30: * <p/>
31: * NOTE: This implementation use {@link java.util.zip.GZIPOutputStream} and
32: * {@link java.util.zip.GZIPInputStream} to compress data.
33: *
34: * @see Object2ByteArrUncompressedFieldConversion
35: * @author Thomas Mahler
36: * @version $Id: Object2ByteArrFieldConversion.java,v 1.6.2.3 2005/12/21 22:23:38 tomdz Exp $
37: */
38: public class Object2ByteArrFieldConversion implements FieldConversion {
39:
40: /*
41: * @see FieldConversion#javaToSql(Object)
42: */
43: public Object javaToSql(Object source) {
44: if (source == null)
45: return null;
46: try {
47: ByteArrayOutputStream bao = new ByteArrayOutputStream();
48: GZIPOutputStream gos = new GZIPOutputStream(bao);
49: ObjectOutputStream oos = new ObjectOutputStream(gos);
50: oos.writeObject(source);
51: oos.close();
52: gos.close();
53: bao.close();
54: byte[] result = bao.toByteArray();
55: return result;
56: } catch (Throwable t) {
57: throw new ConversionException(t);
58: }
59: }
60:
61: /*
62: * @see FieldConversion#sqlToJava(Object)
63: */
64: public Object sqlToJava(Object source) {
65: if (source == null)
66: return null;
67: try {
68: ByteArrayInputStream bais = new ByteArrayInputStream(
69: (byte[]) source);
70: GZIPInputStream gis = new GZIPInputStream(bais);
71: ObjectInputStream ois = new ObjectInputStream(gis);
72: Object result = ois.readObject();
73: ois.close();
74: gis.close();
75: bais.close();
76: return result;
77: } catch (Throwable t) {
78: throw new ConversionException(t);
79: }
80: }
81:
82: }
|