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.common.ByteBuffer;
26 import org.apache.mina.common.IoSession;
27 import org.apache.mina.filter.codec.ProtocolEncoder;
28 import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
29 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
30 import org.apache.mina.util.CharsetUtil;
31
32
33
34
35
36
37
38
39 public class TextLineEncoder extends ProtocolEncoderAdapter {
40 private static final String ENCODER = TextLineEncoder.class.getName()
41 + ".encoder";
42
43 private final Charset charset;
44
45 private final LineDelimiter delimiter;
46
47 private int maxLineLength = Integer.MAX_VALUE;
48
49 public TextLineEncoder() {
50 this(CharsetUtil.getDefaultCharset(), LineDelimiter.UNIX);
51 }
52
53 public TextLineEncoder(LineDelimiter delimiter) {
54 this(CharsetUtil.getDefaultCharset(), delimiter);
55 }
56
57 public TextLineEncoder(Charset charset) {
58 this(charset, LineDelimiter.UNIX);
59 }
60
61 public TextLineEncoder(Charset charset, LineDelimiter delimiter) {
62 if (charset == null) {
63 throw new NullPointerException("charset");
64 }
65 if (delimiter == null) {
66 throw new NullPointerException("delimiter");
67 }
68 if (LineDelimiter.AUTO.equals(delimiter)) {
69 throw new IllegalArgumentException(
70 "AUTO delimiter is not allowed for encoder.");
71 }
72
73 this.charset = charset;
74 this.delimiter = delimiter;
75 }
76
77
78
79
80
81
82
83 public int getMaxLineLength() {
84 return maxLineLength;
85 }
86
87
88
89
90
91
92
93 public void setMaxLineLength(int maxLineLength) {
94 if (maxLineLength <= 0) {
95 throw new IllegalArgumentException("maxLineLength: "
96 + maxLineLength);
97 }
98
99 this.maxLineLength = maxLineLength;
100 }
101
102 public void encode(IoSession session, Object message,
103 ProtocolEncoderOutput out) throws Exception {
104 CharsetEncoder encoder = (CharsetEncoder) session.getAttribute(ENCODER);
105 if (encoder == null) {
106 encoder = charset.newEncoder();
107 session.setAttribute(ENCODER, encoder);
108 }
109
110 String value = message.toString();
111 ByteBuffer buf = ByteBuffer.allocate(value.length())
112 .setAutoExpand(true);
113 buf.putString(value, encoder);
114 if (buf.position() > maxLineLength) {
115 throw new IllegalArgumentException("Line length: " + buf.position());
116 }
117 buf.putString(delimiter.getValue(), encoder);
118 buf.flip();
119 out.write(buf);
120 }
121
122 public void dispose() throws Exception {
123 }
124 }