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.prefixedstring;
21
22 import org.apache.mina.core.buffer.BufferDataException;
23 import org.apache.mina.core.buffer.IoBuffer;
24 import org.apache.mina.core.session.IoSession;
25 import org.apache.mina.filter.codec.CumulativeProtocolDecoder;
26 import org.apache.mina.filter.codec.ProtocolDecoder;
27 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
28
29 import java.nio.charset.Charset;
30
31
32
33
34
35
36
37 public class PrefixedStringDecoder extends CumulativeProtocolDecoder {
38
39 public final static int DEFAULT_PREFIX_LENGTH = 4;
40
41 public final static int DEFAULT_MAX_DATA_LENGTH = 2048;
42
43 private final Charset charset;
44
45 private int prefixLength = DEFAULT_PREFIX_LENGTH;
46
47 private int maxDataLength = DEFAULT_MAX_DATA_LENGTH;
48
49
50
51
52
53
54 public PrefixedStringDecoder(Charset charset, int prefixLength, int maxDataLength) {
55 this.charset = charset;
56 this.prefixLength = prefixLength;
57 this.maxDataLength = maxDataLength;
58 }
59
60 public PrefixedStringDecoder(Charset charset, int prefixLength) {
61 this(charset, prefixLength, DEFAULT_MAX_DATA_LENGTH);
62 }
63
64 public PrefixedStringDecoder(Charset charset) {
65 this(charset, DEFAULT_PREFIX_LENGTH);
66 }
67
68
69
70
71
72
73 public void setPrefixLength(int prefixLength) {
74 this.prefixLength = prefixLength;
75 }
76
77
78
79
80
81
82 public int getPrefixLength() {
83 return prefixLength;
84 }
85
86
87
88
89
90
91
92
93
94
95
96
97 public void setMaxDataLength(int maxDataLength) {
98 this.maxDataLength = maxDataLength;
99 }
100
101
102
103
104
105
106 public int getMaxDataLength() {
107 return maxDataLength;
108 }
109
110 protected boolean doDecode(IoSession session, IoBuffer in, ProtocolDecoderOutput out) throws Exception {
111 if (in.prefixedDataAvailable(prefixLength, maxDataLength)) {
112 String msg = in.getPrefixedString(prefixLength, charset.newDecoder());
113 out.write(msg);
114 return true;
115 } else {
116 return false;
117 }
118 }
119 }