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.Comparator;
023import java.util.Objects;
024import java.util.TreeSet;
025
026import org.apache.hadoop.hbase.Cell;
027import org.apache.hadoop.hbase.CellUtil;
028import org.apache.hadoop.hbase.PrivateCellUtil;
029import org.apache.yetus.audience.InterfaceAudience;
030import org.apache.hadoop.hbase.exceptions.DeserializationException;
031import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
032import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
033import org.apache.hadoop.hbase.shaded.protobuf.generated.FilterProtos;
034import org.apache.hadoop.hbase.util.Bytes;
035
036/**
037 * This filter is used for selecting only those keys with columns that matches
038 * a particular prefix. For example, if prefix is 'an', it will pass keys will
039 * columns like 'and', 'anti' but not keys with columns like 'ball', 'act'.
040 */
041@InterfaceAudience.Public
042public class MultipleColumnPrefixFilter extends FilterBase {
043  protected byte [] hint = null;
044  protected TreeSet<byte []> sortedPrefixes = createTreeSet();
045  private final static int MAX_LOG_PREFIXES = 5;
046
047  public MultipleColumnPrefixFilter(final byte [][] prefixes) {
048    if (prefixes != null) {
049      for (int i = 0; i < prefixes.length; i++) {
050        if (!sortedPrefixes.add(prefixes[i]))
051          throw new IllegalArgumentException ("prefixes must be distinct");
052      }
053    }
054  }
055
056  public byte [][] getPrefix() {
057    int count = 0;
058    byte [][] temp = new byte [sortedPrefixes.size()][];
059    for (byte [] prefixes : sortedPrefixes) {
060      temp [count++] = prefixes;
061    }
062    return temp;
063  }
064
065  @Override
066  public boolean filterRowKey(Cell cell) throws IOException {
067    // Impl in FilterBase might do unnecessary copy for Off heap backed Cells.
068    return false;
069  }
070
071  @Override
072  public ReturnCode filterCell(final Cell c) {
073    if (sortedPrefixes.isEmpty()) {
074      return ReturnCode.INCLUDE;
075    } else {
076      return filterColumn(c);
077    }
078  }
079
080  public ReturnCode filterColumn(Cell cell) {
081    byte [] qualifier = CellUtil.cloneQualifier(cell);
082    TreeSet<byte []> lesserOrEqualPrefixes =
083      (TreeSet<byte []>) sortedPrefixes.headSet(qualifier, true);
084
085    if (lesserOrEqualPrefixes.size() != 0) {
086      byte [] largestPrefixSmallerThanQualifier = lesserOrEqualPrefixes.last();
087      
088      if (Bytes.startsWith(qualifier, largestPrefixSmallerThanQualifier)) {
089        return ReturnCode.INCLUDE;
090      }
091      
092      if (lesserOrEqualPrefixes.size() == sortedPrefixes.size()) {
093        return ReturnCode.NEXT_ROW;
094      } else {
095        hint = sortedPrefixes.higher(largestPrefixSmallerThanQualifier);
096        return ReturnCode.SEEK_NEXT_USING_HINT;
097      }
098    } else {
099      hint = sortedPrefixes.first();
100      return ReturnCode.SEEK_NEXT_USING_HINT;
101    }
102  }
103
104  public static Filter createFilterFromArguments(ArrayList<byte []> filterArguments) {
105    byte [][] prefixes = new byte [filterArguments.size()][];
106    for (int i = 0 ; i < filterArguments.size(); i++) {
107      byte [] columnPrefix = ParseFilter.removeQuotesFromByteArray(filterArguments.get(i));
108      prefixes[i] = columnPrefix;
109    }
110    return new MultipleColumnPrefixFilter(prefixes);
111  }
112
113  /**
114   * @return The filter serialized using pb
115   */
116  @Override
117  public byte [] toByteArray() {
118    FilterProtos.MultipleColumnPrefixFilter.Builder builder =
119      FilterProtos.MultipleColumnPrefixFilter.newBuilder();
120    for (byte [] element : sortedPrefixes) {
121      if (element != null) builder.addSortedPrefixes(UnsafeByteOperations.unsafeWrap(element));
122    }
123    return builder.build().toByteArray();
124  }
125
126  /**
127   * @param pbBytes A pb serialized {@link MultipleColumnPrefixFilter} instance
128   * @return An instance of {@link MultipleColumnPrefixFilter} made from <code>bytes</code>
129   * @throws DeserializationException
130   * @see #toByteArray
131   */
132  public static MultipleColumnPrefixFilter parseFrom(final byte [] pbBytes)
133  throws DeserializationException {
134    FilterProtos.MultipleColumnPrefixFilter proto;
135    try {
136      proto = FilterProtos.MultipleColumnPrefixFilter.parseFrom(pbBytes);
137    } catch (InvalidProtocolBufferException e) {
138      throw new DeserializationException(e);
139    }
140    int numPrefixes = proto.getSortedPrefixesCount();
141    byte [][] prefixes = new byte[numPrefixes][];
142    for (int i = 0; i < numPrefixes; ++i) {
143      prefixes[i] = proto.getSortedPrefixes(i).toByteArray();
144    }
145
146    return new MultipleColumnPrefixFilter(prefixes);
147  }
148
149  /**
150   * @param o the other filter to compare with
151   * @return true if and only if the fields of the filter that are serialized
152   * are equal to the corresponding fields in other.  Used for testing.
153   */
154  @Override
155  boolean areSerializedFieldsEqual(Filter o) {
156    if (o == this) return true;
157    if (!(o instanceof MultipleColumnPrefixFilter)) return false;
158
159    MultipleColumnPrefixFilter other = (MultipleColumnPrefixFilter)o;
160    return this.sortedPrefixes.equals(other.sortedPrefixes);
161  }
162
163  @Override
164  public Cell getNextCellHint(Cell cell) {
165    return PrivateCellUtil.createFirstOnRowCol(cell, hint, 0, hint.length);
166  }
167
168  public TreeSet<byte []> createTreeSet() {
169    return new TreeSet<>(new Comparator<Object>() {
170        @Override
171          public int compare (Object o1, Object o2) {
172          if (o1 == null || o2 == null)
173            throw new IllegalArgumentException ("prefixes can't be null");
174
175          byte [] b1 = (byte []) o1;
176          byte [] b2 = (byte []) o2;
177          return Bytes.compareTo (b1, 0, b1.length, b2, 0, b2.length);
178        }
179      });
180  }
181
182  @Override
183  public String toString() {
184    return toString(MAX_LOG_PREFIXES);
185  }
186
187  protected String toString(int maxPrefixes) {
188    StringBuilder prefixes = new StringBuilder();
189
190    int count = 0;
191    for (byte[] ba : this.sortedPrefixes) {
192      if (count >= maxPrefixes) {
193        break;
194      }
195      ++count;
196      prefixes.append(Bytes.toStringBinary(ba));
197      if (count < this.sortedPrefixes.size() && count < maxPrefixes) {
198        prefixes.append(", ");
199      }
200    }
201
202    return String.format("%s (%d/%d): [%s]", this.getClass().getSimpleName(),
203        count, this.sortedPrefixes.size(), prefixes.toString());
204  }
205
206  @Override
207  public boolean equals(Object obj) {
208    return obj instanceof Filter && areSerializedFieldsEqual((Filter) obj);
209  }
210
211  @Override
212  public int hashCode() {
213    return Objects.hash(this.sortedPrefixes);
214  }
215}