1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38 package com.gargoylesoftware.base.io;
39
40 import java.io.ObjectOutputStream;
41 import java.io.OutputStream;
42 import java.io.IOException;
43 import java.util.List;
44 import java.util.ArrayList;
45
46 /***
47 * A specialized subclass of ObjectOutputStream that is used to serialize
48 * objects. This stream will remove duplicate objects from the stream in
49 * order to shrink the resulting byte stream.<p>
50 *
51 * Only objects of the following types will be condensed: Character, Double,
52 * Integer, Long, Short and String. The biggest benefit will come from
53 * duplicate Strings.
54 *
55 * @version $Revision: 1.4 $
56 * @author <a href="mailto:mbowler@GargoyleSoftware.com">Mike Bowler</a>
57 */
58 public class CondensedObjectOutputStream extends ObjectOutputStream {
59
60 /***
61 * The list of classes that we can try condensing. Only classes that
62 * are immutable should be in this list.
63 */
64 private final String classNames_[] = {
65 "java.lang.Character",
66 "java.lang.Double",
67 "java.lang.Integer",
68 "java.lang.Long",
69 "java.lang.Short",
70 "java.lang.String",
71 };
72
73 private final List classes_;
74 private final List objects_ = new ArrayList();
75
76 /***
77 * Create the stream
78 * @param stream The output stream that we are wrapping
79 * @throws IOException If the superclass throws an IOException in it's
80 * constructor.
81 */
82 public CondensedObjectOutputStream( final OutputStream stream ) throws IOException {
83 super(stream);
84 enableReplaceObject(true);
85
86 classes_ = new ArrayList( classNames_.length );
87 int i;
88 for( i=0; i<classNames_.length; i++ ) {
89 try {
90 classes_.add( Class.forName(classNames_[i]) );
91 }
92 catch( final ClassNotFoundException e ) {
93
94 throw new NoClassDefFoundError( classNames_[i] );
95 }
96 }
97
98 }
99
100 /***
101 * Overrides the superclass to perform substitutions of duplicate
102 * immutable objects.
103 *
104 * @param object The object to be serialized
105 * @return Either the object that was passed in or an identical object
106 * that had previously been passed in.
107 */
108 protected Object replaceObject( final Object object ) {
109
110 Object rc = object;
111
112 if( object != null && classes_.contains( object.getClass() ) ) {
113
114 final int index = objects_.indexOf(object);
115 if( index == -1 ) {
116 objects_.add( object );
117 }
118 else {
119 rc = objects_.get(index);
120 }
121 }
122
123 return rc;
124 }
125 }
126