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 java.io.IOException;
023import java.util.ArrayList;
024
025import org.apache.hadoop.hbase.ByteBufferExtendedCell;
026import org.apache.hadoop.hbase.Cell;
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.ByteBufferUtils;
032import org.apache.hadoop.hbase.util.Bytes;
033
034import org.apache.hbase.thirdparty.com.google.common.base.Preconditions;
035import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
036import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
037
038/**
039 * This filter is used for selecting only those keys with columns that matches
040 * a particular prefix. For example, if prefix is 'an', it will pass keys with
041 * columns like 'and', 'anti' but not keys with columns like 'ball', 'act'.
042 */
043@InterfaceAudience.Public
044public class ColumnPrefixFilter extends FilterBase {
045  protected byte [] prefix = null;
046
047  public ColumnPrefixFilter(final byte [] prefix) {
048    this.prefix = prefix;
049  }
050
051  public byte[] getPrefix() {
052    return prefix;
053  }
054
055  @Override
056  public boolean filterRowKey(Cell cell) throws IOException {
057    // Impl in FilterBase might do unnecessary copy for Off heap backed Cells.
058    return false;
059  }
060
061  @Override
062  public ReturnCode filterCell(final Cell cell) {
063    if (this.prefix == null) {
064      return ReturnCode.INCLUDE;
065    } else {
066      return filterColumn(cell);
067    }
068  }
069
070  public ReturnCode filterColumn(Cell cell) {
071    int qualifierLength = cell.getQualifierLength();
072    if (qualifierLength < prefix.length) {
073      int cmp = compareQualifierPart(cell, qualifierLength, this.prefix);
074      if (cmp <= 0) {
075        return ReturnCode.SEEK_NEXT_USING_HINT;
076      } else {
077        return ReturnCode.NEXT_ROW;
078      }
079    } else {
080      int cmp = compareQualifierPart(cell, this.prefix.length, this.prefix);
081      if (cmp < 0) {
082        return ReturnCode.SEEK_NEXT_USING_HINT;
083      } else if (cmp > 0) {
084        return ReturnCode.NEXT_ROW;
085      } else {
086        return ReturnCode.INCLUDE;
087      }
088    }
089  }
090
091  private static int compareQualifierPart(Cell cell, int length, byte[] prefix) {
092    if (cell instanceof ByteBufferExtendedCell) {
093      return ByteBufferUtils.compareTo(((ByteBufferExtendedCell) cell).getQualifierByteBuffer(),
094          ((ByteBufferExtendedCell) cell).getQualifierPosition(), length, prefix, 0, length);
095    }
096    return Bytes.compareTo(cell.getQualifierArray(), cell.getQualifierOffset(), length, prefix, 0,
097        length);
098  }
099
100  public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
101    Preconditions.checkArgument(filterArguments.size() == 1,
102                                "Expected 1 but got: %s", filterArguments.size());
103    byte [] columnPrefix = ParseFilter.removeQuotesFromByteArray(filterArguments.get(0));
104    return new ColumnPrefixFilter(columnPrefix);
105  }
106
107  /**
108   * @return The filter serialized using pb
109   */
110  @Override
111  public byte [] toByteArray() {
112    FilterProtos.ColumnPrefixFilter.Builder builder =
113      FilterProtos.ColumnPrefixFilter.newBuilder();
114    if (this.prefix != null) builder.setPrefix(UnsafeByteOperations.unsafeWrap(this.prefix));
115    return builder.build().toByteArray();
116  }
117
118  /**
119   * @param pbBytes A pb serialized {@link ColumnPrefixFilter} instance
120   * @return An instance of {@link ColumnPrefixFilter} made from <code>bytes</code>
121   * @throws org.apache.hadoop.hbase.exceptions.DeserializationException
122   * @see #toByteArray
123   */
124  public static ColumnPrefixFilter parseFrom(final byte [] pbBytes)
125  throws DeserializationException {
126    FilterProtos.ColumnPrefixFilter proto;
127    try {
128      proto = FilterProtos.ColumnPrefixFilter.parseFrom(pbBytes);
129    } catch (InvalidProtocolBufferException e) {
130      throw new DeserializationException(e);
131    }
132    return new ColumnPrefixFilter(proto.getPrefix().toByteArray());
133  }
134
135  /**
136   * @param o the other filter to compare with
137   * @return true if and only if the fields of the filter that are serialized
138   * are equal to the corresponding fields in other.  Used for testing.
139   */
140  @Override
141  boolean areSerializedFieldsEqual(Filter o) {
142   if (o == this) return true;
143   if (!(o instanceof ColumnPrefixFilter)) return false;
144
145   ColumnPrefixFilter other = (ColumnPrefixFilter)o;
146    return Bytes.equals(this.getPrefix(), other.getPrefix());
147  }
148
149  @Override
150  public Cell getNextCellHint(Cell cell) {
151    return PrivateCellUtil.createFirstOnRowCol(cell, prefix, 0, prefix.length);
152  }
153
154  @Override
155  public String toString() {
156    return this.getClass().getSimpleName() + " " + Bytes.toStringBinary(this.prefix);
157  }
158
159  @Override
160  public boolean equals(Object obj) {
161    return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
162  }
163
164  @Override
165  public int hashCode() {
166    return Bytes.hashCode(this.getPrefix());
167  }
168}