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.LocationPathSteps;
53 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
63 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
64 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.ResolvedQNameStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.UnresolvedQNameStep;
69 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
74 * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
75 * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
78 public final class SchemaContextUtil {
79 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
80 private static final Splitter COLON_SPLITTER = Splitter.on(':');
81 private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
82 private static final CharMatcher SPACE = CharMatcher.is(' ');
84 private SchemaContextUtil() {
89 * Method attempts to find DataSchemaNode in Schema Context via specified Schema Path. The returned DataSchemaNode
90 * from method will be the node at the end of the SchemaPath. If the DataSchemaNode is not present in the Schema
91 * Context the method will return {@code null}.
94 * In case that Schema Context or Schema Path are not specified correctly (i.e. contains {@code null} values) the
95 * method will throw IllegalArgumentException.
97 * @param context Schema Context
98 * @param schemaPath Schema Path to search for
99 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
100 * @throws NullPointerException if context or schemaPath is null
102 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
103 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
104 if (prefixedPath == null) {
105 LOG.debug("Schema path {} has null path", schemaPath);
109 LOG.trace("Looking for path {} in context {}", schemaPath, context);
110 return findNodeInSchemaContext(context, prefixedPath);
114 * Attempt to find a DataSchemaNode based on its path from root, similar to
115 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
117 * @param context Schema Context
118 * @param path Path to search for
119 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
120 * @throws NullPointerException if a any argument is null or if the path contains a null element
123 public static SchemaNode findDataSchemaNode(final SchemaContext context, final List<QName> path) {
124 return findTargetNode(context, null, YangLocationPath.absolute(
125 path.stream().map(YangXPathAxis.CHILD::asStep).collect(Collectors.toList())));
129 * Attempt to find a DataSchemaNode based on its path from root, similar to
130 * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
132 * @param context Schema Context
133 * @param path Path to search for
134 * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
135 * @throws NullPointerException if a any argument is null or if the path contains a null element
138 public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
139 return findDataSchemaNode(context, Arrays.asList(path));
143 * Method attempts to find DataSchemaNode inside of provided Schema Context
144 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
145 * specified Module MUST be present in Schema Context otherwise the
146 * operation would fail and return <code>null</code>. <br>
147 * The Revision Aware XPath MUST be specified WITHOUT the conditional
148 * statement (i.e. without [cond]) in path, because in this state the Schema
149 * Context is completely unaware of data state and will be not able to
150 * properly resolve XPath. If the XPath contains condition the method will
151 * return IllegalArgumentException. <br>
152 * If the Revision Aware XPath is correct and desired Data Schema Node is
153 * present in Yang module or in depending module in Schema Context the
154 * method will return specified Data Schema Node, otherwise the operation
155 * will fail and method will return <code>null</code>.
161 * @param nonCondXPath
162 * Non Conditional Revision Aware XPath
163 * @return Returns Data Schema Node for specified Schema Context for given
164 * Non-conditional Revision Aware XPath, or <code>null</code> if the
165 * DataSchemaNode is not present in Schema Context.
166 * @throws NullPointerException if any of the arguments is null
168 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
169 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
172 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
173 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
174 // via a derived SchemaContext (i.e. this class would have to have a
176 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
178 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
179 // that feels like an overkill.
180 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
181 final PathExpression nonCondXPath) {
182 requireNonNull(context, "context");
183 requireNonNull(module, "module");
185 final String strXPath = nonCondXPath.getOriginalString();
186 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
187 if (nonCondXPath.isAbsolute()) {
188 return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
194 * Method attempts to find DataSchemaNode inside of provided Schema Context
195 * and Yang Module accordingly to Non-conditional relative Revision Aware
196 * XPath. The specified Module MUST be present in Schema Context otherwise
197 * the operation would fail and return <code>null</code>. <br>
198 * The relative Revision Aware XPath MUST be specified WITHOUT the
199 * conditional statement (i.e. without [cond]) in path, because in this
200 * state the Schema Context is completely unaware of data state and will be
201 * not able to properly resolve XPath. If the XPath contains condition the
202 * method will return IllegalArgumentException. <br>
203 * The Actual Schema Node MUST be specified correctly because from this
204 * Schema Node will search starts. If the Actual Schema Node is not correct
205 * the operation will simply fail, because it will be unable to find desired
206 * DataSchemaNode. <br>
207 * If the Revision Aware XPath doesn't have flag
208 * <code>isAbsolute == false</code> the method will throw
209 * IllegalArgumentException. <br>
210 * If the relative Revision Aware XPath is correct and desired Data Schema
211 * Node is present in Yang module or in depending module in Schema Context
212 * the method will return specified Data Schema Node, otherwise the
213 * operation will fail and method will return <code>null</code>.
219 * @param actualSchemaNode
221 * @param relativeXPath
222 * Relative Non Conditional Revision Aware XPath
223 * @return DataSchemaNode if is present in specified Schema Context for
224 * given relative Revision Aware XPath, otherwise will return
226 * @throws NullPointerException if any argument is null
228 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
229 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
232 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
233 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
234 // via a derived SchemaContext (i.e. this class would have to have a
236 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
238 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
239 // that feels like an overkill.
240 // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
241 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
242 final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
243 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
244 + "for non relative Revision Aware XPath use findDataSchemaNode method");
245 return resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
249 * Returns parent Yang Module for specified Schema Context in which Schema
250 * Node is declared. If the Schema Node is not present in Schema Context the
251 * operation will return <code>null</code>.
253 * @param context Schema Context
254 * @param schemaNode Schema Node
255 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
256 * return <code>null</code>
257 * @throws NullPointerException if any of the arguments is null
259 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
260 final QName qname = schemaNode.getPath().getLastComponent();
261 checkState(qname != null, "Schema Path contains invalid state of path parts. "
262 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
263 return context.findModule(qname.getModule()).orElse(null);
266 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
267 final QName current = path.iterator().next();
269 LOG.trace("Looking up module {} in context {}", current, path);
270 final Optional<Module> module = context.findModule(current.getModule());
271 if (!module.isPresent()) {
272 LOG.debug("Module {} not found", current);
276 return findNodeInModule(module.get(), path);
280 * Returns NotificationDefinition from Schema Context.
282 * @param schema SchemaContext in which lookup should be performed.
283 * @param path Schema Path of notification
284 * @return Notification schema or null, if notification is not present in schema context.
287 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
288 final @NonNull SchemaPath path) {
289 requireNonNull(schema, "Schema context must not be null.");
290 requireNonNull(path, "Schema path must not be null.");
291 for (final NotificationDefinition potential : schema.getNotifications()) {
292 if (path.equals(potential.getPath())) {
300 * Returns RPC Input or Output Data container from RPC definition.
302 * @param schema SchemaContext in which lookup should be performed.
303 * @param path Schema path of RPC input/output data container
304 * @return Notification schema or null, if notification is not present in schema context.
307 public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
308 final @NonNull SchemaPath path) {
309 requireNonNull(schema, "Schema context must not be null.");
310 requireNonNull(path, "Schema path must not be null.");
311 final Iterator<QName> it = path.getPathFromRoot().iterator();
312 checkArgument(it.hasNext(), "Rpc must have QName.");
313 final QName rpcName = it.next();
314 checkArgument(it.hasNext(), "input or output must be part of path.");
315 final QName inOrOut = it.next();
316 for (final RpcDefinition potential : schema.getOperations()) {
317 if (rpcName.equals(potential.getQName())) {
318 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
325 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
327 * @param context SchemaContext to be examined
328 * @return Set of ModuleIdentifiers.
330 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
331 final Set<SourceIdentifier> ret = new HashSet<>();
333 for (Module module : context.getModules()) {
334 ret.add(moduleToIdentifier(module));
336 for (Module submodule : module.getSubmodules()) {
337 ret.add(moduleToIdentifier(submodule));
344 private static SourceIdentifier moduleToIdentifier(final Module module) {
345 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
348 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
349 if (!path.iterator().hasNext()) {
350 LOG.debug("No node matching {} found in node {}", path, module);
354 final QName current = path.iterator().next();
355 LOG.trace("Looking for node {} in module {}", current, module);
357 SchemaNode foundNode = null;
358 final Iterable<QName> nextPath = nextLevel(path);
360 foundNode = module.getDataChildByName(current);
361 if (foundNode != null && nextPath.iterator().hasNext()) {
362 foundNode = findNodeIn(foundNode, nextPath);
365 if (foundNode == null) {
366 foundNode = getGroupingByName(module, current);
367 if (foundNode != null && nextPath.iterator().hasNext()) {
368 foundNode = findNodeIn(foundNode, nextPath);
372 if (foundNode == null) {
373 foundNode = getRpcByName(module, current);
374 if (foundNode != null && nextPath.iterator().hasNext()) {
375 foundNode = findNodeIn(foundNode, nextPath);
379 if (foundNode == null) {
380 foundNode = getNotificationByName(module, current);
381 if (foundNode != null && nextPath.iterator().hasNext()) {
382 foundNode = findNodeIn(foundNode, nextPath);
386 if (foundNode == null) {
387 LOG.debug("No node matching {} found in node {}", path, module);
393 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
394 if (!path.iterator().hasNext()) {
395 LOG.debug("No node matching {} found in node {}", path, parent);
399 final QName current = path.iterator().next();
400 LOG.trace("Looking for node {} in node {}", current, parent);
402 SchemaNode foundNode = null;
403 final Iterable<QName> nextPath = nextLevel(path);
405 if (parent instanceof DataNodeContainer) {
406 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
408 foundNode = parentDataNodeContainer.getDataChildByName(current);
409 if (foundNode != null && nextPath.iterator().hasNext()) {
410 foundNode = findNodeIn(foundNode, nextPath);
413 if (foundNode == null) {
414 foundNode = getGroupingByName(parentDataNodeContainer, current);
415 if (foundNode != null && nextPath.iterator().hasNext()) {
416 foundNode = findNodeIn(foundNode, nextPath);
421 if (foundNode == null && parent instanceof ActionNodeContainer) {
422 foundNode = ((ActionNodeContainer) parent).getActions().stream()
423 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
424 if (foundNode != null && nextPath.iterator().hasNext()) {
425 foundNode = findNodeIn(foundNode, nextPath);
429 if (foundNode == null && parent instanceof NotificationNodeContainer) {
430 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
431 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
432 if (foundNode != null && nextPath.iterator().hasNext()) {
433 foundNode = findNodeIn(foundNode, nextPath);
437 if (foundNode == null && parent instanceof OperationDefinition) {
438 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
440 if (current.getLocalName().equals("input")) {
441 foundNode = parentRpcDefinition.getInput();
442 if (foundNode != null && nextPath.iterator().hasNext()) {
443 foundNode = findNodeIn(foundNode, nextPath);
447 if (current.getLocalName().equals("output")) {
448 foundNode = parentRpcDefinition.getOutput();
449 if (foundNode != null && nextPath.iterator().hasNext()) {
450 foundNode = findNodeIn(foundNode, nextPath);
454 if (foundNode == null) {
455 foundNode = getGroupingByName(parentRpcDefinition, current);
456 if (foundNode != null && nextPath.iterator().hasNext()) {
457 foundNode = findNodeIn(foundNode, nextPath);
462 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
463 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
465 if (foundNode != null && nextPath.iterator().hasNext()) {
466 foundNode = findNodeIn(foundNode, nextPath);
469 if (foundNode == null) {
470 // fallback that tries to map into one of the child cases
471 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
472 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
473 if (maybeChild != null) {
474 foundNode = findNodeIn(maybeChild, nextPath);
481 if (foundNode == null) {
482 LOG.debug("No node matching {} found in node {}", path, parent);
489 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
490 return Iterables.skip(path, 1);
493 private static RpcDefinition getRpcByName(final Module module, final QName name) {
494 for (final RpcDefinition rpc : module.getRpcs()) {
495 if (rpc.getQName().equals(name)) {
502 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
503 for (final NotificationDefinition notification : module.getNotifications()) {
504 if (notification.getQName().equals(name)) {
511 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
512 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
513 if (grouping.getQName().equals(name)) {
520 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
521 for (final GroupingDefinition grouping : rpc.getGroupings()) {
522 if (grouping.getQName().equals(name)) {
530 * Transforms string representation of XPath to Queue of QNames. The XPath
531 * is split by "/" and for each part of XPath is assigned correct module in
533 * If Schema Context, Parent Module or XPath string contains
534 * <code>null</code> values, the method will throws IllegalArgumentException
538 * @param parentModule
542 * @return return a list of QName
544 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
545 final String xpath) {
546 final List<QName> path = new ArrayList<>();
547 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
548 path.add(stringPathPartToQName(context, parentModule, pathComponent));
554 * Transforms part of Prefixed Path as java String to QName. <br>
555 * If the string contains module prefix separated by ":" (i.e.
556 * mod:container) this module is provided from from Parent Module list of
557 * imports. If the Prefixed module is present in Schema Context the QName
558 * can be constructed. <br>
559 * If the Prefixed Path Part does not contains prefix the Parent's Module
560 * namespace is taken for construction of QName. <br>
562 * @param context Schema Context
563 * @param parentModule Parent Module
564 * @param prefixedPathPart Prefixed Path Part string
565 * @return QName from prefixed Path Part String.
566 * @throws NullPointerException if any arguments are null
568 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
569 final String prefixedPathPart) {
570 requireNonNull(context, "context");
572 if (prefixedPathPart.indexOf(':') != -1) {
573 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
574 final String modulePrefix = prefixedName.next();
576 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
577 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
578 modulePrefix, parentModule.getName());
580 return QName.create(module.getQNameModule(), prefixedName.next());
583 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
587 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
588 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
589 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
590 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
592 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
594 * @param context Schema Context
595 * @param module Yang Module
596 * @param prefix Module Prefix
597 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
598 * @throws NullPointerException if any arguments are null
600 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
601 final String prefix) {
602 requireNonNull(context, "context");
604 if (prefix.equals(module.getPrefix())) {
608 final Set<ModuleImport> imports = module.getImports();
609 for (final ModuleImport mi : imports) {
610 if (prefix.equals(mi.getPrefix())) {
611 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
618 * Resolve a relative XPath into a set of QNames.
624 * @param relativeXPath
625 * Non conditional Revision Aware Relative XPath
626 * @param actualSchemaNode
628 * @return target schema node
629 * @throws IllegalArgumentException if any arguments are null
631 private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
632 final PathExpression relativeXPath, final SchemaNode actualSchemaNode) {
633 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
634 + "for non relative Revision Aware XPath use findDataSchemaNode method");
635 checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
637 final String orig = relativeXPath.getOriginalString();
638 return orig.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, orig)
639 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode, doSplitXPath(orig)));
642 private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
643 final SchemaNode actualSchemaNode, final List<String> steps) {
644 // Find out how many "parent" components there are and trim them
645 final int colCount = normalizeXPath(steps);
646 final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
648 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
649 if (Iterables.size(schemaNodePath) - colCount >= 0) {
650 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
651 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
653 return Iterables.concat(schemaNodePath,
654 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
657 private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
658 final SchemaNode actualSchemaNode, final String xpath) {
659 final int paren = xpath.indexOf(')', 6);
660 checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
662 final String derefArg = SPACE.trimFrom(xpath.substring(6, paren));
663 // Look up the node which we need to reference
664 final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
665 doSplitXPath(derefArg)));
666 checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
668 checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
671 // We have a deref() target, decide what to do about it
672 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
673 if (targetType instanceof InstanceIdentifierTypeDefinition) {
674 // Static inference breaks down, we cannot determine where this points to
675 // FIXME: dedicated exception, users can recover from it, derive from IAE
676 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
679 // deref() is define only for instance-identifier and leafref types, handle the latter
680 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
682 final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
683 LOG.debug("Derefencing path {}", targetPath);
685 final SchemaNode deref = targetPath.isAbsolute()
686 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
687 ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
688 : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
690 LOG.debug("Path {} could not be derefenced", targetPath);
694 checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
696 final List<String> qnames = doSplitXPath(SPACE.trimLeadingFrom(xpath.substring(paren + 1)));
697 return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
700 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule defaultModule,
701 final YangLocationPath path) {
702 final Deque<QName> ret = new ArrayDeque<>();
703 for (Step step : path.getSteps()) {
704 if (step instanceof AxisStep) {
705 // We only support parent axis steps
706 final YangXPathAxis axis = ((AxisStep) step).getAxis();
707 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
712 // This has to be a QNameStep
713 checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
715 if (step instanceof ResolvedQNameStep) {
716 qname = ((ResolvedQNameStep) step).getQName();
717 } else if (step instanceof UnresolvedQNameStep) {
718 final AbstractQName toResolve = ((UnresolvedQNameStep) step).getQName();
719 // TODO: should handle qualified QNames, too? parser should have resolved them when we get here...
720 checkState(toResolve instanceof UnqualifiedQName, "Unhandled qname %s in %s", toResolve, path);
721 qname = QName.create(defaultModule, toResolve.getLocalName());
723 throw new IllegalStateException("Unhandled step " + step);
729 return findTargetNode(context, ret);
732 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
733 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
734 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
735 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
736 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
740 static int normalizeXPath(final List<String> xpath) {
741 LOG.trace("Normalize {}", xpath);
743 // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
746 // Next up: count leading ".." components
747 int leadingParents = 0;
749 if (leadingParents == xpath.size()) {
750 return leadingParents;
752 if (!"..".equals(xpath.get(leadingParents))) {
759 // Now let's see if there there is a '..' in the rest
760 final int dots = findDots(xpath, leadingParents + 1);
762 return leadingParents;
765 xpath.remove(dots - 1);
766 xpath.remove(dots - 1);
767 LOG.trace("Next iteration {}", xpath);
771 private static int findDots(final List<String> xpath, final int startIndex) {
772 for (int i = startIndex; i < xpath.size(); ++i) {
773 if ("..".equals(xpath.get(i))) {
781 private static List<String> doSplitXPath(final String xpath) {
782 return SLASH_SPLITTER.splitToList(xpath);
786 * Extracts the base type of node on which schema node points to. If target node is again of type
787 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
789 * @param typeDefinition
790 * type of node which will be extracted
791 * @param schemaContext
795 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
796 * is there to preserve backwards compatibility)
798 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
799 final SchemaContext schemaContext, final SchemaNode schema) {
800 PathExpression pathStatement = typeDefinition.getPathStatement();
801 pathStatement = new PathExpressionImpl(stripConditionsFromXPathString(pathStatement),
802 pathStatement.isAbsolute());
804 final DataSchemaNode dataSchemaNode;
805 if (pathStatement.isAbsolute()) {
806 SchemaNode baseSchema = schema;
807 while (baseSchema instanceof DerivableSchemaNode) {
808 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
809 if (basePotential.isPresent()) {
810 baseSchema = basePotential.get();
816 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
817 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
820 Module parentModule = findParentModule(schemaContext, schema);
821 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
822 parentModule, schema, pathStatement);
825 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
826 // and current expected behaviour for such cases is to just use pure string
827 // This should throw an exception about incorrect XPath in leafref
828 if (dataSchemaNode == null) {
832 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
834 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
835 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
838 return targetTypeDefinition;
842 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
843 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
844 * module as typedef which is then imported to referenced module.
847 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
849 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
850 final SchemaContext schemaContext, final QName qname) {
851 final PathExpression pathStatement = typeDefinition.getPathStatement();
852 final PathExpression strippedPathStatement = new PathExpressionImpl(
853 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
854 if (!strippedPathStatement.isAbsolute()) {
858 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
859 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
861 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
862 parentModule.get(), strippedPathStatement);
863 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
864 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
865 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
868 return targetTypeDefinition;
871 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
872 final SchemaNode schemaNode) {
873 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
874 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
876 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
877 if (nodeType.getBaseType() != null) {
878 while (nodeType.getBaseType() != null) {
879 nodeType = nodeType.getBaseType();
882 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
885 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
888 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
891 * Removes conditions from xPath pointed to target node.
893 * @param pathStatement
894 * xPath to target node
895 * @return string representation of xPath without conditions
898 static String stripConditionsFromXPathString(final PathExpression pathStatement) {
899 return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
903 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
906 * a node representing LeafSchemaNode
907 * @return concrete type definition of node value
909 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
910 TypeDefinition<?> baseType = node.getType();
911 while (baseType.getBaseType() != null) {
912 baseType = baseType.getBaseType();
918 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
921 * a node representing LeafListSchemaNode
922 * @return concrete type definition of node value
924 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
925 TypeDefinition<?> baseType = node.getType();
926 while (baseType.getBaseType() != null) {
927 baseType = baseType.getBaseType();
933 * Gets the base type of DataSchemaNode value.
936 * a node representing DataSchemaNode
937 * @return concrete type definition of node value
939 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
940 if (node instanceof LeafListSchemaNode) {
941 return typeDefinition((LeafListSchemaNode) node);
942 } else if (node instanceof LeafSchemaNode) {
943 return typeDefinition((LeafSchemaNode) node);
945 throw new IllegalArgumentException("Unhandled parameter type: " + node);