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