1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.mybatis.scripting.thymeleaf.expression;
17
18 import java.util.Arrays;
19 import java.util.Collections;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.function.Function;
23 import java.util.stream.Collectors;
24
25
26
27
28
29
30
31
32
33 public class Likes {
34
35 private char escapeChar = '\\';
36
37 private Set<Character> additionalEscapeTargetChars = Collections.emptySet();
38
39 private Function<Character, String> escapeClauseSupplier = targetEscapeChar -> "ESCAPE '" + targetEscapeChar + "'";
40
41
42
43
44 private Likes() {
45
46 }
47
48
49
50
51
52
53
54
55
56
57 public String escapeWildcard(String value) {
58 if (value == null || value.isEmpty()) {
59 return "";
60 }
61 StringBuilder sb = new StringBuilder(value.length() + 16);
62 for (char c : value.toCharArray()) {
63 if (c == escapeChar || c == '%' || c == '_' || additionalEscapeTargetChars.contains(c)) {
64 sb.append(escapeChar);
65 }
66 sb.append(c);
67 }
68 return sb.toString();
69 }
70
71
72
73
74
75
76
77 public String escapeClause() {
78 return escapeClauseSupplier.apply(escapeChar);
79 }
80
81
82
83
84
85
86 public static Builder newBuilder() {
87 return new Builder();
88 }
89
90
91
92
93 public static class Builder {
94
95 private final Likes instance = new Likes();
96
97 private Builder() {
98
99 }
100
101
102
103
104
105
106
107
108
109
110 public Builder escapeChar(Character escapeChar) {
111 Optional.ofNullable(escapeChar).ifPresent(v -> instance.escapeChar = v);
112 return this;
113 }
114
115
116
117
118
119
120
121
122
123
124 public Builder additionalEscapeTargetChars(Character... additionalEscapeTargetChars) {
125 Optional.ofNullable(additionalEscapeTargetChars)
126 .ifPresent(v -> instance.additionalEscapeTargetChars = Arrays.stream(v).collect(Collectors.toSet()));
127 return this;
128 }
129
130
131
132
133
134
135
136
137
138
139 public Builder escapeClauseFormat(String escapeClauseFormat) {
140 Optional.ofNullable(escapeClauseFormat)
141 .ifPresent(v -> instance.escapeClauseSupplier = escapeChar -> String.format(v, escapeChar));
142 return this;
143 }
144
145
146
147
148
149
150 public Likes build() {
151 return instance;
152 }
153
154 }
155
156 }