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.textline;
21
22 import java.nio.charset.Charset;
23 import java.nio.charset.CharsetEncoder;
24
25 import org.apache.mina.core.buffer.IoBuffer;
26 import org.apache.mina.core.session.AttributeKey;
27 import org.apache.mina.core.session.IoSession;
28 import org.apache.mina.filter.codec.ProtocolEncoder;
29 import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
30 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
31
32
33
34
35
36
37
38 public class TextLineEncoder extends ProtocolEncoderAdapter {
39 private final AttributeKey ENCODER = new AttributeKey(getClass(), "encoder");
40
41 private final Charset charset;
42
43 private final LineDelimiter delimiter;
44
45 private int maxLineLength = Integer.MAX_VALUE;
46
47
48
49
50
51 public TextLineEncoder() {
52 this(Charset.defaultCharset(), LineDelimiter.UNIX);
53 }
54
55
56
57
58
59 public TextLineEncoder(String delimiter) {
60 this(new LineDelimiter(delimiter));
61 }
62
63
64
65
66
67 public TextLineEncoder(LineDelimiter delimiter) {
68 this(Charset.defaultCharset(), delimiter);
69 }
70
71
72
73
74
75 public TextLineEncoder(Charset charset) {
76 this(charset, LineDelimiter.UNIX);
77 }
78
79
80
81
82
83 public TextLineEncoder(Charset charset, String delimiter) {
84 this(charset, new LineDelimiter(delimiter));
85 }
86
87
88
89
90
91 public TextLineEncoder(Charset charset, LineDelimiter delimiter) {
92 if (charset == null) {
93 throw new IllegalArgumentException("charset");
94 }
95 if (delimiter == null) {
96 throw new IllegalArgumentException("delimiter");
97 }
98 if (LineDelimiter.AUTO.equals(delimiter)) {
99 throw new IllegalArgumentException("AUTO delimiter is not allowed for encoder.");
100 }
101
102 this.charset = charset;
103 this.delimiter = delimiter;
104 }
105
106
107
108
109
110
111
112 public int getMaxLineLength() {
113 return maxLineLength;
114 }
115
116
117
118
119
120
121
122 public void setMaxLineLength(int maxLineLength) {
123 if (maxLineLength <= 0) {
124 throw new IllegalArgumentException("maxLineLength: " + maxLineLength);
125 }
126
127 this.maxLineLength = maxLineLength;
128 }
129
130 public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
131 CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);
132
133 if (encoder == null) {
134 encoder = charset.newEncoder();
135 session.setAttribute(ENCODER, encoder);
136 }
137
138 String value = (message == null ? "" : message.toString());
139 IoBuffer buf = IoBuffer.allocate(value.length()).setAutoExpand(true);
140 buf.putString(value, encoder);
141
142 if (buf.position() > maxLineLength) {
143 throw new IllegalArgumentException("Line length: " + buf.position());
144 }
145
146 buf.putString(delimiter.getValue(), encoder);
147 buf.flip();
148 out.write(buf);
149 }
150
151 public void dispose() throws Exception {
152
153 }
154 }