01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: SerializationUtils.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.tools;
09:
10: import java.io.*;
11:
12: import com.uwyn.rife.tools.exceptions.DeserializationErrorException;
13: import com.uwyn.rife.tools.exceptions.SerializationErrorException;
14: import com.uwyn.rife.tools.exceptions.SerializationUtilsErrorException;
15: import java.util.zip.GZIPInputStream;
16: import java.util.zip.GZIPOutputStream;
17:
18: public abstract class SerializationUtils {
19: public static <TargetType extends Serializable> TargetType deserializeFromString(
20: String value) throws SerializationUtilsErrorException {
21: if (null == value) {
22: return null;
23: }
24:
25: byte[] value_bytes_decoded = Base64.decode(value);
26: if (null == value_bytes_decoded) {
27: throw new DeserializationErrorException(null);
28: }
29:
30: ByteArrayInputStream bytes_is = new ByteArrayInputStream(
31: value_bytes_decoded);
32: GZIPInputStream gzip_is = null;
33: ObjectInputStream object_is = null;
34: try {
35: gzip_is = new GZIPInputStream(bytes_is);
36: object_is = new ObjectInputStream(gzip_is);
37: return (TargetType) object_is.readObject();
38: } catch (IOException e) {
39: throw new DeserializationErrorException(e);
40: } catch (ClassNotFoundException e) {
41: throw new DeserializationErrorException(e);
42: }
43: }
44:
45: public static String serializeToString(Serializable value)
46: throws SerializationUtilsErrorException {
47: if (null == value)
48: throw new IllegalArgumentException("value can't be null.");
49:
50: ByteArrayOutputStream byte_os = new ByteArrayOutputStream();
51: GZIPOutputStream gzip_os = null;
52: ObjectOutputStream object_os = null;
53: try {
54: gzip_os = new GZIPOutputStream(byte_os);
55: object_os = new ObjectOutputStream(gzip_os);
56: object_os.writeObject(value);
57: object_os.flush();
58: gzip_os.flush();
59: gzip_os.finish();
60: } catch (IOException e) {
61: throw new SerializationErrorException(value, e);
62: }
63:
64: byte[] value_bytes_decoded = byte_os.toByteArray();
65:
66: return Base64.encodeToString(value_bytes_decoded, false);
67: }
68: }
|