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, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.codec;
19  
20  import java.io.EOFException;
21  import java.io.IOException;
22  import java.io.InputStream;
23  
24  import org.apache.commons.logging.Log;
25  import org.apache.commons.logging.LogFactory;
26  import org.apache.hadoop.hbase.Cell;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  
29  /**
30   * TODO javadoc
31   */
32  @InterfaceAudience.Private
33  public abstract class BaseDecoder implements Codec.Decoder {
34    protected static final Log LOG = LogFactory.getLog(BaseDecoder.class);
35    protected final InputStream in;
36    private boolean hasNext = true;
37    private Cell current = null;
38  
39    public BaseDecoder(final InputStream in) {
40      this.in = in;
41    }
42  
43    @Override
44    public boolean advance() throws IOException {
45      if (!this.hasNext) return this.hasNext;
46      if (this.in.available() == 0) {
47        this.hasNext = false;
48        return this.hasNext;
49      }
50      try {
51        this.current = parseCell();
52      } catch (IOException ioEx) {
53        rethrowEofException(ioEx);
54      }
55      return this.hasNext;
56    }
57  
58    private void rethrowEofException(IOException ioEx) throws IOException {
59      boolean isEof = false;
60      try {
61        isEof = this.in.available() == 0;
62      } catch (Throwable t) {
63        LOG.trace("Error getting available for error message - ignoring", t);
64      }
65      if (!isEof) throw ioEx;
66      if (LOG.isTraceEnabled()) {
67        LOG.trace("Partial cell read caused by EOF", ioEx);
68      }
69      EOFException eofEx = new EOFException("Partial cell read");
70      eofEx.initCause(ioEx);
71      throw eofEx;
72    }
73  
74    /**
75     * @return extract a Cell
76     * @throws IOException
77     */
78    protected abstract Cell parseCell() throws IOException;
79  
80    @Override
81    public Cell current() {
82      return this.current;
83    }
84  }