1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package ch.qos.logback.core.boolex;
16
17 import ch.qos.logback.core.util.IntHolder;
18
19 import java.util.ArrayList;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Stack;
24 import java.util.function.BiFunction;
25 import java.util.function.Function;
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41 public class ExpressionPropertyCondition extends PropertyConditionBase {
42
43
44 public static final String MALFORMED_EXPRESSION = "Malformed expression: ";
45
46
47
48
49
50
51
52
53
54
55 protected Map<String, Function<String, Boolean>> functionMap = new HashMap<>();
56
57
58
59
60
61
62
63
64
65
66
67 protected Map<String, BiFunction<String, String, Boolean>> biFunctionMap = new HashMap<>();
68
69 private static final String IS_NULL_FUNCTION_KEY = "isNull";
70 private static final String IS_DEFINED_FUNCTION_KEY = "isDefined";
71
72 private static final String PROPERTY_EQUALS_FUNCTION_KEY = "propertyEquals";
73 private static final String PROPERTY_CONTAINS_FUNCTION_KEY = "propertyContains";
74
75 private static final String TRUE_LITERAL = "true";
76 private static final String FALSE_LITERAL = "false";
77
78 private static final char QUOTE = '"';
79 private static final char COMMA = ',';
80 private static final char LEFT_PAREN = '(';
81 private static final char RIGHT_PAREN = ')';
82
83
84 private static final char NOT_CHAR = '!';
85 private static final char AMPERSAND_CHAR = '&';
86 private static final char OR_CHAR = '|';
87
88 enum Associativity {
89 LEFT, RIGHT;
90 }
91
92 enum TokenType {
93 NOT, AND, OR, TRUE, FALSE, FUNCTION, BI_FUNCTION, LEFT_PAREN, RIGHT_PAREN;
94
95 boolean isLogicalOperator() {
96 return this == NOT || this == AND || this == OR;
97 }
98 }
99
100
101 static class Token {
102 TokenType tokenType;
103 String functionName;
104 String param0;
105 String param1;
106
107 Token(TokenType tokenType) {
108 this.tokenType = tokenType;
109
110 switch (tokenType) {
111 case LEFT_PAREN:
112 case RIGHT_PAREN:
113 case NOT:
114 case AND:
115 case OR:
116 case TRUE:
117 case FALSE:
118 break;
119 default:
120 throw new IllegalStateException("Unexpected value: " + tokenType);
121 }
122 }
123
124 Token(TokenType tokenType, String functionName, String propertyKey, String value) {
125 this.tokenType = tokenType;
126 this.functionName = functionName;
127 this.param0 = propertyKey;
128 this.param1 = value;
129 }
130
131 public static Token valueOf(char c) {
132
133 if (c == LEFT_PAREN)
134 return new Token(TokenType.LEFT_PAREN);
135 if (c == RIGHT_PAREN)
136 return new Token(TokenType.RIGHT_PAREN);
137 throw new IllegalArgumentException("Unexpected char: " + c);
138 }
139 }
140
141
142 String expression;
143 List<Token> rpn;
144
145
146
147
148
149 public ExpressionPropertyCondition() {
150 functionMap.put(IS_NULL_FUNCTION_KEY, this::isNull);
151 functionMap.put(IS_DEFINED_FUNCTION_KEY, this::isDefined);
152 biFunctionMap.put(PROPERTY_EQUALS_FUNCTION_KEY, this::propertyEquals);
153 biFunctionMap.put(PROPERTY_CONTAINS_FUNCTION_KEY, this::propertyContains);
154 }
155
156
157
158
159
160
161
162 public void start() {
163 if (expression == null || expression.isEmpty()) {
164 addError("Empty expression");
165 return;
166 }
167
168 try {
169 List<Token> tokens = tokenize(expression.trim());
170 this.rpn = infixToReversePolishNotation(tokens);
171 } catch (IllegalArgumentException|IllegalStateException e) {
172 addError(MALFORMED_EXPRESSION + e.getMessage());
173 return;
174 }
175 super.start();
176 }
177
178
179
180
181
182
183 public String getExpression() {
184 return expression;
185 }
186
187
188
189
190
191
192 public void setExpression(String expression) {
193 this.expression = expression;
194 }
195
196
197
198
199
200
201
202
203 @Override
204 public boolean evaluate() {
205 if (!isStarted()) {
206 return false;
207 }
208 return evaluateRPN(rpn);
209 }
210
211
212
213
214
215
216
217
218
219 private List<Token> tokenize(String expr) throws IllegalArgumentException, IllegalStateException {
220 List<Token> tokens = new ArrayList<>();
221
222 int i = 0;
223 while (i < expr.length()) {
224 char c = expr.charAt(i);
225
226 if (Character.isWhitespace(c)) {
227 i++;
228 continue;
229 }
230
231 if (c == LEFT_PAREN || c == RIGHT_PAREN) {
232 tokens.add(Token.valueOf(c));
233 i++;
234 continue;
235 }
236
237 if (c == NOT_CHAR) {
238 tokens.add(new Token(TokenType.NOT));
239 i++;
240 continue;
241 }
242
243 if (c == AMPERSAND_CHAR) {
244 i++;
245 c = expr.charAt(i);
246 if (c == AMPERSAND_CHAR) {
247 tokens.add(new Token(TokenType.AND));
248 i++;
249 continue;
250 } else {
251 throw new IllegalArgumentException("Expected '&' after '&'");
252 }
253 }
254
255 if (c == OR_CHAR) {
256 i++;
257 c = expr.charAt(i);
258 if (c == OR_CHAR) {
259 tokens.add(new Token(TokenType.OR));
260 i++;
261 continue;
262 } else {
263 throw new IllegalArgumentException("Expected '|' after '|'");
264 }
265 }
266
267
268 if (Character.isLetter(c)) {
269 StringBuilder sb = new StringBuilder();
270 while (i < expr.length() && Character.isLetter(expr.charAt(i))) {
271 sb.append(expr.charAt(i++));
272 }
273 String identifier = sb.toString();
274
275 if (TRUE_LITERAL.equals(identifier)) {
276 tokens.add(new Token(TokenType.TRUE));
277 continue;
278 }
279 if (FALSE_LITERAL.equals(identifier)) {
280 tokens.add(new Token(TokenType.FALSE));
281 continue;
282 }
283
284 String functionName = identifier;
285
286
287 i = skipWhitespaces(i);
288 checkExpectedCharacter(LEFT_PAREN, i);
289 i++;
290
291 IntHolder intHolder = new IntHolder(i);
292 String param0 = extractQuotedString(intHolder);
293 i = intHolder.value;
294
295 i = skipWhitespaces(i);
296
297
298 if (biFunctionMap.containsKey(functionName)) {
299 checkExpectedCharacter(COMMA, i);
300 i++;
301 intHolder.set(i);
302 String param1 = extractQuotedString(intHolder);
303 i = intHolder.get();
304 i = skipWhitespaces(i);
305 tokens.add(new Token(TokenType.BI_FUNCTION, functionName, param0, param1));
306 } else {
307 tokens.add(new Token(TokenType.FUNCTION, functionName, param0, null));
308 }
309
310
311 checkExpectedCharacter(RIGHT_PAREN, i);
312 i++;
313
314 continue;
315 }
316
317 throw new IllegalArgumentException("Unexpected character '" + c + "' at position " + i + " in [" + expr + "]");
318 }
319 return tokens;
320 }
321
322 private String extractQuotedString(IntHolder intHolder) {
323 int i = intHolder.get();
324 i = skipWhitespaces(i);
325
326
327 checkExpectedCharacter(QUOTE, i);
328 i++;
329
330 int start = i;
331 i = findIndexOfClosingQuote(i);
332 String param = expression.substring(start, i);
333 i++;
334 intHolder.set(i);
335 return param;
336 }
337
338 private int findIndexOfClosingQuote(int i) throws IllegalStateException{
339 while (i < expression.length() && expression.charAt(i) != QUOTE) {
340 i++;
341 }
342 if (i >= expression.length()) {
343 throw new IllegalStateException("Missing closing quote");
344 }
345 return i;
346 }
347
348 void checkExpectedCharacter(char expectedChar, int i) throws IllegalArgumentException{
349 if (i >= expression.length() || expression.charAt(i) != expectedChar) {
350 throw new IllegalArgumentException("In [" + expression + "] expecting '" + expectedChar + "' at position " + i);
351 }
352 }
353
354 private int skipWhitespaces(int i) {
355 while (i < expression.length() && Character.isWhitespace(expression.charAt(i))) {
356 i++;
357 }
358 return i;
359 }
360
361
362
363
364
365
366
367
368
369 private List<Token> infixToReversePolishNotation(List<Token> tokens) {
370 List<Token> output = new ArrayList<>();
371 Stack<Token> operatorStack = new Stack<>();
372
373 for (Token token : tokens) {
374 TokenType tokenType = token.tokenType;
375 if (isPredicate(token)) {
376 output.add(token);
377 } else if (tokenType.isLogicalOperator()) {
378 while (!operatorStack.isEmpty() && precedence(operatorStack.peek()) >= precedence(token) &&
379 operatorAssociativity(token) == Associativity.LEFT) {
380 output.add(operatorStack.pop());
381 }
382 operatorStack.push(token);
383 } else if (tokenType == TokenType.LEFT_PAREN) {
384 operatorStack.push(token);
385 } else if (tokenType == TokenType.RIGHT_PAREN) {
386 while (!operatorStack.isEmpty() && operatorStack.peek().tokenType != TokenType.LEFT_PAREN) {
387 output.add(operatorStack.pop());
388 }
389 if (operatorStack.isEmpty())
390 throw new IllegalArgumentException("Mismatched parentheses, expecting '('");
391 operatorStack.pop();
392 }
393 }
394
395 while (!operatorStack.isEmpty()) {
396 Token token = operatorStack.pop();
397 TokenType tokenType = token.tokenType;
398 if (tokenType == TokenType.LEFT_PAREN)
399 throw new IllegalArgumentException("Mismatched parentheses");
400 output.add(token);
401 }
402
403 return output;
404 }
405
406 private boolean isPredicate(Token token) {
407 TokenType tokenType = token.tokenType;
408 return tokenType == TokenType.FUNCTION
409 || tokenType == TokenType.BI_FUNCTION
410 || tokenType == TokenType.TRUE
411 || tokenType == TokenType.FALSE;
412 }
413
414 private int precedence(Token token) {
415 TokenType tokenType = token.tokenType;
416 switch (tokenType) {
417 case NOT:
418 return 3;
419 case AND:
420 return 2;
421 case OR:
422 return 1;
423 default:
424 return 0;
425 }
426 }
427
428 private Associativity operatorAssociativity(Token token) {
429 TokenType tokenType = token.tokenType;
430
431 return tokenType == TokenType.NOT ? Associativity.RIGHT : Associativity.LEFT;
432 }
433
434
435
436
437
438
439
440
441 private boolean evaluateRPN(List<Token> rpn) throws IllegalStateException {
442 Stack<Boolean> resultStack = new Stack<>();
443
444 for (Token token : rpn) {
445 if (isPredicate(token)) {
446 boolean value = evaluateFunctions(token);
447 resultStack.push(value);
448 } else {
449 switch (token.tokenType) {
450 case NOT:
451 boolean a3 = resultStack.pop();
452 resultStack.push(!a3);
453 break;
454 case AND:
455 boolean b2 = resultStack.pop();
456 boolean a2 = resultStack.pop();
457 resultStack.push(a2 && b2);
458 break;
459
460 case OR:
461 boolean b1 = resultStack.pop();
462 boolean a1 = resultStack.pop();
463 resultStack.push(a1 || b1);
464 break;
465 }
466 }
467 }
468
469 return resultStack.pop();
470 }
471
472
473 private boolean evaluateFunctions(Token token) throws IllegalStateException {
474 if (token.tokenType == TokenType.TRUE) {
475 return true;
476 }
477 if (token.tokenType == TokenType.FALSE) {
478 return false;
479 }
480
481 String functionName = token.functionName;
482 String param0 = token.param0;
483 String param1 = token.param1;
484 Function<String, Boolean> function = functionMap.get(functionName);
485 if (function != null) {
486 return function.apply(param0);
487 }
488
489 BiFunction<String, String, Boolean> biFunction = biFunctionMap.get(functionName);
490 if (biFunction != null) {
491 return biFunction.apply(param0, param1);
492 }
493
494 throw new IllegalStateException("Unknown function: " + token);
495 }
496 }