001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.commons.configuration2.tree;
018
019import java.util.ArrayList;
020import java.util.HashMap;
021import java.util.LinkedList;
022import java.util.List;
023import java.util.Map;
024
025import org.apache.commons.lang3.ObjectUtils;
026
027/**
028 * <p>
029 * A specialized implementation of the {@code NodeCombiner} interface
030 * that performs a merge from two passed in node hierarchies.
031 * </p>
032 * <p>
033 * This combiner performs the merge using a few rules:
034 * </p>
035 * <ol>
036 * <li>Nodes can be merged when attributes that appear in both have the same value.</li>
037 * <li>Only a single node in the second file is considered a match to the node in the first file.</li>
038 * <li>Attributes in nodes that match are merged.
039 * <li>Nodes in both files that do not match are added to the result.</li>
040 * </ol>
041 *
042 * @version $Id: MergeCombiner.java 1790899 2017-04-10 21:56:46Z ggregory $
043 * @since 1.7
044 */
045public class MergeCombiner extends NodeCombiner
046{
047    /**
048     * Combines the given nodes to a new union node.
049     *
050     * @param node1 the first source node
051     * @param node2 the second source node
052     * @return the union node
053     */
054
055    @Override
056    public ImmutableNode combine(ImmutableNode node1, ImmutableNode node2)
057    {
058        ImmutableNode.Builder result = new ImmutableNode.Builder();
059        result.name(node1.getNodeName());
060        result.value(node1.getValue());
061        addAttributes(result, node1, node2);
062
063        // Check if nodes can be combined
064        List<ImmutableNode> children2 = new LinkedList<>(node2.getChildren());
065        for (ImmutableNode child1 : node1.getChildren())
066        {
067            ImmutableNode child2 = canCombine(node2, child1, children2);
068            if (child2 != null)
069            {
070                result.addChild(combine(child1, child2));
071                children2.remove(child2);
072            }
073            else
074            {
075                result.addChild(child1);
076            }
077        }
078
079        // Add remaining children of node 2
080        for (ImmutableNode c : children2)
081        {
082            result.addChild(c);
083        }
084        return result.create();
085    }
086
087    /**
088     * Handles the attributes during a combination process. First all attributes
089     * of the first node will be added to the result. Then all attributes of the
090     * second node, which are not contained in the first node, will also be
091     * added.
092     *
093     * @param result the builder for the resulting node
094     * @param node1 the first node
095     * @param node2 the second node
096     */
097    protected void addAttributes(ImmutableNode.Builder result, ImmutableNode node1,
098            ImmutableNode node2)
099    {
100        Map<String, Object> attributes = new HashMap<>();
101        attributes.putAll(node1.getAttributes());
102        for (Map.Entry<String, Object> e : node2.getAttributes().entrySet())
103        {
104            if (!attributes.containsKey(e.getKey()))
105            {
106                attributes.put(e.getKey(), e.getValue());
107            }
108        }
109        result.addAttributes(attributes);
110    }
111
112    /**
113     * Tests if the first node can be combined with the second node. A node can
114     * only be combined if its attributes are all present in the second node and
115     * they all have the same value.
116     *
117     * @param node2 the second node
118     * @param child the child node (of the first node)
119     * @param children2 the children of the 2nd node
120     * @return a child of the second node, with which a combination is possible
121     */
122    protected ImmutableNode canCombine(ImmutableNode node2,
123            ImmutableNode child, List<ImmutableNode> children2)
124    {
125        Map<String, Object> attrs1 = child.getAttributes();
126        List<ImmutableNode> nodes = new ArrayList<>();
127
128        List<ImmutableNode> children =
129                HANDLER.getChildren(node2, child.getNodeName());
130        for (ImmutableNode node : children)
131        {
132            if (matchAttributes(attrs1, node))
133            {
134                nodes.add(node);
135            }
136        }
137
138        if (nodes.size() == 1)
139        {
140            return nodes.get(0);
141        }
142        if (nodes.size() > 1 && !isListNode(child))
143        {
144            for (ImmutableNode node : nodes)
145            {
146                children2.remove(node);
147            }
148        }
149
150        return null;
151    }
152
153    /**
154     * Checks whether the attributes of the passed in node are compatible.
155     *
156     * @param attrs1 the attributes of the first node
157     * @param node the 2nd node
158     * @return a flag whether these nodes can be combined regarding their
159     *         attributes
160     */
161    private static boolean matchAttributes(Map<String, Object> attrs1,
162            ImmutableNode node)
163    {
164        Map<String, Object> attrs2 = node.getAttributes();
165        for (Map.Entry<String, Object> e : attrs1.entrySet())
166        {
167            if (attrs2.containsKey(e.getKey())
168                    && !ObjectUtils
169                            .equals(e.getValue(), attrs2.get(e.getKey())))
170            {
171                return false;
172            }
173        }
174        return true;
175    }
176}