View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.filter;
20  
21  import com.google.protobuf.InvalidProtocolBufferException;
22  
23  import java.nio.charset.Charset;
24  import java.nio.charset.IllegalCharsetNameException;
25  import java.util.Arrays;
26  import java.util.regex.Pattern;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.hbase.classification.InterfaceStability;
32  import org.apache.hadoop.hbase.exceptions.DeserializationException;
33  import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
34  import org.apache.hadoop.hbase.util.Bytes;
35  
36  import org.jcodings.Encoding;
37  import org.jcodings.EncodingDB;
38  import org.jcodings.specific.UTF8Encoding;
39  import org.joni.Matcher;
40  import org.joni.Option;
41  import org.joni.Regex;
42  import org.joni.Syntax;
43  
44  /**
45   * This comparator is for use with {@link CompareFilter} implementations, such
46   * as {@link RowFilter}, {@link QualifierFilter}, and {@link ValueFilter}, for
47   * filtering based on the value of a given column. Use it to test if a given
48   * regular expression matches a cell value in the column.
49   * <p>
50   * Only EQUAL or NOT_EQUAL comparisons are valid with this comparator.
51   * <p>
52   * For example:
53   * <p>
54   * <pre>
55   * ValueFilter vf = new ValueFilter(CompareOp.EQUAL,
56   *     new RegexStringComparator(
57   *       // v4 IP address
58   *       "(((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3,3}" +
59   *         "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))(\\/[0-9]+)?" +
60   *         "|" +
61   *       // v6 IP address
62   *       "((([\\dA-Fa-f]{1,4}:){7}[\\dA-Fa-f]{1,4})(:([\\d]{1,3}.)" +
63   *         "{3}[\\d]{1,3})?)(\\/[0-9]+)?"));
64   * </pre>
65   * <p>
66   * Supports {@link java.util.regex.Pattern} flags as well:
67   * <p>
68   * <pre>
69   * ValueFilter vf = new ValueFilter(CompareOp.EQUAL,
70   *     new RegexStringComparator("regex", Pattern.CASE_INSENSITIVE | Pattern.DOTALL));
71   * </pre>
72   * @see java.util.regex.Pattern
73   */
74  @InterfaceAudience.Public
75  @InterfaceStability.Stable
76  public class RegexStringComparator extends ByteArrayComparable {
77  
78    private static final Log LOG = LogFactory.getLog(RegexStringComparator.class);
79  
80    private Engine engine;
81  
82    /** Engine implementation type (default=JAVA) */
83    @InterfaceAudience.Public
84    @InterfaceStability.Stable
85    public enum EngineType {
86      JAVA,
87      JONI
88    }
89  
90    /**
91     * Constructor
92     * Adds Pattern.DOTALL to the underlying Pattern
93     * @param expr a valid regular expression
94     */
95    public RegexStringComparator(String expr) {
96      this(expr, Pattern.DOTALL);
97    }
98  
99    /**
100    * Constructor
101    * Adds Pattern.DOTALL to the underlying Pattern
102    * @param expr a valid regular expression
103    * @param engine engine implementation type
104    */
105   public RegexStringComparator(String expr, EngineType engine) {
106     this(expr, Pattern.DOTALL, engine);
107   }
108 
109   /**
110    * Constructor
111    * @param expr a valid regular expression
112    * @param flags java.util.regex.Pattern flags
113    */
114   public RegexStringComparator(String expr, int flags) {
115     this(expr, flags, EngineType.JAVA);
116   }
117 
118   /**
119    * Constructor
120    * @param expr a valid regular expression
121    * @param flags java.util.regex.Pattern flags
122    * @param engine engine implementation type
123    */
124   public RegexStringComparator(String expr, int flags, EngineType engine) {
125     super(Bytes.toBytes(expr));
126     switch (engine) {
127       case JAVA:
128         this.engine = new JavaRegexEngine(expr, flags);
129         break;
130       case JONI:
131         this.engine = new JoniRegexEngine(expr, flags);
132         break;
133     }
134   }
135 
136   /**
137    * Specifies the {@link Charset} to use to convert the row key to a String.
138    * <p>
139    * The row key needs to be converted to a String in order to be matched
140    * against the regular expression.  This method controls which charset is
141    * used to do this conversion.
142    * <p>
143    * If the row key is made of arbitrary bytes, the charset {@code ISO-8859-1}
144    * is recommended.
145    * @param charset The charset to use.
146    */
147   public void setCharset(final Charset charset) {
148     engine.setCharset(charset.name());
149   }
150 
151   @Override
152   public int compareTo(byte[] value, int offset, int length) {
153     return engine.compareTo(value, offset, length);
154   }
155 
156   /**
157    * @return The comparator serialized using pb
158    */
159   @Override
160   public byte [] toByteArray() {
161     return engine.toByteArray();
162   }
163 
164   /**
165    * @param pbBytes A pb serialized {@link RegexStringComparator} instance
166    * @return An instance of {@link RegexStringComparator} made from <code>bytes</code>
167    * @throws DeserializationException
168    * @see #toByteArray
169    */
170   public static RegexStringComparator parseFrom(final byte [] pbBytes)
171   throws DeserializationException {
172     ComparatorProtos.RegexStringComparator proto;
173     try {
174       proto = ComparatorProtos.RegexStringComparator.parseFrom(pbBytes);
175     } catch (InvalidProtocolBufferException e) {
176       throw new DeserializationException(e);
177     }
178     RegexStringComparator comparator;
179     if (proto.hasEngine()) {
180       EngineType engine = EngineType.valueOf(proto.getEngine());
181       comparator = new RegexStringComparator(proto.getPattern(), proto.getPatternFlags(),
182         engine);
183     } else {
184       comparator = new RegexStringComparator(proto.getPattern(), proto.getPatternFlags());
185     }
186     String charset = proto.getCharset();
187     if (charset.length() > 0) {
188       try {
189         comparator.getEngine().setCharset(charset);
190       } catch (IllegalCharsetNameException e) {
191         LOG.error("invalid charset", e);
192       }
193     }
194     return comparator;
195   }
196 
197   /**
198    * @param other
199    * @return true if and only if the fields of the comparator that are serialized
200    * are equal to the corresponding fields in other.  Used for testing.
201    */
202   @Override
203   boolean areSerializedFieldsEqual(ByteArrayComparable other) {
204     if (other == this) return true;
205     if (!(other instanceof RegexStringComparator)) return false;
206     RegexStringComparator comparator = (RegexStringComparator)other;
207     return super.areSerializedFieldsEqual(comparator)
208       && engine.getClass().isInstance(comparator.getEngine())
209       && engine.getPattern().equals(comparator.getEngine().getPattern())
210       && engine.getFlags() == comparator.getEngine().getFlags()
211       && engine.getCharset().equals(comparator.getEngine().getCharset());
212   }
213 
214   Engine getEngine() {
215     return engine;
216   }
217 
218   /**
219    * This is an internal interface for abstracting access to different regular
220    * expression matching engines.
221    */
222   static interface Engine {
223     /**
224      * Returns the string representation of the configured regular expression
225      * for matching
226      */
227     String getPattern();
228 
229     /**
230      * Returns the set of configured match flags, a bit mask that may include
231      * {@link Pattern} flags
232      */
233     int getFlags();
234 
235     /**
236      * Returns the name of the configured charset
237      */
238     String getCharset();
239 
240     /**
241      * Set the charset used when matching
242      * @param charset the name of the desired charset for matching
243      */
244     void setCharset(final String charset);
245 
246     /**
247      * Return the serialized form of the configured matcher
248      */
249     byte [] toByteArray();
250 
251     /**
252      * Match the given input against the configured pattern
253      * @param value the data to be matched
254      * @param offset offset of the data to be matched
255      * @param length length of the data to be matched
256      * @return 0 if a match was made, 1 otherwise
257      */
258     int compareTo(byte[] value, int offset, int length);
259   }
260 
261   /**
262    * Implementation of the Engine interface using Java's Pattern.
263    * <p>
264    * This is the default engine.
265    */
266   static class JavaRegexEngine implements Engine {
267     private Charset charset = Charset.forName("UTF-8");
268     private Pattern pattern;
269 
270     public JavaRegexEngine(String regex, int flags) {
271       this.pattern = Pattern.compile(regex, flags);
272     }
273 
274     @Override
275     public String getPattern() {
276       return pattern.toString();
277     }
278 
279     @Override
280     public int getFlags() {
281       return pattern.flags();
282     }
283 
284     @Override
285     public String getCharset() {
286       return charset.name();
287     }
288 
289     @Override
290     public void setCharset(String charset) {
291       this.charset = Charset.forName(charset);
292     }
293 
294     @Override
295     public int compareTo(byte[] value, int offset, int length) {
296       // Use find() for subsequence match instead of matches() (full sequence
297       // match) to adhere to the principle of least surprise.
298       String tmp;
299       if (length < value.length / 2) {
300         // See HBASE-9428. Make a copy of the relevant part of the byte[],
301         // or the JDK will copy the entire byte[] during String decode
302         tmp = new String(Arrays.copyOfRange(value, offset, offset + length), charset);
303       } else {
304         tmp = new String(value, offset, length, charset);
305       }
306       return pattern.matcher(tmp).find() ? 0 : 1;
307     }
308 
309     @Override
310     public byte[] toByteArray() {
311       ComparatorProtos.RegexStringComparator.Builder builder =
312           ComparatorProtos.RegexStringComparator.newBuilder();
313       builder.setPattern(pattern.pattern());
314       builder.setPatternFlags(pattern.flags());
315       builder.setCharset(charset.name());
316       builder.setEngine(EngineType.JAVA.name());
317       return builder.build().toByteArray();
318     }
319   }
320 
321   /**
322    * Implementation of the Engine interface using Jruby's joni regex engine.
323    * <p>
324    * This engine operates on byte arrays directly so is expected to be more GC
325    * friendly, and reportedly is twice as fast as Java's Pattern engine.
326    * <p>
327    * NOTE: Only the {@link Pattern} flags CASE_INSENSITIVE, DOTALL, and
328    * MULTILINE are supported.
329    */
330   static class JoniRegexEngine implements Engine {
331     private Encoding encoding = UTF8Encoding.INSTANCE;
332     private String regex;
333     private Regex pattern;
334 
335     public JoniRegexEngine(String regex, int flags) {
336       this.regex = regex;
337       byte[] b = Bytes.toBytes(regex);
338       this.pattern = new Regex(b, 0, b.length, patternToJoniFlags(flags), encoding, Syntax.Java);
339     }
340 
341     @Override
342     public String getPattern() {
343       return regex;
344     }
345 
346     @Override
347     public int getFlags() {
348       return pattern.getOptions();
349     }
350 
351     @Override
352     public String getCharset() {
353       return encoding.getCharsetName();
354     }
355 
356     @Override
357     public void setCharset(String name) {
358       setEncoding(name);
359     }
360 
361     @Override
362     public int compareTo(byte[] value, int offset, int length) {
363       // Use subsequence match instead of full sequence match to adhere to the
364       // principle of least surprise.
365       Matcher m = pattern.matcher(value);
366       return m.search(offset, length, pattern.getOptions()) < 0 ? 1 : 0;
367     }
368 
369     @Override
370     public byte[] toByteArray() {
371       ComparatorProtos.RegexStringComparator.Builder builder =
372           ComparatorProtos.RegexStringComparator.newBuilder();
373         builder.setPattern(regex);
374         builder.setPatternFlags(joniToPatternFlags(pattern.getOptions()));
375         builder.setCharset(encoding.getCharsetName());
376         builder.setEngine(EngineType.JONI.name());
377         return builder.build().toByteArray();
378     }
379 
380     private int patternToJoniFlags(int flags) {
381       int newFlags = 0;
382       if ((flags & Pattern.CASE_INSENSITIVE) != 0) {
383         newFlags |= Option.IGNORECASE;
384       }
385       if ((flags & Pattern.DOTALL) != 0) {
386         // This does NOT mean Pattern.MULTILINE
387         newFlags |= Option.MULTILINE;
388       }
389       if ((flags & Pattern.MULTILINE) != 0) {
390         // This is what Java 8's Nashorn engine does when using joni and
391         // translating Pattern's MULTILINE flag
392         newFlags &= ~Option.SINGLELINE;
393         newFlags |= Option.NEGATE_SINGLELINE;
394       }
395       return newFlags;
396     }
397 
398     private int joniToPatternFlags(int flags) {
399       int newFlags = 0;
400       if ((flags & Option.IGNORECASE) != 0) {
401         newFlags |= Pattern.CASE_INSENSITIVE;
402       }
403       // This does NOT mean Pattern.MULTILINE, this is equivalent to Pattern.DOTALL
404       if ((flags & Option.MULTILINE) != 0) {
405         newFlags |= Pattern.DOTALL;
406       }
407       // This means Pattern.MULTILINE. Nice
408       if ((flags & Option.NEGATE_SINGLELINE) != 0) {
409         newFlags |= Pattern.MULTILINE;
410       }
411       return newFlags;
412     }
413 
414     private void setEncoding(String name) {
415       EncodingDB.Entry e = EncodingDB.getEncodings().get(Bytes.toBytes(name));
416       if (e != null) {
417         encoding = e.getEncoding();
418       } else {
419         throw new IllegalCharsetNameException(name);
420       }
421     }
422   }
423 }