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 static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.CharMatcher;
17 import com.google.common.base.Splitter;
18 import com.google.common.collect.Iterables;
19 import java.util.ArrayDeque;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Deque;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Optional;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.opendaylight.yangtools.yang.common.AbstractQName;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
36 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
51 import org.opendaylight.yangtools.yang.model.api.PathExpression;
52 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
53 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
54 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
59 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.ResolvedQNameStep;
69 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
70 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.UnresolvedQNameStep;
71 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
76 * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
77 * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
80 public final class SchemaContextUtil {
81 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
82 private static final Splitter COLON_SPLITTER = Splitter.on(':');
83 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
84 private static final CharMatcher SPACE = CharMatcher.is(' ');
86 private SchemaContextUtil() {
91 * Method attempts to find DataSchemaNode in Schema Context via specified Schema Path. The returned DataSchemaNode
92 * from method will be the node at the end of the SchemaPath. If the DataSchemaNode is not present in the Schema
93 * Context the method will return {@code null}.
96 * In case that Schema Context or Schema Path are not specified correctly (i.e. contains {@code null} values) the
97 * method will throw IllegalArgumentException.
99 * @param context Schema Context
100 * @param schemaPath Schema Path to search for
101 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
102 * @throws NullPointerException if context or schemaPath is null
104 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
105 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
106 if (prefixedPath == null) {
107 LOG.debug("Schema path {} has null path", schemaPath);
111 LOG.trace("Looking for path {} in context {}", schemaPath, context);
112 return findNodeInSchemaContext(context, prefixedPath);
116 * Attempt to find a DataSchemaNode based on its path from root, similar to
117 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
119 * @param context Schema Context
120 * @param path Path to search for
121 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
122 * @throws NullPointerException if a any argument is null or if the path contains a null element
125 public static SchemaNode findDataSchemaNode(final SchemaContext context, final List<QName> path) {
126 return findTargetNode(context, null, YangLocationPath.absolute(
127 path.stream().map(YangXPathAxis.CHILD::asStep).collect(Collectors.toList())));
131 * Attempt to find a DataSchemaNode based on its path from root, similar to
132 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
134 * @param context Schema Context
135 * @param path Path to search for
136 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
137 * @throws NullPointerException if a any argument is null or if the path contains a null element
140 public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
141 return findDataSchemaNode(context, Arrays.asList(path));
145 * Method attempts to find DataSchemaNode inside of provided Schema Context
146 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
147 * specified Module MUST be present in Schema Context otherwise the
148 * operation would fail and return <code>null</code>. <br>
149 * The Revision Aware XPath MUST be specified WITHOUT the conditional
150 * statement (i.e. without [cond]) in path, because in this state the Schema
151 * Context is completely unaware of data state and will be not able to
152 * properly resolve XPath. If the XPath contains condition the method will
153 * return IllegalArgumentException. <br>
154 * If the Revision Aware XPath is correct and desired Data Schema Node is
155 * present in Yang module or in depending module in Schema Context the
156 * method will return specified Data Schema Node, otherwise the operation
157 * will fail and method will return <code>null</code>.
163 * @param nonCondXPath
164 * Non Conditional Revision Aware XPath
165 * @return Returns Data Schema Node for specified Schema Context for given
166 * Non-conditional Revision Aware XPath, or <code>null</code> if the
167 * DataSchemaNode is not present in Schema Context.
168 * @throws NullPointerException if any of the arguments is null
169 * @deprecated Use {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, YangLocationPath)} or
170 * {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, PathExpression)} instead.
172 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
173 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
176 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
177 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
178 // via a derived SchemaContext (i.e. this class would have to have a
180 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
182 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
183 // that feels like an overkill.
185 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
186 final PathExpression nonCondXPath) {
187 requireNonNull(context, "context");
188 requireNonNull(module, "module");
190 final String strXPath = nonCondXPath.getOriginalString();
191 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
192 if (nonCondXPath.isAbsolute()) {
193 return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
199 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
200 final YangLocationPath absPath) {
201 checkArgument(absPath.isAbsolute(), "Unsupported relative path %s", absPath);
202 return findTargetNode(ctx, localModule, absPath);
206 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
207 final PathExpression absPath) {
208 final Steps pathSteps = absPath.getSteps();
209 if (pathSteps instanceof LocationPathSteps) {
210 return findDataTreeSchemaNode(ctx, localModule, ((LocationPathSteps) pathSteps).getLocationPath());
213 // We would need a reference schema node and no, we do not want to use SchemaContext in its SchemaNode capacity
214 checkArgument(!(pathSteps instanceof DerefSteps), "No reference node for steps %s", pathSteps);
216 // We are missing proper API alignment, if this ever triggers
217 throw new IllegalStateException("Unsupported path " + pathSteps);
221 * Method attempts to find DataSchemaNode inside of provided Schema Context
222 * and Yang Module accordingly to Non-conditional relative Revision Aware
223 * XPath. The specified Module MUST be present in Schema Context otherwise
224 * the operation would fail and return <code>null</code>. <br>
225 * The relative Revision Aware XPath MUST be specified WITHOUT the
226 * conditional statement (i.e. without [cond]) in path, because in this
227 * state the Schema Context is completely unaware of data state and will be
228 * not able to properly resolve XPath. If the XPath contains condition the
229 * method will return IllegalArgumentException. <br>
230 * The Actual Schema Node MUST be specified correctly because from this
231 * Schema Node will search starts. If the Actual Schema Node is not correct
232 * the operation will simply fail, because it will be unable to find desired
233 * DataSchemaNode. <br>
234 * If the Revision Aware XPath doesn't have flag
235 * <code>isAbsolute == false</code> the method will throw
236 * IllegalArgumentException. <br>
237 * If the relative Revision Aware XPath is correct and desired Data Schema
238 * Node is present in Yang module or in depending module in Schema Context
239 * the method will return specified Data Schema Node, otherwise the
240 * operation will fail and method will return <code>null</code>.
246 * @param actualSchemaNode
248 * @param relativeXPath
249 * Relative Non Conditional Revision Aware XPath
250 * @return DataSchemaNode if is present in specified Schema Context for
251 * given relative Revision Aware XPath, otherwise will return
253 * @throws NullPointerException if any argument is null
255 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
256 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
259 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
260 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
261 // via a derived SchemaContext (i.e. this class would have to have a
263 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
265 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
266 // that feels like an overkill.
267 // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
268 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
269 final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
270 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
271 + "for non relative Revision Aware XPath use findDataSchemaNode method");
272 return resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
276 * Returns parent Yang Module for specified Schema Context in which Schema
277 * Node is declared. If the Schema Node is not present in Schema Context the
278 * operation will return <code>null</code>.
280 * @param context Schema Context
281 * @param schemaNode Schema Node
282 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
283 * return <code>null</code>
284 * @throws NullPointerException if any of the arguments is null
286 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
287 final QName qname = schemaNode.getPath().getLastComponent();
288 checkState(qname != null, "Schema Path contains invalid state of path parts. "
289 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
290 return context.findModule(qname.getModule()).orElse(null);
293 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
294 final QName current = path.iterator().next();
296 LOG.trace("Looking up module {} in context {}", current, path);
297 final Optional<Module> module = context.findModule(current.getModule());
298 if (!module.isPresent()) {
299 LOG.debug("Module {} not found", current);
303 return findNodeInModule(module.get(), path);
307 * Returns NotificationDefinition from Schema Context.
309 * @param schema SchemaContext in which lookup should be performed.
310 * @param path Schema Path of notification
311 * @return Notification schema or null, if notification is not present in schema context.
314 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
315 final @NonNull SchemaPath path) {
316 requireNonNull(schema, "Schema context must not be null.");
317 requireNonNull(path, "Schema path must not be null.");
318 for (final NotificationDefinition potential : schema.getNotifications()) {
319 if (path.equals(potential.getPath())) {
327 * Returns RPC Input or Output Data container from RPC definition.
329 * @param schema SchemaContext in which lookup should be performed.
330 * @param path Schema path of RPC input/output data container
331 * @return Notification schema or null, if notification is not present in schema context.
334 public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
335 final @NonNull SchemaPath path) {
336 requireNonNull(schema, "Schema context must not be null.");
337 requireNonNull(path, "Schema path must not be null.");
338 final Iterator<QName> it = path.getPathFromRoot().iterator();
339 checkArgument(it.hasNext(), "Rpc must have QName.");
340 final QName rpcName = it.next();
341 checkArgument(it.hasNext(), "input or output must be part of path.");
342 final QName inOrOut = it.next();
343 for (final RpcDefinition potential : schema.getOperations()) {
344 if (rpcName.equals(potential.getQName())) {
345 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
352 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
354 * @param context SchemaContext to be examined
355 * @return Set of ModuleIdentifiers.
357 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
358 final Set<SourceIdentifier> ret = new HashSet<>();
360 for (Module module : context.getModules()) {
361 ret.add(moduleToIdentifier(module));
363 for (Module submodule : module.getSubmodules()) {
364 ret.add(moduleToIdentifier(submodule));
371 private static SourceIdentifier moduleToIdentifier(final Module module) {
372 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
375 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
376 if (!path.iterator().hasNext()) {
377 LOG.debug("No node matching {} found in node {}", path, module);
381 final QName current = path.iterator().next();
382 LOG.trace("Looking for node {} in module {}", current, module);
384 SchemaNode foundNode = null;
385 final Iterable<QName> nextPath = nextLevel(path);
387 foundNode = module.getDataChildByName(current);
388 if (foundNode != null && nextPath.iterator().hasNext()) {
389 foundNode = findNodeIn(foundNode, nextPath);
392 if (foundNode == null) {
393 foundNode = getGroupingByName(module, current);
394 if (foundNode != null && nextPath.iterator().hasNext()) {
395 foundNode = findNodeIn(foundNode, nextPath);
399 if (foundNode == null) {
400 foundNode = getRpcByName(module, current);
401 if (foundNode != null && nextPath.iterator().hasNext()) {
402 foundNode = findNodeIn(foundNode, nextPath);
406 if (foundNode == null) {
407 foundNode = getNotificationByName(module, current);
408 if (foundNode != null && nextPath.iterator().hasNext()) {
409 foundNode = findNodeIn(foundNode, nextPath);
413 if (foundNode == null) {
414 LOG.debug("No node matching {} found in node {}", path, module);
420 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
421 if (!path.iterator().hasNext()) {
422 LOG.debug("No node matching {} found in node {}", path, parent);
426 final QName current = path.iterator().next();
427 LOG.trace("Looking for node {} in node {}", current, parent);
429 SchemaNode foundNode = null;
430 final Iterable<QName> nextPath = nextLevel(path);
432 if (parent instanceof DataNodeContainer) {
433 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
435 foundNode = parentDataNodeContainer.getDataChildByName(current);
436 if (foundNode != null && nextPath.iterator().hasNext()) {
437 foundNode = findNodeIn(foundNode, nextPath);
440 if (foundNode == null) {
441 foundNode = getGroupingByName(parentDataNodeContainer, current);
442 if (foundNode != null && nextPath.iterator().hasNext()) {
443 foundNode = findNodeIn(foundNode, nextPath);
448 if (foundNode == null && parent instanceof ActionNodeContainer) {
449 foundNode = ((ActionNodeContainer) parent).getActions().stream()
450 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
451 if (foundNode != null && nextPath.iterator().hasNext()) {
452 foundNode = findNodeIn(foundNode, nextPath);
456 if (foundNode == null && parent instanceof NotificationNodeContainer) {
457 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
458 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
459 if (foundNode != null && nextPath.iterator().hasNext()) {
460 foundNode = findNodeIn(foundNode, nextPath);
464 if (foundNode == null && parent instanceof OperationDefinition) {
465 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
467 if (current.getLocalName().equals("input")) {
468 foundNode = parentRpcDefinition.getInput();
469 if (foundNode != null && nextPath.iterator().hasNext()) {
470 foundNode = findNodeIn(foundNode, nextPath);
474 if (current.getLocalName().equals("output")) {
475 foundNode = parentRpcDefinition.getOutput();
476 if (foundNode != null && nextPath.iterator().hasNext()) {
477 foundNode = findNodeIn(foundNode, nextPath);
481 if (foundNode == null) {
482 foundNode = getGroupingByName(parentRpcDefinition, current);
483 if (foundNode != null && nextPath.iterator().hasNext()) {
484 foundNode = findNodeIn(foundNode, nextPath);
489 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
490 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
492 if (foundNode != null && nextPath.iterator().hasNext()) {
493 foundNode = findNodeIn(foundNode, nextPath);
496 if (foundNode == null) {
497 // fallback that tries to map into one of the child cases
498 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
499 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
500 if (maybeChild != null) {
501 foundNode = findNodeIn(maybeChild, nextPath);
508 if (foundNode == null) {
509 LOG.debug("No node matching {} found in node {}", path, parent);
516 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
517 return Iterables.skip(path, 1);
520 private static RpcDefinition getRpcByName(final Module module, final QName name) {
521 for (final RpcDefinition rpc : module.getRpcs()) {
522 if (rpc.getQName().equals(name)) {
529 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
530 for (final NotificationDefinition notification : module.getNotifications()) {
531 if (notification.getQName().equals(name)) {
538 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
539 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
540 if (grouping.getQName().equals(name)) {
547 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
548 for (final GroupingDefinition grouping : rpc.getGroupings()) {
549 if (grouping.getQName().equals(name)) {
557 * Transforms string representation of XPath to Queue of QNames. The XPath
558 * is split by "/" and for each part of XPath is assigned correct module in
560 * If Schema Context, Parent Module or XPath string contains
561 * <code>null</code> values, the method will throws IllegalArgumentException
565 * @param parentModule
569 * @return return a list of QName
571 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
572 final String xpath) {
573 final List<QName> path = new ArrayList<>();
574 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
575 path.add(stringPathPartToQName(context, parentModule, pathComponent));
581 * Transforms part of Prefixed Path as java String to QName. <br>
582 * If the string contains module prefix separated by ":" (i.e.
583 * mod:container) this module is provided from from Parent Module list of
584 * imports. If the Prefixed module is present in Schema Context the QName
585 * can be constructed. <br>
586 * If the Prefixed Path Part does not contains prefix the Parent's Module
587 * namespace is taken for construction of QName. <br>
589 * @param context Schema Context
590 * @param parentModule Parent Module
591 * @param prefixedPathPart Prefixed Path Part string
592 * @return QName from prefixed Path Part String.
593 * @throws NullPointerException if any arguments are null
595 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
596 final String prefixedPathPart) {
597 requireNonNull(context, "context");
599 if (prefixedPathPart.indexOf(':') != -1) {
600 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
601 final String modulePrefix = prefixedName.next();
603 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
604 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
605 modulePrefix, parentModule.getName());
607 return QName.create(module.getQNameModule(), prefixedName.next());
610 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
614 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
615 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
616 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
617 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
619 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
621 * @param context Schema Context
622 * @param module Yang Module
623 * @param prefix Module Prefix
624 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
625 * @throws NullPointerException if any arguments are null
627 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
628 final String prefix) {
629 requireNonNull(context, "context");
631 if (prefix.equals(module.getPrefix())) {
635 final Set<ModuleImport> imports = module.getImports();
636 for (final ModuleImport mi : imports) {
637 if (prefix.equals(mi.getPrefix())) {
638 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
645 * Resolve a relative XPath into a set of QNames.
651 * @param relativeXPath
652 * Non conditional Revision Aware Relative XPath
653 * @param actualSchemaNode
655 * @return target schema node
656 * @throws IllegalArgumentException if any arguments are null
658 private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
659 final PathExpression relativeXPath, final SchemaNode actualSchemaNode) {
660 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
661 + "for non relative Revision Aware XPath use findDataSchemaNode method");
662 checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
664 final String orig = relativeXPath.getOriginalString();
665 return orig.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, orig)
666 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode, doSplitXPath(orig)));
669 private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
670 final SchemaNode actualSchemaNode, final List<String> steps) {
671 // Find out how many "parent" components there are and trim them
672 final int colCount = normalizeXPath(steps);
673 final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
675 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
676 if (Iterables.size(schemaNodePath) - colCount >= 0) {
677 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
678 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
680 return Iterables.concat(schemaNodePath,
681 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
684 private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
685 final SchemaNode actualSchemaNode, final String xpath) {
686 final int paren = xpath.indexOf(')', 6);
687 checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
689 final String derefArg = SPACE.trimFrom(xpath.substring(6, paren));
690 // Look up the node which we need to reference
691 final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
692 doSplitXPath(derefArg)));
693 checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
695 checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
698 // We have a deref() target, decide what to do about it
699 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
700 if (targetType instanceof InstanceIdentifierTypeDefinition) {
701 // Static inference breaks down, we cannot determine where this points to
702 // FIXME: dedicated exception, users can recover from it, derive from IAE
703 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
706 // deref() is define only for instance-identifier and leafref types, handle the latter
707 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
709 final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
710 LOG.debug("Derefencing path {}", targetPath);
712 final SchemaNode deref = targetPath.isAbsolute()
713 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
714 ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
715 : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
717 LOG.debug("Path {} could not be derefenced", targetPath);
721 checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
723 final List<String> qnames = doSplitXPath(SPACE.trimLeadingFrom(xpath.substring(paren + 1)));
724 return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
727 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule defaultModule,
728 final YangLocationPath path) {
729 final Deque<QName> ret = new ArrayDeque<>();
730 for (Step step : path.getSteps()) {
731 if (step instanceof AxisStep) {
732 // We only support parent axis steps
733 final YangXPathAxis axis = ((AxisStep) step).getAxis();
734 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
739 // This has to be a QNameStep
740 checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
742 if (step instanceof ResolvedQNameStep) {
743 qname = ((ResolvedQNameStep) step).getQName();
744 } else if (step instanceof UnresolvedQNameStep) {
745 final AbstractQName toResolve = ((UnresolvedQNameStep) step).getQName();
746 // TODO: should handle qualified QNames, too? parser should have resolved them when we get here...
747 checkState(toResolve instanceof UnqualifiedQName, "Unhandled qname %s in %s", toResolve, path);
748 qname = QName.create(defaultModule, toResolve.getLocalName());
750 throw new IllegalStateException("Unhandled step " + step);
756 return findTargetNode(context, ret);
759 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
760 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
761 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
762 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
763 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
767 static int normalizeXPath(final List<String> xpath) {
768 LOG.trace("Normalize {}", xpath);
770 // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
773 // Next up: count leading ".." components
774 int leadingParents = 0;
776 if (leadingParents == xpath.size()) {
777 return leadingParents;
779 if (!"..".equals(xpath.get(leadingParents))) {
786 // Now let's see if there there is a '..' in the rest
787 final int dots = findDots(xpath, leadingParents + 1);
789 return leadingParents;
792 xpath.remove(dots - 1);
793 xpath.remove(dots - 1);
794 LOG.trace("Next iteration {}", xpath);
798 private static int findDots(final List<String> xpath, final int startIndex) {
799 for (int i = startIndex; i < xpath.size(); ++i) {
800 if ("..".equals(xpath.get(i))) {
808 private static List<String> doSplitXPath(final String xpath) {
809 return SLASH_SPLITTER.splitToList(xpath);
813 * Extracts the base type of node on which schema node points to. If target node is again of type
814 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
816 * @param typeDefinition
817 * type of node which will be extracted
818 * @param schemaContext
822 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
823 * is there to preserve backwards compatibility)
825 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
826 final SchemaContext schemaContext, final SchemaNode schema) {
827 PathExpression pathStatement = typeDefinition.getPathStatement();
828 pathStatement = new PathExpressionImpl(stripConditionsFromXPathString(pathStatement),
829 pathStatement.isAbsolute());
831 final DataSchemaNode dataSchemaNode;
832 if (pathStatement.isAbsolute()) {
833 SchemaNode baseSchema = schema;
834 while (baseSchema instanceof DerivableSchemaNode) {
835 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
836 if (basePotential.isPresent()) {
837 baseSchema = basePotential.get();
843 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
844 dataSchemaNode = (DataSchemaNode) findDataSchemaNode(schemaContext, parentModule, pathStatement);
846 Module parentModule = findParentModule(schemaContext, schema);
847 dataSchemaNode = (DataSchemaNode) findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema,
851 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
852 // and current expected behaviour for such cases is to just use pure string
853 // This should throw an exception about incorrect XPath in leafref
854 if (dataSchemaNode == null) {
858 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
860 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
861 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
864 return targetTypeDefinition;
868 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
869 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
870 * module as typedef which is then imported to referenced module.
873 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
875 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
876 final SchemaContext schemaContext, final QName qname) {
877 final PathExpression pathStatement = typeDefinition.getPathStatement();
878 if (!pathStatement.isAbsolute()) {
882 final PathExpression strippedPathStatement = new PathExpressionImpl(
883 stripConditionsFromXPathString(pathStatement), true);
885 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
886 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
888 final DataSchemaNode dataSchemaNode = (DataSchemaNode) findDataSchemaNode(schemaContext, parentModule.get(),
889 strippedPathStatement);
890 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
891 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
892 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
895 return targetTypeDefinition;
898 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
899 final SchemaNode schemaNode) {
900 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
901 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
903 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
904 if (nodeType.getBaseType() != null) {
905 while (nodeType.getBaseType() != null) {
906 nodeType = nodeType.getBaseType();
909 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
912 return findParentModule(schemaContext, schemaNode);
915 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
918 * Removes conditions from xPath pointed to target node.
920 * @param pathStatement
921 * xPath to target node
922 * @return string representation of xPath without conditions
925 static String stripConditionsFromXPathString(final PathExpression pathStatement) {
926 return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
930 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
933 * a node representing LeafSchemaNode
934 * @return concrete type definition of node value
936 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
937 TypeDefinition<?> baseType = node.getType();
938 while (baseType.getBaseType() != null) {
939 baseType = baseType.getBaseType();
945 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
948 * a node representing LeafListSchemaNode
949 * @return concrete type definition of node value
951 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
952 TypeDefinition<?> baseType = node.getType();
953 while (baseType.getBaseType() != null) {
954 baseType = baseType.getBaseType();
960 * Gets the base type of DataSchemaNode value.
963 * a node representing DataSchemaNode
964 * @return concrete type definition of node value
966 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
967 if (node instanceof LeafListSchemaNode) {
968 return typeDefinition((LeafListSchemaNode) node);
969 } else if (node instanceof LeafSchemaNode) {
970 return typeDefinition((LeafSchemaNode) node);
972 throw new IllegalArgumentException("Unhandled parameter type: " + node);