1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
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.ProtocolDecoderException;
24 import org.apache.mina.filter.codec.ProtocolDecoderOutput;
25
26 /**
27 * @author The Apache MINA Project (dev@mina.apache.org)
28 * @version $Rev: 601994 $, $Date: 2007-12-06 21:58:00 -0700 (Thu, 06 Dec 2007) $
29 */
30 public abstract class IntegerDecodingState implements DecodingState {
31
32 private int firstByte;
33 private int secondByte;
34 private int thirdByte;
35 private int counter;
36
37 public IntegerDecodingState() {
38 }
39
40 public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out)
41 throws Exception {
42 while (in.hasRemaining()) {
43 switch (counter) {
44 case 0:
45 firstByte = in.getUnsigned();
46 break;
47 case 1:
48 secondByte = in.getUnsigned();
49 break;
50 case 2:
51 thirdByte = in.getUnsigned();
52 break;
53 case 3:
54 counter = 0;
55 return finishDecode(
56 (firstByte << 24) | (secondByte << 16) | (thirdByte << 8) | in.getUnsigned(),
57 out);
58 default:
59 throw new InternalError();
60 }
61 counter ++;
62 }
63
64 return this;
65 }
66
67 public DecodingState finishDecode(ProtocolDecoderOutput out)
68 throws Exception {
69 throw new ProtocolDecoderException(
70 "Unexpected end of session while waiting for an integer.");
71 }
72
73 protected abstract DecodingState finishDecode(int value,
74 ProtocolDecoderOutput out) throws Exception;
75 }