Merge changes I9886ddb7,I851fa16e,I3b7b0bf5,Ib7f2ce87,I7d0cf295,I35ae6fcb,I14c86257...
[yangtools.git] / yang / yang-data-impl / src / main / java / org / opendaylight / yangtools / yang / data / impl / NodeUtils.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.data.impl;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Joiner;
12 import com.google.common.collect.Iterables;
13 import com.google.common.collect.Lists;
14 import com.google.common.collect.Maps;
15
16 import java.util.AbstractMap.SimpleEntry;
17 import java.util.ArrayDeque;
18 import java.util.ArrayList;
19 import java.util.Deque;
20 import java.util.HashMap;
21 import java.util.List;
22 import java.util.Map;
23
24 import javax.xml.parsers.DocumentBuilder;
25 import javax.xml.parsers.DocumentBuilderFactory;
26 import javax.xml.parsers.ParserConfigurationException;
27 import javax.xml.xpath.XPath;
28 import javax.xml.xpath.XPathConstants;
29 import javax.xml.xpath.XPathExpression;
30 import javax.xml.xpath.XPathExpressionException;
31 import javax.xml.xpath.XPathFactory;
32
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
35 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
36 import org.opendaylight.yangtools.yang.data.api.Node;
37 import org.opendaylight.yangtools.yang.data.api.NodeModification;
38 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45 import org.w3c.dom.Element;
46
47 /**
48  * @author michal.rehak
49  *
50  */
51 public abstract class NodeUtils {
52     private static final Joiner DOT_JOINER = Joiner.on(".");
53     private static final Logger LOG = LoggerFactory.getLogger(NodeUtils.class);
54     private static final Function<QName, String> LOCALNAME_FUNCTION = new Function<QName, String>() {
55         @Override
56         public String apply(final QName input) {
57             return input.getLocalName();
58         }
59     };
60
61     /**
62      *
63      */
64     private static final String USER_KEY_NODE = "node";
65
66     /**
67      * @param node
68      * @return node path up till root node
69      */
70     public static String buildPath(final Node<?> node) {
71         List<String> breadCrumbs = new ArrayList<>();
72         Node<?> tmpNode = node;
73         while (tmpNode != null) {
74             breadCrumbs.add(0, tmpNode.getNodeType().getLocalName());
75             tmpNode = tmpNode.getParent();
76         }
77
78         return DOT_JOINER.join(breadCrumbs);
79     }
80
81     /**
82      * @param treeRootNode
83      * @return dom tree, containing same node structure, yang nodes are
84      *         associated to dom nodes as user data
85      */
86     public static org.w3c.dom.Document buildShadowDomTree(final CompositeNode treeRootNode) {
87         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
88         org.w3c.dom.Document doc = null;
89         try {
90             DocumentBuilder bob = dbf.newDocumentBuilder();
91             doc = bob.newDocument();
92         } catch (ParserConfigurationException e) {
93             LOG.error("documentBuilder problem", e);
94             return null;
95         }
96
97         final Deque<SimpleEntry<org.w3c.dom.Node, Node<?>>> jobQueue = new ArrayDeque<>();
98         jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(doc, treeRootNode));
99
100         while (!jobQueue.isEmpty()) {
101             SimpleEntry<org.w3c.dom.Node, Node<?>> job = jobQueue.pop();
102             org.w3c.dom.Node jointPlace = job.getKey();
103             Node<?> item = job.getValue();
104             QName nodeType = item.getNodeType();
105             Element itemEl = doc.createElementNS(nodeType.getNamespace().toString(), item.getNodeType().getLocalName());
106             itemEl.setUserData(USER_KEY_NODE, item, null);
107             if (item instanceof SimpleNode<?>) {
108                 Object value = ((SimpleNode<?>) item).getValue();
109                 if(value != null) {
110                     itemEl.setTextContent(String.valueOf(value));
111                 }
112             }
113             if (item instanceof NodeModification) {
114                 ModifyAction modificationAction = ((NodeModification) item).getModificationAction();
115                 if (modificationAction != null) {
116                     itemEl.setAttribute("modifyAction", modificationAction.toString());
117                 }
118             }
119
120             jointPlace.appendChild(itemEl);
121
122             if (item instanceof CompositeNode) {
123                 for (Node<?> child : ((CompositeNode) item).getValue()) {
124                     jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(itemEl, child));
125                 }
126             }
127         }
128
129         return doc;
130     }
131
132     /**
133      * @param doc
134      * @param xpathEx
135      * @return user data value on found node
136      * @throws XPathExpressionException
137      */
138     @SuppressWarnings("unchecked")
139     public static <T> T findNodeByXpath(final org.w3c.dom.Document doc, final String xpathEx) throws XPathExpressionException {
140         T userNode = null;
141         XPathFactory xPathfactory = XPathFactory.newInstance();
142         XPath xpath = xPathfactory.newXPath();
143         XPathExpression expr = xpath.compile(xpathEx);
144
145         org.w3c.dom.Node result = (org.w3c.dom.Node) expr.evaluate(doc, XPathConstants.NODE);
146         if (result != null) {
147             userNode = (T) result.getUserData(USER_KEY_NODE);
148         }
149
150         return userNode;
151     }
152
153     /**
154      * build NodeMap, where key = qName; value = node
155      *
156      * @param value
157      * @return map of children, where key = qName and value is list of children
158      *         groupped by qName
159      */
160     public static Map<QName, List<Node<?>>> buildNodeMap(final List<Node<?>> value) {
161         Map<QName, List<Node<?>>> nodeMapTmp = Maps.newLinkedHashMap();
162         if (value == null) {
163             throw new IllegalStateException("nodeList should not be null or empty");
164         }
165         for (Node<?> node : value) {
166             List<Node<?>> qList = nodeMapTmp.get(node.getNodeType());
167             if (qList == null) {
168                 qList = new ArrayList<>();
169                 nodeMapTmp.put(node.getNodeType(), qList);
170             }
171             qList.add(node);
172         }
173         return nodeMapTmp;
174     }
175
176     /**
177      * @param context
178      * @return map of lists, where key = path; value = {@link DataSchemaNode}
179      */
180     public static Map<String, ListSchemaNode> buildMapOfListNodes(final SchemaContext context) {
181         Map<String, ListSchemaNode> mapOfLists = new HashMap<>();
182
183         final Deque<DataSchemaNode> jobQueue = new ArrayDeque<>();
184         jobQueue.addAll(context.getDataDefinitions());
185
186         while (!jobQueue.isEmpty()) {
187             DataSchemaNode dataSchema = jobQueue.pop();
188             if (dataSchema instanceof ListSchemaNode) {
189                 mapOfLists.put(schemaPathToPath(dataSchema.getPath().getPathFromRoot()), (ListSchemaNode) dataSchema);
190             }
191
192             if (dataSchema instanceof DataNodeContainer) {
193                 jobQueue.addAll(((DataNodeContainer) dataSchema).getChildNodes());
194             }
195         }
196
197         return mapOfLists;
198     }
199
200     /**
201      * @param qNamesPath
202      * @return path
203      */
204     private static String schemaPathToPath(final Iterable<QName> qNamesPath) {
205         return DOT_JOINER.join(Iterables.transform(qNamesPath, LOCALNAME_FUNCTION));
206     }
207
208     /**
209      * add given node to it's parent's list of children
210      *
211      * @param newNode
212      */
213     public static void fixParentRelation(final Node<?> newNode) {
214         if (newNode.getParent() != null) {
215             List<Node<?>> siblings = newNode.getParent().getValue();
216             if (!siblings.contains(newNode)) {
217                 siblings.add(newNode);
218             }
219         }
220     }
221
222     /**
223      * crawl all children of given node and assign it as their parent
224      *
225      * @param parentNode
226      */
227     public static void fixChildrenRelation(final CompositeNode parentNode) {
228         if (parentNode.getValue() != null) {
229             for (Node<?> child : parentNode.getValue()) {
230                 if (child instanceof AbstractNodeTO<?>) {
231                     ((AbstractNodeTO<?>) child).setParent(parentNode);
232                 }
233             }
234         }
235     }
236
237     /**
238      * @param keys
239      * @param dataMap
240      * @return list of values of map, found by given keys
241      */
242     public static <T, K> List<K> collectMapValues(final List<T> keys, final Map<T, K> dataMap) {
243         List<K> valueSubList = new ArrayList<>();
244         for (T key : keys) {
245             valueSubList.add(dataMap.get(key));
246         }
247
248         return valueSubList;
249     }
250
251     /**
252      * @param nodes
253      * @return list of children in list of appropriate type
254      */
255     public static List<Node<?>> buildChildrenList(final Node<?>... nodes) {
256         return Lists.newArrayList(nodes);
257     }
258
259 }