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.TypedSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
50 * The Schema Context Util contains support methods for searching through Schema
51 * Context modules for specified schema nodes via Schema Path or Revision Aware
52 * XPath. The Schema Context Util is designed as mixin, so it is not
56 public final class SchemaContextUtil {
57 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
58 private static final Splitter COLON_SPLITTER = Splitter.on(':');
59 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
61 private SchemaContextUtil() {
65 * Method attempts to find DataSchemaNode in Schema Context via specified
66 * Schema Path. The returned DataSchemaNode from method will be the node at
67 * the end of the SchemaPath. If the DataSchemaNode is not present in the
68 * Schema Context the method will return <code>null</code>. <br>
69 * In case that Schema Context or Schema Path are not specified correctly
70 * (i.e. contains <code>null</code> values) the method will return
71 * IllegalArgumentException.
73 * @throws IllegalArgumentException
78 * Schema Path to search for
79 * @return SchemaNode from the end of the Schema Path or <code>null</code>
80 * if the Node is not present.
82 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
83 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
84 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
86 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
87 if (prefixedPath == null) {
88 LOG.debug("Schema path {} has null path", schemaPath);
92 LOG.trace("Looking for path {} in context {}", schemaPath, context);
93 return findNodeInSchemaContext(context, prefixedPath);
97 * Method attempts to find DataSchemaNode inside of provided Schema Context
98 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
99 * specified Module MUST be present in Schema Context otherwise the
100 * operation would fail and return <code>null</code>. <br>
101 * The Revision Aware XPath MUST be specified WITHOUT the conditional
102 * statement (i.e. without [cond]) in path, because in this state the Schema
103 * Context is completely unaware of data state and will be not able to
104 * properly resolve XPath. If the XPath contains condition the method will
105 * return IllegalArgumentException. <br>
106 * In case that Schema Context or Module or Revision Aware XPath contains
107 * <code>null</code> references the method will throw
108 * IllegalArgumentException <br>
109 * If the Revision Aware XPath is correct and desired Data Schema Node is
110 * present in Yang module or in depending module in Schema Context the
111 * method will return specified Data Schema Node, otherwise the operation
112 * will fail and method will return <code>null</code>.
114 * @throws IllegalArgumentException
120 * @param nonCondXPath
121 * Non Conditional Revision Aware XPath
122 * @return Returns Data Schema Node for specified Schema Context for given
123 * Non-conditional Revision Aware XPath, or <code>null</code> if the
124 * DataSchemaNode is not present in Schema Context.
126 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
127 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
128 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
129 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
131 final String strXPath = nonCondXPath.toString();
132 if (strXPath != null) {
133 Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
134 if (nonCondXPath.isAbsolute()) {
135 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
136 if (qnamedPath != null) {
137 return findNodeInSchemaContext(context, qnamedPath);
145 * Method attempts to find DataSchemaNode inside of provided Schema Context
146 * and Yang Module accordingly to Non-conditional relative Revision Aware
147 * XPath. The specified Module MUST be present in Schema Context otherwise
148 * the operation would fail and return <code>null</code>. <br>
149 * The relative Revision Aware XPath MUST be specified WITHOUT the
150 * conditional statement (i.e. without [cond]) in path, because in this
151 * state the Schema Context is completely unaware of data state and will be
152 * not able to properly resolve XPath. If the XPath contains condition the
153 * method will return IllegalArgumentException. <br>
154 * The Actual Schema Node MUST be specified correctly because from this
155 * Schema Node will search starts. If the Actual Schema Node is not correct
156 * the operation will simply fail, because it will be unable to find desired
157 * DataSchemaNode. <br>
158 * In case that Schema Context or Module or Actual Schema Node or relative
159 * Revision Aware XPath contains <code>null</code> references the method
160 * will throw IllegalArgumentException <br>
161 * If the Revision Aware XPath doesn't have flag
162 * <code>isAbsolute == false</code> the method will throw
163 * IllegalArgumentException. <br>
164 * If the relative Revision Aware XPath is correct and desired Data Schema
165 * Node is present in Yang module or in depending module in Schema Context
166 * the method will return specified Data Schema Node, otherwise the
167 * operation will fail and method will return <code>null</code>.
169 * @throws IllegalArgumentException
175 * @param actualSchemaNode
177 * @param relativeXPath
178 * Relative Non Conditional Revision Aware XPath
179 * @return DataSchemaNode if is present in specified Schema Context for
180 * given relative Revision Aware XPath, otherwise will return
183 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
184 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
185 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
186 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
187 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
188 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
189 Preconditions.checkState(!relativeXPath.isAbsolute(),
190 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
191 + "for non relative Revision Aware XPath use findDataSchemaNode method");
193 final SchemaPath actualNodePath = actualSchemaNode.getPath();
194 if (actualNodePath != null) {
195 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
197 if (qnamePath != null) {
198 return findNodeInSchemaContext(context, qnamePath);
205 * Returns parent Yang Module for specified Schema Context in which Schema
206 * Node is declared. If the Schema Node is not present in Schema Context the
207 * operation will return <code>null</code>. <br>
208 * If Schema Context or Schema Node contains <code>null</code> references
209 * the method will throw IllegalArgumentException
211 * @throws IllegalArgumentException
217 * @return Yang Module for specified Schema Context and Schema Node, if
218 * Schema Node is NOT present, the method will returns
221 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
222 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
223 Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
224 Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
225 + "set properly (Schema Path is NULL)");
227 final QName qname = schemaNode.getPath().getLastComponent();
228 Preconditions.checkState(qname != null,
229 "Schema Path contains invalid state of path parts. " +
230 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
231 return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
234 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
235 final QName current = path.iterator().next();
237 LOG.trace("Looking up module {} in context {}", current, path);
238 final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
239 if (module == null) {
240 LOG.debug("Module {} not found", current);
244 return findNodeInModule(module, path);
248 * Returns NotificationDefinition from Schema Context
250 * @param schema SchemaContext in which lookup should be performed.
251 * @param path Schema Path of notification
252 * @return Notification schema or null, if notification is not present in schema context.
255 @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
256 Preconditions.checkNotNull(schema, "Schema context must not be null.");
257 Preconditions.checkNotNull(path, "Schema path must not be null.");
258 for (final NotificationDefinition potential : schema.getNotifications()) {
259 if (path.equals(potential.getPath())) {
267 * Returns RPC Input or Output Data container from RPC definition.
269 * @param schema SchemaContext in which lookup should be performed.
270 * @param path Schema path of RPC input/output data container
271 * @return Notification schema or null, if notification is not present in schema context.
274 @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema, @Nonnull final SchemaPath path) {
275 Preconditions.checkNotNull(schema, "Schema context must not be null.");
276 Preconditions.checkNotNull(path, "Schema path must not be null.");
277 final Iterator<QName> it = path.getPathFromRoot().iterator();
278 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
279 final QName rpcName = it.next();
280 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
281 final QName inOrOut = it.next();
282 for (final RpcDefinition potential : schema.getOperations()) {
283 if (rpcName.equals(potential.getQName())) {
284 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
290 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
292 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
293 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
295 if (!path.iterator().hasNext()) {
296 LOG.debug("No node matching {} found in node {}", path, module);
300 final QName current = path.iterator().next();
301 LOG.trace("Looking for node {} in module {}", current, module);
303 SchemaNode foundNode = null;
304 final Iterable<QName> nextPath = nextLevel(path);
306 foundNode = module.getDataChildByName(current);
307 if (foundNode != null && nextPath.iterator().hasNext()) {
308 foundNode = findNodeIn(foundNode, nextPath);
311 if (foundNode == null) {
312 foundNode = getGroupingByName(module, current);
313 if (foundNode != null && nextPath.iterator().hasNext()) {
314 foundNode = findNodeIn(foundNode, nextPath);
318 if (foundNode == null) {
319 foundNode = getRpcByName(module, current);
320 if (foundNode != null && nextPath.iterator().hasNext()) {
321 foundNode = findNodeIn(foundNode, nextPath);
325 if (foundNode == null) {
326 foundNode = getNotificationByName(module, current);
327 if (foundNode != null && nextPath.iterator().hasNext()) {
328 foundNode = findNodeIn(foundNode, nextPath);
332 if (foundNode == null) {
333 LOG.debug("No node matching {} found in node {}", path, module);
340 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
342 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
343 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
345 if (!path.iterator().hasNext()) {
346 LOG.debug("No node matching {} found in node {}", path, parent);
350 final QName current = path.iterator().next();
351 LOG.trace("Looking for node {} in node {}", current, parent);
353 SchemaNode foundNode = null;
354 final Iterable<QName> nextPath = nextLevel(path);
356 if (parent instanceof DataNodeContainer) {
357 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
359 foundNode = parentDataNodeContainer.getDataChildByName(current);
360 if (foundNode != null && nextPath.iterator().hasNext()) {
361 foundNode = findNodeIn(foundNode, nextPath);
364 if (foundNode == null) {
365 foundNode = getGroupingByName(parentDataNodeContainer, current);
366 if (foundNode != null && nextPath.iterator().hasNext()) {
367 foundNode = findNodeIn(foundNode, nextPath);
372 if (foundNode == null && parent instanceof RpcDefinition) {
373 final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
375 if (current.getLocalName().equals("input")) {
376 foundNode = parentRpcDefinition.getInput();
377 if (foundNode != null && nextPath.iterator().hasNext()) {
378 foundNode = findNodeIn(foundNode, nextPath);
382 if (current.getLocalName().equals("output")) {
383 foundNode = parentRpcDefinition.getOutput();
384 if (foundNode != null && nextPath.iterator().hasNext()) {
385 foundNode = findNodeIn(foundNode, nextPath);
389 if (foundNode == null) {
390 foundNode = getGroupingByName(parentRpcDefinition, current);
391 if (foundNode != null && nextPath.iterator().hasNext()) {
392 foundNode = findNodeIn(foundNode, nextPath);
397 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
398 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
399 if (foundNode != null && nextPath.iterator().hasNext()) {
400 foundNode = findNodeIn(foundNode, nextPath);
404 if (foundNode == null) {
405 LOG.debug("No node matching {} found in node {}", path, parent);
412 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
413 return Iterables.skip(path, 1);
416 private static RpcDefinition getRpcByName(final Module module, final QName name) {
417 for (final RpcDefinition rpc : module.getRpcs()) {
418 if (rpc.getQName().equals(name)) {
425 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
426 for (final NotificationDefinition notification : module.getNotifications()) {
427 if (notification.getQName().equals(name)) {
434 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
435 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
436 if (grouping.getQName().equals(name)) {
443 private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
444 for (final GroupingDefinition grouping : rpc.getGroupings()) {
445 if (grouping.getQName().equals(name)) {
453 * Transforms string representation of XPath to Queue of QNames. The XPath
454 * is split by "/" and for each part of XPath is assigned correct module in
456 * If Schema Context, Parent Module or XPath string contains
457 * <code>null</code> values, the method will throws IllegalArgumentException
459 * @throws IllegalArgumentException
463 * @param parentModule
467 * @return return a list of QName
469 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
470 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
471 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
472 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
474 final List<QName> path = new LinkedList<>();
475 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
476 if (!pathComponent.isEmpty()) {
477 path.add(stringPathPartToQName(context, parentModule, pathComponent));
484 * Transforms part of Prefixed Path as java String to QName. <br>
485 * If the string contains module prefix separated by ":" (i.e.
486 * mod:container) this module is provided from from Parent Module list of
487 * imports. If the Prefixed module is present in Schema Context the QName
488 * can be constructed. <br>
489 * If the Prefixed Path Part does not contains prefix the Parent's Module
490 * namespace is taken for construction of QName. <br>
491 * If Schema Context, Parent Module or Prefixed Path Part refers to
492 * <code>null</code> the method will throw IllegalArgumentException
494 * @throws IllegalArgumentException
498 * @param parentModule
500 * @param prefixedPathPart
501 * Prefixed Path Part string
502 * @return QName from prefixed Path Part String.
504 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
505 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
506 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
507 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
509 if (prefixedPathPart.indexOf(':') != -1) {
510 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
511 final String modulePrefix = prefixedName.next();
513 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
514 Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
515 modulePrefix, parentModule.getName());
517 return QName.create(module.getQNameModule(), prefixedName.next());
519 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
524 * Method will attempt to resolve and provide Module reference for specified
525 * module prefix. Each Yang module could contains multiple imports which
526 * MUST be associated with corresponding module prefix. The method simply
527 * looks into module imports and returns the module that is bounded with
528 * specified prefix. If the prefix is not present in module or the prefixed
529 * module is not present in specified Schema Context, the method will return
530 * <code>null</code>. <br>
531 * If String prefix is the same as prefix of the specified Module the
532 * reference to this module is returned. <br>
533 * If Schema Context, Module or Prefix are referring to <code>null</code>
534 * the method will return IllegalArgumentException
536 * @throws IllegalArgumentException
544 * @return Module for given prefix in specified Schema Context if is
545 * present, otherwise returns <code>null</code>
547 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
548 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
549 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
550 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
552 if (prefix.equals(module.getPrefix())) {
556 final Set<ModuleImport> imports = module.getImports();
557 for (final ModuleImport mi : imports) {
558 if (prefix.equals(mi.getPrefix())) {
559 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
566 * @throws IllegalArgumentException
572 * @param relativeXPath
573 * Non conditional Revision Aware Relative XPath
574 * @param actualSchemaNode
576 * @return list of QName
578 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
579 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
580 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
581 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
582 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
583 Preconditions.checkState(!relativeXPath.isAbsolute(),
584 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
585 + "for non relative Revision Aware XPath use findDataSchemaNode method");
586 Preconditions.checkState(actualSchemaNode.getPath() != null,
587 "Schema Path reference for Leafref cannot be NULL");
589 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
591 // Find out how many "parent" components there are
592 // FIXME: is .contains() the right check here?
593 // FIXME: case ../../node1/node2/../node3/../node4
595 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
599 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
601 if (Iterables.size(schemaNodePath) - colCount >= 0) {
602 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
603 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
605 public QName apply(final String input) {
606 return stringPathPartToQName(context, module, input);
610 return Iterables.concat(schemaNodePath,
611 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
613 public QName apply(final String input) {
614 return stringPathPartToQName(context, module, input);
620 * 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
623 * @param typeDefinition
624 * type of node which will be extracted
625 * @param schemaContext
629 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
631 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
632 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
633 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
635 final DataSchemaNode dataSchemaNode;
636 if (pathStatement.isAbsolute()) {
637 SchemaNode baseSchema = schema;
638 while (baseSchema instanceof DerivableSchemaNode) {
639 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
640 if (basePotential.isPresent()) {
641 baseSchema = basePotential.get();
647 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
648 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
651 Module parentModule = findParentModule(schemaContext, schema);
652 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
653 parentModule, schema, pathStatement);
656 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
657 // and current expected behaviour for such cases is to just use pure string
658 // This should throw an exception about incorrect XPath in leafref
659 if (dataSchemaNode == null) {
663 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
665 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
666 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
668 return targetTypeDefinition;
672 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
673 final SchemaNode schemaNode) {
674 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
675 Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
677 TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
678 if (nodeType.getBaseType() != null) {
679 while (nodeType.getBaseType() != null) {
680 nodeType = nodeType.getBaseType();
683 final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
684 return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
685 typeDefModuleQname.getRevision());
688 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
692 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case
693 * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef
694 * which is then imported to referenced module.
696 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
698 * @param typeDefinition
699 * @param schemaContext
703 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
704 final SchemaContext schemaContext, final QName qName) {
705 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
706 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
707 if (!strippedPathStatement.isAbsolute()) {
711 final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision());
712 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement);
713 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
714 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
715 return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
717 return targetTypeDefinition;
721 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
724 * Removes conditions from xPath pointed to target node.
726 * @param pathStatement
727 * xPath to target node
728 * @return string representation of xPath without conditions
732 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
733 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
737 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
740 * a node representing LeafSchemaNode
741 * @return concrete type definition of node value
743 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
744 TypeDefinition<?> baseType = node.getType();
745 while (baseType.getBaseType() != null) {
746 baseType = baseType.getBaseType();
752 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
755 * a node representing LeafListSchemaNode
756 * @return concrete type definition of node value
758 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
759 TypeDefinition<?> baseType = node.getType();
760 while (baseType.getBaseType() != null) {
761 baseType = baseType.getBaseType();
767 * Gets the base type of DataSchemaNode value.
770 * a node representing DataSchemaNode
771 * @return concrete type definition of node value
773 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
774 if (node instanceof LeafListSchemaNode) {
775 return typeDefinition((LeafListSchemaNode) node);
776 } else if (node instanceof LeafSchemaNode) {
777 return typeDefinition((LeafSchemaNode) node);
779 throw new IllegalArgumentException("Unhandled parameter types: " + Collections.<Object>singletonList(node).toString());