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
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.Map;
26 import java.util.Set;
27 import java.util.Stack;
28
29 /***
30 * A Rule class implementing logical or.
31 *
32 * @author Scott Deboy (sdeboy@apache.org)
33 */
34 public class OrRule extends AbstractRule {
35 /***
36 * Serialization ID.
37 */
38 static final long serialVersionUID = 2088765995061413165L;
39 /***
40 * rule 1.
41 */
42 private final Rule rule1;
43 /***
44 * Rule 2.
45 */
46 private final Rule rule2;
47
48 /***
49 * Create new instance.
50 * @param firstParam first rule
51 * @param secondParam second rule
52 */
53 private OrRule(final Rule firstParam, final Rule secondParam) {
54 super();
55 this.rule1 = firstParam;
56 this.rule2 = secondParam;
57 }
58
59 /***
60 * Create new instance.
61 * @param firstParam first rule
62 * @param secondParam second rule
63 * @return new instance
64 */
65 public static Rule getRule(final Rule firstParam, final Rule secondParam) {
66 return new OrRule(firstParam, secondParam);
67 }
68
69 /***
70 * Create new instance from top two elements of stack.
71 * @param stack stack
72 * @return new instance
73 */
74 public static Rule getRule(final Stack stack) {
75 if (stack.size() < 2) {
76 throw new IllegalArgumentException(
77 "Invalid OR rule - expected two rules but received "
78 + stack.size());
79 }
80 Object o2 = stack.pop();
81 Object o1 = stack.pop();
82 if ((o2 instanceof Rule) && (o1 instanceof Rule)) {
83 Rule p2 = (Rule) o2;
84 Rule p1 = (Rule) o1;
85 return new OrRule(p1, p2);
86 }
87 throw new IllegalArgumentException("Invalid OR rule: " + o2 + "..." + o1);
88 }
89
90 /*** {@inheritDoc} */
91 public boolean evaluate(final LoggingEvent event, Map matches) {
92 if (matches == null) {
93 return (rule1.evaluate(event, null) || rule2.evaluate(event, null));
94 }
95 Map tempMatches1 = new HashMap();
96 Map tempMatches2 = new HashMap();
97
98 boolean result1 = rule1.evaluate(event, tempMatches1);
99 boolean result2 = rule2.evaluate(event, tempMatches2);
100 boolean result = result1 || result2;
101 if (result) {
102 for (Iterator iter = tempMatches1.entrySet().iterator();iter.hasNext();) {
103 Map.Entry entry = (Map.Entry)iter.next();
104 Object key = entry.getKey();
105 Set value = (Set)entry.getValue();
106 Set mainSet = (Set) matches.get(key);
107 if (mainSet == null) {
108 mainSet = new HashSet();
109 matches.put(key, mainSet);
110 }
111 mainSet.addAll(value);
112 }
113 for (Iterator iter = tempMatches2.entrySet().iterator();iter.hasNext();) {
114 Map.Entry entry = (Map.Entry)iter.next();
115 Object key = entry.getKey();
116 Set value = (Set)entry.getValue();
117 Set mainSet = (Set) matches.get(key);
118 if (mainSet == null) {
119 mainSet = new HashSet();
120 matches.put(key, mainSet);
121 }
122 mainSet.addAll(value);
123 }
124 }
125 return result;
126 }
127 }