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 ConsumeToTerminatorDecodingState implements DecodingState {
32
33 private final byte terminator;
34
35 private IoBuffer buffer;
36
37
38
39
40
41
42 public ConsumeToTerminatorDecodingState(byte terminator) {
43 this.terminator = terminator;
44 }
45
46
47
48
49 public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out) throws Exception {
50 int terminatorPos = in.indexOf(terminator);
51
52 if (terminatorPos >= 0) {
53 int limit = in.limit();
54 IoBuffer product;
55
56 if (in.position() < terminatorPos) {
57 in.limit(terminatorPos);
58
59 if (buffer == null) {
60 product = in.slice();
61 } else {
62 buffer.put(in);
63 product = buffer.flip();
64 buffer = null;
65 }
66
67 in.limit(limit);
68 } else {
69
70 if (buffer == null) {
71 product = IoBuffer.allocate(0);
72 } else {
73 product = buffer.flip();
74 buffer = null;
75 }
76 }
77 in.position(terminatorPos + 1);
78 return finishDecode(product, out);
79 }
80
81 if (buffer == null) {
82 buffer = IoBuffer.allocate(in.remaining());
83 buffer.setAutoExpand(true);
84 }
85
86 buffer.put(in);
87 return this;
88 }
89
90
91
92
93 public DecodingState finishDecode(ProtocolDecoderOutput out) throws Exception {
94 IoBuffer product;
95
96 if (buffer == null) {
97 product = IoBuffer.allocate(0);
98 } else {
99 product = buffer.flip();
100 buffer = null;
101 }
102 return finishDecode(product, out);
103 }
104
105
106
107
108
109
110
111
112
113
114
115
116 protected abstract DecodingState finishDecode(IoBuffer product, ProtocolDecoderOutput out) throws Exception;
117 }