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