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