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