4564784738a58f0d3555733d679e88b2d9d992bc
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaContextUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.yangtools.yang.model.util;
9
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;
13
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;
26 import java.util.Set;
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;
73
74 /**
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
77  * instantiable.
78  */
79 public final class SchemaContextUtil {
80     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
81     private static final Splitter COLON_SPLITTER = Splitter.on(':');
82     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
83
84     private SchemaContextUtil() {
85         // Hidden on purpose
86     }
87
88     /**
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}.
92      *
93      * <p>
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.
96      *
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
101      */
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);
106             return null;
107         }
108
109         LOG.trace("Looking for path {} in context {}", schemaPath, context);
110         return findNodeInSchemaContext(context, prefixedPath);
111     }
112
113     /**
114      * Attempt to find a DataSchemaNode based on its path from root, similar to
115      * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
116      *
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
121      */
122     @Beta
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())));
126     }
127
128     /**
129      * Attempt to find a DataSchemaNode based on its path from root, similar to
130      * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
131      *
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
136      */
137     @Beta
138     public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
139         return findDataSchemaNode(context, Arrays.asList(path));
140     }
141
142     /**
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>.
156      *
157      * @param context
158      *            Schema Context
159      * @param module
160      *            Yang Module
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.
169      */
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
172     //        of RFC7950.
173     //
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
177     //
178     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
179     //
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.
182     @Deprecated
183     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
184             final PathExpression nonCondXPath) {
185         requireNonNull(context, "context");
186         requireNonNull(module, "module");
187
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));
192         }
193         return null;
194     }
195
196     @Beta
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);
201     }
202
203     @Beta
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());
209         }
210
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);
213
214         // We are missing proper API alignment, if this ever triggers
215         throw new IllegalStateException("Unsupported path " + pathSteps);
216     }
217
218     /**
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>.
239      *
240      * @param context
241      *            Schema Context
242      * @param module
243      *            Yang Module
244      * @param actualSchemaNode
245      *            Actual Schema Node
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
250      *         <code>null</code>.
251      * @throws NullPointerException if any argument is null
252      */
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
255     //        of RFC7950.
256     //
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
260     //
261     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
262     //
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);
271     }
272
273     /**
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>.
277      *
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
283      */
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);
289     }
290
291     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
292         final QName current = path.iterator().next();
293
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);
298             return null;
299         }
300
301         return findNodeInModule(module.get(), path);
302     }
303
304     /**
305      * Returns NotificationDefinition from Schema Context.
306      *
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.
310      */
311     @Beta
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())) {
318                 return potential;
319             }
320         }
321         return null;
322     }
323
324     /**
325      * Returns RPC Input or Output Data container from RPC definition.
326      *
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.
330      */
331     @Beta
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);
344             }
345         }
346         return null;
347     }
348
349     /**
350      * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
351      *
352      * @param context SchemaContext to be examined
353      * @return Set of ModuleIdentifiers.
354      */
355     public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
356         final Set<SourceIdentifier> ret = new HashSet<>();
357
358         for (Module module : context.getModules()) {
359             ret.add(moduleToIdentifier(module));
360
361             for (Module submodule : module.getSubmodules()) {
362                 ret.add(moduleToIdentifier(submodule));
363             }
364         }
365
366         return ret;
367     }
368
369     private static SourceIdentifier moduleToIdentifier(final Module module) {
370         return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
371     }
372
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);
376             return null;
377         }
378
379         final QName current = path.iterator().next();
380         LOG.trace("Looking for node {} in module {}", current, module);
381
382         SchemaNode foundNode = null;
383         final Iterable<QName> nextPath = nextLevel(path);
384
385         foundNode = module.getDataChildByName(current);
386         if (foundNode != null && nextPath.iterator().hasNext()) {
387             foundNode = findNodeIn(foundNode, nextPath);
388         }
389
390         if (foundNode == null) {
391             foundNode = getGroupingByName(module, current);
392             if (foundNode != null && nextPath.iterator().hasNext()) {
393                 foundNode = findNodeIn(foundNode, nextPath);
394             }
395         }
396
397         if (foundNode == null) {
398             foundNode = getRpcByName(module, current);
399             if (foundNode != null && nextPath.iterator().hasNext()) {
400                 foundNode = findNodeIn(foundNode, nextPath);
401             }
402         }
403
404         if (foundNode == null) {
405             foundNode = getNotificationByName(module, current);
406             if (foundNode != null && nextPath.iterator().hasNext()) {
407                 foundNode = findNodeIn(foundNode, nextPath);
408             }
409         }
410
411         if (foundNode == null) {
412             LOG.debug("No node matching {} found in node {}", path, module);
413         }
414
415         return foundNode;
416     }
417
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);
421             return null;
422         }
423
424         final QName current = path.iterator().next();
425         LOG.trace("Looking for node {} in node {}", current, parent);
426
427         SchemaNode foundNode = null;
428         final Iterable<QName> nextPath = nextLevel(path);
429
430         if (parent instanceof DataNodeContainer) {
431             final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
432
433             foundNode = parentDataNodeContainer.getDataChildByName(current);
434             if (foundNode != null && nextPath.iterator().hasNext()) {
435                 foundNode = findNodeIn(foundNode, nextPath);
436             }
437
438             if (foundNode == null) {
439                 foundNode = getGroupingByName(parentDataNodeContainer, current);
440                 if (foundNode != null && nextPath.iterator().hasNext()) {
441                     foundNode = findNodeIn(foundNode, nextPath);
442                 }
443             }
444         }
445
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);
451             }
452         }
453
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);
459             }
460         }
461
462         if (foundNode == null && parent instanceof OperationDefinition) {
463             final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
464
465             if (current.getLocalName().equals("input")) {
466                 foundNode = parentRpcDefinition.getInput();
467                 if (foundNode != null && nextPath.iterator().hasNext()) {
468                     foundNode = findNodeIn(foundNode, nextPath);
469                 }
470             }
471
472             if (current.getLocalName().equals("output")) {
473                 foundNode = parentRpcDefinition.getOutput();
474                 if (foundNode != null && nextPath.iterator().hasNext()) {
475                     foundNode = findNodeIn(foundNode, nextPath);
476                 }
477             }
478
479             if (foundNode == null) {
480                 foundNode = getGroupingByName(parentRpcDefinition, current);
481                 if (foundNode != null && nextPath.iterator().hasNext()) {
482                     foundNode = findNodeIn(foundNode, nextPath);
483                 }
484             }
485         }
486
487         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
488             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
489
490             if (foundNode != null && nextPath.iterator().hasNext()) {
491                 foundNode = findNodeIn(foundNode, nextPath);
492             }
493
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);
500                         break;
501                     }
502                 }
503             }
504         }
505
506         if (foundNode == null) {
507             LOG.debug("No node matching {} found in node {}", path, parent);
508         }
509
510         return foundNode;
511
512     }
513
514     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
515         return Iterables.skip(path, 1);
516     }
517
518     private static RpcDefinition getRpcByName(final Module module, final QName name) {
519         for (final RpcDefinition rpc : module.getRpcs()) {
520             if (rpc.getQName().equals(name)) {
521                 return rpc;
522             }
523         }
524         return null;
525     }
526
527     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
528         for (final NotificationDefinition notification : module.getNotifications()) {
529             if (notification.getQName().equals(name)) {
530                 return notification;
531             }
532         }
533         return null;
534     }
535
536     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
537         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
538             if (grouping.getQName().equals(name)) {
539                 return grouping;
540             }
541         }
542         return null;
543     }
544
545     private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
546         for (final GroupingDefinition grouping : rpc.getGroupings()) {
547             if (grouping.getQName().equals(name)) {
548                 return grouping;
549             }
550         }
551         return null;
552     }
553
554     /**
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
557      * Schema Path. <br>
558      * If Schema Context, Parent Module or XPath string contains
559      * <code>null</code> values, the method will throws IllegalArgumentException
560      *
561      * @param context
562      *            Schema Context
563      * @param parentModule
564      *            Parent Module
565      * @param xpath
566      *            XPath String
567      * @return return a list of QName
568      */
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));
574         }
575         return path;
576     }
577
578     /**
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>
586      *
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
592      */
593     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
594             final String prefixedPathPart) {
595         requireNonNull(context, "context");
596
597         if (prefixedPathPart.indexOf(':') != -1) {
598             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
599             final String modulePrefix = prefixedName.next();
600
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());
604
605             return QName.create(module.getQNameModule(), prefixedName.next());
606         }
607
608         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
609     }
610
611     /**
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}.
616      * <br>
617      * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
618      *
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
624      */
625     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
626             final String prefix) {
627         requireNonNull(context, "context");
628
629         if (prefix.equals(module.getPrefix())) {
630             return module;
631         }
632
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);
637             }
638         }
639         return null;
640     }
641
642     /**
643      * Resolve a relative XPath into a set of QNames.
644      *
645      * @param context
646      *            Schema Context
647      * @param module
648      *            Yang Module
649      * @param relativeXPath
650      *            Non conditional Revision Aware Relative XPath
651      * @param actualSchemaNode
652      *            actual schema node
653      * @return target schema node
654      * @throws IllegalArgumentException if any arguments are null
655      */
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");
661
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)));
665     }
666
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());
672
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)));
677         }
678         return Iterables.concat(schemaNodePath,
679                 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
680     }
681
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);
686
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,
692                 actualSchemaNode);
693         checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
694             derefTarget);
695
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);
702         }
703
704         // deref() is define only for instance-identifier and leafref types, handle the latter
705         checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
706
707         final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
708         LOG.debug("Derefencing path {}", targetPath);
709
710         final SchemaNode deref = targetPath.isAbsolute()
711                 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
712                     ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
713                         : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
714         if (deref == null) {
715             LOG.debug("Path {} could not be derefenced", targetPath);
716             return null;
717         }
718
719         checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
720
721         final List<String> qnames = doSplitXPath(xpath.substring(paren + 1).stripLeading());
722         return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
723     }
724
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);
733                 ret.removeLast();
734                 continue;
735             }
736
737             // This has to be a QNameStep
738             checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
739             final QName qname;
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());
747             } else {
748                 throw new IllegalStateException("Unhandled step " + step);
749             }
750
751             ret.addLast(qname);
752         }
753
754         return findTargetNode(context, ret);
755     }
756
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);
762     }
763
764     @VisibleForTesting
765     static int normalizeXPath(final List<String> xpath) {
766         LOG.trace("Normalize {}", xpath);
767
768         // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
769         // is "../../def"
770         while (true) {
771             // Next up: count leading ".." components
772             int leadingParents = 0;
773             while (true) {
774                 if (leadingParents == xpath.size()) {
775                     return leadingParents;
776                 }
777                 if (!"..".equals(xpath.get(leadingParents))) {
778                     break;
779                 }
780
781                 ++leadingParents;
782             }
783
784             // Now let's see if there there is a '..' in the rest
785             final int dots = findDots(xpath, leadingParents + 1);
786             if (dots == -1) {
787                 return leadingParents;
788             }
789
790             xpath.remove(dots - 1);
791             xpath.remove(dots - 1);
792             LOG.trace("Next iteration {}", xpath);
793         }
794     }
795
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))) {
799                 return i;
800             }
801         }
802
803         return -1;
804     }
805
806     private static List<String> doSplitXPath(final String xpath) {
807         return SLASH_SPLITTER.splitToList(xpath);
808     }
809
810     /**
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.
813      *
814      * @param typeDefinition
815      *            type of node which will be extracted
816      * @param schemaContext
817      *            Schema Context
818      * @param schema
819      *            Schema Node
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)
822      */
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());
828
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();
836                 } else {
837                     break;
838                 }
839             }
840
841             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
842             dataSchemaNode = (DataSchemaNode) findDataSchemaNode(schemaContext, parentModule, pathStatement);
843         } else {
844             Module parentModule = findParentModule(schemaContext, schema);
845             dataSchemaNode = (DataSchemaNode) findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema,
846                 pathStatement);
847         }
848
849         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
850         // and current expected behaviour for such cases is to just use pure string
851         // This should throw an exception about incorrect XPath in leafref
852         if (dataSchemaNode == null) {
853             return null;
854         }
855
856         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
857
858         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
859             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
860         }
861
862         return targetTypeDefinition;
863     }
864
865     /**
866      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
867      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
868      * module as typedef which is then imported to referenced module.
869      *
870      * <p>
871      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
872      */
873     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
874             final SchemaContext schemaContext, final QName qname) {
875         final PathExpression pathStatement = typeDefinition.getPathStatement();
876         final PathExpression strippedPathStatement = new PathExpressionImpl(
877             stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
878         if (!strippedPathStatement.isAbsolute()) {
879             return null;
880         }
881
882         final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
883         checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
884
885         final DataSchemaNode dataSchemaNode = (DataSchemaNode) findDataSchemaNode(schemaContext, parentModule.get(),
886             strippedPathStatement);
887         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
888         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
889             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
890         }
891
892         return targetTypeDefinition;
893     }
894
895     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
896             final SchemaNode schemaNode) {
897         checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
898         checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
899
900         TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
901         if (nodeType.getBaseType() != null) {
902             while (nodeType.getBaseType() != null) {
903                 nodeType = nodeType.getBaseType();
904             }
905
906             return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
907         }
908
909         return findParentModule(schemaContext, schemaNode);
910     }
911
912     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
913
914     /**
915      * Removes conditions from xPath pointed to target node.
916      *
917      * @param pathStatement
918      *            xPath to target node
919      * @return string representation of xPath without conditions
920      */
921     @VisibleForTesting
922     static String stripConditionsFromXPathString(final PathExpression pathStatement) {
923         return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
924     }
925
926     /**
927      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
928      *
929      * @param node
930      *            a node representing LeafSchemaNode
931      * @return concrete type definition of node value
932      */
933     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
934         TypeDefinition<?> baseType = node.getType();
935         while (baseType.getBaseType() != null) {
936             baseType = baseType.getBaseType();
937         }
938         return baseType;
939     }
940
941     /**
942      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
943      *
944      * @param node
945      *            a node representing LeafListSchemaNode
946      * @return concrete type definition of node value
947      */
948     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
949         TypeDefinition<?> baseType = node.getType();
950         while (baseType.getBaseType() != null) {
951             baseType = baseType.getBaseType();
952         }
953         return baseType;
954     }
955
956     /**
957      * Gets the base type of DataSchemaNode value.
958      *
959      * @param node
960      *            a node representing DataSchemaNode
961      * @return concrete type definition of node value
962      */
963     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
964         if (node instanceof LeafListSchemaNode) {
965             return typeDefinition((LeafListSchemaNode) node);
966         } else if (node instanceof LeafSchemaNode) {
967             return typeDefinition((LeafSchemaNode) node);
968         } else {
969             throw new IllegalArgumentException("Unhandled parameter type: " + node);
970         }
971     }
972 }