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.annotations.Beta;
11 import com.google.common.base.Function;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Iterables;
16 import java.util.Arrays;
17 import java.util.Iterator;
18 import java.util.LinkedList;
19 import java.util.List;
21 import java.util.regex.Pattern;
22 import javax.annotation.Nonnull;
23 import javax.annotation.Nullable;
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.common.QNameModule;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
32 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.Module;
35 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
36 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
37 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
38 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
39 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
40 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
48 * The Schema Context Util contains support methods for searching through Schema
49 * Context modules for specified schema nodes via Schema Path or Revision Aware
50 * XPath. The Schema Context Util is designed as mixin, so it is not
54 public final class SchemaContextUtil {
55 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
56 private static final Splitter COLON_SPLITTER = Splitter.on(':');
57 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
59 private SchemaContextUtil() {
63 * Method attempts to find DataSchemaNode in Schema Context via specified
64 * Schema Path. The returned DataSchemaNode from method will be the node at
65 * the end of the SchemaPath. If the DataSchemaNode is not present in the
66 * Schema Context the method will return <code>null</code>. <br>
67 * In case that Schema Context or Schema Path are not specified correctly
68 * (i.e. contains <code>null</code> values) the method will return
69 * IllegalArgumentException.
71 * @throws IllegalArgumentException
76 * Schema Path to search for
77 * @return SchemaNode from the end of the Schema Path or <code>null</code>
78 * if the Node is not present.
80 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
81 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
82 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
84 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
85 if (prefixedPath == null) {
86 LOG.debug("Schema path {} has null path", schemaPath);
90 LOG.trace("Looking for path {} in context {}", schemaPath, context);
91 return findNodeInSchemaContext(context, prefixedPath);
95 * Method attempts to find DataSchemaNode inside of provided Schema Context
96 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
97 * specified Module MUST be present in Schema Context otherwise the
98 * operation would fail and return <code>null</code>. <br>
99 * The Revision Aware XPath MUST be specified WITHOUT the conditional
100 * statement (i.e. without [cond]) in path, because in this state the Schema
101 * Context is completely unaware of data state and will be not able to
102 * properly resolve XPath. If the XPath contains condition the method will
103 * return IllegalArgumentException. <br>
104 * In case that Schema Context or Module or Revision Aware XPath contains
105 * <code>null</code> references the method will throw
106 * IllegalArgumentException <br>
107 * If the Revision Aware XPath is correct and desired Data Schema Node is
108 * present in Yang module or in depending module in Schema Context the
109 * method will return specified Data Schema Node, otherwise the operation
110 * will fail and method will return <code>null</code>.
112 * @throws IllegalArgumentException
118 * @param nonCondXPath
119 * Non Conditional Revision Aware XPath
120 * @return Returns Data Schema Node for specified Schema Context for given
121 * Non-conditional Revision Aware XPath, or <code>null</code> if the
122 * DataSchemaNode is not present in Schema Context.
124 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
125 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
126 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
127 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
129 final String strXPath = nonCondXPath.toString();
130 if (strXPath != null) {
131 Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
132 if (nonCondXPath.isAbsolute()) {
133 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
134 if (qnamedPath != null) {
135 return findNodeInSchemaContext(context, qnamedPath);
143 * Method attempts to find DataSchemaNode inside of provided Schema Context
144 * and Yang Module accordingly to Non-conditional relative Revision Aware
145 * XPath. The specified Module MUST be present in Schema Context otherwise
146 * the operation would fail and return <code>null</code>. <br>
147 * The relative Revision Aware XPath MUST be specified WITHOUT the
148 * conditional statement (i.e. without [cond]) in path, because in this
149 * state the Schema Context is completely unaware of data state and will be
150 * not able to properly resolve XPath. If the XPath contains condition the
151 * method will return IllegalArgumentException. <br>
152 * The Actual Schema Node MUST be specified correctly because from this
153 * Schema Node will search starts. If the Actual Schema Node is not correct
154 * the operation will simply fail, because it will be unable to find desired
155 * DataSchemaNode. <br>
156 * In case that Schema Context or Module or Actual Schema Node or relative
157 * Revision Aware XPath contains <code>null</code> references the method
158 * will throw IllegalArgumentException <br>
159 * If the Revision Aware XPath doesn't have flag
160 * <code>isAbsolute == false</code> the method will throw
161 * IllegalArgumentException. <br>
162 * If the relative Revision Aware XPath is correct and desired Data Schema
163 * Node is present in Yang module or in depending module in Schema Context
164 * the method will return specified Data Schema Node, otherwise the
165 * operation will fail and method will return <code>null</code>.
167 * @throws IllegalArgumentException
173 * @param actualSchemaNode
175 * @param relativeXPath
176 * Relative Non Conditional Revision Aware XPath
177 * @return DataSchemaNode if is present in specified Schema Context for
178 * given relative Revision Aware XPath, otherwise will return
181 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
182 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
183 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
184 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
185 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
186 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
187 Preconditions.checkState(!relativeXPath.isAbsolute(),
188 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
189 + "for non relative Revision Aware XPath use findDataSchemaNode method");
191 final SchemaPath actualNodePath = actualSchemaNode.getPath();
192 if (actualNodePath != null) {
193 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
195 if (qnamePath != null) {
196 return findNodeInSchemaContext(context, qnamePath);
203 * Returns parent Yang Module for specified Schema Context in which Schema
204 * Node is declared. If the Schema Node is not present in Schema Context the
205 * operation will return <code>null</code>. <br>
206 * If Schema Context or Schema Node contains <code>null</code> references
207 * the method will throw IllegalArgumentException
209 * @throws IllegalArgumentException
215 * @return Yang Module for specified Schema Context and Schema Node, if
216 * Schema Node is NOT present, the method will returns
219 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
220 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
221 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
222 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
223 + "set properly (Schema Path is NULL)");
225 final QName qname = schemaNode.getPath().getLastComponent();
226 Preconditions.checkState(qname != null,
227 "Schema Path contains invalid state of path parts. " +
228 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
229 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
232 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
233 final QName current = path.iterator().next();
235 LOG.trace("Looking up module {} in context {}", current, path);
236 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
237 if (module == null) {
238 LOG.debug("Module {} not found", current);
242 return findNodeInModule(module, path);
246 * Returns NotificationDefinition from Schema Context
248 * @param schema SchemaContext in which lookup should be performed.
249 * @param path Schema Path of notification
250 * @return Notification schema or null, if notification is not present in schema context.
253 @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
254 Preconditions.checkNotNull(schema, "Schema context must not be null.");
255 Preconditions.checkNotNull(path, "Schema path must not be null.");
256 for (final NotificationDefinition potential : schema.getNotifications()) {
257 if (path.equals(potential.getPath())) {
265 * Returns RPC Input or Output Data container from RPC definition.
267 * @param schema SchemaContext in which lookup should be performed.
268 * @param path Schema path of RPC input/output data container
269 * @return Notification schema or null, if notification is not present in schema context.
272 @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
273 Preconditions.checkNotNull(schema, "Schema context must not be null.");
274 Preconditions.checkNotNull(path, "Schema path must not be null.");
275 final Iterator<QName> it = path.getPathFromRoot().iterator();
276 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
277 final QName rpcName = it.next();
278 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
279 final QName inOrOut = it.next();
280 for (final RpcDefinition potential : schema.getOperations()) {
281 if (rpcName.equals(potential.getQName())) {
282 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
288 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
290 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
291 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
293 if (!path.iterator().hasNext()) {
294 LOG.debug("No node matching {} found in node {}", path, module);
298 final QName current = path.iterator().next();
299 LOG.trace("Looking for node {} in module {}", current, module);
301 SchemaNode foundNode = null;
302 final Iterable<QName> nextPath = nextLevel(path);
304 foundNode = module.getDataChildByName(current);
305 if (foundNode != null && nextPath.iterator().hasNext()) {
306 foundNode = findNodeIn(foundNode, nextPath);
309 if (foundNode == null) {
310 foundNode = getGroupingByName(module, current);
311 if (foundNode != null && nextPath.iterator().hasNext()) {
312 foundNode = findNodeIn(foundNode, nextPath);
316 if (foundNode == null) {
317 foundNode = getRpcByName(module, current);
318 if (foundNode != null && nextPath.iterator().hasNext()) {
319 foundNode = findNodeIn(foundNode, nextPath);
323 if (foundNode == null) {
324 foundNode = getNotificationByName(module, current);
325 if (foundNode != null && nextPath.iterator().hasNext()) {
326 foundNode = findNodeIn(foundNode, nextPath);
330 if (foundNode == null) {
331 LOG.debug("No node matching {} found in node {}", path, module);
338 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
340 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
341 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
343 if (!path.iterator().hasNext()) {
344 LOG.debug("No node matching {} found in node {}", path, parent);
348 final QName current = path.iterator().next();
349 LOG.trace("Looking for node {} in node {}", current, parent);
351 SchemaNode foundNode = null;
352 final Iterable<QName> nextPath = nextLevel(path);
354 if (parent instanceof DataNodeContainer) {
355 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
357 foundNode = parentDataNodeContainer.getDataChildByName(current);
358 if (foundNode != null && nextPath.iterator().hasNext()) {
359 foundNode = findNodeIn(foundNode, nextPath);
362 if (foundNode == null) {
363 foundNode = getGroupingByName(parentDataNodeContainer, current);
364 if (foundNode != null && nextPath.iterator().hasNext()) {
365 foundNode = findNodeIn(foundNode, nextPath);
370 if (foundNode == null && parent instanceof RpcDefinition) {
371 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
373 if (current.getLocalName().equals("input")) {
374 foundNode = parentRpcDefinition.getInput();
375 if (foundNode != null && nextPath.iterator().hasNext()) {
376 foundNode = findNodeIn(foundNode, nextPath);
380 if (current.getLocalName().equals("output")) {
381 foundNode = parentRpcDefinition.getOutput();
382 if (foundNode != null && nextPath.iterator().hasNext()) {
383 foundNode = findNodeIn(foundNode, nextPath);
387 if (foundNode == null) {
388 foundNode = getGroupingByName(parentRpcDefinition, current);
389 if (foundNode != null && nextPath.iterator().hasNext()) {
390 foundNode = findNodeIn(foundNode, nextPath);
395 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
396 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
397 if (foundNode != null && nextPath.iterator().hasNext()) {
398 foundNode = findNodeIn(foundNode, nextPath);
402 if (foundNode == null) {
403 LOG.debug("No node matching {} found in node {}", path, parent);
410 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
411 return Iterables.skip(path, 1);
414 private static RpcDefinition getRpcByName(final Module module, final QName name) {
415 for (final RpcDefinition rpc : module.getRpcs()) {
416 if (rpc.getQName().equals(name)) {
423 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
424 for (final NotificationDefinition notification : module.getNotifications()) {
425 if (notification.getQName().equals(name)) {
432 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
433 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
434 if (grouping.getQName().equals(name)) {
441 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
442 for (final GroupingDefinition grouping : rpc.getGroupings()) {
443 if (grouping.getQName().equals(name)) {
451 * Transforms string representation of XPath to Queue of QNames. The XPath
452 * is split by "/" and for each part of XPath is assigned correct module in
454 * If Schema Context, Parent Module or XPath string contains
455 * <code>null</code> values, the method will throws IllegalArgumentException
457 * @throws IllegalArgumentException
461 * @param parentModule
465 * @return return a list of QName
467 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
468 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
469 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
470 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
472 final List<QName> path = new LinkedList<QName>();
473 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
474 if (!pathComponent.isEmpty()) {
475 path.add(stringPathPartToQName(context, parentModule, pathComponent));
482 * Transforms part of Prefixed Path as java String to QName. <br>
483 * If the string contains module prefix separated by ":" (i.e.
484 * mod:container) this module is provided from from Parent Module list of
485 * imports. If the Prefixed module is present in Schema Context the QName
486 * can be constructed. <br>
487 * If the Prefixed Path Part does not contains prefix the Parent's Module
488 * namespace is taken for construction of QName. <br>
489 * If Schema Context, Parent Module or Prefixed Path Part refers to
490 * <code>null</code> the method will throw IllegalArgumentException
492 * @throws IllegalArgumentException
496 * @param parentModule
498 * @param prefixedPathPart
499 * Prefixed Path Part string
500 * @return QName from prefixed Path Part String.
502 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
503 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
504 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
505 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
507 if (prefixedPathPart.indexOf(':') != -1) {
508 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
509 final String modulePrefix = prefixedName.next();
511 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
512 Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
513 modulePrefix, parentModule.getName());
515 return QName.create(module.getQNameModule(), prefixedName.next());
517 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
522 * Method will attempt to resolve and provide Module reference for specified
523 * module prefix. Each Yang module could contains multiple imports which
524 * MUST be associated with corresponding module prefix. The method simply
525 * looks into module imports and returns the module that is bounded with
526 * specified prefix. If the prefix is not present in module or the prefixed
527 * module is not present in specified Schema Context, the method will return
528 * <code>null</code>. <br>
529 * If String prefix is the same as prefix of the specified Module the
530 * reference to this module is returned. <br>
531 * If Schema Context, Module or Prefix are referring to <code>null</code>
532 * the method will return IllegalArgumentException
534 * @throws IllegalArgumentException
542 * @return Module for given prefix in specified Schema Context if is
543 * present, otherwise returns <code>null</code>
545 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
546 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
547 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
548 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
550 if (prefix.equals(module.getPrefix())) {
554 final Set<ModuleImport> imports = module.getImports();
555 for (final ModuleImport mi : imports) {
556 if (prefix.equals(mi.getPrefix())) {
557 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
564 * @throws IllegalArgumentException
570 * @param relativeXPath
571 * Non conditional Revision Aware Relative XPath
572 * @param actualSchemaNode
574 * @return list of QName
576 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
577 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
578 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
579 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
580 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
581 Preconditions.checkState(!relativeXPath.isAbsolute(),
582 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
583 + "for non relative Revision Aware XPath use findDataSchemaNode method");
584 Preconditions.checkState(actualSchemaNode.getPath() != null,
585 "Schema Path reference for Leafref cannot be NULL");
587 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
589 // Find out how many "parent" components there are
590 // FIXME: is .contains() the right check here?
591 // FIXME: case ../../node1/node2/../node3/../node4
593 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
597 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
599 if (Iterables.size(schemaNodePath) - colCount >= 0) {
600 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
601 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
603 public QName apply(final String input) {
604 return stringPathPartToQName(context, module, input);
608 return Iterables.concat(schemaNodePath,
609 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
611 public QName apply(final String input) {
612 return stringPathPartToQName(context, module, input);
618 * 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
621 * @param typeDefinition
622 * type of node which will be extracted
623 * @param schemaContext
627 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
629 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
630 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
631 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
633 SchemaNode baseSchema = schema;
634 while (baseSchema instanceof DerivableSchemaNode) {
635 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
636 if (basePotential.isPresent()) {
637 baseSchema = basePotential.get();
643 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
645 final DataSchemaNode dataSchemaNode;
646 if(pathStatement.isAbsolute()) {
647 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, pathStatement);
649 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, baseSchema, pathStatement);
652 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
653 // and current expected behaviour for such cases is to just use pure string
654 // This should throw an exception about incorrect XPath in leafref
655 if(dataSchemaNode == null) {
659 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
661 if(targetTypeDefinition instanceof LeafrefTypeDefinition) {
662 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
664 return targetTypeDefinition;
668 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
669 final SchemaNode schemaNode) {
670 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
671 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
672 TypeDefinition<?> nodeType = null;
674 if (schemaNode instanceof LeafSchemaNode) {
675 nodeType = ((LeafSchemaNode) schemaNode).getType();
676 } else if (schemaNode instanceof LeafListSchemaNode) {
677 nodeType = ((LeafListSchemaNode) schemaNode).getType();
680 if (nodeType.getBaseType() != null) {
681 while (nodeType.getBaseType() != null) {
682 nodeType = nodeType.getBaseType();
685 final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
686 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
687 typeDefModuleQname.getRevision());
690 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
694 * @deprecated due to expensive lookup
695 * Returns parent Yang Module for specified Schema Context in which Schema
696 * Node is declared. If Schema Node is of type 'ExtendedType' it tries to find parent module
697 * in which the type was originally declared (needed for correct leafref path resolution). <br>
698 * If the Schema Node is not present in Schema Context the
699 * operation will return <code>null</code>. <br>
700 * If Schema Context or Schema Node contains <code>null</code> references
701 * the method will throw IllegalArgumentException
703 * @throws IllegalArgumentException
705 * @param schemaContext
709 * @return Yang Module for specified Schema Context and Schema Node, if
710 * Schema Node is NOT present, the method will returns
714 public static Module findParentModuleByType(final SchemaContext schemaContext, final SchemaNode schemaNode) {
715 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
716 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
717 TypeDefinition<?> nodeType = null;
719 if (schemaNode instanceof LeafSchemaNode) {
720 nodeType = ((LeafSchemaNode) schemaNode).getType();
721 } else if (schemaNode instanceof LeafListSchemaNode) {
722 nodeType = ((LeafListSchemaNode) schemaNode).getType();
725 if (!BaseTypes.isYangBuildInType(nodeType) && nodeType.getBaseType() != null) {
726 while (nodeType.getBaseType() != null && !BaseTypes.isYangBuildInType(nodeType.getBaseType())) {
727 nodeType = nodeType.getBaseType();
730 QNameModule typeDefModuleQname = nodeType.getQName().getModule();
732 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
733 typeDefModuleQname.getRevision());
736 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
740 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case
741 * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef
742 * which is then imported to referenced module.
744 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
746 * @param typeDefinition
747 * @param schemaContext
751 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
752 final SchemaContext schemaContext, final QName qName) {
753 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
754 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
755 if (!strippedPathStatement.isAbsolute()) {
759 final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision());
760 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement);
761 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
762 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
763 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
765 return targetTypeDefinition;
769 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[.*\\]");
772 * Removes conditions from xPath pointed to target node.
774 * @param pathStatement
775 * xPath to target node
776 * @return string representation of xPath without conditions
779 private static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
780 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
784 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
787 * a node representing LeafSchemaNode
788 * @return concrete type definition of node value
790 private static TypeDefinition<? extends Object> typeDefinition(final LeafSchemaNode node) {
791 TypeDefinition<?> baseType = node.getType();
792 while (baseType.getBaseType() != null) {
793 baseType = baseType.getBaseType();
799 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
802 * a node representing LeafListSchemaNode
803 * @return concrete type definition of node value
805 private static TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
806 TypeDefinition<?> baseType = node.getType();
807 while (baseType.getBaseType() != null) {
808 baseType = baseType.getBaseType();
814 * Gets the base type of DataSchemaNode value.
817 * a node representing DataSchemaNode
818 * @return concrete type definition of node value
820 private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
821 if (node instanceof LeafListSchemaNode) {
822 return typeDefinition((LeafListSchemaNode) node);
823 } else if (node instanceof LeafSchemaNode) {
824 return typeDefinition((LeafSchemaNode) node);
826 throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());