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