2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.model.util;
10 import com.google.common.base.Function;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Splitter;
13 import com.google.common.collect.Iterables;
14 import java.util.Arrays;
15 import java.util.Iterator;
16 import java.util.LinkedList;
17 import java.util.List;
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
22 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
23 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
25 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
27 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
32 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
33 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
34 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
35 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
36 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
38 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
39 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * The Schema Context Util contains support methods for searching through Schema
45 * Context modules for specified schema nodes via Schema Path or Revision Aware
46 * XPath. The Schema Context Util is designed as mixin, so it is not
50 public final class SchemaContextUtil {
51 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
52 private static final Splitter COLON_SPLITTER = Splitter.on(':');
53 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
55 private SchemaContextUtil() {
59 * Method attempts to find DataSchemaNode in Schema Context via specified
60 * Schema Path. The returned DataSchemaNode from method will be the node at
61 * the end of the SchemaPath. If the DataSchemaNode is not present in the
62 * Schema Context the method will return <code>null</code>. <br>
63 * In case that Schema Context or Schema Path are not specified correctly
64 * (i.e. contains <code>null</code> values) the method will return
65 * IllegalArgumentException.
67 * @throws IllegalArgumentException
72 * Schema Path to search for
73 * @return SchemaNode from the end of the Schema Path or <code>null</code>
74 * if the Node is not present.
76 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
77 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
78 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
80 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
81 if (prefixedPath == null) {
82 LOG.debug("Schema path {} has null path", schemaPath);
86 LOG.trace("Looking for path {} in context {}", schemaPath, context);
87 return findNodeInSchemaContext(context, prefixedPath);
91 * Method attempts to find DataSchemaNode inside of provided Schema Context
92 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
93 * specified Module MUST be present in Schema Context otherwise the
94 * operation would fail and return <code>null</code>. <br>
95 * The Revision Aware XPath MUST be specified WITHOUT the conditional
96 * statement (i.e. without [cond]) in path, because in this state the Schema
97 * Context is completely unaware of data state and will be not able to
98 * properly resolve XPath. If the XPath contains condition the method will
99 * return IllegalArgumentException. <br>
100 * In case that Schema Context or Module or Revision Aware XPath contains
101 * <code>null</code> references the method will throw
102 * IllegalArgumentException <br>
103 * If the Revision Aware XPath is correct and desired Data Schema Node is
104 * present in Yang module or in depending module in Schema Context the
105 * method will return specified Data Schema Node, otherwise the operation
106 * will fail and method will return <code>null</code>.
108 * @throws IllegalArgumentException
114 * @param nonCondXPath
115 * Non Conditional Revision Aware XPath
116 * @return Returns Data Schema Node for specified Schema Context for given
117 * Non-conditional Revision Aware XPath, or <code>null</code> if the
118 * DataSchemaNode is not present in Schema Context.
120 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
121 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
122 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
123 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
125 String strXPath = nonCondXPath.toString();
126 if (strXPath != null) {
127 Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
128 if (nonCondXPath.isAbsolute()) {
129 List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
130 if (qnamedPath != null) {
131 return findNodeInSchemaContext(context, qnamedPath);
139 * Method attempts to find DataSchemaNode inside of provided Schema Context
140 * and Yang Module accordingly to Non-conditional relative Revision Aware
141 * XPath. The specified Module MUST be present in Schema Context otherwise
142 * the operation would fail and return <code>null</code>. <br>
143 * The relative Revision Aware XPath MUST be specified WITHOUT the
144 * conditional statement (i.e. without [cond]) in path, because in this
145 * state the Schema Context is completely unaware of data state and will be
146 * not able to properly resolve XPath. If the XPath contains condition the
147 * method will return IllegalArgumentException. <br>
148 * The Actual Schema Node MUST be specified correctly because from this
149 * Schema Node will search starts. If the Actual Schema Node is not correct
150 * the operation will simply fail, because it will be unable to find desired
151 * DataSchemaNode. <br>
152 * In case that Schema Context or Module or Actual Schema Node or relative
153 * Revision Aware XPath contains <code>null</code> references the method
154 * will throw IllegalArgumentException <br>
155 * If the Revision Aware XPath doesn't have flag
156 * <code>isAbsolute == false</code> the method will throw
157 * IllegalArgumentException. <br>
158 * If the relative Revision Aware XPath is correct and desired Data Schema
159 * Node is present in Yang module or in depending module in Schema Context
160 * the method will return specified Data Schema Node, otherwise the
161 * operation will fail and method will return <code>null</code>.
163 * @throws IllegalArgumentException
169 * @param actualSchemaNode
171 * @param relativeXPath
172 * Relative Non Conditional Revision Aware XPath
173 * @return DataSchemaNode if is present in specified Schema Context for
174 * given relative Revision Aware XPath, otherwise will return
177 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
178 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
179 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
180 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
181 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
182 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
183 Preconditions.checkState(!relativeXPath.isAbsolute(),
184 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
185 + "for non relative Revision Aware XPath use findDataSchemaNode method");
187 SchemaPath actualNodePath = actualSchemaNode.getPath();
188 if (actualNodePath != null) {
189 Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
191 if (qnamePath != null) {
192 return findNodeInSchemaContext(context, qnamePath);
199 * Returns parent Yang Module for specified Schema Context in which Schema
200 * Node is declared. If the Schema Node is not present in Schema Context the
201 * operation will return <code>null</code>. <br>
202 * If Schema Context or Schema Node contains <code>null</code> references
203 * the method will throw IllegalArgumentException
205 * @throws IllegalArgumentException
211 * @return Yang Module for specified Schema Context and Schema Node, if
212 * Schema Node is NOT present, the method will returns
215 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
216 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
217 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
218 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
219 + "set properly (Schema Path is NULL)");
221 final QName qname = Iterables.getFirst(schemaNode.getPath().getPathTowardsRoot(), null);
222 Preconditions.checkState(qname != null,
223 "Schema Path contains invalid state of path parts. " +
224 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
225 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
228 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
229 final QName current = path.iterator().next();
231 LOG.trace("Looking up module {} in context {}", current, path);
232 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
233 if (module == null) {
234 LOG.debug("Module {} not found", current);
238 return findNodeInModule(module, path);
241 private static SchemaNode findNodeInModule(Module module, Iterable<QName> path) {
243 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
244 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
246 if (!path.iterator().hasNext()) {
247 LOG.debug("No node matching {} found in node {}", path, module);
251 QName current = path.iterator().next();
252 LOG.trace("Looking for node {} in module {}", current, module);
254 SchemaNode foundNode = null;
255 Iterable<QName> nextPath = nextLevel(path);
257 foundNode = module.getDataChildByName(current);
258 if (foundNode != null && nextPath.iterator().hasNext())
259 foundNode = findNodeIn(foundNode, nextPath);
261 if (foundNode == null) {
262 foundNode = getGroupingByName(module, current);
263 if (foundNode != null && nextPath.iterator().hasNext())
264 foundNode = findNodeIn(foundNode, nextPath);
267 if (foundNode == null) {
268 foundNode = getRpcByName(module, current);
269 if (foundNode != null && nextPath.iterator().hasNext())
270 foundNode = findNodeIn(foundNode, nextPath);
273 if (foundNode == null) {
274 foundNode = getNotificationByName(module, current);
275 if (foundNode != null && nextPath.iterator().hasNext())
276 foundNode = findNodeIn(foundNode, nextPath);
279 if (foundNode == null)
280 LOG.debug("No node matching {} found in node {}", path, module);
286 private static SchemaNode findNodeIn(SchemaNode parent, Iterable<QName> path) {
288 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
289 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
291 if (!path.iterator().hasNext()) {
292 LOG.debug("No node matching {} found in node {}", path, parent);
296 QName current = path.iterator().next();
297 LOG.trace("Looking for node {} in node {}", current, parent);
299 SchemaNode foundNode = null;
300 Iterable<QName> nextPath = nextLevel(path);
302 if (parent instanceof DataNodeContainer) {
303 DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
305 foundNode = parentDataNodeContainer.getDataChildByName(current);
306 if (foundNode != null && nextPath.iterator().hasNext())
307 foundNode = findNodeIn(foundNode, nextPath);
309 if (foundNode == null) {
310 foundNode = getGroupingByName(parentDataNodeContainer, current);
311 if (foundNode != null && nextPath.iterator().hasNext())
312 foundNode = findNodeIn(foundNode, nextPath);
316 if (foundNode == null && parent instanceof RpcDefinition) {
317 RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
319 if (current.getLocalName().equals("input")) {
320 foundNode = parentRpcDefinition.getInput();
321 if (foundNode != null && nextPath.iterator().hasNext())
322 foundNode = findNodeIn(foundNode, nextPath);
325 if (current.getLocalName().equals("output")) {
326 foundNode = parentRpcDefinition.getOutput();
327 if (foundNode != null && nextPath.iterator().hasNext())
328 foundNode = findNodeIn(foundNode, nextPath);
331 if (foundNode == null) {
332 foundNode = getGroupingByName(parentRpcDefinition, current);
333 if (foundNode != null && nextPath.iterator().hasNext())
334 foundNode = findNodeIn(foundNode, nextPath);
338 if (foundNode == null && parent instanceof ChoiceNode) {
339 foundNode = ((ChoiceNode) parent).getCaseNodeByName(current);
340 if (foundNode != null && nextPath.iterator().hasNext())
341 foundNode = findNodeIn(foundNode, nextPath);
344 if (foundNode == null)
345 LOG.debug("No node matching {} found in node {}", path, parent);
351 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
352 return Iterables.skip(path, 1);
355 private static RpcDefinition getRpcByName(final Module module, final QName name) {
356 for (RpcDefinition rpc : module.getRpcs()) {
357 if (rpc.getQName().equals(name)) {
364 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
365 for (NotificationDefinition notification : module.getNotifications()) {
366 if (notification.getQName().equals(name)) {
373 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
374 for (GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
375 if (grouping.getQName().equals(name)) {
382 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
383 for (GroupingDefinition grouping : rpc.getGroupings()) {
384 if (grouping.getQName().equals(name)) {
392 * Transforms string representation of XPath to Queue of QNames. The XPath
393 * is split by "/" and for each part of XPath is assigned correct module in
395 * If Schema Context, Parent Module or XPath string contains
396 * <code>null</code> values, the method will throws IllegalArgumentException
398 * @throws IllegalArgumentException
402 * @param parentModule
406 * @return return a list of QName
408 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
409 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
410 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
411 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
413 List<QName> path = new LinkedList<QName>();
414 for (String pathComponent : SLASH_SPLITTER.split(xpath)) {
415 if (!pathComponent.isEmpty()) {
416 path.add(stringPathPartToQName(context, parentModule, pathComponent));
423 * Transforms part of Prefixed Path as java String to QName. <br>
424 * If the string contains module prefix separated by ":" (i.e.
425 * mod:container) this module is provided from from Parent Module list of
426 * imports. If the Prefixed module is present in Schema Context the QName
427 * can be constructed. <br>
428 * If the Prefixed Path Part does not contains prefix the Parent's Module
429 * namespace is taken for construction of QName. <br>
430 * If Schema Context, Parent Module or Prefixed Path Part refers to
431 * <code>null</code> the method will throw IllegalArgumentException
433 * @throws IllegalArgumentException
437 * @param parentModule
439 * @param prefixedPathPart
440 * Prefixed Path Part string
441 * @return QName from prefixed Path Part String.
443 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
444 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
445 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
446 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
448 if (prefixedPathPart.indexOf(':') != -1) {
449 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
450 final String modulePrefix = prefixedName.next();
452 Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
453 Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
454 modulePrefix, parentModule.getName());
456 return QName.create(module.getQNameModule(), prefixedName.next());
458 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
463 * Method will attempt to resolve and provide Module reference for specified
464 * module prefix. Each Yang module could contains multiple imports which
465 * MUST be associated with corresponding module prefix. The method simply
466 * looks into module imports and returns the module that is bounded with
467 * specified prefix. If the prefix is not present in module or the prefixed
468 * module is not present in specified Schema Context, the method will return
469 * <code>null</code>. <br>
470 * If String prefix is the same as prefix of the specified Module the
471 * reference to this module is returned. <br>
472 * If Schema Context, Module or Prefix are referring to <code>null</code>
473 * the method will return IllegalArgumentException
475 * @throws IllegalArgumentException
483 * @return Module for given prefix in specified Schema Context if is
484 * present, otherwise returns <code>null</code>
486 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
487 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
488 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
489 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
491 if (prefix.equals(module.getPrefix())) {
495 Set<ModuleImport> imports = module.getImports();
496 for (ModuleImport mi : imports) {
497 if (prefix.equals(mi.getPrefix())) {
498 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
505 * @throws IllegalArgumentException
511 * @param relativeXPath
512 * Non conditional Revision Aware Relative XPath
513 * @param actualSchemaNode
515 * @return list of QName
517 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
518 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
519 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
520 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
521 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
522 Preconditions.checkState(!relativeXPath.isAbsolute(),
523 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
524 + "for non relative Revision Aware XPath use findDataSchemaNode method");
525 Preconditions.checkState(actualSchemaNode.getPath() != null,
526 "Schema Path reference for Leafref cannot be NULL");
528 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
530 // Find out how many "parent" components there are
531 // FIXME: is .contains() the right check here?
532 // FIXME: case ../../node1/node2/../node3/../node4
534 for (Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
538 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
540 if (Iterables.size(schemaNodePath) - colCount >= 0) {
541 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
542 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
544 public QName apply(final String input) {
545 return stringPathPartToQName(context, module, input);
549 return Iterables.concat(schemaNodePath,
550 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
552 public QName apply(final String input) {
553 return stringPathPartToQName(context, module, input);
559 * Extracts the base type of node on which schema node points to. If target node is again of type LeafrefTypeDefinition, methods will be call recursively until it reach concrete
562 * @param typeDefinition
563 * type of node which will be extracted
564 * @param schemaContext
568 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
570 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
571 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
572 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
574 final Module parentModule = SchemaContextUtil.findParentModule(schemaContext, schema);
576 final DataSchemaNode dataSchemaNode;
577 if(pathStatement.isAbsolute()) {
578 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, pathStatement);
580 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema, pathStatement);
583 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
584 // and current expected behaviour for such cases is to just use pure string
585 // This should throw an exception about incorrect XPath in leafref
586 if(dataSchemaNode == null) {
590 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
592 if(targetTypeDefinition instanceof LeafrefTypeDefinition) {
593 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
595 return targetTypeDefinition;
600 * Removes conditions from xPath pointed to target node.
602 * @param pathStatement
603 * xPath to target node
604 * @return string representation of xPath without conditions
607 private static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
608 return pathStatement.toString().replaceAll("\\[.*\\]", "");
612 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
615 * a node representing LeafSchemaNode
616 * @return concrete type definition of node value
618 private static TypeDefinition<? extends Object> typeDefinition(final LeafSchemaNode node) {
619 TypeDefinition<?> baseType = node.getType();
620 while (baseType.getBaseType() != null) {
621 baseType = baseType.getBaseType();
627 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
630 * a node representing LeafListSchemaNode
631 * @return concrete type definition of node value
633 private static TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
634 TypeDefinition<?> baseType = node.getType();
635 while (baseType.getBaseType() != null) {
636 baseType = baseType.getBaseType();
642 * Gets the base type of DataSchemaNode value.
645 * a node representing DataSchemaNode
646 * @return concrete type definition of node value
648 private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
649 if (node instanceof LeafListSchemaNode) {
650 return typeDefinition((LeafListSchemaNode) node);
651 } else if (node instanceof LeafSchemaNode) {
652 return typeDefinition((LeafSchemaNode) node);
654 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());