View Javadoc

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.ProtocolDecoderOutput;
24  
25  /**
26   * Skips data until {@link #canSkip(byte)} returns <tt>false</tt>.
27   *
28   * @author The Apache MINA Project (dev@mina.apache.org)
29   * @version $Rev: 601994 $, $Date: 2007-12-06 21:58:00 -0700 (Thu, 06 Dec 2007) $
30   */
31  public abstract class SkippingState implements DecodingState {
32  
33      private int skippedBytes;
34  
35      /**
36       * Creates a new instance.
37       */
38      public SkippingState() {
39      }
40  
41      public DecodingState decode(IoBuffer in, ProtocolDecoderOutput out)
42              throws Exception {
43          int beginPos = in.position();
44          int limit = in.limit();
45          for (int i = beginPos; i < limit; i++) {
46              byte b = in.get(i);
47              if (!canSkip(b)) {
48                  in.position(i);
49                  int answer = this.skippedBytes;
50                  this.skippedBytes = 0;
51                  return finishDecode(answer);
52              } else {
53                  skippedBytes++;
54              }
55          }
56  
57          in.position(limit);
58          return this;
59      }
60  
61      public DecodingState finishDecode(ProtocolDecoderOutput out)
62              throws Exception {
63          return finishDecode(skippedBytes);
64      }
65  
66      protected abstract boolean canSkip(byte b);
67  
68      protected abstract DecodingState finishDecode(int skippedBytes)
69              throws Exception;
70  }