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