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.annotations.VisibleForTesting;
12 import com.google.common.base.Function;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Splitter;
16 import com.google.common.collect.Iterables;
17 import java.util.Collections;
18 import java.util.Iterator;
19 import java.util.LinkedList;
20 import java.util.List;
22 import java.util.regex.Pattern;
23 import javax.annotation.Nonnull;
24 import javax.annotation.Nullable;
25 import org.opendaylight.yangtools.yang.common.QName;
26 import org.opendaylight.yangtools.yang.common.QNameModule;
27 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
37 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
38 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
43 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * The Schema Context Util contains support methods for searching through Schema
50 * Context modules for specified schema nodes via Schema Path or Revision Aware
51 * XPath. The Schema Context Util is designed as mixin, so it is not
55 public final class SchemaContextUtil {
56 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
57 private static final Splitter COLON_SPLITTER = Splitter.on(':');
58 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
60 private SchemaContextUtil() {
64 * Method attempts to find DataSchemaNode in Schema Context via specified
65 * Schema Path. The returned DataSchemaNode from method will be the node at
66 * the end of the SchemaPath. If the DataSchemaNode is not present in the
67 * Schema Context the method will return <code>null</code>. <br>
68 * In case that Schema Context or Schema Path are not specified correctly
69 * (i.e. contains <code>null</code> values) the method will return
70 * IllegalArgumentException.
72 * @throws IllegalArgumentException
77 * Schema Path to search for
78 * @return SchemaNode from the end of the Schema Path or <code>null</code>
79 * if the Node is not present.
81 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
82 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
83 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
85 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
86 if (prefixedPath == null) {
87 LOG.debug("Schema path {} has null path", schemaPath);
91 LOG.trace("Looking for path {} in context {}", schemaPath, context);
92 return findNodeInSchemaContext(context, prefixedPath);
96 * Method attempts to find DataSchemaNode inside of provided Schema Context
97 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
98 * specified Module MUST be present in Schema Context otherwise the
99 * operation would fail and return <code>null</code>. <br>
100 * The Revision Aware XPath MUST be specified WITHOUT the conditional
101 * statement (i.e. without [cond]) in path, because in this state the Schema
102 * Context is completely unaware of data state and will be not able to
103 * properly resolve XPath. If the XPath contains condition the method will
104 * return IllegalArgumentException. <br>
105 * In case that Schema Context or Module or Revision Aware XPath contains
106 * <code>null</code> references the method will throw
107 * IllegalArgumentException <br>
108 * If the Revision Aware XPath is correct and desired Data Schema Node is
109 * present in Yang module or in depending module in Schema Context the
110 * method will return specified Data Schema Node, otherwise the operation
111 * will fail and method will return <code>null</code>.
113 * @throws IllegalArgumentException
119 * @param nonCondXPath
120 * Non Conditional Revision Aware XPath
121 * @return Returns Data Schema Node for specified Schema Context for given
122 * Non-conditional Revision Aware XPath, or <code>null</code> if the
123 * DataSchemaNode is not present in Schema Context.
125 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
126 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
127 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
128 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
130 final String strXPath = nonCondXPath.toString();
131 if (strXPath != null) {
132 Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
133 if (nonCondXPath.isAbsolute()) {
134 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
135 if (qnamedPath != null) {
136 return findNodeInSchemaContext(context, qnamedPath);
144 * Method attempts to find DataSchemaNode inside of provided Schema Context
145 * and Yang Module accordingly to Non-conditional relative Revision Aware
146 * XPath. The specified Module MUST be present in Schema Context otherwise
147 * the operation would fail and return <code>null</code>. <br>
148 * The relative Revision Aware XPath MUST be specified WITHOUT the
149 * conditional statement (i.e. without [cond]) in path, because in this
150 * state the Schema Context is completely unaware of data state and will be
151 * not able to properly resolve XPath. If the XPath contains condition the
152 * method will return IllegalArgumentException. <br>
153 * The Actual Schema Node MUST be specified correctly because from this
154 * Schema Node will search starts. If the Actual Schema Node is not correct
155 * the operation will simply fail, because it will be unable to find desired
156 * DataSchemaNode. <br>
157 * In case that Schema Context or Module or Actual Schema Node or relative
158 * Revision Aware XPath contains <code>null</code> references the method
159 * will throw IllegalArgumentException <br>
160 * If the Revision Aware XPath doesn't have flag
161 * <code>isAbsolute == false</code> the method will throw
162 * IllegalArgumentException. <br>
163 * If the relative Revision Aware XPath is correct and desired Data Schema
164 * Node is present in Yang module or in depending module in Schema Context
165 * the method will return specified Data Schema Node, otherwise the
166 * operation will fail and method will return <code>null</code>.
168 * @throws IllegalArgumentException
174 * @param actualSchemaNode
176 * @param relativeXPath
177 * Relative Non Conditional Revision Aware XPath
178 * @return DataSchemaNode if is present in specified Schema Context for
179 * given relative Revision Aware XPath, otherwise will return
182 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
183 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
184 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
185 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
186 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
187 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
188 Preconditions.checkState(!relativeXPath.isAbsolute(),
189 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
190 + "for non relative Revision Aware XPath use findDataSchemaNode method");
192 final SchemaPath actualNodePath = actualSchemaNode.getPath();
193 if (actualNodePath != null) {
194 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
196 if (qnamePath != null) {
197 return findNodeInSchemaContext(context, qnamePath);
204 * Returns parent Yang Module for specified Schema Context in which Schema
205 * Node is declared. If the Schema Node is not present in Schema Context the
206 * operation will return <code>null</code>. <br>
207 * If Schema Context or Schema Node contains <code>null</code> references
208 * the method will throw IllegalArgumentException
210 * @throws IllegalArgumentException
216 * @return Yang Module for specified Schema Context and Schema Node, if
217 * Schema Node is NOT present, the method will returns
220 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
221 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
222 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
223 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
224 + "set properly (Schema Path is NULL)");
226 final QName qname = schemaNode.getPath().getLastComponent();
227 Preconditions.checkState(qname != null,
228 "Schema Path contains invalid state of path parts. " +
229 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
230 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
233 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
234 final QName current = path.iterator().next();
236 LOG.trace("Looking up module {} in context {}", current, path);
237 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
238 if (module == null) {
239 LOG.debug("Module {} not found", current);
243 return findNodeInModule(module, path);
247 * Returns NotificationDefinition from Schema Context
249 * @param schema SchemaContext in which lookup should be performed.
250 * @param path Schema Path of notification
251 * @return Notification schema or null, if notification is not present in schema context.
254 @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
255 Preconditions.checkNotNull(schema, "Schema context must not be null.");
256 Preconditions.checkNotNull(path, "Schema path must not be null.");
257 for (final NotificationDefinition potential : schema.getNotifications()) {
258 if (path.equals(potential.getPath())) {
266 * Returns RPC Input or Output Data container from RPC definition.
268 * @param schema SchemaContext in which lookup should be performed.
269 * @param path Schema path of RPC input/output data container
270 * @return Notification schema or null, if notification is not present in schema context.
273 @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
274 Preconditions.checkNotNull(schema, "Schema context must not be null.");
275 Preconditions.checkNotNull(path, "Schema path must not be null.");
276 final Iterator<QName> it = path.getPathFromRoot().iterator();
277 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
278 final QName rpcName = it.next();
279 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
280 final QName inOrOut = it.next();
281 for (final RpcDefinition potential : schema.getOperations()) {
282 if (rpcName.equals(potential.getQName())) {
283 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
289 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
291 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
292 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
294 if (!path.iterator().hasNext()) {
295 LOG.debug("No node matching {} found in node {}", path, module);
299 final QName current = path.iterator().next();
300 LOG.trace("Looking for node {} in module {}", current, module);
302 SchemaNode foundNode = null;
303 final Iterable<QName> nextPath = nextLevel(path);
305 foundNode = module.getDataChildByName(current);
306 if (foundNode != null && nextPath.iterator().hasNext()) {
307 foundNode = findNodeIn(foundNode, nextPath);
310 if (foundNode == null) {
311 foundNode = getGroupingByName(module, current);
312 if (foundNode != null && nextPath.iterator().hasNext()) {
313 foundNode = findNodeIn(foundNode, nextPath);
317 if (foundNode == null) {
318 foundNode = getRpcByName(module, current);
319 if (foundNode != null && nextPath.iterator().hasNext()) {
320 foundNode = findNodeIn(foundNode, nextPath);
324 if (foundNode == null) {
325 foundNode = getNotificationByName(module, current);
326 if (foundNode != null && nextPath.iterator().hasNext()) {
327 foundNode = findNodeIn(foundNode, nextPath);
331 if (foundNode == null) {
332 LOG.debug("No node matching {} found in node {}", path, module);
339 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
341 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
342 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
344 if (!path.iterator().hasNext()) {
345 LOG.debug("No node matching {} found in node {}", path, parent);
349 final QName current = path.iterator().next();
350 LOG.trace("Looking for node {} in node {}", current, parent);
352 SchemaNode foundNode = null;
353 final Iterable<QName> nextPath = nextLevel(path);
355 if (parent instanceof DataNodeContainer) {
356 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
358 foundNode = parentDataNodeContainer.getDataChildByName(current);
359 if (foundNode != null && nextPath.iterator().hasNext()) {
360 foundNode = findNodeIn(foundNode, nextPath);
363 if (foundNode == null) {
364 foundNode = getGroupingByName(parentDataNodeContainer, current);
365 if (foundNode != null && nextPath.iterator().hasNext()) {
366 foundNode = findNodeIn(foundNode, nextPath);
371 if (foundNode == null && parent instanceof RpcDefinition) {
372 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
374 if (current.getLocalName().equals("input")) {
375 foundNode = parentRpcDefinition.getInput();
376 if (foundNode != null && nextPath.iterator().hasNext()) {
377 foundNode = findNodeIn(foundNode, nextPath);
381 if (current.getLocalName().equals("output")) {
382 foundNode = parentRpcDefinition.getOutput();
383 if (foundNode != null && nextPath.iterator().hasNext()) {
384 foundNode = findNodeIn(foundNode, nextPath);
388 if (foundNode == null) {
389 foundNode = getGroupingByName(parentRpcDefinition, current);
390 if (foundNode != null && nextPath.iterator().hasNext()) {
391 foundNode = findNodeIn(foundNode, nextPath);
396 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
397 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
398 if (foundNode != null && nextPath.iterator().hasNext()) {
399 foundNode = findNodeIn(foundNode, nextPath);
403 if (foundNode == null) {
404 LOG.debug("No node matching {} found in node {}", path, parent);
411 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
412 return Iterables.skip(path, 1);
415 private static RpcDefinition getRpcByName(final Module module, final QName name) {
416 for (final RpcDefinition rpc : module.getRpcs()) {
417 if (rpc.getQName().equals(name)) {
424 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
425 for (final NotificationDefinition notification : module.getNotifications()) {
426 if (notification.getQName().equals(name)) {
433 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
434 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
435 if (grouping.getQName().equals(name)) {
442 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
443 for (final GroupingDefinition grouping : rpc.getGroupings()) {
444 if (grouping.getQName().equals(name)) {
452 * Transforms string representation of XPath to Queue of QNames. The XPath
453 * is split by "/" and for each part of XPath is assigned correct module in
455 * If Schema Context, Parent Module or XPath string contains
456 * <code>null</code> values, the method will throws IllegalArgumentException
458 * @throws IllegalArgumentException
462 * @param parentModule
466 * @return return a list of QName
468 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
469 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
470 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
471 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
473 final List<QName> path = new LinkedList<QName>();
474 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
475 if (!pathComponent.isEmpty()) {
476 path.add(stringPathPartToQName(context, parentModule, pathComponent));
483 * Transforms part of Prefixed Path as java String to QName. <br>
484 * If the string contains module prefix separated by ":" (i.e.
485 * mod:container) this module is provided from from Parent Module list of
486 * imports. If the Prefixed module is present in Schema Context the QName
487 * can be constructed. <br>
488 * If the Prefixed Path Part does not contains prefix the Parent's Module
489 * namespace is taken for construction of QName. <br>
490 * If Schema Context, Parent Module or Prefixed Path Part refers to
491 * <code>null</code> the method will throw IllegalArgumentException
493 * @throws IllegalArgumentException
497 * @param parentModule
499 * @param prefixedPathPart
500 * Prefixed Path Part string
501 * @return QName from prefixed Path Part String.
503 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
504 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
505 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
506 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
508 if (prefixedPathPart.indexOf(':') != -1) {
509 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
510 final String modulePrefix = prefixedName.next();
512 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
513 Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
514 modulePrefix, parentModule.getName());
516 return QName.create(module.getQNameModule(), prefixedName.next());
518 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
523 * Method will attempt to resolve and provide Module reference for specified
524 * module prefix. Each Yang module could contains multiple imports which
525 * MUST be associated with corresponding module prefix. The method simply
526 * looks into module imports and returns the module that is bounded with
527 * specified prefix. If the prefix is not present in module or the prefixed
528 * module is not present in specified Schema Context, the method will return
529 * <code>null</code>. <br>
530 * If String prefix is the same as prefix of the specified Module the
531 * reference to this module is returned. <br>
532 * If Schema Context, Module or Prefix are referring to <code>null</code>
533 * the method will return IllegalArgumentException
535 * @throws IllegalArgumentException
543 * @return Module for given prefix in specified Schema Context if is
544 * present, otherwise returns <code>null</code>
546 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
547 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
548 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
549 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
551 if (prefix.equals(module.getPrefix())) {
555 final Set<ModuleImport> imports = module.getImports();
556 for (final ModuleImport mi : imports) {
557 if (prefix.equals(mi.getPrefix())) {
558 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
565 * @throws IllegalArgumentException
571 * @param relativeXPath
572 * Non conditional Revision Aware Relative XPath
573 * @param actualSchemaNode
575 * @return list of QName
577 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
578 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
579 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
580 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
581 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
582 Preconditions.checkState(!relativeXPath.isAbsolute(),
583 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
584 + "for non relative Revision Aware XPath use findDataSchemaNode method");
585 Preconditions.checkState(actualSchemaNode.getPath() != null,
586 "Schema Path reference for Leafref cannot be NULL");
588 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
590 // Find out how many "parent" components there are
591 // FIXME: is .contains() the right check here?
592 // FIXME: case ../../node1/node2/../node3/../node4
594 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
598 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
600 if (Iterables.size(schemaNodePath) - colCount >= 0) {
601 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
602 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
604 public QName apply(final String input) {
605 return stringPathPartToQName(context, module, input);
609 return Iterables.concat(schemaNodePath,
610 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
612 public QName apply(final String input) {
613 return stringPathPartToQName(context, module, input);
619 * 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
622 * @param typeDefinition
623 * type of node which will be extracted
624 * @param schemaContext
628 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
630 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
631 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
632 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
634 final DataSchemaNode dataSchemaNode;
635 if (pathStatement.isAbsolute()) {
636 SchemaNode baseSchema = schema;
637 while (baseSchema instanceof DerivableSchemaNode) {
638 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
639 if (basePotential.isPresent()) {
640 baseSchema = basePotential.get();
646 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
647 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
650 Module parentModule = findParentModule(schemaContext, schema);
651 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
652 parentModule, schema, pathStatement);
655 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
656 // and current expected behaviour for such cases is to just use pure string
657 // This should throw an exception about incorrect XPath in leafref
658 if(dataSchemaNode == null) {
662 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
664 if(targetTypeDefinition instanceof LeafrefTypeDefinition) {
665 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
667 return targetTypeDefinition;
671 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
672 final SchemaNode schemaNode) {
673 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
674 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
675 TypeDefinition<?> nodeType = null;
677 if (schemaNode instanceof LeafSchemaNode) {
678 nodeType = ((LeafSchemaNode) schemaNode).getType();
679 } else if (schemaNode instanceof LeafListSchemaNode) {
680 nodeType = ((LeafListSchemaNode) schemaNode).getType();
683 if (nodeType instanceof ExtendedType) {
684 while (nodeType.getBaseType() instanceof ExtendedType) {
685 nodeType = nodeType.getBaseType();
688 QNameModule typeDefModuleQname = nodeType.getQName().getModule();
689 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
690 typeDefModuleQname.getRevision());
691 } else if (nodeType.getBaseType() != null) {
692 while (nodeType.getBaseType() != null) {
693 nodeType = nodeType.getBaseType();
696 final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
697 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
698 typeDefModuleQname.getRevision());
701 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
705 * @deprecated due to expensive lookup
706 * Returns parent Yang Module for specified Schema Context in which Schema
707 * Node is declared. If Schema Node is of type 'ExtendedType' it tries to find parent module
708 * in which the type was originally declared (needed for correct leafref path resolution). <br>
709 * If the Schema Node is not present in Schema Context the
710 * operation will return <code>null</code>. <br>
711 * If Schema Context or Schema Node contains <code>null</code> references
712 * the method will throw IllegalArgumentException
714 * @throws IllegalArgumentException
716 * @param schemaContext
720 * @return Yang Module for specified Schema Context and Schema Node, if
721 * Schema Node is NOT present, the method will returns
725 public static Module findParentModuleByType(final SchemaContext schemaContext, final SchemaNode schemaNode) {
726 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
727 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
728 TypeDefinition<?> nodeType = null;
730 if (schemaNode instanceof LeafSchemaNode) {
731 nodeType = ((LeafSchemaNode) schemaNode).getType();
732 } else if (schemaNode instanceof LeafListSchemaNode) {
733 nodeType = ((LeafListSchemaNode) schemaNode).getType();
736 if (!BaseTypes.isYangBuildInType(nodeType) && nodeType.getBaseType() != null) {
737 while (nodeType.getBaseType() != null && !BaseTypes.isYangBuildInType(nodeType.getBaseType())) {
738 nodeType = nodeType.getBaseType();
741 QNameModule typeDefModuleQname = nodeType.getQName().getModule();
743 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
744 typeDefModuleQname.getRevision());
747 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
751 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case
752 * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef
753 * which is then imported to referenced module.
755 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
757 * @param typeDefinition
758 * @param schemaContext
762 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
763 final SchemaContext schemaContext, final QName qName) {
764 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
765 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
766 if (!strippedPathStatement.isAbsolute()) {
770 final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision());
771 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement);
772 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
773 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
774 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
776 return targetTypeDefinition;
780 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
783 * Removes conditions from xPath pointed to target node.
785 * @param pathStatement
786 * xPath to target node
787 * @return string representation of xPath without conditions
791 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
792 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
796 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
799 * a node representing LeafSchemaNode
800 * @return concrete type definition of node value
802 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
803 TypeDefinition<?> baseType = node.getType();
804 while (baseType.getBaseType() != null) {
805 baseType = baseType.getBaseType();
811 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
814 * a node representing LeafListSchemaNode
815 * @return concrete type definition of node value
817 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
818 TypeDefinition<?> baseType = node.getType();
819 while (baseType.getBaseType() != null) {
820 baseType = baseType.getBaseType();
826 * Gets the base type of DataSchemaNode value.
829 * a node representing DataSchemaNode
830 * @return concrete type definition of node value
832 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
833 if (node instanceof LeafListSchemaNode) {
834 return typeDefinition((LeafListSchemaNode) node);
835 } else if (node instanceof LeafSchemaNode) {
836 return typeDefinition((LeafSchemaNode) node);
838 throw new IllegalArgumentException("Unhandled parameter types: " + Collections.<Object>singletonList(node).toString());