1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.codec.textline;
21
22 import java.nio.ByteBuffer;
23 import java.nio.CharBuffer;
24 import java.nio.charset.CharacterCodingException;
25 import java.nio.charset.Charset;
26 import java.nio.charset.CharsetEncoder;
27
28 import org.apache.mina.codec.ProtocolEncoder;
29 import org.apache.mina.codec.StatelessProtocolEncoder;
30
31
32
33
34
35
36
37 public class TextLineEncoder implements StatelessProtocolEncoder<String, ByteBuffer> {
38 private final CharsetEncoder charsetEncoder;
39
40 private final LineDelimiter delimiter;
41
42 private int maxLineLength = Integer.MAX_VALUE;
43
44
45
46
47
48 public TextLineEncoder() {
49 this(Charset.defaultCharset(), LineDelimiter.UNIX);
50 }
51
52
53
54
55
56 public TextLineEncoder(String delimiter) {
57 this(new LineDelimiter(delimiter));
58 }
59
60
61
62
63
64 public TextLineEncoder(LineDelimiter delimiter) {
65 this(Charset.defaultCharset(), delimiter);
66 }
67
68
69
70
71
72 public TextLineEncoder(Charset charset) {
73 this(charset, LineDelimiter.UNIX);
74 }
75
76
77
78
79
80 public TextLineEncoder(Charset charset, String delimiter) {
81 this(charset, new LineDelimiter(delimiter));
82 }
83
84
85
86
87
88 public TextLineEncoder(Charset charset, LineDelimiter delimiter) {
89 if (charset == null) {
90 throw new IllegalArgumentException("charset");
91 }
92 if (delimiter == null) {
93 throw new IllegalArgumentException("delimiter");
94 }
95 if (LineDelimiter.AUTO.equals(delimiter)) {
96 throw new IllegalArgumentException("AUTO delimiter is not allowed for encoder.");
97 }
98
99 this.charsetEncoder = charset.newEncoder();
100 this.delimiter = delimiter;
101 }
102
103
104
105
106
107
108
109 public int getMaxLineLength() {
110 return maxLineLength;
111 }
112
113
114
115
116
117
118
119 public void setMaxLineLength(int maxLineLength) {
120 if (maxLineLength <= 0) {
121 throw new IllegalArgumentException("maxLineLength: " + maxLineLength);
122 }
123
124 this.maxLineLength = maxLineLength;
125 }
126
127 @Override
128 public Void createEncoderState() {
129 return null;
130 }
131
132 @Override
133 public ByteBuffer encode(String message, Void context) {
134 try {
135 String value = (message == null ? "" : message);
136
137 if (value.length() > maxLineLength) {
138 throw new IllegalArgumentException("Line length: " + message.length());
139 }
140 return charsetEncoder.encode(CharBuffer.wrap(value + delimiter.getValue()));
141 } catch (CharacterCodingException e) {
142 throw new RuntimeException(e);
143 }
144 }
145
146 }