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.HashSet;
19 import java.util.Iterator;
20 import java.util.LinkedList;
21 import java.util.List;
22 import java.util.Optional;
24 import java.util.regex.Pattern;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
40 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
41 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
43 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
44 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
52 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
57 * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
58 * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
61 public final class SchemaContextUtil {
62 private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
63 private static final Splitter COLON_SPLITTER = Splitter.on(':');
64 private static final Splitter SLASH_SPLITTER = Splitter.on('/');
66 private SchemaContextUtil() {
70 * Method attempts to find DataSchemaNode in Schema Context via specified
71 * Schema Path. The returned DataSchemaNode from method will be the node at
72 * the end of the SchemaPath. If the DataSchemaNode is not present in the
73 * Schema Context the method will return <code>null</code>. <br>
74 * In case that Schema Context or Schema Path are not specified correctly
75 * (i.e. contains <code>null</code> values) the method will throw
76 * IllegalArgumentException.
81 * Schema Path to search for
82 * @return SchemaNode from the end of the Schema Path or <code>null</code>
83 * if the Node is not present.
84 * @throws IllegalArgumentException if context or schemaPath is not correct.
86 public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
87 checkArgument(context != null, "Schema Context reference cannot be NULL");
88 checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
90 final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
91 if (prefixedPath == null) {
92 LOG.debug("Schema path {} has null path", schemaPath);
96 LOG.trace("Looking for path {} in context {}", schemaPath, context);
97 return findNodeInSchemaContext(context, prefixedPath);
101 * Method attempts to find DataSchemaNode inside of provided Schema Context
102 * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
103 * specified Module MUST be present in Schema Context otherwise the
104 * operation would fail and return <code>null</code>. <br>
105 * The Revision Aware XPath MUST be specified WITHOUT the conditional
106 * statement (i.e. without [cond]) in path, because in this state the Schema
107 * Context is completely unaware of data state and will be not able to
108 * properly resolve XPath. If the XPath contains condition the method will
109 * return IllegalArgumentException. <br>
110 * In case that Schema Context or Module or Revision Aware XPath contains
111 * <code>null</code> references the method will throw
112 * IllegalArgumentException <br>
113 * If the Revision Aware XPath is correct and desired Data Schema Node is
114 * present in Yang module or in depending module in Schema Context the
115 * method will return specified Data Schema Node, otherwise the operation
116 * will fail and method will return <code>null</code>.
122 * @param nonCondXPath
123 * Non Conditional Revision Aware XPath
124 * @return Returns Data Schema Node for specified Schema Context for given
125 * Non-conditional Revision Aware XPath, or <code>null</code> if the
126 * DataSchemaNode is not present in Schema Context.
128 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
129 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
132 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
133 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
134 // via a derived SchemaContext (i.e. this class would have to have a
136 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
138 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
139 // that feels like an overkill.
140 public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
141 final RevisionAwareXPath nonCondXPath) {
142 checkArgument(context != null, "Schema Context reference cannot be NULL");
143 checkArgument(module != null, "Module reference cannot be NULL");
144 checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
146 final String strXPath = nonCondXPath.toString();
147 if (strXPath != null) {
148 checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
149 if (nonCondXPath.isAbsolute()) {
150 final List<QName> path = xpathToQNamePath(context, module, strXPath);
152 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
153 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
154 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(path);
155 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, path);
162 * Method attempts to find DataSchemaNode inside of provided Schema Context
163 * and Yang Module accordingly to Non-conditional relative Revision Aware
164 * XPath. The specified Module MUST be present in Schema Context otherwise
165 * the operation would fail and return <code>null</code>. <br>
166 * The relative Revision Aware XPath MUST be specified WITHOUT the
167 * conditional statement (i.e. without [cond]) in path, because in this
168 * state the Schema Context is completely unaware of data state and will be
169 * not able to properly resolve XPath. If the XPath contains condition the
170 * method will return IllegalArgumentException. <br>
171 * The Actual Schema Node MUST be specified correctly because from this
172 * Schema Node will search starts. If the Actual Schema Node is not correct
173 * the operation will simply fail, because it will be unable to find desired
174 * DataSchemaNode. <br>
175 * In case that Schema Context or Module or Actual Schema Node or relative
176 * Revision Aware XPath contains <code>null</code> references the method
177 * will throw IllegalArgumentException <br>
178 * If the Revision Aware XPath doesn't have flag
179 * <code>isAbsolute == false</code> the method will throw
180 * IllegalArgumentException. <br>
181 * If the relative Revision Aware XPath is correct and desired Data Schema
182 * Node is present in Yang module or in depending module in Schema Context
183 * the method will return specified Data Schema Node, otherwise the
184 * operation will fail and method will return <code>null</code>.
190 * @param actualSchemaNode
192 * @param relativeXPath
193 * Relative Non Conditional Revision Aware XPath
194 * @return DataSchemaNode if is present in specified Schema Context for
195 * given relative Revision Aware XPath, otherwise will return
198 // FIXME: This entire method is ill-defined, as the resolution process depends on where the XPath is defined --
199 // notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
202 // Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
203 // a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
204 // via a derived SchemaContext (i.e. this class would have to have a
206 // SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
208 // which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
209 // that feels like an overkill.
210 public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
211 final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
212 checkArgument(context != null, "Schema Context reference cannot be NULL");
213 checkArgument(module != null, "Module reference cannot be NULL");
214 checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
215 checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
216 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
217 + "for non relative Revision Aware XPath use findDataSchemaNode method");
219 final SchemaPath actualNodePath = actualSchemaNode.getPath();
220 if (actualNodePath != null) {
221 final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
223 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
224 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
225 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
226 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
232 * Returns parent Yang Module for specified Schema Context in which Schema
233 * Node is declared. If the Schema Node is not present in Schema Context the
234 * operation will return <code>null</code>. <br>
235 * If Schema Context or Schema Node contains <code>null</code> references
236 * the method will throw IllegalArgumentException
242 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
243 * return <code>null</code>
245 public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
246 checkArgument(context != null, "Schema Context reference cannot be NULL!");
247 checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
248 checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not set properly (Schema Path is "
251 final QName qname = schemaNode.getPath().getLastComponent();
252 checkState(qname != null, "Schema Path contains invalid state of path parts. "
253 + "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
254 return context.findModule(qname.getModule()).orElse(null);
257 public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
258 final QName current = path.iterator().next();
260 LOG.trace("Looking up module {} in context {}", current, path);
261 final Optional<Module> module = context.findModule(current.getModule());
262 if (!module.isPresent()) {
263 LOG.debug("Module {} not found", current);
267 return findNodeInModule(module.get(), path);
271 * Returns NotificationDefinition from Schema Context.
273 * @param schema SchemaContext in which lookup should be performed.
274 * @param path Schema Path of notification
275 * @return Notification schema or null, if notification is not present in schema context.
278 public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
279 final @NonNull SchemaPath path) {
280 requireNonNull(schema, "Schema context must not be null.");
281 requireNonNull(path, "Schema path must not be null.");
282 for (final NotificationDefinition potential : schema.getNotifications()) {
283 if (path.equals(potential.getPath())) {
291 * Returns RPC Input or Output Data container from RPC definition.
293 * @param schema SchemaContext in which lookup should be performed.
294 * @param path Schema path of RPC input/output data container
295 * @return Notification schema or null, if notification is not present in schema context.
298 public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
299 final @NonNull SchemaPath path) {
300 requireNonNull(schema, "Schema context must not be null.");
301 requireNonNull(path, "Schema path must not be null.");
302 final Iterator<QName> it = path.getPathFromRoot().iterator();
303 checkArgument(it.hasNext(), "Rpc must have QName.");
304 final QName rpcName = it.next();
305 checkArgument(it.hasNext(), "input or output must be part of path.");
306 final QName inOrOut = it.next();
307 for (final RpcDefinition potential : schema.getOperations()) {
308 if (rpcName.equals(potential.getQName())) {
309 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
316 * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
318 * @param context SchemaContext to be examined
319 * @return Set of ModuleIdentifiers.
321 public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
322 final Set<SourceIdentifier> ret = new HashSet<>();
324 for (Module module : context.getModules()) {
325 ret.add(moduleToIdentifier(module));
327 for (Module submodule : module.getSubmodules()) {
328 ret.add(moduleToIdentifier(submodule));
335 private static SourceIdentifier moduleToIdentifier(final Module module) {
336 return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
339 private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
340 checkArgument(module != null, "Parent reference cannot be NULL");
341 checkArgument(path != null, "Path reference cannot be NULL");
343 if (!path.iterator().hasNext()) {
344 LOG.debug("No node matching {} found in node {}", path, module);
348 final QName current = path.iterator().next();
349 LOG.trace("Looking for node {} in module {}", current, module);
351 SchemaNode foundNode = null;
352 final Iterable<QName> nextPath = nextLevel(path);
354 foundNode = module.getDataChildByName(current);
355 if (foundNode != null && nextPath.iterator().hasNext()) {
356 foundNode = findNodeIn(foundNode, nextPath);
359 if (foundNode == null) {
360 foundNode = getGroupingByName(module, current);
361 if (foundNode != null && nextPath.iterator().hasNext()) {
362 foundNode = findNodeIn(foundNode, nextPath);
366 if (foundNode == null) {
367 foundNode = getRpcByName(module, current);
368 if (foundNode != null && nextPath.iterator().hasNext()) {
369 foundNode = findNodeIn(foundNode, nextPath);
373 if (foundNode == null) {
374 foundNode = getNotificationByName(module, current);
375 if (foundNode != null && nextPath.iterator().hasNext()) {
376 foundNode = findNodeIn(foundNode, nextPath);
380 if (foundNode == null) {
381 LOG.debug("No node matching {} found in node {}", path, module);
388 private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
389 checkArgument(parent != null, "Parent reference cannot be NULL");
390 checkArgument(path != null, "Path reference cannot be NULL");
392 if (!path.iterator().hasNext()) {
393 LOG.debug("No node matching {} found in node {}", path, parent);
397 final QName current = path.iterator().next();
398 LOG.trace("Looking for node {} in node {}", current, parent);
400 SchemaNode foundNode = null;
401 final Iterable<QName> nextPath = nextLevel(path);
403 if (parent instanceof DataNodeContainer) {
404 final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
406 foundNode = parentDataNodeContainer.getDataChildByName(current);
407 if (foundNode != null && nextPath.iterator().hasNext()) {
408 foundNode = findNodeIn(foundNode, nextPath);
411 if (foundNode == null) {
412 foundNode = getGroupingByName(parentDataNodeContainer, current);
413 if (foundNode != null && nextPath.iterator().hasNext()) {
414 foundNode = findNodeIn(foundNode, nextPath);
419 if (foundNode == null && parent instanceof ActionNodeContainer) {
420 foundNode = ((ActionNodeContainer) parent).getActions().stream()
421 .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
422 if (foundNode != null && nextPath.iterator().hasNext()) {
423 foundNode = findNodeIn(foundNode, nextPath);
427 if (foundNode == null && parent instanceof NotificationNodeContainer) {
428 foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
429 .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
430 if (foundNode != null && nextPath.iterator().hasNext()) {
431 foundNode = findNodeIn(foundNode, nextPath);
435 if (foundNode == null && parent instanceof OperationDefinition) {
436 final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
438 if (current.getLocalName().equals("input")) {
439 foundNode = parentRpcDefinition.getInput();
440 if (foundNode != null && nextPath.iterator().hasNext()) {
441 foundNode = findNodeIn(foundNode, nextPath);
445 if (current.getLocalName().equals("output")) {
446 foundNode = parentRpcDefinition.getOutput();
447 if (foundNode != null && nextPath.iterator().hasNext()) {
448 foundNode = findNodeIn(foundNode, nextPath);
452 if (foundNode == null) {
453 foundNode = getGroupingByName(parentRpcDefinition, current);
454 if (foundNode != null && nextPath.iterator().hasNext()) {
455 foundNode = findNodeIn(foundNode, nextPath);
460 if (foundNode == null && parent instanceof ChoiceSchemaNode) {
461 foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
463 if (foundNode != null && nextPath.iterator().hasNext()) {
464 foundNode = findNodeIn(foundNode, nextPath);
467 if (foundNode == null) {
468 // fallback that tries to map into one of the child cases
469 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
470 final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
471 if (maybeChild != null) {
472 foundNode = findNodeIn(maybeChild, nextPath);
479 if (foundNode == null) {
480 LOG.debug("No node matching {} found in node {}", path, parent);
487 private static Iterable<QName> nextLevel(final Iterable<QName> path) {
488 return Iterables.skip(path, 1);
491 private static RpcDefinition getRpcByName(final Module module, final QName name) {
492 for (final RpcDefinition rpc : module.getRpcs()) {
493 if (rpc.getQName().equals(name)) {
500 private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
501 for (final NotificationDefinition notification : module.getNotifications()) {
502 if (notification.getQName().equals(name)) {
509 private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
510 for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
511 if (grouping.getQName().equals(name)) {
518 private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
519 for (final GroupingDefinition grouping : rpc.getGroupings()) {
520 if (grouping.getQName().equals(name)) {
528 * Transforms string representation of XPath to Queue of QNames. The XPath
529 * is split by "/" and for each part of XPath is assigned correct module in
531 * If Schema Context, Parent Module or XPath string contains
532 * <code>null</code> values, the method will throws IllegalArgumentException
536 * @param parentModule
540 * @return return a list of QName
542 * @throws IllegalArgumentException if any arguments are null
545 private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
546 final String xpath) {
547 // FIXME: 3.0.0: this should throw NPE, not IAE
548 checkArgument(context != null, "Schema Context reference cannot be NULL");
549 checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
550 checkArgument(xpath != null, "XPath string reference cannot be NULL");
552 final List<QName> path = new LinkedList<>();
553 for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
554 if (!pathComponent.isEmpty()) {
555 path.add(stringPathPartToQName(context, parentModule, pathComponent));
562 * Transforms part of Prefixed Path as java String to QName. <br>
563 * If the string contains module prefix separated by ":" (i.e.
564 * mod:container) this module is provided from from Parent Module list of
565 * imports. If the Prefixed module is present in Schema Context the QName
566 * can be constructed. <br>
567 * If the Prefixed Path Part does not contains prefix the Parent's Module
568 * namespace is taken for construction of QName. <br>
569 * If Schema Context, Parent Module or Prefixed Path Part refers to
570 * <code>null</code> the method will throw IllegalArgumentException
572 * @param context Schema Context
573 * @param parentModule Parent Module
574 * @param prefixedPathPart Prefixed Path Part string
575 * @return QName from prefixed Path Part String.
576 * @throws IllegalArgumentException if any arguments are null
578 private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
579 final String prefixedPathPart) {
580 // FIXME: 3.0.0: this should throw NPE, not IAE
581 checkArgument(context != null, "Schema Context reference cannot be NULL");
582 checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
583 checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
585 if (prefixedPathPart.indexOf(':') != -1) {
586 final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
587 final String modulePrefix = prefixedName.next();
589 final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
590 checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
591 modulePrefix, parentModule.getName());
593 return QName.create(module.getQNameModule(), prefixedName.next());
596 return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
600 * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
601 * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
602 * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
603 * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
605 * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
606 * If Schema Context, Module or Prefix are referring to {@code null} the method will throw IllegalArgumentException.
608 * @param context Schema Context
609 * @param module Yang Module
610 * @param prefix Module Prefix
611 * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
612 * @throws IllegalArgumentException if any arguments are null
614 private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
615 final String prefix) {
616 // FIXME: 3.0.0: this should throw NPE, not IAE
617 checkArgument(context != null, "Schema Context reference cannot be NULL");
618 checkArgument(module != null, "Module reference cannot be NULL");
619 checkArgument(prefix != null, "Prefix string cannot be NULL");
621 if (prefix.equals(module.getPrefix())) {
625 final Set<ModuleImport> imports = module.getImports();
626 for (final ModuleImport mi : imports) {
627 if (prefix.equals(mi.getPrefix())) {
628 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
635 * Resolve a relative XPath into a set of QNames.
641 * @param relativeXPath
642 * Non conditional Revision Aware Relative XPath
643 * @param actualSchemaNode
645 * @return list of QName
646 * @throws IllegalArgumentException if any arguments are null
648 private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
649 final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
650 // FIXME: 3.0.0: this should throw NPE, not IAE
651 checkArgument(context != null, "Schema Context reference cannot be NULL");
652 checkArgument(module != null, "Module reference cannot be NULL");
653 checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
654 checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
655 + "for non relative Revision Aware XPath use findDataSchemaNode method");
656 checkState(actualSchemaNode.getPath() != null,
657 "Schema Path reference for Leafref cannot be NULL");
659 final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
661 // Find out how many "parent" components there are
662 // FIXME: is .contains() the right check here?
663 // FIXME: case ../../node1/node2/../node3/../node4
665 for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
669 final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
671 if (Iterables.size(schemaNodePath) - colCount >= 0) {
672 return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
673 Iterables.transform(Iterables.skip(xpaths, colCount),
674 input -> stringPathPartToQName(context, module, input)));
676 return Iterables.concat(schemaNodePath,
677 Iterables.transform(Iterables.skip(xpaths, colCount),
678 input -> stringPathPartToQName(context, module, input)));
682 * Extracts the base type of node on which schema node points to. If target node is again of type
683 * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
685 * @param typeDefinition
686 * type of node which will be extracted
687 * @param schemaContext
691 * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
692 * is there to preserve backwards compatibility)
694 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
695 final SchemaContext schemaContext, final SchemaNode schema) {
696 RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
697 pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
698 pathStatement.isAbsolute());
700 final DataSchemaNode dataSchemaNode;
701 if (pathStatement.isAbsolute()) {
702 SchemaNode baseSchema = schema;
703 while (baseSchema instanceof DerivableSchemaNode) {
704 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
705 if (basePotential.isPresent()) {
706 baseSchema = basePotential.get();
712 Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
713 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
716 Module parentModule = findParentModule(schemaContext, schema);
717 dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
718 parentModule, schema, pathStatement);
721 // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
722 // and current expected behaviour for such cases is to just use pure string
723 // This should throw an exception about incorrect XPath in leafref
724 if (dataSchemaNode == null) {
728 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
730 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
731 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
734 return targetTypeDefinition;
738 * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
739 * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
740 * module as typedef which is then imported to referenced module.
743 * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
745 public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
746 final SchemaContext schemaContext, final QName qname) {
747 final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
748 final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
749 stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
750 if (!strippedPathStatement.isAbsolute()) {
754 final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
755 checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
757 final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
758 parentModule.get(), strippedPathStatement);
759 final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
760 if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
761 return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
764 return targetTypeDefinition;
767 private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
768 final SchemaNode schemaNode) {
769 checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
770 checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
772 TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
773 if (nodeType.getBaseType() != null) {
774 while (nodeType.getBaseType() != null) {
775 nodeType = nodeType.getBaseType();
778 return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
781 return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
784 private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
787 * Removes conditions from xPath pointed to target node.
789 * @param pathStatement
790 * xPath to target node
791 * @return string representation of xPath without conditions
794 static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
795 return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
799 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
802 * a node representing LeafSchemaNode
803 * @return concrete type definition of node value
805 private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
806 TypeDefinition<?> baseType = node.getType();
807 while (baseType.getBaseType() != null) {
808 baseType = baseType.getBaseType();
814 * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
817 * a node representing LeafListSchemaNode
818 * @return concrete type definition of node value
820 private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
821 TypeDefinition<?> baseType = node.getType();
822 while (baseType.getBaseType() != null) {
823 baseType = baseType.getBaseType();
829 * Gets the base type of DataSchemaNode value.
832 * a node representing DataSchemaNode
833 * @return concrete type definition of node value
835 private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
836 if (node instanceof LeafListSchemaNode) {
837 return typeDefinition((LeafListSchemaNode) node);
838 } else if (node instanceof LeafSchemaNode) {
839 return typeDefinition((LeafSchemaNode) node);
841 throw new IllegalArgumentException("Unhandled parameter type: " + node);