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.Iterator;
15 import java.util.LinkedList;
16 import java.util.List;
18 import org.opendaylight.yangtools.yang.common.QName;
19 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
20 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
21 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
22 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
23 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
24 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
25 import org.opendaylight.yangtools.yang.model.api.Module;
26 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
27 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
28 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
29 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
30 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
31 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
37 * The Schema Context Util contains support methods for searching through Schema
38 * Context modules for specified schema nodes via Schema Path or Revision Aware
39 * XPath. The Schema Context Util is designed as mixin, so it is not
43 public final class SchemaContextUtil {
44 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
45 private static final Splitter COLON_SPLITTER = Splitter.on(':');
46 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
48 private SchemaContextUtil() {
52 * Method attempts to find DataSchemaNode in Schema Context via specified
53 * Schema Path. The returned DataSchemaNode from method will be the node at
54 * the end of the SchemaPath. If the DataSchemaNode is not present in the
55 * Schema Context the method will return <code>null</code>. <br>
56 * In case that Schema Context or Schema Path are not specified correctly
57 * (i.e. contains <code>null</code> values) the method will return
58 * IllegalArgumentException.
60 * @throws IllegalArgumentException
65 * Schema Path to search for
66 * @return SchemaNode from the end of the Schema Path or <code>null</code>
67 * if the Node is not present.
69 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
70 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
71 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
73 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
74 if (prefixedPath == null) {
75 LOG.debug("Schema path {} has null path", schemaPath);
79 LOG.trace("Looking for path {} in context {}", schemaPath, context);
80 return findNodeInSchemaContext(context, prefixedPath);
84 * Method attempts to find DataSchemaNode inside of provided Schema Context
85 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
86 * specified Module MUST be present in Schema Context otherwise the
87 * operation would fail and return <code>null</code>. <br>
88 * The Revision Aware XPath MUST be specified WITHOUT the conditional
89 * statement (i.e. without [cond]) in path, because in this state the Schema
90 * Context is completely unaware of data state and will be not able to
91 * properly resolve XPath. If the XPath contains condition the method will
92 * return IllegalArgumentException. <br>
93 * In case that Schema Context or Module or Revision Aware XPath contains
94 * <code>null</code> references the method will throw
95 * IllegalArgumentException <br>
96 * If the Revision Aware XPath is correct and desired Data Schema Node is
97 * present in Yang module or in depending module in Schema Context the
98 * method will return specified Data Schema Node, otherwise the operation
99 * will fail and method will return <code>null</code>.
101 * @throws IllegalArgumentException
107 * @param nonCondXPath
108 * Non Conditional Revision Aware XPath
109 * @return Returns Data Schema Node for specified Schema Context for given
110 * Non-conditional Revision Aware XPath, or <code>null</code> if the
111 * DataSchemaNode is not present in Schema Context.
113 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
114 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
115 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
116 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
118 String strXPath = nonCondXPath.toString();
119 if (strXPath != null) {
120 Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
121 if (nonCondXPath.isAbsolute()) {
122 List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
123 if (qnamedPath != null) {
124 return findNodeInSchemaContext(context, qnamedPath);
132 * Method attempts to find DataSchemaNode inside of provided Schema Context
133 * and Yang Module accordingly to Non-conditional relative Revision Aware
134 * XPath. The specified Module MUST be present in Schema Context otherwise
135 * the operation would fail and return <code>null</code>. <br>
136 * The relative Revision Aware XPath MUST be specified WITHOUT the
137 * conditional statement (i.e. without [cond]) in path, because in this
138 * state the Schema Context is completely unaware of data state and will be
139 * not able to properly resolve XPath. If the XPath contains condition the
140 * method will return IllegalArgumentException. <br>
141 * The Actual Schema Node MUST be specified correctly because from this
142 * Schema Node will search starts. If the Actual Schema Node is not correct
143 * the operation will simply fail, because it will be unable to find desired
144 * DataSchemaNode. <br>
145 * In case that Schema Context or Module or Actual Schema Node or relative
146 * Revision Aware XPath contains <code>null</code> references the method
147 * will throw IllegalArgumentException <br>
148 * If the Revision Aware XPath doesn't have flag
149 * <code>isAbsolute == false</code> the method will throw
150 * IllegalArgumentException. <br>
151 * If the relative Revision Aware XPath is correct and desired Data Schema
152 * Node is present in Yang module or in depending module in Schema Context
153 * the method will return specified Data Schema Node, otherwise the
154 * operation will fail and method will return <code>null</code>.
156 * @throws IllegalArgumentException
162 * @param actualSchemaNode
164 * @param relativeXPath
165 * Relative Non Conditional Revision Aware XPath
166 * @return DataSchemaNode if is present in specified Schema Context for
167 * given relative Revision Aware XPath, otherwise will return
170 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
171 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
172 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
173 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
174 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
175 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
176 Preconditions.checkState(!relativeXPath.isAbsolute(),
177 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
178 + "for non relative Revision Aware XPath use findDataSchemaNode method");
180 SchemaPath actualNodePath = actualSchemaNode.getPath();
181 if (actualNodePath != null) {
182 Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
184 if (qnamePath != null) {
185 return findNodeInSchemaContext(context, qnamePath);
192 * Returns parent Yang Module for specified Schema Context in which Schema
193 * Node is declared. If the Schema Node is not present in Schema Context the
194 * operation will return <code>null</code>. <br>
195 * If Schema Context or Schema Node contains <code>null</code> references
196 * the method will throw IllegalArgumentException
198 * @throws IllegalArgumentException
204 * @return Yang Module for specified Schema Context and Schema Node, if
205 * Schema Node is NOT present, the method will returns
208 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
209 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
210 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
211 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
212 + "set properly (Schema Path is NULL)");
214 final QName qname = Iterables.getFirst(schemaNode.getPath().getPathTowardsRoot(), null);
215 Preconditions.checkState(qname != null,
216 "Schema Path contains invalid state of path parts. " +
217 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
218 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
221 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
222 final QName current = path.iterator().next();
224 LOG.trace("Looking up module {} in context {}", current, path);
225 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
226 if (module == null) {
227 LOG.debug("Module {} not found", current);
231 return findNodeInModule(module, path);
234 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
235 final QName current = path.iterator().next();
237 LOG.trace("Looking for data container {} in module {}", current, module);
238 SchemaNode parent = module.getDataChildByName(current);
239 if (parent != null) {
240 final SchemaNode ret = findNode((DataSchemaNode) parent, nextLevel(path));
246 LOG.trace("Looking for RPC {} in module {}", current, module);
247 parent = getRpcByName(module, current);
248 if (parent != null) {
249 final SchemaNode ret = findNodeInRpc((RpcDefinition) parent, nextLevel(path));
255 LOG.trace("Looking for notification {} in module {}", current, module);
256 parent = getNotificationByName(module, current);
257 if (parent != null) {
258 final SchemaNode ret = findNodeInNotification((NotificationDefinition) parent, nextLevel(path));
264 LOG.trace("Looking for grouping {} in module {}", current, module);
265 parent = getGroupingByName(module, current);
266 if (parent != null) {
267 final SchemaNode ret = findNodeInGrouping((GroupingDefinition) parent, nextLevel(path));
273 LOG.debug("No node matching {} found in module {}", path, module);
277 private static SchemaNode findNodeInGrouping(final GroupingDefinition grouping, final Iterable<QName> path) {
278 final QName current = Iterables.getFirst(path, null);
279 if (current == null) {
280 LOG.debug("Found grouping {}", grouping);
284 LOG.trace("Looking for path {} in grouping {}", path, grouping);
285 final DataSchemaNode node = grouping.getDataChildByName(current);
287 LOG.debug("No node matching {} found in grouping {}", current, grouping);
291 return findNode(node, nextLevel(path));
294 private static SchemaNode findNodeInRpc(final RpcDefinition rpc, final Iterable<QName> path) {
295 final QName current = Iterables.getFirst(path, null);
296 if (current == null) {
297 LOG.debug("Found RPC {}", rpc);
301 LOG.trace("Looking for path {} in rpc {}", path, rpc);
302 switch (current.getLocalName()) {
304 return findNode(rpc.getInput(), nextLevel(path));
306 return findNode(rpc.getOutput(), nextLevel(path));
308 LOG.debug("Invalid component {} of path {} in RPC {}", current, path, rpc);
313 private static SchemaNode findNodeInNotification(final NotificationDefinition ntf, final Iterable<QName> path) {
314 final QName current = Iterables.getFirst(path, null);
315 if (current == null) {
316 LOG.debug("Found notification {}", ntf);
320 LOG.trace("Looking for path {} in notification {}", path, ntf);
321 DataSchemaNode node = ntf.getDataChildByName(current);
323 LOG.debug("No node matching {} found in notification {}", current, ntf);
327 return findNode(node, nextLevel(path));
330 private static SchemaNode findNode(final ChoiceNode parent, final Iterable<QName> path) {
331 final QName current = Iterables.getFirst(path, null);
332 if (current == null) {
335 ChoiceCaseNode node = parent.getCaseNodeByName(current);
337 return findNodeInCase(node, nextLevel(path));
342 private static SchemaNode findNode(final ContainerSchemaNode parent, final Iterable<QName> path) {
343 final QName current = Iterables.getFirst(path, null);
344 if (current == null) {
348 final DataSchemaNode node = parent.getDataChildByName(current);
350 LOG.debug("Failed to find {} in parent {}", path, parent);
354 return findNode(node, nextLevel(path));
357 private static SchemaNode findNode(final ListSchemaNode parent, final Iterable<QName> path) {
358 final QName current = Iterables.getFirst(path, null);
359 if (current == null) {
363 DataSchemaNode node = parent.getDataChildByName(current);
365 LOG.debug("Failed to find {} in parent {}", path, parent);
368 return findNode(node, nextLevel(path));
371 private static SchemaNode findNode(final DataSchemaNode parent, final Iterable<QName> path) {
372 final SchemaNode node;
373 if (!Iterables.isEmpty(path)) {
374 if (parent instanceof ContainerSchemaNode) {
375 node = findNode((ContainerSchemaNode) parent, path);
376 } else if (parent instanceof ListSchemaNode) {
377 node = findNode((ListSchemaNode) parent, path);
378 } else if (parent instanceof ChoiceNode) {
379 node = findNode((ChoiceNode) parent, path);
381 throw new IllegalArgumentException(
382 String.format("Path nesting violation in parent %s path %s", parent, path));
389 LOG.debug("Failed to find {} in parent {}", path, parent);
395 private static SchemaNode findNodeInCase(final ChoiceCaseNode parent, final Iterable<QName> path) {
396 final QName current = Iterables.getFirst(path, null);
397 if (current == null) {
401 DataSchemaNode node = parent.getDataChildByName(current);
403 LOG.debug("Failed to find {} in parent {}", path, parent);
406 return findNode(node, nextLevel(path));
409 private static RpcDefinition getRpcByName(final Module module, final QName name) {
410 for (RpcDefinition rpc : module.getRpcs()) {
411 if (rpc.getQName().equals(name)) {
418 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
419 return Iterables.skip(path, 1);
422 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
423 for (NotificationDefinition notification : module.getNotifications()) {
424 if (notification.getQName().equals(name)) {
431 private static GroupingDefinition getGroupingByName(final Module module, final QName name) {
432 for (GroupingDefinition grouping : module.getGroupings()) {
433 if (grouping.getQName().equals(name)) {
441 * Transforms string representation of XPath to Queue of QNames. The XPath
442 * is split by "/" and for each part of XPath is assigned correct module in
444 * If Schema Context, Parent Module or XPath string contains
445 * <code>null</code> values, the method will throws IllegalArgumentException
447 * @throws IllegalArgumentException
451 * @param parentModule
455 * @return return a list of QName
457 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
458 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
459 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
460 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
462 List<QName> path = new LinkedList<QName>();
463 for (String pathComponent : SLASH_SPLITTER.split(xpath)) {
464 if (!pathComponent.isEmpty()) {
465 path.add(stringPathPartToQName(context, parentModule, pathComponent));
472 * Transforms part of Prefixed Path as java String to QName. <br>
473 * If the string contains module prefix separated by ":" (i.e.
474 * mod:container) this module is provided from from Parent Module list of
475 * imports. If the Prefixed module is present in Schema Context the QName
476 * can be constructed. <br>
477 * If the Prefixed Path Part does not contains prefix the Parent's Module
478 * namespace is taken for construction of QName. <br>
479 * If Schema Context, Parent Module or Prefixed Path Part refers to
480 * <code>null</code> the method will throw IllegalArgumentException
482 * @throws IllegalArgumentException
486 * @param parentModule
488 * @param prefixedPathPart
489 * Prefixed Path Part string
490 * @return QName from prefixed Path Part String.
492 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
493 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
494 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
495 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
497 if (prefixedPathPart.indexOf(':') != -1) {
498 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
499 final String modulePrefix = prefixedName.next();
501 Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
502 Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
503 modulePrefix, parentModule.getName());
505 // FIXME: Module should have a QNameModule handle
506 return QName.create(module.getNamespace(), module.getRevision(), prefixedName.next());
508 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
513 * Method will attempt to resolve and provide Module reference for specified
514 * module prefix. Each Yang module could contains multiple imports which
515 * MUST be associated with corresponding module prefix. The method simply
516 * looks into module imports and returns the module that is bounded with
517 * specified prefix. If the prefix is not present in module or the prefixed
518 * module is not present in specified Schema Context, the method will return
519 * <code>null</code>. <br>
520 * If String prefix is the same as prefix of the specified Module the
521 * reference to this module is returned. <br>
522 * If Schema Context, Module or Prefix are referring to <code>null</code>
523 * the method will return IllegalArgumentException
525 * @throws IllegalArgumentException
533 * @return Module for given prefix in specified Schema Context if is
534 * present, otherwise returns <code>null</code>
536 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
537 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
538 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
539 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
541 if (prefix.equals(module.getPrefix())) {
545 Set<ModuleImport> imports = module.getImports();
546 for (ModuleImport mi : imports) {
547 if (prefix.equals(mi.getPrefix())) {
548 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
555 * @throws IllegalArgumentException
561 * @param relativeXPath
562 * Non conditional Revision Aware Relative XPath
563 * @param leafrefSchemaPath
564 * Schema Path for Leafref
565 * @return list of QName
567 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
568 final RevisionAwareXPath relativeXPath, final SchemaNode leafrefParentNode) {
569 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
570 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
571 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
572 Preconditions.checkState(!relativeXPath.isAbsolute(),
573 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
574 + "for non relative Revision Aware XPath use findDataSchemaNode method");
575 Preconditions.checkState(leafrefParentNode.getPath() != null,
576 "Schema Path reference for Leafref cannot be NULL");
578 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
580 // Find out how many "parent" components there are
581 // FIXME: is .contains() the right check here?
583 for (Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
587 final Iterable<QName> parent = leafrefParentNode.getPath().getPathFromRoot();
588 return Iterables.concat(Iterables.limit(parent, Iterables.size(parent) - colCount),
589 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
591 public QName apply(final String input) {
592 return stringPathPartToQName(context, module, input);