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