1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.filter.codec.serialization;
21
22 import java.io.DataOutputStream;
23 import java.io.IOException;
24 import java.io.ObjectOutput;
25 import java.io.OutputStream;
26
27 import org.apache.mina.core.buffer.IoBuffer;
28
29
30
31
32
33
34
35 public class ObjectSerializationOutputStream extends OutputStream implements
36 ObjectOutput {
37
38 private final DataOutputStream out;
39
40 private int maxObjectSize = Integer.MAX_VALUE;
41
42 public ObjectSerializationOutputStream(OutputStream out) {
43 if (out == null) {
44 throw new NullPointerException("out");
45 }
46
47 if (out instanceof DataOutputStream) {
48 this.out = (DataOutputStream) out;
49 } else {
50 this.out = new DataOutputStream(out);
51 }
52 }
53
54
55
56
57
58
59
60 public int getMaxObjectSize() {
61 return maxObjectSize;
62 }
63
64
65
66
67
68
69
70 public void setMaxObjectSize(int maxObjectSize) {
71 if (maxObjectSize <= 0) {
72 throw new IllegalArgumentException("maxObjectSize: "
73 + maxObjectSize);
74 }
75
76 this.maxObjectSize = maxObjectSize;
77 }
78
79 @Override
80 public void close() throws IOException {
81 out.close();
82 }
83
84 @Override
85 public void flush() throws IOException {
86 out.flush();
87 }
88
89 @Override
90 public void write(int b) throws IOException {
91 out.write(b);
92 }
93
94 @Override
95 public void write(byte[] b) throws IOException {
96 out.write(b);
97 }
98
99 @Override
100 public void write(byte[] b, int off, int len) throws IOException {
101 out.write(b, off, len);
102 }
103
104 public void writeObject(Object obj) throws IOException {
105 IoBuffer buf = IoBuffer.allocate(64, false);
106 buf.setAutoExpand(true);
107 buf.putObject(obj);
108
109 int objectSize = buf.position() - 4;
110 if (objectSize > maxObjectSize) {
111 throw new IllegalArgumentException(
112 "The encoded object is too big: " + objectSize + " (> "
113 + maxObjectSize + ')');
114 }
115
116 out.write(buf.array(), 0, buf.position());
117 }
118
119 public void writeBoolean(boolean v) throws IOException {
120 out.writeBoolean(v);
121 }
122
123 public void writeByte(int v) throws IOException {
124 out.writeByte(v);
125 }
126
127 public void writeBytes(String s) throws IOException {
128 out.writeBytes(s);
129 }
130
131 public void writeChar(int v) throws IOException {
132 out.writeChar(v);
133 }
134
135 public void writeChars(String s) throws IOException {
136 out.writeChars(s);
137 }
138
139 public void writeDouble(double v) throws IOException {
140 out.writeDouble(v);
141 }
142
143 public void writeFloat(float v) throws IOException {
144 out.writeFloat(v);
145 }
146
147 public void writeInt(int v) throws IOException {
148 out.writeInt(v);
149 }
150
151 public void writeLong(long v) throws IOException {
152 out.writeLong(v);
153 }
154
155 public void writeShort(int v) throws IOException {
156 out.writeShort(v);
157 }
158
159 public void writeUTF(String str) throws IOException {
160 out.writeUTF(str);
161 }
162 }