1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.configuration.tree;
18
19 import java.util.ArrayList;
20 import java.util.Iterator;
21 import java.util.LinkedList;
22 import java.util.List;
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 public class MergeCombiner extends NodeCombiner
46 {
47
48
49
50
51
52
53
54
55 @Override
56 public ConfigurationNode combine(ConfigurationNode node1, ConfigurationNode node2)
57 {
58 ViewNode result = createViewNode();
59 result.setName(node1.getName());
60 result.setValue(node1.getValue());
61 addAttributes(result, node1, node2);
62
63
64 List<ConfigurationNode> children2 = new LinkedList<ConfigurationNode>(node2.getChildren());
65 for (ConfigurationNode child1 : node1.getChildren())
66 {
67 ConfigurationNode child2 = canCombine(node1, node2, child1, children2);
68 if (child2 != null)
69 {
70 result.addChild(combine(child1, child2));
71 children2.remove(child2);
72 }
73 else
74 {
75 result.addChild(child1);
76 }
77 }
78
79
80 for (ConfigurationNode c : children2)
81 {
82 result.addChild(c);
83 }
84 return result;
85 }
86
87
88
89
90
91
92
93
94
95
96
97 protected void addAttributes(ViewNode result, ConfigurationNode node1,
98 ConfigurationNode node2)
99 {
100 result.appendAttributes(node1);
101 for (ConfigurationNode attr : node2.getAttributes())
102 {
103 if (node1.getAttributeCount(attr.getName()) == 0)
104 {
105 result.addAttribute(attr);
106 }
107 }
108 }
109
110
111
112
113
114
115
116
117
118
119
120 protected ConfigurationNode canCombine(ConfigurationNode node1,
121 ConfigurationNode node2, ConfigurationNode child, List<ConfigurationNode> children2)
122 {
123 List<ConfigurationNode> attrs1 = child.getAttributes();
124 List<ConfigurationNode> nodes = new ArrayList<ConfigurationNode>();
125
126 List<ConfigurationNode> children = node2.getChildren(child.getName());
127 Iterator<ConfigurationNode> it = children.iterator();
128 while (it.hasNext())
129 {
130 ConfigurationNode node = it.next();
131 Iterator<ConfigurationNode> iter = attrs1.iterator();
132 while (iter.hasNext())
133 {
134 ConfigurationNode attr1 = iter.next();
135 List<ConfigurationNode> list2 = node.getAttributes(attr1.getName());
136 if (list2.size() == 1
137 && !attr1.getValue().equals(list2.get(0).getValue()))
138 {
139 node = null;
140 break;
141 }
142 }
143 if (node != null)
144 {
145 nodes.add(node);
146 }
147 }
148
149 if (nodes.size() == 1)
150 {
151 return nodes.get(0);
152 }
153 if (nodes.size() > 1 && !isListNode(child))
154 {
155 Iterator<ConfigurationNode> iter = nodes.iterator();
156 while (iter.hasNext())
157 {
158 children2.remove(iter.next());
159 }
160 }
161
162 return null;
163 }
164 }