001/*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.filter;
020
021import java.io.IOException;
022import java.util.ArrayList;
023import java.util.Objects;
024
025import org.apache.hadoop.hbase.Cell;
026import org.apache.hadoop.hbase.CellUtil;
027import org.apache.hadoop.hbase.PrivateCellUtil;
028import org.apache.yetus.audience.InterfaceAudience;
029import org.apache.hadoop.hbase.exceptions.DeserializationException;
030import org.apache.hadoop.hbase.shaded.protobuf.generated.FilterProtos;
031import org.apache.hadoop.hbase.util.Bytes;
032
033import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
034import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
035import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
036
037/**
038 * A filter, based on the ColumnCountGetFilter, takes two arguments: limit and offset.
039 * This filter can be used for row-based indexing, where references to other tables are stored across many columns,
040 * in order to efficient lookups and paginated results for end users. Only most recent versions are considered
041 * for pagination.
042 */
043@InterfaceAudience.Public
044public class ColumnPaginationFilter extends FilterBase {
045
046  private int limit = 0;
047  private int offset = -1;
048  private byte[] columnOffset = null;
049  private int count = 0;
050
051  /**
052   * Initializes filter with an integer offset and limit. The offset is arrived at
053   * scanning sequentially and skipping entries. @limit number of columns are
054   * then retrieved. If multiple column families are involved, the columns may be spread
055   * across them.
056   *
057   * @param limit Max number of columns to return.
058   * @param offset The integer offset where to start pagination.
059   */
060  public ColumnPaginationFilter(final int limit, final int offset)
061  {
062    Preconditions.checkArgument(limit >= 0, "limit must be positive %s", limit);
063    Preconditions.checkArgument(offset >= 0, "offset must be positive %s", offset);
064    this.limit = limit;
065    this.offset = offset;
066  }
067
068  /**
069   * Initializes filter with a string/bookmark based offset and limit. The offset is arrived
070   * at, by seeking to it using scanner hints. If multiple column families are involved,
071   * pagination starts at the first column family which contains @columnOffset. Columns are
072   * then retrieved sequentially upto @limit number of columns which maybe spread across
073   * multiple column families, depending on how the scan is setup.
074   *
075   * @param limit Max number of columns to return.
076   * @param columnOffset The string/bookmark offset on where to start pagination.
077   */
078  public ColumnPaginationFilter(final int limit, final byte[] columnOffset) {
079    Preconditions.checkArgument(limit >= 0, "limit must be positive %s", limit);
080    Preconditions.checkArgument(columnOffset != null,
081                                "columnOffset must be non-null %s",
082                                columnOffset);
083    this.limit = limit;
084    this.columnOffset = columnOffset;
085  }
086
087  /**
088   * @return limit
089   */
090  public int getLimit() {
091    return limit;
092  }
093
094  /**
095   * @return offset
096   */
097  public int getOffset() {
098    return offset;
099  }
100
101  /**
102   * @return columnOffset
103   */
104  public byte[] getColumnOffset() {
105    return columnOffset;
106  }
107
108  @Override
109  public boolean filterRowKey(Cell cell) throws IOException {
110    // Impl in FilterBase might do unnecessary copy for Off heap backed Cells.
111    return false;
112  }
113
114  @Override
115  public ReturnCode filterCell(final Cell c)
116  {
117    if (columnOffset != null) {
118      if (count >= limit) {
119        return ReturnCode.NEXT_ROW;
120      }
121      int cmp = 0;
122      // Only compare if no KV's have been seen so far.
123      if (count == 0) {
124        cmp = CellUtil.compareQualifiers(c, this.columnOffset, 0, this.columnOffset.length);
125      }
126      if (cmp < 0) {
127        return ReturnCode.SEEK_NEXT_USING_HINT;
128      } else {
129        count++;
130        return ReturnCode.INCLUDE_AND_NEXT_COL;
131      }
132    } else {
133      if (count >= offset + limit) {
134        return ReturnCode.NEXT_ROW;
135      }
136
137      ReturnCode code = count < offset ? ReturnCode.NEXT_COL :
138                                         ReturnCode.INCLUDE_AND_NEXT_COL;
139      count++;
140      return code;
141    }
142  }
143
144  @Override
145  public Cell getNextCellHint(Cell cell) {
146    return PrivateCellUtil.createFirstOnRowCol(cell, columnOffset, 0, columnOffset.length);
147  }
148
149  @Override
150  public void reset()
151  {
152    this.count = 0;
153  }
154
155  public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
156    Preconditions.checkArgument(filterArguments.size() == 2,
157                                "Expected 2 but got: %s", filterArguments.size());
158    int limit = ParseFilter.convertByteArrayToInt(filterArguments.get(0));
159    int offset = ParseFilter.convertByteArrayToInt(filterArguments.get(1));
160    return new ColumnPaginationFilter(limit, offset);
161  }
162
163  /**
164   * @return The filter serialized using pb
165   */
166  @Override
167  public byte [] toByteArray() {
168    FilterProtos.ColumnPaginationFilter.Builder builder =
169      FilterProtos.ColumnPaginationFilter.newBuilder();
170    builder.setLimit(this.limit);
171    if (this.offset >= 0) {
172      builder.setOffset(this.offset);
173    }
174    if (this.columnOffset != null) {
175      builder.setColumnOffset(UnsafeByteOperations.unsafeWrap(this.columnOffset));
176    }
177    return builder.build().toByteArray();
178  }
179
180  /**
181   * @param pbBytes A pb serialized {@link ColumnPaginationFilter} instance
182   * @return An instance of {@link ColumnPaginationFilter} made from <code>bytes</code>
183   * @throws DeserializationException
184   * @see #toByteArray
185   */
186  public static ColumnPaginationFilter parseFrom(final byte [] pbBytes)
187  throws DeserializationException {
188    FilterProtos.ColumnPaginationFilter proto;
189    try {
190      proto = FilterProtos.ColumnPaginationFilter.parseFrom(pbBytes);
191    } catch (InvalidProtocolBufferException e) {
192      throw new DeserializationException(e);
193    }
194    if (proto.hasColumnOffset()) {
195      return new ColumnPaginationFilter(proto.getLimit(),
196                                        proto.getColumnOffset().toByteArray());
197    }
198    return new ColumnPaginationFilter(proto.getLimit(),proto.getOffset());
199  }
200
201  /**
202   * @param o the other filter to compare with
203   * @return true if and only if the fields of the filter that are serialized
204   * are equal to the corresponding fields in other.  Used for testing.
205   */
206  @Override
207  boolean areSerializedFieldsEqual(Filter o) {
208    if (o == this) return true;
209    if (!(o instanceof ColumnPaginationFilter)) return false;
210
211    ColumnPaginationFilter other = (ColumnPaginationFilter)o;
212    if (this.columnOffset != null) {
213      return this.getLimit() == other.getLimit() &&
214          Bytes.equals(this.getColumnOffset(), other.getColumnOffset());
215    }
216    return this.getLimit() == other.getLimit() && this.getOffset() == other.getOffset();
217  }
218
219  @Override
220  public String toString() {
221    if (this.columnOffset != null) {
222      return (this.getClass().getSimpleName() + "(" + this.limit + ", " +
223          Bytes.toStringBinary(this.columnOffset) + ")");
224    }
225    return String.format("%s (%d, %d)", this.getClass().getSimpleName(),
226        this.limit, this.offset);
227  }
228
229  @Override
230  public boolean equals(Object obj) {
231    return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
232  }
233
234  @Override
235  public int hashCode() {
236    return columnOffset == null ? Objects.hash(this.limit, this.offset) :
237      Objects.hash(this.limit, Bytes.hashCode(this.columnOffset));
238  }
239}