1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.log4j.rule;
19
20 import org.apache.log4j.spi.LoggingEvent;
21 import org.apache.log4j.spi.LoggingEventFieldResolver;
22
23 import java.util.HashSet;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.Stack;
27
28
29 /***
30 * A Rule class implementing case-insensitive
31 * partial-text matches against two strings.
32 *
33 * @author Scott Deboy (sdeboy@apache.org)
34 */
35 public class PartialTextMatchRule extends AbstractRule {
36 /***
37 * Serialization ID.
38 */
39 static final long serialVersionUID = 6963284773637727558L;
40 /***
41 * Resolver.
42 */
43 private static final LoggingEventFieldResolver RESOLVER =
44 LoggingEventFieldResolver.getInstance();
45 /***
46 * Field.
47 */
48 private final String field;
49 /***
50 * Value.
51 */
52 private final String value;
53
54 /***
55 * Create new instance.
56 * @param field field
57 * @param value value
58 */
59 private PartialTextMatchRule(final String field, final String value) {
60 super();
61 if (!RESOLVER.isField(field)) {
62 throw new IllegalArgumentException(
63 "Invalid partial text rule - " + field + " is not a supported field");
64 }
65
66 this.field = field;
67 this.value = value;
68 }
69
70 /***
71 * Create new instance.
72 * @param field field
73 * @param value value
74 * @return new instance
75 */
76 public static Rule getRule(final String field, final String value) {
77 return new PartialTextMatchRule(field, value);
78 }
79
80 /***
81 * Create new instance from top two elements of stack.
82 * @param stack stack
83 * @return new instance
84 */
85 public static Rule getRule(final Stack stack) {
86 if (stack.size() < 2) {
87 throw new IllegalArgumentException(
88 "invalid partial text rule - expected two parameters but received "
89 + stack.size());
90 }
91
92 String p2 = stack.pop().toString();
93 String p1 = stack.pop().toString();
94
95 return new PartialTextMatchRule(p1, p2);
96 }
97
98 /*** {@inheritDoc} */
99 public boolean evaluate(final LoggingEvent event, Map matches) {
100 Object p2 = RESOLVER.getValue(field, event);
101 boolean result = ((p2 != null) && (value != null) && (p2.toString().toLowerCase().indexOf(value.toLowerCase()) > -1));
102 if (result && matches != null) {
103 Set entries = (Set) matches.get(field.toUpperCase());
104 if (entries == null) {
105 entries = new HashSet();
106 matches.put(field.toUpperCase(), entries);
107 }
108 entries.add(value);
109 }
110 return result;
111 }
112 }