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