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.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Iterables;
15 import java.util.HashSet;
16 import java.util.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Optional;
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.model.api.ActionNodeContainer;
26 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
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.NotificationNodeContainer;
39 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
40 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
41 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
49 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
54 * The Schema Context Util contains support methods for searching through Schema
55 * Context modules for specified schema nodes via Schema Path or Revision Aware
56 * XPath. The Schema Context Util is designed as mixin, so it is not
60 public final class SchemaContextUtil {
61 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
62 private static final Splitter COLON_SPLITTER = Splitter.on(':');
63 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
65 private SchemaContextUtil() {
69 * Method attempts to find DataSchemaNode in Schema Context via specified
70 * Schema Path. The returned DataSchemaNode from method will be the node at
71 * the end of the SchemaPath. If the DataSchemaNode is not present in the
72 * Schema Context the method will return <code>null</code>. <br>
73 * In case that Schema Context or Schema Path are not specified correctly
74 * (i.e. contains <code>null</code> values) the method will throw
75 * IllegalArgumentException.
80 * Schema Path to search for
81 * @return SchemaNode from the end of the Schema Path or <code>null</code>
82 * if the Node is not present.
83 * @throws IllegalArgumentException if context or schemaPath is not correct.
85 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
86 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
87 Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
89 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
90 if (prefixedPath == null) {
91 LOG.debug("Schema path {} has null path", schemaPath);
95 LOG.trace("Looking for path {} in context {}", schemaPath, context);
96 return findNodeInSchemaContext(context, prefixedPath);
100 * Method attempts to find DataSchemaNode inside of provided Schema Context
101 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
102 * specified Module MUST be present in Schema Context otherwise the
103 * operation would fail and return <code>null</code>. <br>
104 * The Revision Aware XPath MUST be specified WITHOUT the conditional
105 * statement (i.e. without [cond]) in path, because in this state the Schema
106 * Context is completely unaware of data state and will be not able to
107 * properly resolve XPath. If the XPath contains condition the method will
108 * return IllegalArgumentException. <br>
109 * In case that Schema Context or Module or Revision Aware XPath contains
110 * <code>null</code> references the method will throw
111 * IllegalArgumentException <br>
112 * If the Revision Aware XPath is correct and desired Data Schema Node is
113 * present in Yang module or in depending module in Schema Context the
114 * method will return specified Data Schema Node, otherwise the operation
115 * will fail and method will return <code>null</code>.
121 * @param nonCondXPath
122 * Non Conditional Revision Aware XPath
123 * @return Returns Data Schema Node for specified Schema Context for given
124 * Non-conditional Revision Aware XPath, or <code>null</code> if the
125 * DataSchemaNode is not present in Schema Context.
127 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
128 final RevisionAwareXPath nonCondXPath) {
129 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
130 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
131 Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
133 final String strXPath = nonCondXPath.toString();
134 if (strXPath != null) {
135 Preconditions.checkArgument(strXPath.indexOf('[') == -1,
136 "Revision Aware XPath may not contain a condition");
137 if (nonCondXPath.isAbsolute()) {
138 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
139 if (qnamedPath != null) {
140 return findNodeInSchemaContext(context, qnamedPath);
148 * Method attempts to find DataSchemaNode inside of provided Schema Context
149 * and Yang Module accordingly to Non-conditional relative Revision Aware
150 * XPath. The specified Module MUST be present in Schema Context otherwise
151 * the operation would fail and return <code>null</code>. <br>
152 * The relative Revision Aware XPath MUST be specified WITHOUT the
153 * conditional statement (i.e. without [cond]) in path, because in this
154 * state the Schema Context is completely unaware of data state and will be
155 * not able to properly resolve XPath. If the XPath contains condition the
156 * method will return IllegalArgumentException. <br>
157 * The Actual Schema Node MUST be specified correctly because from this
158 * Schema Node will search starts. If the Actual Schema Node is not correct
159 * the operation will simply fail, because it will be unable to find desired
160 * DataSchemaNode. <br>
161 * In case that Schema Context or Module or Actual Schema Node or relative
162 * Revision Aware XPath contains <code>null</code> references the method
163 * will throw IllegalArgumentException <br>
164 * If the Revision Aware XPath doesn't have flag
165 * <code>isAbsolute == false</code> the method will throw
166 * IllegalArgumentException. <br>
167 * If the relative Revision Aware XPath is correct and desired Data Schema
168 * Node is present in Yang module or in depending module in Schema Context
169 * the method will return specified Data Schema Node, otherwise the
170 * operation will fail and method will return <code>null</code>.
176 * @param actualSchemaNode
178 * @param relativeXPath
179 * Relative Non Conditional Revision Aware XPath
180 * @return DataSchemaNode if is present in specified Schema Context for
181 * given relative Revision Aware XPath, otherwise will return
184 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
185 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
186 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
187 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
188 Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
189 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
190 Preconditions.checkState(!relativeXPath.isAbsolute(),
191 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
192 + "for non relative Revision Aware XPath use findDataSchemaNode method");
194 final SchemaPath actualNodePath = actualSchemaNode.getPath();
195 if (actualNodePath != null) {
196 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
198 if (qnamePath != null) {
199 return findNodeInSchemaContext(context, qnamePath);
206 * Returns parent Yang Module for specified Schema Context in which Schema
207 * Node is declared. If the Schema Node is not present in Schema Context the
208 * operation will return <code>null</code>. <br>
209 * If Schema Context or Schema Node contains <code>null</code> references
210 * the method will throw IllegalArgumentException
216 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
217 * return <code>null</code>
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, "Schema Path contains invalid state of path parts. "
227 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
228 return context.findModule(qname.getModule()).orElse(null);
231 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
232 final QName current = path.iterator().next();
234 LOG.trace("Looking up module {} in context {}", current, path);
235 final Optional<Module> module = context.findModule(current.getModule());
236 if (!module.isPresent()) {
237 LOG.debug("Module {} not found", current);
241 return findNodeInModule(module.get(), path);
245 * Returns NotificationDefinition from Schema Context.
247 * @param schema SchemaContext in which lookup should be performed.
248 * @param path Schema Path of notification
249 * @return Notification schema or null, if notification is not present in schema context.
253 public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
254 @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.
274 public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
275 @Nonnull final SchemaPath path) {
276 Preconditions.checkNotNull(schema, "Schema context must not be null.");
277 Preconditions.checkNotNull(path, "Schema path must not be null.");
278 final Iterator<QName> it = path.getPathFromRoot().iterator();
279 Preconditions.checkArgument(it.hasNext(), "Rpc must have QName.");
280 final QName rpcName = it.next();
281 Preconditions.checkArgument(it.hasNext(), "input or output must be part of path.");
282 final QName inOrOut = it.next();
283 for (final RpcDefinition potential : schema.getOperations()) {
284 if (rpcName.equals(potential.getQName())) {
285 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
292 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
294 * @param context SchemaContext to be examined
295 * @return Set of ModuleIdentifiers.
297 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
298 final Set<SourceIdentifier> ret = new HashSet<>();
300 for (Module module : context.getModules()) {
301 ret.add(moduleToIdentifier(module));
303 for (Module submodule : module.getSubmodules()) {
304 ret.add(moduleToIdentifier(submodule));
311 private static SourceIdentifier moduleToIdentifier(final Module module) {
312 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
315 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
317 Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
318 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
320 if (!path.iterator().hasNext()) {
321 LOG.debug("No node matching {} found in node {}", path, module);
325 final QName current = path.iterator().next();
326 LOG.trace("Looking for node {} in module {}", current, module);
328 SchemaNode foundNode = null;
329 final Iterable<QName> nextPath = nextLevel(path);
331 foundNode = module.getDataChildByName(current);
332 if (foundNode != null && nextPath.iterator().hasNext()) {
333 foundNode = findNodeIn(foundNode, nextPath);
336 if (foundNode == null) {
337 foundNode = getGroupingByName(module, current);
338 if (foundNode != null && nextPath.iterator().hasNext()) {
339 foundNode = findNodeIn(foundNode, nextPath);
343 if (foundNode == null) {
344 foundNode = getRpcByName(module, current);
345 if (foundNode != null && nextPath.iterator().hasNext()) {
346 foundNode = findNodeIn(foundNode, nextPath);
350 if (foundNode == null) {
351 foundNode = getNotificationByName(module, current);
352 if (foundNode != null && nextPath.iterator().hasNext()) {
353 foundNode = findNodeIn(foundNode, nextPath);
357 if (foundNode == null) {
358 LOG.debug("No node matching {} found in node {}", path, module);
365 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
367 Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
368 Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
370 if (!path.iterator().hasNext()) {
371 LOG.debug("No node matching {} found in node {}", path, parent);
375 final QName current = path.iterator().next();
376 LOG.trace("Looking for node {} in node {}", current, parent);
378 SchemaNode foundNode = null;
379 final Iterable<QName> nextPath = nextLevel(path);
381 if (parent instanceof DataNodeContainer) {
382 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
384 foundNode = parentDataNodeContainer.getDataChildByName(current);
385 if (foundNode != null && nextPath.iterator().hasNext()) {
386 foundNode = findNodeIn(foundNode, nextPath);
389 if (foundNode == null) {
390 foundNode = getGroupingByName(parentDataNodeContainer, current);
391 if (foundNode != null && nextPath.iterator().hasNext()) {
392 foundNode = findNodeIn(foundNode, nextPath);
397 if (foundNode == null && parent instanceof ActionNodeContainer) {
398 foundNode = ((ActionNodeContainer) parent).getActions().stream()
399 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
400 if (foundNode != null && nextPath.iterator().hasNext()) {
401 foundNode = findNodeIn(foundNode, nextPath);
405 if (foundNode == null && parent instanceof NotificationNodeContainer) {
406 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
407 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
408 if (foundNode != null && nextPath.iterator().hasNext()) {
409 foundNode = findNodeIn(foundNode, nextPath);
413 if (foundNode == null && parent instanceof OperationDefinition) {
414 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
416 if (current.getLocalName().equals("input")) {
417 foundNode = parentRpcDefinition.getInput();
418 if (foundNode != null && nextPath.iterator().hasNext()) {
419 foundNode = findNodeIn(foundNode, nextPath);
423 if (current.getLocalName().equals("output")) {
424 foundNode = parentRpcDefinition.getOutput();
425 if (foundNode != null && nextPath.iterator().hasNext()) {
426 foundNode = findNodeIn(foundNode, nextPath);
430 if (foundNode == null) {
431 foundNode = getGroupingByName(parentRpcDefinition, current);
432 if (foundNode != null && nextPath.iterator().hasNext()) {
433 foundNode = findNodeIn(foundNode, nextPath);
438 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
439 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
441 if (foundNode != null && nextPath.iterator().hasNext()) {
442 foundNode = findNodeIn(foundNode, nextPath);
445 if (foundNode == null) {
446 // fallback that tries to map into one of the child cases
447 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
448 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
449 if (maybeChild != null) {
450 foundNode = findNodeIn(maybeChild, nextPath);
457 if (foundNode == null) {
458 LOG.debug("No node matching {} found in node {}", path, parent);
465 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
466 return Iterables.skip(path, 1);
469 private static RpcDefinition getRpcByName(final Module module, final QName name) {
470 for (final RpcDefinition rpc : module.getRpcs()) {
471 if (rpc.getQName().equals(name)) {
478 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
479 for (final NotificationDefinition notification : module.getNotifications()) {
480 if (notification.getQName().equals(name)) {
487 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
488 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
489 if (grouping.getQName().equals(name)) {
496 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
497 for (final GroupingDefinition grouping : rpc.getGroupings()) {
498 if (grouping.getQName().equals(name)) {
506 * Transforms string representation of XPath to Queue of QNames. The XPath
507 * is split by "/" and for each part of XPath is assigned correct module in
509 * If Schema Context, Parent Module or XPath string contains
510 * <code>null</code> values, the method will throws IllegalArgumentException
514 * @param parentModule
518 * @return return a list of QName
520 * @throws IllegalArgumentException if any arguments are null
523 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
524 final String xpath) {
525 // FIXME: 2.0.0: this should throw NPE, not IAE
526 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
527 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
528 Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
530 final List<QName> path = new LinkedList<>();
531 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
532 if (!pathComponent.isEmpty()) {
533 path.add(stringPathPartToQName(context, parentModule, pathComponent));
540 * Transforms part of Prefixed Path as java String to QName. <br>
541 * If the string contains module prefix separated by ":" (i.e.
542 * mod:container) this module is provided from from Parent Module list of
543 * imports. If the Prefixed module is present in Schema Context the QName
544 * can be constructed. <br>
545 * If the Prefixed Path Part does not contains prefix the Parent's Module
546 * namespace is taken for construction of QName. <br>
547 * If Schema Context, Parent Module or Prefixed Path Part refers to
548 * <code>null</code> the method will throw IllegalArgumentException
552 * @param parentModule
554 * @param prefixedPathPart
555 * Prefixed Path Part string
556 * @return QName from prefixed Path Part String.
557 * @throws IllegalArgumentException if any arguments are null
559 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
560 final String prefixedPathPart) {
561 // FIXME: 2.0.0: this should throw NPE, not IAE
562 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
563 Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
564 Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
566 if (prefixedPathPart.indexOf(':') != -1) {
567 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
568 final String modulePrefix = prefixedName.next();
570 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
571 Preconditions.checkArgument(module != null,
572 "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
573 parentModule.getName());
575 return QName.create(module.getQNameModule(), prefixedName.next());
578 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
582 * Method will attempt to resolve and provide Module reference for specified
583 * module prefix. Each Yang module could contains multiple imports which
584 * MUST be associated with corresponding module prefix. The method simply
585 * looks into module imports and returns the module that is bounded with
586 * specified prefix. If the prefix is not present in module or the prefixed
587 * module is not present in specified Schema Context, the method will return
588 * <code>null</code>. <br>
589 * If String prefix is the same as prefix of the specified Module the
590 * reference to this module is returned. <br>
591 * If Schema Context, Module or Prefix are referring to <code>null</code>
592 * the method will return IllegalArgumentException
600 * @return Module for given prefix in specified Schema Context if is
601 * present, otherwise returns <code>null</code>
602 * @throws IllegalArgumentException if any arguments are null
604 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
605 final String prefix) {
606 // FIXME: 2.0.0: this should throw NPE, not IAE
607 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
608 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
609 Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
611 if (prefix.equals(module.getPrefix())) {
615 final Set<ModuleImport> imports = module.getImports();
616 for (final ModuleImport mi : imports) {
617 if (prefix.equals(mi.getPrefix())) {
618 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
625 * Resolve a relative XPath into a set of QNames.
631 * @param relativeXPath
632 * Non conditional Revision Aware Relative XPath
633 * @param actualSchemaNode
635 * @return list of QName
636 * @throws IllegalArgumentException if any arguments are null
638 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
639 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
640 // FIXME: 2.0.0: this should throw NPE, not IAE
641 Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
642 Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
643 Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
644 Preconditions.checkState(!relativeXPath.isAbsolute(),
645 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
646 + "for non relative Revision Aware XPath use findDataSchemaNode method");
647 Preconditions.checkState(actualSchemaNode.getPath() != null,
648 "Schema Path reference for Leafref cannot be NULL");
650 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
652 // Find out how many "parent" components there are
653 // FIXME: is .contains() the right check here?
654 // FIXME: case ../../node1/node2/../node3/../node4
656 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
660 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
662 if (Iterables.size(schemaNodePath) - colCount >= 0) {
663 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
664 Iterables.transform(Iterables.skip(xpaths, colCount),
665 input -> stringPathPartToQName(context, module, input)));
667 return Iterables.concat(schemaNodePath,
668 Iterables.transform(Iterables.skip(xpaths, colCount),
669 input -> stringPathPartToQName(context, module, input)));
673 * Extracts the base type of node on which schema node points to. If target node is again of type
674 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
676 * @param typeDefinition
677 * type of node which will be extracted
678 * @param schemaContext
682 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
683 * is there to preserve backwards compatibility)
685 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
686 final SchemaContext schemaContext, final SchemaNode schema) {
687 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
688 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
689 pathStatement.isAbsolute());
691 final DataSchemaNode dataSchemaNode;
692 if (pathStatement.isAbsolute()) {
693 SchemaNode baseSchema = schema;
694 while (baseSchema instanceof DerivableSchemaNode) {
695 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
696 if (basePotential.isPresent()) {
697 baseSchema = basePotential.get();
703 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
704 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
707 Module parentModule = findParentModule(schemaContext, schema);
708 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
709 parentModule, schema, pathStatement);
712 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
713 // and current expected behaviour for such cases is to just use pure string
714 // This should throw an exception about incorrect XPath in leafref
715 if (dataSchemaNode == null) {
719 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
721 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
722 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
725 return targetTypeDefinition;
729 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
730 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
731 * module as typedef which is then imported to referenced module.
734 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
736 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
737 final SchemaContext schemaContext, final QName qname) {
738 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
739 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
740 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
741 if (!strippedPathStatement.isAbsolute()) {
745 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
746 Preconditions.checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
748 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
749 parentModule.get(), strippedPathStatement);
750 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
751 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
752 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
755 return targetTypeDefinition;
758 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
759 final SchemaNode schemaNode) {
760 Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
761 Preconditions.checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
763 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
764 if (nodeType.getBaseType() != null) {
765 while (nodeType.getBaseType() != null) {
766 nodeType = nodeType.getBaseType();
769 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
772 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
775 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
778 * Removes conditions from xPath pointed to target node.
780 * @param pathStatement
781 * xPath to target node
782 * @return string representation of xPath without conditions
785 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
786 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
790 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
793 * a node representing LeafSchemaNode
794 * @return concrete type definition of node value
796 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
797 TypeDefinition<?> baseType = node.getType();
798 while (baseType.getBaseType() != null) {
799 baseType = baseType.getBaseType();
805 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
808 * a node representing LeafListSchemaNode
809 * @return concrete type definition of node value
811 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
812 TypeDefinition<?> baseType = node.getType();
813 while (baseType.getBaseType() != null) {
814 baseType = baseType.getBaseType();
820 * Gets the base type of DataSchemaNode value.
823 * a node representing DataSchemaNode
824 * @return concrete type definition of node value
826 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
827 if (node instanceof LeafListSchemaNode) {
828 return typeDefinition((LeafListSchemaNode) node);
829 } else if (node instanceof LeafSchemaNode) {
830 return typeDefinition((LeafSchemaNode) node);
832 throw new IllegalArgumentException("Unhandled parameter type: " + node);