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.common.ByteBuffer;
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 public void close() throws IOException {
81 out.close();
82 }
83
84 public void flush() throws IOException {
85 out.flush();
86 }
87
88 public void write(int b) throws IOException {
89 out.write(b);
90 }
91
92 public void write(byte[] b) throws IOException {
93 out.write(b);
94 }
95
96 public void write(byte[] b, int off, int len) throws IOException {
97 out.write(b, off, len);
98 }
99
100 public void writeObject(Object obj) throws IOException {
101 ByteBuffer buf = ByteBuffer.allocate(64, false);
102 buf.setAutoExpand(true);
103 buf.putObject(obj);
104
105 int objectSize = buf.position() - 4;
106 if (objectSize > maxObjectSize) {
107 buf.release();
108 throw new IllegalArgumentException(
109 "The encoded object is too big: " + objectSize + " (> "
110 + maxObjectSize + ')');
111 }
112
113 out.write(buf.array(), 0, buf.position());
114 buf.release();
115 }
116
117 public void writeBoolean(boolean v) throws IOException {
118 out.writeBoolean(v);
119 }
120
121 public void writeByte(int v) throws IOException {
122 out.writeByte(v);
123 }
124
125 public void writeBytes(String s) throws IOException {
126 out.writeBytes(s);
127 }
128
129 public void writeChar(int v) throws IOException {
130 out.writeChar(v);
131 }
132
133 public void writeChars(String s) throws IOException {
134 out.writeChars(s);
135 }
136
137 public void writeDouble(double v) throws IOException {
138 out.writeDouble(v);
139 }
140
141 public void writeFloat(float v) throws IOException {
142 out.writeFloat(v);
143 }
144
145 public void writeInt(int v) throws IOException {
146 out.writeInt(v);
147 }
148
149 public void writeLong(long v) throws IOException {
150 out.writeLong(v);
151 }
152
153 public void writeShort(int v) throws IOException {
154 out.writeShort(v);
155 }
156
157 public void writeUTF(String str) throws IOException {
158 out.writeUTF(str);
159 }
160 }