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.Splitter;
17 import com.google.common.collect.Iterables;
18 import com.google.common.collect.Lists;
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.ContainerLike;
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.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
47 import org.opendaylight.yangtools.yang.model.api.ModuleLike;
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.Submodule;
60 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
69 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
70 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
71 import org.slf4j.Logger;
72 import org.slf4j.LoggerFactory;
75 * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
76 * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
79 public final class SchemaContextUtil {
80 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
81 private static final Splitter COLON_SPLITTER = Splitter.on(':');
82 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
83 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
85 private SchemaContextUtil() {
90 * Method attempts to find DataSchemaNode in Schema Context via specified Schema Path. The returned DataSchemaNode
91 * from method will be the node at the end of the SchemaPath. If the DataSchemaNode is not present in the Schema
92 * Context the method will return {@code null}.
95 * In case that Schema Context or Schema Path are not specified correctly (i.e. contains {@code null} values) the
96 * method will throw IllegalArgumentException.
98 * @param context Schema Context
99 * @param schemaPath Schema Path to search for
100 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
101 * @throws NullPointerException if context or schemaPath is null
103 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
104 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
105 if (prefixedPath == null) {
106 LOG.debug("Schema path {} has null path", schemaPath);
110 LOG.trace("Looking for path {} in context {}", schemaPath, context);
111 return findNodeInSchemaContext(context, prefixedPath);
115 * Attempt to find a DataSchemaNode based on its path from root, similar to
116 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
118 * @param context Schema Context
119 * @param path Path to search for
120 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
121 * @throws NullPointerException if a any argument is null or if the path contains a null element
124 public static SchemaNode findDataSchemaNode(final SchemaContext context, final List<QName> path) {
125 return findTargetNode(context, null, YangLocationPath.absolute(
126 path.stream().map(YangXPathAxis.CHILD::asStep).collect(Collectors.toList())));
130 * Attempt to find a DataSchemaNode based on its path from root, similar to
131 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
133 * @param context Schema Context
134 * @param path Path to search for
135 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
136 * @throws NullPointerException if a any argument is null or if the path contains a null element
139 public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
140 return findDataSchemaNode(context, Arrays.asList(path));
144 * Method attempts to find DataSchemaNode inside of provided Schema Context
145 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
146 * specified Module MUST be present in Schema Context otherwise the
147 * operation would fail and return <code>null</code>. <br>
148 * The Revision Aware XPath MUST be specified WITHOUT the conditional
149 * statement (i.e. without [cond]) in path, because in this state the Schema
150 * Context is completely unaware of data state and will be not able to
151 * properly resolve XPath. If the XPath contains condition the method will
152 * return IllegalArgumentException. <br>
153 * If the Revision Aware XPath is correct and desired Data Schema Node is
154 * present in Yang module or in depending module in Schema Context the
155 * method will return specified Data Schema Node, otherwise the operation
156 * will fail and method will return <code>null</code>.
162 * @param nonCondXPath
163 * Non Conditional Revision Aware XPath
164 * @return Returns Data Schema Node for specified Schema Context for given
165 * Non-conditional Revision Aware XPath, or <code>null</code> if the
166 * DataSchemaNode is not present in Schema Context.
167 * @throws NullPointerException if any of the arguments is null
168 * @deprecated Use {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, YangLocationPath)} or
169 * {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, PathExpression)} instead.
171 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
172 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
175 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
176 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
177 // via a derived SchemaContext (i.e. this class would have to have a
179 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
181 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
182 // that feels like an overkill.
184 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
185 final PathExpression nonCondXPath) {
186 requireNonNull(context, "context");
187 requireNonNull(module, "module");
189 final String strXPath = nonCondXPath.getOriginalString();
190 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
191 if (nonCondXPath.isAbsolute()) {
192 return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
198 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
199 final YangLocationPath absPath) {
200 checkArgument(absPath.isAbsolute(), "Unsupported relative path %s", absPath);
201 return findTargetNode(ctx, localModule, absPath);
205 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
206 final PathExpression absPath) {
207 final Steps pathSteps = absPath.getSteps();
208 if (pathSteps instanceof LocationPathSteps) {
209 return findDataTreeSchemaNode(ctx, localModule, ((LocationPathSteps) pathSteps).getLocationPath());
212 // We would need a reference schema node and no, we do not want to use SchemaContext in its SchemaNode capacity
213 checkArgument(!(pathSteps instanceof DerefSteps), "No reference node for steps %s", pathSteps);
215 // We are missing proper API alignment, if this ever triggers
216 throw new IllegalStateException("Unsupported path " + pathSteps);
220 * Method attempts to find DataSchemaNode inside of provided Schema Context
221 * and Yang Module accordingly to Non-conditional relative Revision Aware
222 * XPath. The specified Module MUST be present in Schema Context otherwise
223 * the operation would fail and return <code>null</code>. <br>
224 * The relative Revision Aware XPath MUST be specified WITHOUT the
225 * conditional statement (i.e. without [cond]) in path, because in this
226 * state the Schema Context is completely unaware of data state and will be
227 * not able to properly resolve XPath. If the XPath contains condition the
228 * method will return IllegalArgumentException. <br>
229 * The Actual Schema Node MUST be specified correctly because from this
230 * Schema Node will search starts. If the Actual Schema Node is not correct
231 * the operation will simply fail, because it will be unable to find desired
232 * DataSchemaNode. <br>
233 * If the Revision Aware XPath doesn't have flag
234 * <code>isAbsolute == false</code> the method will throw
235 * IllegalArgumentException. <br>
236 * If the relative Revision Aware XPath is correct and desired Data Schema
237 * Node is present in Yang module or in depending module in Schema Context
238 * the method will return specified Data Schema Node, otherwise the
239 * operation will fail and method will return <code>null</code>.
245 * @param actualSchemaNode
247 * @param relativeXPath
248 * Relative Non Conditional Revision Aware XPath
249 * @return DataSchemaNode if is present in specified Schema Context for
250 * given relative Revision Aware XPath, otherwise will return
252 * @throws NullPointerException if any argument is null
254 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
255 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
258 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
259 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
260 // via a derived SchemaContext (i.e. this class would have to have a
262 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
264 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
265 // that feels like an overkill.
266 // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
267 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
268 final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
269 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
270 + "for non relative Revision Aware XPath use findDataSchemaNode method");
271 return resolveRelativeXPath(context, module, removePredicatesFromXpath(relativeXPath.getOriginalString()),
275 private static String removePredicatesFromXpath(final String xpath) {
276 return GROUPS_PATTERN.matcher(xpath).replaceAll("");
280 * Returns parent Yang Module for specified Schema Context in which Schema
281 * Node is declared. If the Schema Node is not present in Schema Context the
282 * operation will return <code>null</code>.
284 * @param context Schema Context
285 * @param schemaNode Schema Node
286 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
287 * return <code>null</code>
288 * @throws NullPointerException if any of the arguments is null
290 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
291 final QName qname = schemaNode.getPath().getLastComponent();
292 checkState(qname != null, "Schema Path contains invalid state of path parts. "
293 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
294 return context.findModule(qname.getModule()).orElse(null);
297 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
298 final QName current = path.iterator().next();
300 LOG.trace("Looking up module {} in context {}", current, path);
301 final Optional<Module> module = context.findModule(current.getModule());
302 if (module.isEmpty()) {
303 LOG.debug("Module {} not found", current);
307 return findNodeInModule(module.get(), path);
311 * Returns NotificationDefinition from Schema Context.
313 * @param schema SchemaContext in which lookup should be performed.
314 * @param path Schema Path of notification
315 * @return Notification schema or null, if notification is not present in schema context.
318 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
319 final @NonNull SchemaPath path) {
320 requireNonNull(schema, "Schema context must not be null.");
321 requireNonNull(path, "Schema path must not be null.");
322 for (final NotificationDefinition potential : schema.getNotifications()) {
323 if (path.equals(potential.getPath())) {
331 * Returns RPC Input or Output Data container from RPC definition.
333 * @param schema SchemaContext in which lookup should be performed.
334 * @param path Schema path of RPC input/output data container
335 * @return Notification schema or null, if notification is not present in schema context.
338 public static @Nullable ContainerLike getRpcDataSchema(final @NonNull SchemaContext schema,
339 final @NonNull SchemaPath path) {
340 requireNonNull(schema, "Schema context must not be null.");
341 requireNonNull(path, "Schema path must not be null.");
342 final Iterator<QName> it = path.getPathFromRoot().iterator();
343 checkArgument(it.hasNext(), "Rpc must have QName.");
344 final QName rpcName = it.next();
345 checkArgument(it.hasNext(), "input or output must be part of path.");
346 final QName inOrOut = it.next();
347 for (final RpcDefinition potential : schema.getOperations()) {
348 if (rpcName.equals(potential.getQName())) {
349 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
356 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
358 * @param context SchemaContext to be examined
359 * @return Set of ModuleIdentifiers.
361 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
362 final Set<SourceIdentifier> ret = new HashSet<>();
364 for (Module module : context.getModules()) {
365 ret.add(moduleToIdentifier(module));
367 for (Submodule submodule : module.getSubmodules()) {
368 ret.add(moduleToIdentifier(submodule));
375 private static SourceIdentifier moduleToIdentifier(final ModuleLike module) {
376 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
379 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
380 if (!path.iterator().hasNext()) {
381 LOG.debug("No node matching {} found in node {}", path, module);
385 final QName current = path.iterator().next();
386 LOG.trace("Looking for node {} in module {}", current, module);
388 SchemaNode foundNode = null;
389 final Iterable<QName> nextPath = nextLevel(path);
391 foundNode = module.dataChildByName(current);
392 if (foundNode != null && nextPath.iterator().hasNext()) {
393 foundNode = findNodeIn(foundNode, nextPath);
396 if (foundNode == null) {
397 foundNode = getGroupingByName(module, current);
398 if (foundNode != null && nextPath.iterator().hasNext()) {
399 foundNode = findNodeIn(foundNode, nextPath);
403 if (foundNode == null) {
404 foundNode = getRpcByName(module, current);
405 if (foundNode != null && nextPath.iterator().hasNext()) {
406 foundNode = findNodeIn(foundNode, nextPath);
410 if (foundNode == null) {
411 foundNode = getNotificationByName(module, current);
412 if (foundNode != null && nextPath.iterator().hasNext()) {
413 foundNode = findNodeIn(foundNode, nextPath);
417 if (foundNode == null) {
418 LOG.debug("No node matching {} found in node {}", path, module);
424 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
425 if (!path.iterator().hasNext()) {
426 LOG.debug("No node matching {} found in node {}", path, parent);
430 final QName current = path.iterator().next();
431 LOG.trace("Looking for node {} in node {}", current, parent);
433 SchemaNode foundNode = null;
434 final Iterable<QName> nextPath = nextLevel(path);
436 if (parent instanceof DataNodeContainer) {
437 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
439 foundNode = parentDataNodeContainer.dataChildByName(current);
440 if (foundNode != null && nextPath.iterator().hasNext()) {
441 foundNode = findNodeIn(foundNode, nextPath);
444 if (foundNode == null) {
445 foundNode = getGroupingByName(parentDataNodeContainer, current);
446 if (foundNode != null && nextPath.iterator().hasNext()) {
447 foundNode = findNodeIn(foundNode, nextPath);
452 if (foundNode == null && parent instanceof ActionNodeContainer) {
453 final Optional<? extends SchemaNode> next = ((ActionNodeContainer) parent).getActions().stream()
454 .filter(act -> current.equals(act.getQName())).findFirst();
455 if (next.isPresent() && nextPath.iterator().hasNext()) {
456 foundNode = findNodeIn(next.orElseThrow(), nextPath);
460 if (foundNode == null && parent instanceof NotificationNodeContainer) {
461 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
462 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
463 if (foundNode != null && nextPath.iterator().hasNext()) {
464 foundNode = findNodeIn(foundNode, nextPath);
468 if (foundNode == null && parent instanceof OperationDefinition) {
469 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
471 if (current.getLocalName().equals("input")) {
472 foundNode = parentRpcDefinition.getInput();
473 if (foundNode != null && nextPath.iterator().hasNext()) {
474 foundNode = findNodeIn(foundNode, nextPath);
478 if (current.getLocalName().equals("output")) {
479 foundNode = parentRpcDefinition.getOutput();
480 if (foundNode != null && nextPath.iterator().hasNext()) {
481 foundNode = findNodeIn(foundNode, nextPath);
485 if (foundNode == null) {
486 foundNode = getGroupingByName(parentRpcDefinition, current);
487 if (foundNode != null && nextPath.iterator().hasNext()) {
488 foundNode = findNodeIn(foundNode, nextPath);
493 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
494 foundNode = ((ChoiceSchemaNode) parent).findCase(current).orElse(null);
496 if (foundNode != null && nextPath.iterator().hasNext()) {
497 foundNode = findNodeIn(foundNode, nextPath);
500 if (foundNode == null) {
501 // fallback that tries to map into one of the child cases
502 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
503 final DataSchemaNode maybeChild = caseNode.dataChildByName(current);
504 if (maybeChild != null) {
505 foundNode = findNodeIn(maybeChild, nextPath);
512 if (foundNode == null) {
513 LOG.debug("No node matching {} found in node {}", path, parent);
520 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
521 return Iterables.skip(path, 1);
524 private static RpcDefinition getRpcByName(final Module module, final QName name) {
525 for (final RpcDefinition rpc : module.getRpcs()) {
526 if (rpc.getQName().equals(name)) {
533 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
534 for (final NotificationDefinition notification : module.getNotifications()) {
535 if (notification.getQName().equals(name)) {
542 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
543 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
544 if (grouping.getQName().equals(name)) {
551 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
552 for (final GroupingDefinition grouping : rpc.getGroupings()) {
553 if (grouping.getQName().equals(name)) {
561 * Transforms string representation of XPath to Queue of QNames. The XPath
562 * is split by "/" and for each part of XPath is assigned correct module in
564 * If Schema Context, Parent Module or XPath string contains
565 * <code>null</code> values, the method will throws IllegalArgumentException
569 * @param parentModule
573 * @return return a list of QName
575 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
576 final String xpath) {
577 final List<QName> path = new ArrayList<>();
578 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
579 path.add(stringPathPartToQName(context, parentModule, pathComponent));
585 * Transforms part of Prefixed Path as java String to QName. <br>
586 * If the string contains module prefix separated by ":" (i.e.
587 * mod:container) this module is provided from from Parent Module list of
588 * imports. If the Prefixed module is present in Schema Context the QName
589 * can be constructed. <br>
590 * If the Prefixed Path Part does not contains prefix the Parent's Module
591 * namespace is taken for construction of QName. <br>
593 * @param context Schema Context
594 * @param parentModule Parent Module
595 * @param prefixedPathPart Prefixed Path Part string
596 * @return QName from prefixed Path Part String.
597 * @throws NullPointerException if any arguments are null
599 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
600 final String prefixedPathPart) {
601 requireNonNull(context, "context");
603 if (prefixedPathPart.indexOf(':') != -1) {
604 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
605 final String modulePrefix = prefixedName.next();
607 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
608 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
609 modulePrefix, parentModule.getName());
611 return QName.create(module.getQNameModule(), prefixedName.next());
614 return QName.create(parentModule.getQNameModule(), prefixedPathPart);
618 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
619 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
620 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
621 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
623 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
625 * @param context Schema Context
626 * @param module Yang Module
627 * @param prefix Module Prefix
628 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
629 * @throws NullPointerException if any arguments are null
631 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
632 final String prefix) {
633 requireNonNull(context, "context");
635 if (prefix.equals(module.getPrefix())) {
639 for (final ModuleImport mi : module.getImports()) {
640 if (prefix.equals(mi.getPrefix())) {
641 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
648 * Resolve a relative XPath into a set of QNames.
656 * @param actualSchemaNode
658 * @return target schema node
659 * @throws IllegalArgumentException if any arguments are null
661 private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
662 final String pathStr, final SchemaNode actualSchemaNode) {
663 checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
665 return pathStr.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, pathStr)
666 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
667 doSplitXPath(pathStr)));
670 private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
671 final SchemaNode actualSchemaNode, final List<String> steps) {
672 // Find out how many "parent" components there are and trim them
673 final int colCount = normalizeXPath(steps);
674 final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
676 final List<QName> walkablePath = createWalkablePath(actualSchemaNode.getPath().getPathFromRoot(),
679 if (walkablePath.size() - colCount >= 0) {
680 return Iterables.concat(Iterables.limit(walkablePath, walkablePath.size() - colCount),
681 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
683 return Iterables.concat(walkablePath,
684 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
688 * Return List of qNames that are walkable using xPath. When getting a path from schema node it will return path
689 * with parents like CaseSchemaNode and ChoiceSchemaNode as well if they are parents of the node. We need to get
690 * rid of these in order to find the node that xPath is pointing to. Also we can not remove any node beyond the
691 * amount of "../" because we will not be able to find the correct schema node from schema context
693 * @param schemaNodePath list of qNames as a path to the leaf of type leafref
694 * @param context create schema context
695 * @param colCount amount of "../" in the xPath expression
696 * @return list of QNames as a path where we should be able to find referenced node
698 private static List<QName> createWalkablePath(final Iterable<QName> schemaNodePath, final SchemaContext context,
699 final int colCount) {
700 final List<Integer> indexToRemove = new ArrayList<>();
701 List<QName> schemaNodePathRet = Lists.newArrayList(schemaNodePath);
702 for (int j = 0, i = schemaNodePathRet.size() - 1; i >= 0 && j != colCount; i--, j++) {
703 final SchemaNode nodeIn = findTargetNode(context, schemaNodePathRet);
704 if (nodeIn instanceof CaseSchemaNode || nodeIn instanceof ChoiceSchemaNode) {
705 indexToRemove.add(i);
708 schemaNodePathRet.remove(i);
710 schemaNodePathRet = Lists.newArrayList(schemaNodePath);
711 for (int i : indexToRemove) {
712 schemaNodePathRet.remove(i);
714 return schemaNodePathRet;
717 private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
718 final SchemaNode actualSchemaNode, final String xpath) {
719 final int paren = xpath.indexOf(')', 6);
720 checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
722 final String derefArg = xpath.substring(6, paren).strip();
723 // Look up the node which we need to reference
724 final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
725 doSplitXPath(derefArg)));
726 checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
728 checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
731 // We have a deref() target, decide what to do about it
732 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
733 if (targetType instanceof InstanceIdentifierTypeDefinition) {
734 // Static inference breaks down, we cannot determine where this points to
735 // FIXME: dedicated exception, users can recover from it, derive from IAE
736 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
739 // deref() is define only for instance-identifier and leafref types, handle the latter
740 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
742 final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
743 LOG.debug("Derefencing path {}", targetPath);
745 final SchemaNode deref = targetPath.isAbsolute()
746 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
747 ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
748 : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
750 LOG.debug("Path {} could not be derefenced", targetPath);
754 checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
756 final List<String> qnames = doSplitXPath(xpath.substring(paren + 1).stripLeading());
757 return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
760 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule localNamespace,
761 final YangLocationPath path) {
762 final Deque<QName> ret = new ArrayDeque<>();
763 for (Step step : path.getSteps()) {
764 if (step instanceof AxisStep) {
765 // We only support parent axis steps
766 final YangXPathAxis axis = ((AxisStep) step).getAxis();
767 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
772 // This has to be a QNameStep
773 checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
774 ret.addLast(resolve(((QNameStep) step).getQName(), localNamespace));
777 return findTargetNode(context, ret);
780 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
781 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
782 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
783 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
784 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
787 private static QName resolve(final AbstractQName toResolve, final QNameModule localNamespace) {
788 if (toResolve instanceof QName) {
789 return (QName) toResolve;
790 } else if (toResolve instanceof UnqualifiedQName) {
791 return ((UnqualifiedQName) toResolve).bindTo(localNamespace);
793 throw new IllegalStateException("Unhandled step " + toResolve);
798 static int normalizeXPath(final List<String> xpath) {
799 LOG.trace("Normalize {}", xpath);
801 // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
804 // Next up: count leading ".." components
805 int leadingParents = 0;
807 if (leadingParents == xpath.size()) {
808 return leadingParents;
810 if (!"..".equals(xpath.get(leadingParents))) {
817 // Now let's see if there there is a '..' in the rest
818 final int dots = findDots(xpath, leadingParents + 1);
820 return leadingParents;
823 xpath.remove(dots - 1);
824 xpath.remove(dots - 1);
825 LOG.trace("Next iteration {}", xpath);
829 private static int findDots(final List<String> xpath, final int startIndex) {
830 for (int i = startIndex; i < xpath.size(); ++i) {
831 if ("..".equals(xpath.get(i))) {
839 private static List<String> doSplitXPath(final String xpath) {
840 final List<String> ret = new ArrayList<>();
841 for (String str : SLASH_SPLITTER.split(xpath)) {
848 * Extracts the base type of node on which schema node points to. If target node is again of type
849 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
851 * @param typeDefinition
852 * type of node which will be extracted
853 * @param schemaContext
857 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
858 * is there to preserve backwards compatibility)
860 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
861 final SchemaContext schemaContext, final SchemaNode schema) {
862 final PathExpression pathStatement = typeDefinition.getPathStatement();
863 final String pathStr = stripConditionsFromXPathString(pathStatement);
865 final DataSchemaNode dataSchemaNode;
866 if (pathStatement.isAbsolute()) {
867 SchemaNode baseSchema = schema;
868 while (baseSchema instanceof DerivableSchemaNode) {
869 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
870 if (basePotential.isPresent()) {
871 baseSchema = basePotential.get();
877 final Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
878 dataSchemaNode = (DataSchemaNode) findTargetNode(schemaContext,
879 xpathToQNamePath(schemaContext, parentModule, pathStr));
881 Module parentModule = findParentModule(schemaContext, schema);
882 dataSchemaNode = (DataSchemaNode) resolveRelativeXPath(schemaContext, parentModule, pathStr, schema);
885 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
886 // and current expected behaviour for such cases is to just use pure string
887 // This should throw an exception about incorrect XPath in leafref
888 if (dataSchemaNode == null) {
892 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
894 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
895 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
898 return targetTypeDefinition;
902 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
903 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
904 * module as typedef which is then imported to referenced module.
907 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
909 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
910 final SchemaContext schemaContext, final QName qname) {
911 final PathExpression pathStatement = typeDefinition.getPathStatement();
912 if (!pathStatement.isAbsolute()) {
916 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
917 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
919 final DataSchemaNode dataSchemaNode = (DataSchemaNode) findTargetNode(schemaContext,
920 xpathToQNamePath(schemaContext, parentModule.get(), stripConditionsFromXPathString(pathStatement)));
921 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
922 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
923 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
926 return targetTypeDefinition;
929 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
930 final SchemaNode schemaNode) {
931 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
932 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
934 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
935 if (nodeType.getBaseType() != null) {
936 while (nodeType.getBaseType() != null) {
937 nodeType = nodeType.getBaseType();
940 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
943 return findParentModule(schemaContext, schemaNode);
946 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
949 * Removes conditions from xPath pointed to target node.
951 * @param pathStatement
952 * xPath to target node
953 * @return string representation of xPath without conditions
956 static String stripConditionsFromXPathString(final PathExpression pathStatement) {
957 return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
961 * Gets the base type of DataSchemaNode value.
964 * a node representing DataSchemaNode
965 * @return concrete type definition of node value
967 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
968 checkArgument(node instanceof TypedDataSchemaNode, "Unhandled parameter type %s", node);
970 TypeDefinition<?> current = ((TypedDataSchemaNode) node).getType();
971 // TODO: don't we have a utility for this?
972 TypeDefinition<?> base = current.getBaseType();
973 while (base != null) {
975 base = current.getBaseType();