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 */
019
020package org.apache.hadoop.hbase.filter;
021
022import static org.apache.hadoop.hbase.util.Bytes.len;
023
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.Objects;
027
028import org.apache.hadoop.hbase.Cell;
029import org.apache.hadoop.hbase.CellUtil;
030import org.apache.hadoop.hbase.PrivateCellUtil;
031import org.apache.yetus.audience.InterfaceAudience;
032import org.apache.hadoop.hbase.exceptions.DeserializationException;
033import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
034import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
035import org.apache.hadoop.hbase.shaded.protobuf.generated.FilterProtos;
036import org.apache.hadoop.hbase.util.Bytes;
037
038import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
039
040/**
041 * This filter is used for selecting only those keys with columns that are
042 * between minColumn to maxColumn. For example, if minColumn is 'an', and
043 * maxColumn is 'be', it will pass keys with columns like 'ana', 'bad', but not
044 * keys with columns like 'bed', 'eye'
045 *
046 * If minColumn is null, there is no lower bound. If maxColumn is null, there is
047 * no upper bound.
048 *
049 * minColumnInclusive and maxColumnInclusive specify if the ranges are inclusive
050 * or not.
051 */
052@InterfaceAudience.Public
053public class ColumnRangeFilter extends FilterBase {
054  protected byte[] minColumn = null;
055  protected boolean minColumnInclusive = true;
056  protected byte[] maxColumn = null;
057  protected boolean maxColumnInclusive = false;
058
059  /**
060   * Create a filter to select those keys with columns that are between minColumn
061   * and maxColumn.
062   * @param minColumn minimum value for the column range. If if it's null,
063   * there is no lower bound.
064   * @param minColumnInclusive if true, include minColumn in the range.
065   * @param maxColumn maximum value for the column range. If it's null,
066   * @param maxColumnInclusive if true, include maxColumn in the range.
067   * there is no upper bound.
068   */
069  public ColumnRangeFilter(final byte[] minColumn, boolean minColumnInclusive,
070      final byte[] maxColumn, boolean maxColumnInclusive) {
071    this.minColumn = minColumn;
072    this.minColumnInclusive = minColumnInclusive;
073    this.maxColumn = maxColumn;
074    this.maxColumnInclusive = maxColumnInclusive;
075  }
076
077  /**
078   * @return if min column range is inclusive.
079   */
080  public boolean isMinColumnInclusive() {
081    return minColumnInclusive;
082  }
083
084  /**
085   * @return if max column range is inclusive.
086   */
087  public boolean isMaxColumnInclusive() {
088    return maxColumnInclusive;
089  }
090
091  /**
092   * @return the min column range for the filter
093   */
094  public byte[] getMinColumn() {
095    return this.minColumn;
096  }
097
098  /**
099   * @return true if min column is inclusive, false otherwise
100   */
101  public boolean getMinColumnInclusive() {
102    return this.minColumnInclusive;
103  }
104
105  /**
106   * @return the max column range for the filter
107   */
108  public byte[] getMaxColumn() {
109    return this.maxColumn;
110  }
111
112  /**
113   * @return true if max column is inclusive, false otherwise
114   */
115  public boolean getMaxColumnInclusive() {
116    return this.maxColumnInclusive;
117  }
118
119  @Override
120  public boolean filterRowKey(Cell cell) throws IOException {
121    // Impl in FilterBase might do unnecessary copy for Off heap backed Cells.
122    return false;
123  }
124
125  @Override
126  public ReturnCode filterCell(final Cell c) {
127    int cmpMin = 1;
128
129    if (this.minColumn != null) {
130      cmpMin = CellUtil.compareQualifiers(c, this.minColumn, 0, this.minColumn.length);
131    }
132
133    if (cmpMin < 0) {
134      return ReturnCode.SEEK_NEXT_USING_HINT;
135    }
136
137    if (!this.minColumnInclusive && cmpMin == 0) {
138      return ReturnCode.NEXT_COL;
139    }
140
141    if (this.maxColumn == null) {
142      return ReturnCode.INCLUDE;
143    }
144
145    int cmpMax = CellUtil.compareQualifiers(c, this.maxColumn, 0, this.maxColumn.length);
146
147    if ((this.maxColumnInclusive && cmpMax <= 0) || (!this.maxColumnInclusive && cmpMax < 0)) {
148      return ReturnCode.INCLUDE;
149    }
150
151    return ReturnCode.NEXT_ROW;
152  }
153
154  public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
155    Preconditions.checkArgument(filterArguments.size() == 4,
156                                "Expected 4 but got: %s", filterArguments.size());
157    byte [] minColumn = ParseFilter.removeQuotesFromByteArray(filterArguments.get(0));
158    boolean minColumnInclusive = ParseFilter.convertByteArrayToBoolean(filterArguments.get(1));
159    byte [] maxColumn = ParseFilter.removeQuotesFromByteArray(filterArguments.get(2));
160    boolean maxColumnInclusive = ParseFilter.convertByteArrayToBoolean(filterArguments.get(3));
161
162    if (minColumn.length == 0)
163      minColumn = null;
164    if (maxColumn.length == 0)
165      maxColumn = null;
166    return new ColumnRangeFilter(minColumn, minColumnInclusive,
167                                 maxColumn, maxColumnInclusive);
168  }
169
170  /**
171   * @return The filter serialized using pb
172   */
173  @Override
174  public byte [] toByteArray() {
175    FilterProtos.ColumnRangeFilter.Builder builder =
176      FilterProtos.ColumnRangeFilter.newBuilder();
177    if (this.minColumn != null) builder.setMinColumn(
178        UnsafeByteOperations.unsafeWrap(this.minColumn));
179    builder.setMinColumnInclusive(this.minColumnInclusive);
180    if (this.maxColumn != null) builder.setMaxColumn(
181        UnsafeByteOperations.unsafeWrap(this.maxColumn));
182    builder.setMaxColumnInclusive(this.maxColumnInclusive);
183    return builder.build().toByteArray();
184  }
185
186  /**
187   * @param pbBytes A pb serialized {@link ColumnRangeFilter} instance
188   * @return An instance of {@link ColumnRangeFilter} made from <code>bytes</code>
189   * @throws DeserializationException
190   * @see #toByteArray
191   */
192  public static ColumnRangeFilter parseFrom(final byte [] pbBytes)
193  throws DeserializationException {
194    FilterProtos.ColumnRangeFilter proto;
195    try {
196      proto = FilterProtos.ColumnRangeFilter.parseFrom(pbBytes);
197    } catch (InvalidProtocolBufferException e) {
198      throw new DeserializationException(e);
199    }
200    return new ColumnRangeFilter(proto.hasMinColumn()?proto.getMinColumn().toByteArray():null,
201      proto.getMinColumnInclusive(),proto.hasMaxColumn()?proto.getMaxColumn().toByteArray():null,
202      proto.getMaxColumnInclusive());
203  }
204
205  /**
206   * @param o filter to serialize.
207   * @return true if and only if the fields of the filter that are serialized are equal to the
208   *         corresponding fields in other. Used for testing.
209   */
210  @Override
211  boolean areSerializedFieldsEqual(Filter o) {
212    if (o == this) {
213      return true;
214    }
215    if (!(o instanceof ColumnRangeFilter)) {
216      return false;
217    }
218    ColumnRangeFilter other = (ColumnRangeFilter) o;
219    return Bytes.equals(this.getMinColumn(), other.getMinColumn())
220        && this.getMinColumnInclusive() == other.getMinColumnInclusive()
221        && Bytes.equals(this.getMaxColumn(), other.getMaxColumn())
222        && this.getMaxColumnInclusive() == other.getMaxColumnInclusive();
223  }
224
225  @Override
226  public Cell getNextCellHint(Cell cell) {
227    return PrivateCellUtil.createFirstOnRowCol(cell, this.minColumn, 0, len(this.minColumn));
228  }
229
230  @Override
231  public String toString() {
232    return this.getClass().getSimpleName() + " "
233        + (this.minColumnInclusive ? "[" : "(") + Bytes.toStringBinary(this.minColumn)
234        + ", " + Bytes.toStringBinary(this.maxColumn)
235        + (this.maxColumnInclusive ? "]" : ")");
236  }
237
238  @Override
239  public boolean equals(Object obj) {
240    return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
241  }
242
243  @Override
244  public int hashCode() {
245    return Objects.hash(Bytes.hashCode(getMinColumn()), getMinColumnInclusive(),
246      Bytes.hashCode(getMaxColumn()), getMaxColumnInclusive());
247  }
248}