1
2
3
4
5
6
7
8
9
10 package org.dom4j.rule;
11
12 import java.util.ArrayList;
13 import java.util.Collections;
14
15 import org.dom4j.Node;
16
17 /*** <p><code>RuleSet</code> manages a set of rules which are sorted
18 * in order of relevance according to the XSLT defined conflict
19 * resolution policy. This makes finding the correct rule for
20 * a DOM4J Node using the XSLT processing model efficient as the
21 * rules can be evaluated in order of priority.</p>
22 *
23 * @author <a href="mailto:james.strachan@metastuff.com">James Strachan</a>
24 * @version $Revision: 1.8 $
25 */
26 public class RuleSet {
27
28 /*** An unordered list of Rule objects */
29 private ArrayList rules = new ArrayList();
30
31 /*** A lazily evaluated and cached array of rules sorted */
32 private Rule[] ruleArray;
33
34 public RuleSet() {
35 }
36
37 public String toString() {
38 return super.toString() + " [RuleSet: " + rules + " ]";
39 }
40
41
42 /*** Performs an XSLT processing model match for the rule
43 * which matches the given Node the best.
44 *
45 * @param node is the DOM4J Node to match against
46 * @return the matching Rule or no rule if none matched
47 */
48 public Rule getMatchingRule( Node node ) {
49 Rule[] rules = getRuleArray();
50 for ( int i = rules.length - 1; i >= 0; i-- ) {
51 Rule rule = rules[i];
52 if ( rule.matches( node ) ) {
53 return rule;
54 }
55 }
56 return null;
57 }
58
59 public void addRule(Rule rule) {
60 rules.add( rule );
61 ruleArray = null;
62 }
63
64 public void removeRule(Rule rule) {
65 rules.remove( rule );
66 ruleArray = null;
67 }
68
69 /*** Adds all the rules to this RuleSet from the given other rule set.
70 */
71 public void addAll(RuleSet that) {
72 rules.addAll( that.rules );
73 ruleArray = null;
74 }
75
76 /*** Returns an array of sorted rules.
77 *
78 * @return the rules as a sorted array in ascending precendence
79 * so that the rules at the end of the array should be used first
80 */
81 protected Rule[] getRuleArray() {
82 if ( ruleArray == null ) {
83 Collections.sort( rules );
84 int size = rules.size();
85 ruleArray = new Rule[ size ];
86 rules.toArray( ruleArray );
87 }
88 return ruleArray;
89 }
90
91 }
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139