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 java.util.ArrayDeque;
19 import java.util.ArrayList;
20 import java.util.Arrays;
21 import java.util.Deque;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.List;
25 import java.util.Optional;
27 import java.util.regex.Pattern;
28 import java.util.stream.Collectors;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.yangtools.yang.common.AbstractQName;
32 import org.opendaylight.yangtools.yang.common.QName;
33 import org.opendaylight.yangtools.yang.common.QNameModule;
34 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
35 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
36 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
40 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
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.ResolvedQNameStep;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
69 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.UnresolvedQNameStep;
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();
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
167 * @deprecated Use {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, YangLocationPath)} or
168 * {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, PathExpression)} instead.
170 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
171 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
174 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
175 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
176 // via a derived SchemaContext (i.e. this class would have to have a
178 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
180 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
181 // that feels like an overkill.
183 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
184 final PathExpression nonCondXPath) {
185 requireNonNull(context, "context");
186 requireNonNull(module, "module");
188 final String strXPath = nonCondXPath.getOriginalString();
189 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
190 if (nonCondXPath.isAbsolute()) {
191 return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
197 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
198 final YangLocationPath absPath) {
199 checkArgument(absPath.isAbsolute(), "Unsupported relative path %s", absPath);
200 return findTargetNode(ctx, localModule, absPath);
204 public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
205 final PathExpression absPath) {
206 final Steps pathSteps = absPath.getSteps();
207 if (pathSteps instanceof LocationPathSteps) {
208 return findDataTreeSchemaNode(ctx, localModule, ((LocationPathSteps) pathSteps).getLocationPath());
211 // We would need a reference schema node and no, we do not want to use SchemaContext in its SchemaNode capacity
212 checkArgument(!(pathSteps instanceof DerefSteps), "No reference node for steps %s", pathSteps);
214 // We are missing proper API alignment, if this ever triggers
215 throw new IllegalStateException("Unsupported path " + pathSteps);
219 * Method attempts to find DataSchemaNode inside of provided Schema Context
220 * and Yang Module accordingly to Non-conditional relative Revision Aware
221 * XPath. The specified Module MUST be present in Schema Context otherwise
222 * the operation would fail and return <code>null</code>. <br>
223 * The relative Revision Aware XPath MUST be specified WITHOUT the
224 * conditional statement (i.e. without [cond]) in path, because in this
225 * state the Schema Context is completely unaware of data state and will be
226 * not able to properly resolve XPath. If the XPath contains condition the
227 * method will return IllegalArgumentException. <br>
228 * The Actual Schema Node MUST be specified correctly because from this
229 * Schema Node will search starts. If the Actual Schema Node is not correct
230 * the operation will simply fail, because it will be unable to find desired
231 * DataSchemaNode. <br>
232 * If the Revision Aware XPath doesn't have flag
233 * <code>isAbsolute == false</code> the method will throw
234 * IllegalArgumentException. <br>
235 * If the relative Revision Aware XPath is correct and desired Data Schema
236 * Node is present in Yang module or in depending module in Schema Context
237 * the method will return specified Data Schema Node, otherwise the
238 * operation will fail and method will return <code>null</code>.
244 * @param actualSchemaNode
246 * @param relativeXPath
247 * Relative Non Conditional Revision Aware XPath
248 * @return DataSchemaNode if is present in specified Schema Context for
249 * given relative Revision Aware XPath, otherwise will return
251 * @throws NullPointerException if any argument is null
253 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
254 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
257 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
258 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
259 // via a derived SchemaContext (i.e. this class would have to have a
261 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
263 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
264 // that feels like an overkill.
265 // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
266 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
267 final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
268 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
269 + "for non relative Revision Aware XPath use findDataSchemaNode method");
270 return resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
274 * Returns parent Yang Module for specified Schema Context in which Schema
275 * Node is declared. If the Schema Node is not present in Schema Context the
276 * operation will return <code>null</code>.
278 * @param context Schema Context
279 * @param schemaNode Schema Node
280 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
281 * return <code>null</code>
282 * @throws NullPointerException if any of the arguments is null
284 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
285 final QName qname = schemaNode.getPath().getLastComponent();
286 checkState(qname != null, "Schema Path contains invalid state of path parts. "
287 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
288 return context.findModule(qname.getModule()).orElse(null);
291 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
292 final QName current = path.iterator().next();
294 LOG.trace("Looking up module {} in context {}", current, path);
295 final Optional<Module> module = context.findModule(current.getModule());
296 if (module.isEmpty()) {
297 LOG.debug("Module {} not found", current);
301 return findNodeInModule(module.get(), path);
305 * Returns NotificationDefinition from Schema Context.
307 * @param schema SchemaContext in which lookup should be performed.
308 * @param path Schema Path of notification
309 * @return Notification schema or null, if notification is not present in schema context.
312 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
313 final @NonNull SchemaPath path) {
314 requireNonNull(schema, "Schema context must not be null.");
315 requireNonNull(path, "Schema path must not be null.");
316 for (final NotificationDefinition potential : schema.getNotifications()) {
317 if (path.equals(potential.getPath())) {
325 * Returns RPC Input or Output Data container from RPC definition.
327 * @param schema SchemaContext in which lookup should be performed.
328 * @param path Schema path of RPC input/output data container
329 * @return Notification schema or null, if notification is not present in schema context.
332 public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
333 final @NonNull SchemaPath path) {
334 requireNonNull(schema, "Schema context must not be null.");
335 requireNonNull(path, "Schema path must not be null.");
336 final Iterator<QName> it = path.getPathFromRoot().iterator();
337 checkArgument(it.hasNext(), "Rpc must have QName.");
338 final QName rpcName = it.next();
339 checkArgument(it.hasNext(), "input or output must be part of path.");
340 final QName inOrOut = it.next();
341 for (final RpcDefinition potential : schema.getOperations()) {
342 if (rpcName.equals(potential.getQName())) {
343 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
350 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
352 * @param context SchemaContext to be examined
353 * @return Set of ModuleIdentifiers.
355 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
356 final Set<SourceIdentifier> ret = new HashSet<>();
358 for (Module module : context.getModules()) {
359 ret.add(moduleToIdentifier(module));
361 for (Module submodule : module.getSubmodules()) {
362 ret.add(moduleToIdentifier(submodule));
369 private static SourceIdentifier moduleToIdentifier(final Module module) {
370 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
373 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
374 if (!path.iterator().hasNext()) {
375 LOG.debug("No node matching {} found in node {}", path, module);
379 final QName current = path.iterator().next();
380 LOG.trace("Looking for node {} in module {}", current, module);
382 SchemaNode foundNode = null;
383 final Iterable<QName> nextPath = nextLevel(path);
385 foundNode = module.getDataChildByName(current);
386 if (foundNode != null && nextPath.iterator().hasNext()) {
387 foundNode = findNodeIn(foundNode, nextPath);
390 if (foundNode == null) {
391 foundNode = getGroupingByName(module, current);
392 if (foundNode != null && nextPath.iterator().hasNext()) {
393 foundNode = findNodeIn(foundNode, nextPath);
397 if (foundNode == null) {
398 foundNode = getRpcByName(module, current);
399 if (foundNode != null && nextPath.iterator().hasNext()) {
400 foundNode = findNodeIn(foundNode, nextPath);
404 if (foundNode == null) {
405 foundNode = getNotificationByName(module, current);
406 if (foundNode != null && nextPath.iterator().hasNext()) {
407 foundNode = findNodeIn(foundNode, nextPath);
411 if (foundNode == null) {
412 LOG.debug("No node matching {} found in node {}", path, module);
418 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
419 if (!path.iterator().hasNext()) {
420 LOG.debug("No node matching {} found in node {}", path, parent);
424 final QName current = path.iterator().next();
425 LOG.trace("Looking for node {} in node {}", current, parent);
427 SchemaNode foundNode = null;
428 final Iterable<QName> nextPath = nextLevel(path);
430 if (parent instanceof DataNodeContainer) {
431 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
433 foundNode = parentDataNodeContainer.getDataChildByName(current);
434 if (foundNode != null && nextPath.iterator().hasNext()) {
435 foundNode = findNodeIn(foundNode, nextPath);
438 if (foundNode == null) {
439 foundNode = getGroupingByName(parentDataNodeContainer, current);
440 if (foundNode != null && nextPath.iterator().hasNext()) {
441 foundNode = findNodeIn(foundNode, nextPath);
446 if (foundNode == null && parent instanceof ActionNodeContainer) {
447 foundNode = ((ActionNodeContainer) parent).getActions().stream()
448 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
449 if (foundNode != null && nextPath.iterator().hasNext()) {
450 foundNode = findNodeIn(foundNode, nextPath);
454 if (foundNode == null && parent instanceof NotificationNodeContainer) {
455 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
456 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
457 if (foundNode != null && nextPath.iterator().hasNext()) {
458 foundNode = findNodeIn(foundNode, nextPath);
462 if (foundNode == null && parent instanceof OperationDefinition) {
463 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
465 if (current.getLocalName().equals("input")) {
466 foundNode = parentRpcDefinition.getInput();
467 if (foundNode != null && nextPath.iterator().hasNext()) {
468 foundNode = findNodeIn(foundNode, nextPath);
472 if (current.getLocalName().equals("output")) {
473 foundNode = parentRpcDefinition.getOutput();
474 if (foundNode != null && nextPath.iterator().hasNext()) {
475 foundNode = findNodeIn(foundNode, nextPath);
479 if (foundNode == null) {
480 foundNode = getGroupingByName(parentRpcDefinition, current);
481 if (foundNode != null && nextPath.iterator().hasNext()) {
482 foundNode = findNodeIn(foundNode, nextPath);
487 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
488 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
490 if (foundNode != null && nextPath.iterator().hasNext()) {
491 foundNode = findNodeIn(foundNode, nextPath);
494 if (foundNode == null) {
495 // fallback that tries to map into one of the child cases
496 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
497 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
498 if (maybeChild != null) {
499 foundNode = findNodeIn(maybeChild, nextPath);
506 if (foundNode == null) {
507 LOG.debug("No node matching {} found in node {}", path, parent);
514 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
515 return Iterables.skip(path, 1);
518 private static RpcDefinition getRpcByName(final Module module, final QName name) {
519 for (final RpcDefinition rpc : module.getRpcs()) {
520 if (rpc.getQName().equals(name)) {
527 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
528 for (final NotificationDefinition notification : module.getNotifications()) {
529 if (notification.getQName().equals(name)) {
536 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
537 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
538 if (grouping.getQName().equals(name)) {
545 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
546 for (final GroupingDefinition grouping : rpc.getGroupings()) {
547 if (grouping.getQName().equals(name)) {
555 * Transforms string representation of XPath to Queue of QNames. The XPath
556 * is split by "/" and for each part of XPath is assigned correct module in
558 * If Schema Context, Parent Module or XPath string contains
559 * <code>null</code> values, the method will throws IllegalArgumentException
563 * @param parentModule
567 * @return return a list of QName
569 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
570 final String xpath) {
571 final List<QName> path = new ArrayList<>();
572 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
573 path.add(stringPathPartToQName(context, parentModule, pathComponent));
579 * Transforms part of Prefixed Path as java String to QName. <br>
580 * If the string contains module prefix separated by ":" (i.e.
581 * mod:container) this module is provided from from Parent Module list of
582 * imports. If the Prefixed module is present in Schema Context the QName
583 * can be constructed. <br>
584 * If the Prefixed Path Part does not contains prefix the Parent's Module
585 * namespace is taken for construction of QName. <br>
587 * @param context Schema Context
588 * @param parentModule Parent Module
589 * @param prefixedPathPart Prefixed Path Part string
590 * @return QName from prefixed Path Part String.
591 * @throws NullPointerException if any arguments are null
593 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
594 final String prefixedPathPart) {
595 requireNonNull(context, "context");
597 if (prefixedPathPart.indexOf(':') != -1) {
598 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
599 final String modulePrefix = prefixedName.next();
601 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
602 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
603 modulePrefix, parentModule.getName());
605 return QName.create(module.getQNameModule(), prefixedName.next());
608 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
612 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
613 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
614 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
615 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
617 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
619 * @param context Schema Context
620 * @param module Yang Module
621 * @param prefix Module Prefix
622 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
623 * @throws NullPointerException if any arguments are null
625 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
626 final String prefix) {
627 requireNonNull(context, "context");
629 if (prefix.equals(module.getPrefix())) {
633 final Set<ModuleImport> imports = module.getImports();
634 for (final ModuleImport mi : imports) {
635 if (prefix.equals(mi.getPrefix())) {
636 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
643 * Resolve a relative XPath into a set of QNames.
649 * @param relativeXPath
650 * Non conditional Revision Aware Relative XPath
651 * @param actualSchemaNode
653 * @return target schema node
654 * @throws IllegalArgumentException if any arguments are null
656 private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
657 final PathExpression relativeXPath, final SchemaNode actualSchemaNode) {
658 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
659 + "for non relative Revision Aware XPath use findDataSchemaNode method");
660 checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
662 final String orig = relativeXPath.getOriginalString();
663 return orig.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, orig)
664 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode, doSplitXPath(orig)));
667 private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
668 final SchemaNode actualSchemaNode, final List<String> steps) {
669 // Find out how many "parent" components there are and trim them
670 final int colCount = normalizeXPath(steps);
671 final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
673 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
674 if (Iterables.size(schemaNodePath) - colCount >= 0) {
675 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
676 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
678 return Iterables.concat(schemaNodePath,
679 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
682 private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
683 final SchemaNode actualSchemaNode, final String xpath) {
684 final int paren = xpath.indexOf(')', 6);
685 checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
687 final String derefArg = xpath.substring(6, paren).strip();
688 // Look up the node which we need to reference
689 final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
690 doSplitXPath(derefArg)));
691 checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
693 checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
696 // We have a deref() target, decide what to do about it
697 final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
698 if (targetType instanceof InstanceIdentifierTypeDefinition) {
699 // Static inference breaks down, we cannot determine where this points to
700 // FIXME: dedicated exception, users can recover from it, derive from IAE
701 throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
704 // deref() is define only for instance-identifier and leafref types, handle the latter
705 checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
707 final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
708 LOG.debug("Derefencing path {}", targetPath);
710 final SchemaNode deref = targetPath.isAbsolute()
711 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
712 ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
713 : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
715 LOG.debug("Path {} could not be derefenced", targetPath);
719 checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
721 final List<String> qnames = doSplitXPath(xpath.substring(paren + 1).stripLeading());
722 return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
725 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule defaultModule,
726 final YangLocationPath path) {
727 final Deque<QName> ret = new ArrayDeque<>();
728 for (Step step : path.getSteps()) {
729 if (step instanceof AxisStep) {
730 // We only support parent axis steps
731 final YangXPathAxis axis = ((AxisStep) step).getAxis();
732 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
737 // This has to be a QNameStep
738 checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
740 if (step instanceof ResolvedQNameStep) {
741 qname = ((ResolvedQNameStep) step).getQName();
742 } else if (step instanceof UnresolvedQNameStep) {
743 final AbstractQName toResolve = ((UnresolvedQNameStep) step).getQName();
744 // TODO: should handle qualified QNames, too? parser should have resolved them when we get here...
745 checkState(toResolve instanceof UnqualifiedQName, "Unhandled qname %s in %s", toResolve, path);
746 qname = QName.create(defaultModule, toResolve.getLocalName());
748 throw new IllegalStateException("Unhandled step " + step);
754 return findTargetNode(context, ret);
757 private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
758 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
759 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
760 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
761 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
765 static int normalizeXPath(final List<String> xpath) {
766 LOG.trace("Normalize {}", xpath);
768 // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
771 // Next up: count leading ".." components
772 int leadingParents = 0;
774 if (leadingParents == xpath.size()) {
775 return leadingParents;
777 if (!"..".equals(xpath.get(leadingParents))) {
784 // Now let's see if there there is a '..' in the rest
785 final int dots = findDots(xpath, leadingParents + 1);
787 return leadingParents;
790 xpath.remove(dots - 1);
791 xpath.remove(dots - 1);
792 LOG.trace("Next iteration {}", xpath);
796 private static int findDots(final List<String> xpath, final int startIndex) {
797 for (int i = startIndex; i < xpath.size(); ++i) {
798 if ("..".equals(xpath.get(i))) {
806 private static List<String> doSplitXPath(final String xpath) {
807 return SLASH_SPLITTER.splitToList(xpath);
811 * Extracts the base type of node on which schema node points to. If target node is again of type
812 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
814 * @param typeDefinition
815 * type of node which will be extracted
816 * @param schemaContext
820 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
821 * is there to preserve backwards compatibility)
823 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
824 final SchemaContext schemaContext, final SchemaNode schema) {
825 PathExpression pathStatement = typeDefinition.getPathStatement();
826 pathStatement = new PathExpressionImpl(stripConditionsFromXPathString(pathStatement),
827 pathStatement.isAbsolute());
829 final DataSchemaNode dataSchemaNode;
830 if (pathStatement.isAbsolute()) {
831 SchemaNode baseSchema = schema;
832 while (baseSchema instanceof DerivableSchemaNode) {
833 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
834 if (basePotential.isPresent()) {
835 baseSchema = basePotential.get();
841 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
842 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
845 Module parentModule = findParentModule(schemaContext, schema);
846 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
847 parentModule, schema, pathStatement);
850 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
851 // and current expected behaviour for such cases is to just use pure string
852 // This should throw an exception about incorrect XPath in leafref
853 if (dataSchemaNode == null) {
857 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
859 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
860 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
863 return targetTypeDefinition;
867 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
868 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
869 * module as typedef which is then imported to referenced module.
872 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
874 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
875 final SchemaContext schemaContext, final QName qname) {
876 final PathExpression pathStatement = typeDefinition.getPathStatement();
877 final PathExpression strippedPathStatement = new PathExpressionImpl(
878 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
879 if (!strippedPathStatement.isAbsolute()) {
883 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
884 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
886 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
887 parentModule.get(), strippedPathStatement);
888 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
889 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
890 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
893 return targetTypeDefinition;
896 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
897 final SchemaNode schemaNode) {
898 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
899 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
901 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
902 if (nodeType.getBaseType() != null) {
903 while (nodeType.getBaseType() != null) {
904 nodeType = nodeType.getBaseType();
907 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
910 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
913 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
916 * Removes conditions from xPath pointed to target node.
918 * @param pathStatement
919 * xPath to target node
920 * @return string representation of xPath without conditions
923 static String stripConditionsFromXPathString(final PathExpression pathStatement) {
924 return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
928 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
931 * a node representing LeafSchemaNode
932 * @return concrete type definition of node value
934 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
935 TypeDefinition<?> baseType = node.getType();
936 while (baseType.getBaseType() != null) {
937 baseType = baseType.getBaseType();
943 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
946 * a node representing LeafListSchemaNode
947 * @return concrete type definition of node value
949 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
950 TypeDefinition<?> baseType = node.getType();
951 while (baseType.getBaseType() != null) {
952 baseType = baseType.getBaseType();
958 * Gets the base type of DataSchemaNode value.
961 * a node representing DataSchemaNode
962 * @return concrete type definition of node value
964 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
965 if (node instanceof LeafListSchemaNode) {
966 return typeDefinition((LeafListSchemaNode) node);
967 } else if (node instanceof LeafSchemaNode) {
968 return typeDefinition((LeafSchemaNode) node);
970 throw new IllegalArgumentException("Unhandled parameter type: " + node);