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.KeyValue;
27  
28  public abstract class BaseDecoder implements Decoder {
29    protected static final Log LOG = LogFactory.getLog(BaseDecoder.class);
30    protected final InputStream in;
31    private boolean hasNext = true;
32    protected KeyValue current = null;
33  
34    public BaseDecoder(final InputStream in) {
35      this.in = in;
36    }
37  
38    @Override
39    public boolean advance() throws IOException {
40      if (!this.hasNext) return this.hasNext;
41      if (this.in.available() == 0) {
42        this.hasNext = false;
43        return this.hasNext;
44      }
45      try {
46        this.current = parseCell();
47      } catch (IOException ioEx) {
48        rethrowEofException(ioEx);
49      }
50      return this.hasNext;
51    }
52  
53    private void rethrowEofException(IOException ioEx) throws IOException {
54      boolean isEof = false;
55      try {
56        isEof = this.in.available() == 0;
57      } catch (Throwable t) {
58        LOG.trace("Error getting available for error message - ignoring", t);
59      }
60      if (!isEof) throw ioEx;
61      LOG.error("Partial cell read caused by EOF: " + ioEx);
62      EOFException eofEx = new EOFException("Partial cell read");
63      eofEx.initCause(ioEx);
64      throw eofEx;
65    }
66  
67    /**
68     * @return extract a Cell
69     * @throws IOException
70     */
71    protected abstract KeyValue parseCell() throws IOException;
72  
73    @Override
74    public KeyValue current() {
75      return this.current;
76    }
77  }