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.statemachine;
21
22 import org.apache.mina.core.buffer.IoBuffer;
23 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
24
25
26
27
28
29
30
31 public abstract class ConsumeToCrLfDecodingState implements DecodingState {
32
33
34
35
36 private static final byte CR = 13;
37
38
39
40
41 private static final byte LF = 10;
42
43 private boolean lastIsCR;
44
45 private IoBuffer buffer;
46
47
48
49
50 public ConsumeToCrLfDecodingState() {
51
52 }
53
54 public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out)
55 throws Exception {
56 int beginPos = in.position();
57 int limit = in.limit();
58 int terminatorPos = -1;
59
60 for (int i = beginPos; i < limit; i++) {
61 byte b = in.get(i);
62 if (b == CR) {
63 lastIsCR = true;
64 } else {
65 if (b == LF && lastIsCR) {
66 terminatorPos = i;
67 break;
68 }
69 lastIsCR = false;
70 }
71 }
72
73 if (terminatorPos >= 0) {
74 IoBuffer product;
75
76 int endPos = terminatorPos - 1;
77
78 if (beginPos < endPos) {
79 in.limit(endPos);
80
81 if (buffer == null) {
82 product = in.slice();
83 } else {
84 buffer.put(in);
85 product = buffer.flip();
86 buffer = null;
87 }
88
89 in.limit(limit);
90 } else {
91
92 if (buffer == null) {
93 product = IoBuffer.allocate(0);
94 } else {
95 product = buffer.flip();
96 buffer = null;
97 }
98 }
99 in.position(terminatorPos + 1);
100 return finishDecode(product, out);
101 }
102
103 in.position(beginPos);
104
105 if (buffer == null) {
106 buffer = IoBuffer.allocate(in.remaining());
107 buffer.setAutoExpand(true);
108 }
109
110 buffer.put(in);
111
112 if (lastIsCR) {
113 buffer.position(buffer.position() - 1);
114 }
115
116 return this;
117 }
118
119
120
121
122 public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception {
123 IoBuffer product;
124
125 if (buffer == null) {
126 product = IoBuffer.allocate(0);
127 } else {
128 product = buffer.flip();
129 buffer = null;
130 }
131 return finishDecode(product, out);
132 }
133
134
135
136
137
138
139
140
141
142
143
144
145 protected abstract DecodingState finishDecode(IoBuffer product,
146 ProtocolDecoderOutput out) throws Exception;
147 }