/
LikePredicateImpl.java
64 lines (53 loc) · 2.25 KB
/
LikePredicateImpl.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* Copyright (c) 2017 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* Contributors:
* Bosch Software Innovations GmbH - initial contribution
*/
package org.eclipse.ditto.model.query.model.criteria;
import java.util.regex.Pattern;
import org.eclipse.ditto.model.query.model.criteria.visitors.PredicateVisitor;
/**
* Like predicate.
*/
public class LikePredicateImpl extends AbstractSinglePredicate {
private static final String LEADING_WILDCARD = "\\Q\\E.*";
private static final String TRAILING_WILDCARD = ".*\\Q\\E";
public LikePredicateImpl(final Object value) {
super(value);
}
private String convertToRegexSyntaxAndGetOption() {
// simplify expression by replacing repeating wildcard with a single one
final String valueString = replaceRepeatingWildcards(getValue().toString());
// shortcut for single * wildcard
if ("*".equals(valueString)) {
return ".*";
}
// first escape the whole string
String escapedString = Pattern.compile(Pattern.quote(valueString)).toString();
// then enable allowed wildcards (* and ?) again
escapedString = escapedString.replaceAll("\\*", "\\\\E.*\\\\Q");
escapedString = escapedString.replaceAll("\\?", "\\\\E.\\\\Q"); // escape Char wild cards for ?
// prepend ^ if is a prefix match (no * at the beginning of the string, much faster)
if (!valueString.startsWith(LEADING_WILDCARD)) {
escapedString = "^" + escapedString;
}
// append $ if is a postfix match (no * at the end of the string, much faster)
if (!valueString.endsWith(TRAILING_WILDCARD)) {
escapedString = escapedString + "$";
}
return escapedString;
}
private String replaceRepeatingWildcards(final String value) {
return value.replaceAll("\\*{2,}", "*");
}
@Override
public <T> T accept(final PredicateVisitor<T> visitor) {
return visitor.visitLike(convertToRegexSyntaxAndGetOption());
}
}