001package org.atteo.xmlcombiner;
002
003import java.util.ArrayList;
004import java.util.LinkedHashMap;
005import java.util.List;
006import java.util.Map;
007
008import org.w3c.dom.Attr;
009import org.w3c.dom.Element;
010
011public class KeyAttributesChildContextsMapper implements ChildContextsMapper {
012
013    @Override
014    public Map<Key, List<Context>> mapChildContexts(Context parent,
015            List<String> keyAttributeNames) {
016        List<Context> contexts = parent.groupChildContexts();
017
018        Map<Key, List<Context>> map = new LinkedHashMap<>();
019        for (Context context : contexts) {
020            Element contextElement = context.getElement();
021
022            if (contextElement != null) {
023                Map<String, String> keys = new LinkedHashMap<>();
024                for (String keyAttributeName : keyAttributeNames) {
025                    Attr keyNode = contextElement.getAttributeNode(keyAttributeName);
026                    if (keyNode != null) {
027                        keys.put(keyAttributeName, keyNode.getValue());
028                    }
029                }
030                {
031                    Attr keyNode = contextElement.getAttributeNode(Context.ID_ATTRIBUTE_NAME);
032                    if (keyNode != null) {
033                        keys.put(Context.ID_ATTRIBUTE_NAME, keyNode.getValue());
034                    }
035                }
036                Key key = new Key(contextElement.getTagName(), keys);
037
038                List<Context> destinationContexts = map.computeIfAbsent(key, k -> new ArrayList<>());
039                destinationContexts.add(context);
040
041            } else {
042                List<Context> destinationContexts = map.computeIfAbsent(Key.BEFORE_END, k -> new ArrayList<>());
043                destinationContexts.add(context);
044            }
045        }
046        return map;
047    }
048}