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.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.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.NotificationDefinition;
48 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
50 import org.opendaylight.yangtools.yang.model.api.PathExpression;
51 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
52 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
53 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
54 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
58 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
68 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
69 import org.slf4j.Logger;
70 import org.slf4j.LoggerFactory;
73 * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
74 * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
77 public final class SchemaContextUtil {
78 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
79 private static final Splitter COLON_SPLITTER = Splitter.on(':');
80 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
81 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
83 private SchemaContextUtil() {
88 * Method attempts to find DataSchemaNode in Schema Context via specified Schema Path. The returned DataSchemaNode
89 * from method will be the node at the end of the SchemaPath. If the DataSchemaNode is not present in the Schema
90 * Context the method will return {@code null}.
93 * In case that Schema Context or Schema Path are not specified correctly (i.e. contains {@code null} values) the
94 * method will throw IllegalArgumentException.
96 * @param context Schema Context
97 * @param schemaPath Schema Path to search for
98 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
99 * @throws NullPointerException if context or schemaPath is null
101 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
102 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
103 if (prefixedPath == null) {
104 LOG.debug("Schema path {} has null path", schemaPath);
108 LOG.trace("Looking for path {} in context {}", schemaPath, context);
109 return findNodeInSchemaContext(context, prefixedPath);
113 * Attempt to find a DataSchemaNode based on its path from root, similar to
114 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
116 * @param context Schema Context
117 * @param path Path to search for
118 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
119 * @throws NullPointerException if a any argument is null or if the path contains a null element
122 public static SchemaNode findDataSchemaNode(final SchemaContext context, final List<QName> path) {
123 return findTargetNode(context, null, YangLocationPath.absolute(
124 path.stream().map(YangXPathAxis.CHILD::asStep).collect(Collectors.toList())));
128 * Attempt to find a DataSchemaNode based on its path from root, similar to
129 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
131 * @param context Schema Context
132 * @param path Path to search for
133 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
134 * @throws NullPointerException if a any argument is null or if the path contains a null element
137 public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
138 return findDataSchemaNode(context, Arrays.asList(path));
142 * Method attempts to find DataSchemaNode inside of provided Schema Context
143 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
144 * specified Module MUST be present in Schema Context otherwise the
145 * operation would fail and return <code>null</code>. <br>
146 * The Revision Aware XPath MUST be specified WITHOUT the conditional
147 * statement (i.e. without [cond]) in path, because in this state the Schema
148 * Context is completely unaware of data state and will be not able to
149 * properly resolve XPath. If the XPath contains condition the method will
150 * return IllegalArgumentException. <br>
151 * If the Revision Aware XPath is correct and desired Data Schema Node is
152 * present in Yang module or in depending module in Schema Context the
153 * method will return specified Data Schema Node, otherwise the operation
154 * will fail and method will return <code>null</code>.
160 * @param nonCondXPath
161 * Non Conditional Revision Aware XPath
162 * @return Returns Data Schema Node for specified Schema Context for given
163 * Non-conditional Revision Aware XPath, or <code>null</code> if the
164 * DataSchemaNode is not present in Schema Context.
165 * @throws NullPointerException if any of the arguments is null
166 * @deprecated Use {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, YangLocationPath)} or
167 * {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, PathExpression)} instead.
169 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
170 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
173 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
174 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
175 // via a derived SchemaContext (i.e. this class would have to have a
177 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
179 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
180 // that feels like an overkill.
182 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
183 final PathExpression nonCondXPath) {
184 requireNonNull(context, "context");
185 requireNonNull(module, "module");
187 final String strXPath = nonCondXPath.getOriginalString();
188 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
189 if (nonCondXPath.isAbsolute()) {
190 return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
196 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
197 final YangLocationPath absPath) {
198 checkArgument(absPath.isAbsolute(), "Unsupported relative path %s", absPath);
199 return findTargetNode(ctx, localModule, absPath);
203 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
204 final PathExpression absPath) {
205 final Steps pathSteps = absPath.getSteps();
206 if (pathSteps instanceof LocationPathSteps) {
207 return findDataTreeSchemaNode(ctx, localModule, ((LocationPathSteps) pathSteps).getLocationPath());
210 // We would need a reference schema node and no, we do not want to use SchemaContext in its SchemaNode capacity
211 checkArgument(!(pathSteps instanceof DerefSteps), "No reference node for steps %s", pathSteps);
213 // We are missing proper API alignment, if this ever triggers
214 throw new IllegalStateException("Unsupported path " + pathSteps);
218 * Method attempts to find DataSchemaNode inside of provided Schema Context
219 * and Yang Module accordingly to Non-conditional relative Revision Aware
220 * XPath. The specified Module MUST be present in Schema Context otherwise
221 * the operation would fail and return <code>null</code>. <br>
222 * The relative Revision Aware XPath MUST be specified WITHOUT the
223 * conditional statement (i.e. without [cond]) in path, because in this
224 * state the Schema Context is completely unaware of data state and will be
225 * not able to properly resolve XPath. If the XPath contains condition the
226 * method will return IllegalArgumentException. <br>
227 * The Actual Schema Node MUST be specified correctly because from this
228 * Schema Node will search starts. If the Actual Schema Node is not correct
229 * the operation will simply fail, because it will be unable to find desired
230 * DataSchemaNode. <br>
231 * If the Revision Aware XPath doesn't have flag
232 * <code>isAbsolute == false</code> the method will throw
233 * IllegalArgumentException. <br>
234 * If the relative Revision Aware XPath is correct and desired Data Schema
235 * Node is present in Yang module or in depending module in Schema Context
236 * the method will return specified Data Schema Node, otherwise the
237 * operation will fail and method will return <code>null</code>.
243 * @param actualSchemaNode
245 * @param relativeXPath
246 * Relative Non Conditional Revision Aware XPath
247 * @return DataSchemaNode if is present in specified Schema Context for
248 * given relative Revision Aware XPath, otherwise will return
250 * @throws NullPointerException if any argument is null
252 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
253 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
256 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
257 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
258 // via a derived SchemaContext (i.e. this class would have to have a
260 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
262 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
263 // that feels like an overkill.
264 // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
265 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
266 final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
267 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
268 + "for non relative Revision Aware XPath use findDataSchemaNode method");
269 return resolveRelativeXPath(context, module, removePredicatesFromXpath(relativeXPath.getOriginalString()),
273 private static String removePredicatesFromXpath(final String xpath) {
274 return GROUPS_PATTERN.matcher(xpath).replaceAll("");
278 * Returns parent Yang Module for specified Schema Context in which Schema
279 * Node is declared. If the Schema Node is not present in Schema Context the
280 * operation will return <code>null</code>.
282 * @param context Schema Context
283 * @param schemaNode Schema Node
284 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
285 * return <code>null</code>
286 * @throws NullPointerException if any of the arguments is null
288 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
289 final QName qname = schemaNode.getPath().getLastComponent();
290 checkState(qname != null, "Schema Path contains invalid state of path parts. "
291 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
292 return context.findModule(qname.getModule()).orElse(null);
295 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
296 final QName current = path.iterator().next();
298 LOG.trace("Looking up module {} in context {}", current, path);
299 final Optional<Module> module = context.findModule(current.getModule());
300 if (module.isEmpty()) {
301 LOG.debug("Module {} not found", current);
305 return findNodeInModule(module.get(), path);
309 * Returns NotificationDefinition from Schema Context.
311 * @param schema SchemaContext in which lookup should be performed.
312 * @param path Schema Path of notification
313 * @return Notification schema or null, if notification is not present in schema context.
316 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
317 final @NonNull SchemaPath path) {
318 requireNonNull(schema, "Schema context must not be null.");
319 requireNonNull(path, "Schema path must not be null.");
320 for (final NotificationDefinition potential : schema.getNotifications()) {
321 if (path.equals(potential.getPath())) {
329 * Returns RPC Input or Output Data container from RPC definition.
331 * @param schema SchemaContext in which lookup should be performed.
332 * @param path Schema path of RPC input/output data container
333 * @return Notification schema or null, if notification is not present in schema context.
336 public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
337 final @NonNull SchemaPath path) {
338 requireNonNull(schema, "Schema context must not be null.");
339 requireNonNull(path, "Schema path must not be null.");
340 final Iterator<QName> it = path.getPathFromRoot().iterator();
341 checkArgument(it.hasNext(), "Rpc must have QName.");
342 final QName rpcName = it.next();
343 checkArgument(it.hasNext(), "input or output must be part of path.");
344 final QName inOrOut = it.next();
345 for (final RpcDefinition potential : schema.getOperations()) {
346 if (rpcName.equals(potential.getQName())) {
347 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
354 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
356 * @param context SchemaContext to be examined
357 * @return Set of ModuleIdentifiers.
359 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
360 final Set<SourceIdentifier> ret = new HashSet<>();
362 for (Module module : context.getModules()) {
363 ret.add(moduleToIdentifier(module));
365 for (Module submodule : module.getSubmodules()) {
366 ret.add(moduleToIdentifier(submodule));
373 private static SourceIdentifier moduleToIdentifier(final Module module) {
374 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
377 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
378 if (!path.iterator().hasNext()) {
379 LOG.debug("No node matching {} found in node {}", path, module);
383 final QName current = path.iterator().next();
384 LOG.trace("Looking for node {} in module {}", current, module);
386 SchemaNode foundNode = null;
387 final Iterable<QName> nextPath = nextLevel(path);
389 foundNode = module.getDataChildByName(current);
390 if (foundNode != null && nextPath.iterator().hasNext()) {
391 foundNode = findNodeIn(foundNode, nextPath);
394 if (foundNode == null) {
395 foundNode = getGroupingByName(module, current);
396 if (foundNode != null && nextPath.iterator().hasNext()) {
397 foundNode = findNodeIn(foundNode, nextPath);
401 if (foundNode == null) {
402 foundNode = getRpcByName(module, current);
403 if (foundNode != null && nextPath.iterator().hasNext()) {
404 foundNode = findNodeIn(foundNode, nextPath);
408 if (foundNode == null) {
409 foundNode = getNotificationByName(module, current);
410 if (foundNode != null && nextPath.iterator().hasNext()) {
411 foundNode = findNodeIn(foundNode, nextPath);
415 if (foundNode == null) {
416 LOG.debug("No node matching {} found in node {}", path, module);
422 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
423 if (!path.iterator().hasNext()) {
424 LOG.debug("No node matching {} found in node {}", path, parent);
428 final QName current = path.iterator().next();
429 LOG.trace("Looking for node {} in node {}", current, parent);
431 SchemaNode foundNode = null;
432 final Iterable<QName> nextPath = nextLevel(path);
434 if (parent instanceof DataNodeContainer) {
435 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
437 foundNode = parentDataNodeContainer.getDataChildByName(current);
438 if (foundNode != null && nextPath.iterator().hasNext()) {
439 foundNode = findNodeIn(foundNode, nextPath);
442 if (foundNode == null) {
443 foundNode = getGroupingByName(parentDataNodeContainer, current);
444 if (foundNode != null && nextPath.iterator().hasNext()) {
445 foundNode = findNodeIn(foundNode, nextPath);
450 if (foundNode == null && parent instanceof ActionNodeContainer) {
451 foundNode = ((ActionNodeContainer) parent).getActions().stream()
452 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
453 if (foundNode != null && nextPath.iterator().hasNext()) {
454 foundNode = findNodeIn(foundNode, nextPath);
458 if (foundNode == null && parent instanceof NotificationNodeContainer) {
459 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
460 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
461 if (foundNode != null && nextPath.iterator().hasNext()) {
462 foundNode = findNodeIn(foundNode, nextPath);
466 if (foundNode == null && parent instanceof OperationDefinition) {
467 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
469 if (current.getLocalName().equals("input")) {
470 foundNode = parentRpcDefinition.getInput();
471 if (foundNode != null && nextPath.iterator().hasNext()) {
472 foundNode = findNodeIn(foundNode, nextPath);
476 if (current.getLocalName().equals("output")) {
477 foundNode = parentRpcDefinition.getOutput();
478 if (foundNode != null && nextPath.iterator().hasNext()) {
479 foundNode = findNodeIn(foundNode, nextPath);
483 if (foundNode == null) {
484 foundNode = getGroupingByName(parentRpcDefinition, current);
485 if (foundNode != null && nextPath.iterator().hasNext()) {
486 foundNode = findNodeIn(foundNode, nextPath);
491 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
492 foundNode = ((ChoiceSchemaNode) parent).findCase(current).orElse(null);
494 if (foundNode != null && nextPath.iterator().hasNext()) {
495 foundNode = findNodeIn(foundNode, nextPath);
498 if (foundNode == null) {
499 // fallback that tries to map into one of the child cases
500 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
501 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
502 if (maybeChild != null) {
503 foundNode = findNodeIn(maybeChild, nextPath);
510 if (foundNode == null) {
511 LOG.debug("No node matching {} found in node {}", path, parent);
518 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
519 return Iterables.skip(path, 1);
522 private static RpcDefinition getRpcByName(final Module module, final QName name) {
523 for (final RpcDefinition rpc : module.getRpcs()) {
524 if (rpc.getQName().equals(name)) {
531 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
532 for (final NotificationDefinition notification : module.getNotifications()) {
533 if (notification.getQName().equals(name)) {
540 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
541 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
542 if (grouping.getQName().equals(name)) {
549 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
550 for (final GroupingDefinition grouping : rpc.getGroupings()) {
551 if (grouping.getQName().equals(name)) {
559 * Transforms string representation of XPath to Queue of QNames. The XPath
560 * is split by "/" and for each part of XPath is assigned correct module in
562 * If Schema Context, Parent Module or XPath string contains
563 * <code>null</code> values, the method will throws IllegalArgumentException
567 * @param parentModule
571 * @return return a list of QName
573 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
574 final String xpath) {
575 final List<QName> path = new ArrayList<>();
576 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
577 path.add(stringPathPartToQName(context, parentModule, pathComponent));
583 * Transforms part of Prefixed Path as java String to QName. <br>
584 * If the string contains module prefix separated by ":" (i.e.
585 * mod:container) this module is provided from from Parent Module list of
586 * imports. If the Prefixed module is present in Schema Context the QName
587 * can be constructed. <br>
588 * If the Prefixed Path Part does not contains prefix the Parent's Module
589 * namespace is taken for construction of QName. <br>
591 * @param context Schema Context
592 * @param parentModule Parent Module
593 * @param prefixedPathPart Prefixed Path Part string
594 * @return QName from prefixed Path Part String.
595 * @throws NullPointerException if any arguments are null
597 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
598 final String prefixedPathPart) {
599 requireNonNull(context, "context");
601 if (prefixedPathPart.indexOf(':') != -1) {
602 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
603 final String modulePrefix = prefixedName.next();
605 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
606 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
607 modulePrefix, parentModule.getName());
609 return QName.create(module.getQNameModule(), prefixedName.next());
612 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
616 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
617 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
618 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
619 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
621 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
623 * @param context Schema Context
624 * @param module Yang Module
625 * @param prefix Module Prefix
626 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
627 * @throws NullPointerException if any arguments are null
629 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
630 final String prefix) {
631 requireNonNull(context, "context");
633 if (prefix.equals(module.getPrefix())) {
637 for (final ModuleImport mi : module.getImports()) {
638 if (prefix.equals(mi.getPrefix())) {
639 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
646 * Resolve a relative XPath into a set of QNames.
654 * @param actualSchemaNode
656 * @return target schema node
657 * @throws IllegalArgumentException if any arguments are null
659 private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
660 final String pathStr, final SchemaNode actualSchemaNode) {
661 checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
663 return pathStr.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, pathStr)
664 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
665 doSplitXPath(pathStr)));
668 private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
669 final SchemaNode actualSchemaNode, final List<String> steps) {
670 // Find out how many "parent" components there are and trim them
671 final int colCount = normalizeXPath(steps);
672 final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
674 final List<QName> walkablePath = createWalkablePath(actualSchemaNode.getPath().getPathFromRoot(),
677 if (walkablePath.size() - colCount >= 0) {
678 return Iterables.concat(Iterables.limit(walkablePath, walkablePath.size() - colCount),
679 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
681 return Iterables.concat(walkablePath,
682 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
686 * Return List of qNames that are walkable using xPath. When getting a path from schema node it will return path
687 * with parents like CaseSchemaNode and ChoiceSchemaNode as well if they are parents of the node. We need to get
688 * rid of these in order to find the node that xPath is pointing to. Also we can not remove any node beyond the
689 * amount of "../" because we will not be able to find the correct schema node from schema context
691 * @param schemaNodePath list of qNames as a path to the leaf of type leafref
692 * @param context create schema context
693 * @param colCount amount of "../" in the xPath expression
694 * @return list of QNames as a path where we should be able to find referenced node
696 private static List<QName> createWalkablePath(final Iterable<QName> schemaNodePath, final SchemaContext context,
697 final int colCount) {
698 final List<Integer> indexToRemove = new ArrayList<>();
699 List<QName> schemaNodePathRet = Lists.newArrayList(schemaNodePath);
700 for (int j = 0, i = schemaNodePathRet.size() - 1; i >= 0 && j != colCount; i--, j++) {
701 final SchemaNode nodeIn = findTargetNode(context, schemaNodePathRet);
702 if (nodeIn instanceof CaseSchemaNode || nodeIn instanceof ChoiceSchemaNode) {
703 indexToRemove.add(i);
706 schemaNodePathRet.remove(i);
708 schemaNodePathRet = Lists.newArrayList(schemaNodePath);
709 for (int i : indexToRemove) {
710 schemaNodePathRet.remove(i);
712 return schemaNodePathRet;
715 private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
716 final SchemaNode actualSchemaNode, final String xpath) {
717 final int paren = xpath.indexOf(')', 6);
718 checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
720 final String derefArg = xpath.substring(6, paren).strip();
721 // Look up the node which we need to reference
722 final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
723 doSplitXPath(derefArg)));
724 checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
726 checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
729 // We have a deref() target, decide what to do about it
730 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
731 if (targetType instanceof InstanceIdentifierTypeDefinition) {
732 // Static inference breaks down, we cannot determine where this points to
733 // FIXME: dedicated exception, users can recover from it, derive from IAE
734 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
737 // deref() is define only for instance-identifier and leafref types, handle the latter
738 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
740 final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
741 LOG.debug("Derefencing path {}", targetPath);
743 final SchemaNode deref = targetPath.isAbsolute()
744 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
745 ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
746 : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
748 LOG.debug("Path {} could not be derefenced", targetPath);
752 checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
754 final List<String> qnames = doSplitXPath(xpath.substring(paren + 1).stripLeading());
755 return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
758 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule localNamespace,
759 final YangLocationPath path) {
760 final Deque<QName> ret = new ArrayDeque<>();
761 for (Step step : path.getSteps()) {
762 if (step instanceof AxisStep) {
763 // We only support parent axis steps
764 final YangXPathAxis axis = ((AxisStep) step).getAxis();
765 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
770 // This has to be a QNameStep
771 checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
772 ret.addLast(resolve(((QNameStep) step).getQName(), localNamespace));
775 return findTargetNode(context, ret);
778 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
779 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
780 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
781 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
782 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
785 private static QName resolve(final AbstractQName toResolve, final QNameModule localNamespace) {
786 if (toResolve instanceof QName) {
787 return (QName) toResolve;
788 } else if (toResolve instanceof UnqualifiedQName) {
789 return ((UnqualifiedQName) toResolve).bindTo(localNamespace);
791 throw new IllegalStateException("Unhandled step " + toResolve);
796 static int normalizeXPath(final List<String> xpath) {
797 LOG.trace("Normalize {}", xpath);
799 // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
802 // Next up: count leading ".." components
803 int leadingParents = 0;
805 if (leadingParents == xpath.size()) {
806 return leadingParents;
808 if (!"..".equals(xpath.get(leadingParents))) {
815 // Now let's see if there there is a '..' in the rest
816 final int dots = findDots(xpath, leadingParents + 1);
818 return leadingParents;
821 xpath.remove(dots - 1);
822 xpath.remove(dots - 1);
823 LOG.trace("Next iteration {}", xpath);
827 private static int findDots(final List<String> xpath, final int startIndex) {
828 for (int i = startIndex; i < xpath.size(); ++i) {
829 if ("..".equals(xpath.get(i))) {
837 private static List<String> doSplitXPath(final String xpath) {
838 final List<String> ret = new ArrayList<>();
839 for (String str : SLASH_SPLITTER.split(xpath)) {
846 * Extracts the base type of node on which schema node points to. If target node is again of type
847 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
849 * @param typeDefinition
850 * type of node which will be extracted
851 * @param schemaContext
855 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
856 * is there to preserve backwards compatibility)
858 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
859 final SchemaContext schemaContext, final SchemaNode schema) {
860 final PathExpression pathStatement = typeDefinition.getPathStatement();
861 final String pathStr = stripConditionsFromXPathString(pathStatement);
863 final DataSchemaNode dataSchemaNode;
864 if (pathStatement.isAbsolute()) {
865 SchemaNode baseSchema = schema;
866 while (baseSchema instanceof DerivableSchemaNode) {
867 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
868 if (basePotential.isPresent()) {
869 baseSchema = basePotential.get();
875 final Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
876 dataSchemaNode = (DataSchemaNode) findTargetNode(schemaContext,
877 xpathToQNamePath(schemaContext, parentModule, pathStr));
879 Module parentModule = findParentModule(schemaContext, schema);
880 dataSchemaNode = (DataSchemaNode) resolveRelativeXPath(schemaContext, parentModule, pathStr, schema);
883 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
884 // and current expected behaviour for such cases is to just use pure string
885 // This should throw an exception about incorrect XPath in leafref
886 if (dataSchemaNode == null) {
890 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
892 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
893 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
896 return targetTypeDefinition;
900 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
901 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
902 * module as typedef which is then imported to referenced module.
905 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
907 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
908 final SchemaContext schemaContext, final QName qname) {
909 final PathExpression pathStatement = typeDefinition.getPathStatement();
910 if (!pathStatement.isAbsolute()) {
914 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
915 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
917 final DataSchemaNode dataSchemaNode = (DataSchemaNode) findTargetNode(schemaContext,
918 xpathToQNamePath(schemaContext, parentModule.get(), stripConditionsFromXPathString(pathStatement)));
919 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
920 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
921 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
924 return targetTypeDefinition;
927 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
928 final SchemaNode schemaNode) {
929 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
930 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
932 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
933 if (nodeType.getBaseType() != null) {
934 while (nodeType.getBaseType() != null) {
935 nodeType = nodeType.getBaseType();
938 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
941 return findParentModule(schemaContext, schemaNode);
944 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
947 * Removes conditions from xPath pointed to target node.
949 * @param pathStatement
950 * xPath to target node
951 * @return string representation of xPath without conditions
954 static String stripConditionsFromXPathString(final PathExpression pathStatement) {
955 return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
959 * Gets the base type of DataSchemaNode value.
962 * a node representing DataSchemaNode
963 * @return concrete type definition of node value
965 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
966 checkArgument(node instanceof TypedDataSchemaNode, "Unhandled parameter type %s", node);
968 TypeDefinition<?> current = ((TypedDataSchemaNode) node).getType();
969 // TODO: don't we have a utility for this?
970 TypeDefinition<?> base = current.getBaseType();
971 while (base != null) {
973 base = current.getBaseType();