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