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.common.IoBuffer;
23 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
24
25
26
27
28
29
30
31
32
33
34 public abstract class FixedLengthDecodingState implements DecodingState {
35
36 private final int length;
37
38 private IoBuffer buffer;
39
40
41
42
43
44
45 public FixedLengthDecodingState(int length) {
46 this.length = length;
47 }
48
49 public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out)
50 throws Exception {
51 if (buffer == null) {
52 if (in.remaining() >= length) {
53 int limit = in.limit();
54 in.limit(in.position() + length);
55 IoBuffer product = in.slice();
56 in.position(in.position() + length);
57 in.limit(limit);
58 return finishDecode(product, out);
59 } else {
60 buffer = IoBuffer.allocate(length);
61 buffer.put(in);
62 return this;
63 }
64 } else {
65 if (in.remaining() >= length - buffer.position()) {
66 int limit = in.limit();
67 in.limit(in.position() + length - buffer.position());
68 buffer.put(in);
69 in.limit(limit);
70 IoBuffer product = this.buffer;
71 this.buffer = null;
72 return finishDecode(product.flip(), out);
73 } else {
74 buffer.put(in);
75 return this;
76 }
77 }
78 }
79
80 public DecodingState finishDecode(ProtocolDecoderOutput out)
81 throws Exception {
82 IoBuffer readData;
83 if (buffer == null) {
84 readData = IoBuffer.allocate(0);
85 } else {
86 readData = buffer.flip();
87 buffer = null;
88 }
89 return finishDecode(readData ,out);
90 }
91
92 protected abstract DecodingState finishDecode(IoBuffer readData,
93 ProtocolDecoderOutput out) throws Exception;
94 }