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 which returns the result of
31 * performing equals against two strings.
32 *
33 * @author Scott Deboy (sdeboy@apache.org)
34 */
35 public class EqualsRule extends AbstractRule {
36 /***
37 * Serialization ID.
38 */
39 static final long serialVersionUID = 1712851553477517245L;
40 /***
41 * Resolver.
42 */
43 private static final LoggingEventFieldResolver RESOLVER =
44 LoggingEventFieldResolver.getInstance();
45 /***
46 * Value.
47 */
48 private final String value;
49 /***
50 * Field.
51 */
52 private final String field;
53
54 /***
55 * Create new instance.
56 * @param field field
57 * @param value value
58 */
59 private EqualsRule(final String field, final String value) {
60 super();
61 if (!RESOLVER.isField(field)) {
62 throw new IllegalArgumentException(
63 "Invalid EQUALS rule - " + field + " is not a supported field");
64 }
65
66 this.field = field;
67 this.value = value;
68 }
69
70 /***
71 * Create new instance from top two elements of stack.
72 * @param stack stack
73 * @return new instance
74 */
75 public static Rule getRule(final Stack stack) {
76 if (stack.size() < 2) {
77 throw new IllegalArgumentException(
78 "Invalid EQUALS rule - expected two parameters but received "
79 + stack.size());
80 }
81
82 String p2 = stack.pop().toString();
83 String p1 = stack.pop().toString();
84
85 return getRule(p1, p2);
86 }
87
88 /***
89 * Create new instance.
90 * @param p1 field, special treatment for level and timestamp.
91 * @param p2 value
92 * @return new instance
93 */
94 public static Rule getRule(final String p1, final String p2) {
95 if (p1.equalsIgnoreCase(LoggingEventFieldResolver.LEVEL_FIELD)) {
96 return LevelEqualsRule.getRule(p2);
97 } else if (p1.equalsIgnoreCase(LoggingEventFieldResolver.TIMESTAMP_FIELD)) {
98 return TimestampEqualsRule.getRule(p2);
99 } else {
100 return new EqualsRule(p1, p2);
101 }
102 }
103
104 /*** {@inheritDoc} */
105 public boolean evaluate(final LoggingEvent event, Map matches) {
106 Object p2 = RESOLVER.getValue(field, event);
107
108 boolean result = (p2 != null) && p2.toString().equals(value);
109 if (result && matches != null) {
110 Set entries = (Set) matches.get(field.toUpperCase());
111 if (entries == null) {
112 entries = new HashSet();
113 matches.put(field.toUpperCase(), entries);
114 }
115 entries.add(value);
116 }
117 return result;
118 }
119 }