c047ead58f252add5b6803478d3304fa65de96e7
[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.CharMatcher;
17 import com.google.common.base.Splitter;
18 import com.google.common.collect.Iterables;
19 import java.util.ArrayDeque;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Deque;
23 import java.util.HashSet;
24 import java.util.Iterator;
25 import java.util.List;
26 import java.util.Optional;
27 import java.util.Set;
28 import java.util.regex.Pattern;
29 import java.util.stream.Collectors;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.opendaylight.yangtools.yang.common.AbstractQName;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.common.QNameModule;
35 import org.opendaylight.yangtools.yang.common.UnqualifiedQName;
36 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
37 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
41 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
48 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
49 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
51 import org.opendaylight.yangtools.yang.model.api.PathExpression;
52 import org.opendaylight.yangtools.yang.model.api.PathExpression.DerefSteps;
53 import org.opendaylight.yangtools.yang.model.api.PathExpression.LocationPathSteps;
54 import org.opendaylight.yangtools.yang.model.api.PathExpression.Steps;
55 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
59 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath;
66 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.AxisStep;
67 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.QNameStep;
68 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.ResolvedQNameStep;
69 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.Step;
70 import org.opendaylight.yangtools.yang.xpath.api.YangLocationPath.UnresolvedQNameStep;
71 import org.opendaylight.yangtools.yang.xpath.api.YangXPathAxis;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 /**
76  * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
77  * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
78  * instantiable.
79  */
80 public final class SchemaContextUtil {
81     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
82     private static final Splitter COLON_SPLITTER = Splitter.on(':');
83     private static final Splitter SLASH_SPLITTER = Splitter.on('/').omitEmptyStrings();
84     private static final CharMatcher SPACE = CharMatcher.is(' ');
85
86     private SchemaContextUtil() {
87         // Hidden on purpose
88     }
89
90     /**
91      * Method attempts to find DataSchemaNode in Schema Context via specified Schema Path. The returned DataSchemaNode
92      * from method will be the node at the end of the SchemaPath. If the DataSchemaNode is not present in the Schema
93      * Context the method will return {@code null}.
94      *
95      * <p>
96      * In case that Schema Context or Schema Path are not specified correctly (i.e. contains {@code null} values) the
97      * method will throw IllegalArgumentException.
98      *
99      * @param context Schema Context
100      * @param schemaPath Schema Path to search for
101      * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
102      * @throws NullPointerException if context or schemaPath is null
103      */
104     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
105         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
106         if (prefixedPath == null) {
107             LOG.debug("Schema path {} has null path", schemaPath);
108             return null;
109         }
110
111         LOG.trace("Looking for path {} in context {}", schemaPath, context);
112         return findNodeInSchemaContext(context, prefixedPath);
113     }
114
115     /**
116      * Attempt to find a DataSchemaNode based on its path from root, similar to
117      * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
118      *
119      * @param context Schema Context
120      * @param path Path to search for
121      * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
122      * @throws NullPointerException if a any argument is null or if the path contains a null element
123      */
124     @Beta
125     public static SchemaNode findDataSchemaNode(final SchemaContext context, final List<QName> path) {
126         return findTargetNode(context, null, YangLocationPath.absolute(
127             path.stream().map(YangXPathAxis.CHILD::asStep).collect(Collectors.toList())));
128     }
129
130     /**
131      * Attempt to find a DataSchemaNode based on its path from root, similar to
132      * {@link #findDataSchemaNode(SchemaContext, Module, PathExpression)} without requiring an expression.
133      *
134      * @param context Schema Context
135      * @param path Path to search for
136      * @return SchemaNode from the end of the Schema Path or {@code null} if the Node is not present.
137      * @throws NullPointerException if a any argument is null or if the path contains a null element
138      */
139     @Beta
140     public static SchemaNode findDataSchemaNode(final SchemaContext context, final QName... path) {
141         return findDataSchemaNode(context, Arrays.asList(path));
142     }
143
144     /**
145      * Method attempts to find DataSchemaNode inside of provided Schema Context
146      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
147      * specified Module MUST be present in Schema Context otherwise the
148      * operation would fail and return <code>null</code>. <br>
149      * The Revision Aware XPath MUST be specified WITHOUT the conditional
150      * statement (i.e. without [cond]) in path, because in this state the Schema
151      * Context is completely unaware of data state and will be not able to
152      * properly resolve XPath. If the XPath contains condition the method will
153      * return IllegalArgumentException. <br>
154      * If the Revision Aware XPath is correct and desired Data Schema Node is
155      * present in Yang module or in depending module in Schema Context the
156      * method will return specified Data Schema Node, otherwise the operation
157      * will fail and method will return <code>null</code>.
158      *
159      * @param context
160      *            Schema Context
161      * @param module
162      *            Yang Module
163      * @param nonCondXPath
164      *            Non Conditional Revision Aware XPath
165      * @return Returns Data Schema Node for specified Schema Context for given
166      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
167      *         DataSchemaNode is not present in Schema Context.
168      * @throws NullPointerException if any of the arguments is null
169      * @deprecated Use {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, YangLocationPath)} or
170      *             {@link #findDataTreeSchemaNode(SchemaContext, QNameModule, PathExpression)} instead.
171      */
172     // FIXME: This entire method is ill-defined, as the resolution process depends on  where the XPath is defined --
173     //        notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
174     //        of RFC7950.
175     //
176     //        Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
177     //        a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
178     //        via a derived SchemaContext (i.e. this class would have to have a
179     //
180     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
181     //
182     //        which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
183     //        that feels like an overkill.
184     @Deprecated
185     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
186             final PathExpression nonCondXPath) {
187         requireNonNull(context, "context");
188         requireNonNull(module, "module");
189
190         final String strXPath = nonCondXPath.getOriginalString();
191         checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
192         if (nonCondXPath.isAbsolute()) {
193             return findTargetNode(context, xpathToQNamePath(context, module, strXPath));
194         }
195         return null;
196     }
197
198     @Beta
199     public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
200             final YangLocationPath absPath) {
201         checkArgument(absPath.isAbsolute(), "Unsupported relative path %s", absPath);
202         return findTargetNode(ctx, localModule, absPath);
203     }
204
205     @Beta
206     public static SchemaNode findDataTreeSchemaNode(final SchemaContext ctx, final QNameModule localModule,
207             final PathExpression absPath) {
208         final Steps pathSteps = absPath.getSteps();
209         if (pathSteps instanceof LocationPathSteps) {
210             return findDataTreeSchemaNode(ctx, localModule, ((LocationPathSteps) pathSteps).getLocationPath());
211         }
212
213         // We would need a reference schema node and no, we do not want to use SchemaContext in its SchemaNode capacity
214         checkArgument(!(pathSteps instanceof DerefSteps), "No reference node for steps %s", pathSteps);
215
216         // We are missing proper API alignment, if this ever triggers
217         throw new IllegalStateException("Unsupported path " + pathSteps);
218     }
219
220     /**
221      * Method attempts to find DataSchemaNode inside of provided Schema Context
222      * and Yang Module accordingly to Non-conditional relative Revision Aware
223      * XPath. The specified Module MUST be present in Schema Context otherwise
224      * the operation would fail and return <code>null</code>. <br>
225      * The relative Revision Aware XPath MUST be specified WITHOUT the
226      * conditional statement (i.e. without [cond]) in path, because in this
227      * state the Schema Context is completely unaware of data state and will be
228      * not able to properly resolve XPath. If the XPath contains condition the
229      * method will return IllegalArgumentException. <br>
230      * The Actual Schema Node MUST be specified correctly because from this
231      * Schema Node will search starts. If the Actual Schema Node is not correct
232      * the operation will simply fail, because it will be unable to find desired
233      * DataSchemaNode. <br>
234      * If the Revision Aware XPath doesn't have flag
235      * <code>isAbsolute == false</code> the method will throw
236      * IllegalArgumentException. <br>
237      * If the relative Revision Aware XPath is correct and desired Data Schema
238      * Node is present in Yang module or in depending module in Schema Context
239      * the method will return specified Data Schema Node, otherwise the
240      * operation will fail and method will return <code>null</code>.
241      *
242      * @param context
243      *            Schema Context
244      * @param module
245      *            Yang Module
246      * @param actualSchemaNode
247      *            Actual Schema Node
248      * @param relativeXPath
249      *            Relative Non Conditional Revision Aware XPath
250      * @return DataSchemaNode if is present in specified Schema Context for
251      *         given relative Revision Aware XPath, otherwise will return
252      *         <code>null</code>.
253      * @throws NullPointerException if any argument is null
254      */
255     // FIXME: This entire method is ill-defined, as the resolution process depends on  where the XPath is defined --
256     //        notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
257     //        of RFC7950.
258     //
259     //        Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
260     //        a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
261     //        via a derived SchemaContext (i.e. this class would have to have a
262     //
263     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
264     //
265     //        which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
266     //        that feels like an overkill.
267     // FIXME: YANGTOOLS-1052: this is a static analysis util, move it to a dedicated class
268     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
269             final SchemaNode actualSchemaNode, final PathExpression relativeXPath) {
270         checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
271                 + "for non relative Revision Aware XPath use findDataSchemaNode method");
272         return resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
273     }
274
275     /**
276      * Returns parent Yang Module for specified Schema Context in which Schema
277      * Node is declared. If the Schema Node is not present in Schema Context the
278      * operation will return <code>null</code>.
279      *
280      * @param context Schema Context
281      * @param schemaNode Schema Node
282      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
283      *         return <code>null</code>
284      * @throws NullPointerException if any of the arguments is null
285      */
286     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
287         final QName qname = schemaNode.getPath().getLastComponent();
288         checkState(qname != null, "Schema Path contains invalid state of path parts. "
289                 + "The Schema Path MUST contain at least ONE QName  which defines namespace and Local name of path.");
290         return context.findModule(qname.getModule()).orElse(null);
291     }
292
293     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
294         final QName current = path.iterator().next();
295
296         LOG.trace("Looking up module {} in context {}", current, path);
297         final Optional<Module> module = context.findModule(current.getModule());
298         if (!module.isPresent()) {
299             LOG.debug("Module {} not found", current);
300             return null;
301         }
302
303         return findNodeInModule(module.get(), path);
304     }
305
306     /**
307      * Returns NotificationDefinition from Schema Context.
308      *
309      * @param schema SchemaContext in which lookup should be performed.
310      * @param path Schema Path of notification
311      * @return Notification schema or null, if notification is not present in schema context.
312      */
313     @Beta
314     public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
315             final @NonNull SchemaPath path) {
316         requireNonNull(schema, "Schema context must not be null.");
317         requireNonNull(path, "Schema path must not be null.");
318         for (final NotificationDefinition potential : schema.getNotifications()) {
319             if (path.equals(potential.getPath())) {
320                 return potential;
321             }
322         }
323         return null;
324     }
325
326     /**
327      * Returns RPC Input or Output Data container from RPC definition.
328      *
329      * @param schema SchemaContext in which lookup should be performed.
330      * @param path Schema path of RPC input/output data container
331      * @return Notification schema or null, if notification is not present in schema context.
332      */
333     @Beta
334     public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
335             final @NonNull SchemaPath path) {
336         requireNonNull(schema, "Schema context must not be null.");
337         requireNonNull(path, "Schema path must not be null.");
338         final Iterator<QName> it = path.getPathFromRoot().iterator();
339         checkArgument(it.hasNext(), "Rpc must have QName.");
340         final QName rpcName = it.next();
341         checkArgument(it.hasNext(), "input or output must be part of path.");
342         final QName inOrOut = it.next();
343         for (final RpcDefinition potential : schema.getOperations()) {
344             if (rpcName.equals(potential.getQName())) {
345                 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
346             }
347         }
348         return null;
349     }
350
351     /**
352      * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
353      *
354      * @param context SchemaContext to be examined
355      * @return Set of ModuleIdentifiers.
356      */
357     public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
358         final Set<SourceIdentifier> ret = new HashSet<>();
359
360         for (Module module : context.getModules()) {
361             ret.add(moduleToIdentifier(module));
362
363             for (Module submodule : module.getSubmodules()) {
364                 ret.add(moduleToIdentifier(submodule));
365             }
366         }
367
368         return ret;
369     }
370
371     private static SourceIdentifier moduleToIdentifier(final Module module) {
372         return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
373     }
374
375     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
376         if (!path.iterator().hasNext()) {
377             LOG.debug("No node matching {} found in node {}", path, module);
378             return null;
379         }
380
381         final QName current = path.iterator().next();
382         LOG.trace("Looking for node {} in module {}", current, module);
383
384         SchemaNode foundNode = null;
385         final Iterable<QName> nextPath = nextLevel(path);
386
387         foundNode = module.getDataChildByName(current);
388         if (foundNode != null && nextPath.iterator().hasNext()) {
389             foundNode = findNodeIn(foundNode, nextPath);
390         }
391
392         if (foundNode == null) {
393             foundNode = getGroupingByName(module, current);
394             if (foundNode != null && nextPath.iterator().hasNext()) {
395                 foundNode = findNodeIn(foundNode, nextPath);
396             }
397         }
398
399         if (foundNode == null) {
400             foundNode = getRpcByName(module, current);
401             if (foundNode != null && nextPath.iterator().hasNext()) {
402                 foundNode = findNodeIn(foundNode, nextPath);
403             }
404         }
405
406         if (foundNode == null) {
407             foundNode = getNotificationByName(module, current);
408             if (foundNode != null && nextPath.iterator().hasNext()) {
409                 foundNode = findNodeIn(foundNode, nextPath);
410             }
411         }
412
413         if (foundNode == null) {
414             LOG.debug("No node matching {} found in node {}", path, module);
415         }
416
417         return foundNode;
418     }
419
420     private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
421         if (!path.iterator().hasNext()) {
422             LOG.debug("No node matching {} found in node {}", path, parent);
423             return null;
424         }
425
426         final QName current = path.iterator().next();
427         LOG.trace("Looking for node {} in node {}", current, parent);
428
429         SchemaNode foundNode = null;
430         final Iterable<QName> nextPath = nextLevel(path);
431
432         if (parent instanceof DataNodeContainer) {
433             final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
434
435             foundNode = parentDataNodeContainer.getDataChildByName(current);
436             if (foundNode != null && nextPath.iterator().hasNext()) {
437                 foundNode = findNodeIn(foundNode, nextPath);
438             }
439
440             if (foundNode == null) {
441                 foundNode = getGroupingByName(parentDataNodeContainer, current);
442                 if (foundNode != null && nextPath.iterator().hasNext()) {
443                     foundNode = findNodeIn(foundNode, nextPath);
444                 }
445             }
446         }
447
448         if (foundNode == null && parent instanceof ActionNodeContainer) {
449             foundNode = ((ActionNodeContainer) parent).getActions().stream()
450                     .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
451             if (foundNode != null && nextPath.iterator().hasNext()) {
452                 foundNode = findNodeIn(foundNode, nextPath);
453             }
454         }
455
456         if (foundNode == null && parent instanceof NotificationNodeContainer) {
457             foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
458                     .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
459             if (foundNode != null && nextPath.iterator().hasNext()) {
460                 foundNode = findNodeIn(foundNode, nextPath);
461             }
462         }
463
464         if (foundNode == null && parent instanceof OperationDefinition) {
465             final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
466
467             if (current.getLocalName().equals("input")) {
468                 foundNode = parentRpcDefinition.getInput();
469                 if (foundNode != null && nextPath.iterator().hasNext()) {
470                     foundNode = findNodeIn(foundNode, nextPath);
471                 }
472             }
473
474             if (current.getLocalName().equals("output")) {
475                 foundNode = parentRpcDefinition.getOutput();
476                 if (foundNode != null && nextPath.iterator().hasNext()) {
477                     foundNode = findNodeIn(foundNode, nextPath);
478                 }
479             }
480
481             if (foundNode == null) {
482                 foundNode = getGroupingByName(parentRpcDefinition, current);
483                 if (foundNode != null && nextPath.iterator().hasNext()) {
484                     foundNode = findNodeIn(foundNode, nextPath);
485                 }
486             }
487         }
488
489         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
490             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
491
492             if (foundNode != null && nextPath.iterator().hasNext()) {
493                 foundNode = findNodeIn(foundNode, nextPath);
494             }
495
496             if (foundNode == null) {
497                 // fallback that tries to map into one of the child cases
498                 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
499                     final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
500                     if (maybeChild != null) {
501                         foundNode = findNodeIn(maybeChild, nextPath);
502                         break;
503                     }
504                 }
505             }
506         }
507
508         if (foundNode == null) {
509             LOG.debug("No node matching {} found in node {}", path, parent);
510         }
511
512         return foundNode;
513
514     }
515
516     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
517         return Iterables.skip(path, 1);
518     }
519
520     private static RpcDefinition getRpcByName(final Module module, final QName name) {
521         for (final RpcDefinition rpc : module.getRpcs()) {
522             if (rpc.getQName().equals(name)) {
523                 return rpc;
524             }
525         }
526         return null;
527     }
528
529     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
530         for (final NotificationDefinition notification : module.getNotifications()) {
531             if (notification.getQName().equals(name)) {
532                 return notification;
533             }
534         }
535         return null;
536     }
537
538     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
539         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
540             if (grouping.getQName().equals(name)) {
541                 return grouping;
542             }
543         }
544         return null;
545     }
546
547     private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
548         for (final GroupingDefinition grouping : rpc.getGroupings()) {
549             if (grouping.getQName().equals(name)) {
550                 return grouping;
551             }
552         }
553         return null;
554     }
555
556     /**
557      * Transforms string representation of XPath to Queue of QNames. The XPath
558      * is split by "/" and for each part of XPath is assigned correct module in
559      * Schema Path. <br>
560      * If Schema Context, Parent Module or XPath string contains
561      * <code>null</code> values, the method will throws IllegalArgumentException
562      *
563      * @param context
564      *            Schema Context
565      * @param parentModule
566      *            Parent Module
567      * @param xpath
568      *            XPath String
569      * @return return a list of QName
570      */
571     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
572             final String xpath) {
573         final List<QName> path = new ArrayList<>();
574         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
575             path.add(stringPathPartToQName(context, parentModule, pathComponent));
576         }
577         return path;
578     }
579
580     /**
581      * Transforms part of Prefixed Path as java String to QName. <br>
582      * If the string contains module prefix separated by ":" (i.e.
583      * mod:container) this module is provided from from Parent Module list of
584      * imports. If the Prefixed module is present in Schema Context the QName
585      * can be constructed. <br>
586      * If the Prefixed Path Part does not contains prefix the Parent's Module
587      * namespace is taken for construction of QName. <br>
588      *
589      * @param context Schema Context
590      * @param parentModule Parent Module
591      * @param prefixedPathPart Prefixed Path Part string
592      * @return QName from prefixed Path Part String.
593      * @throws NullPointerException if any arguments are null
594      */
595     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
596             final String prefixedPathPart) {
597         requireNonNull(context, "context");
598
599         if (prefixedPathPart.indexOf(':') != -1) {
600             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
601             final String modulePrefix = prefixedName.next();
602
603             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
604             checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
605                     modulePrefix, parentModule.getName());
606
607             return QName.create(module.getQNameModule(), prefixedName.next());
608         }
609
610         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
611     }
612
613     /**
614      * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
615      * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
616      * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
617      * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
618      * <br>
619      * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
620      *
621      * @param context Schema Context
622      * @param module Yang Module
623      * @param prefix Module Prefix
624      * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
625      * @throws NullPointerException if any arguments are null
626      */
627     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
628             final String prefix) {
629         requireNonNull(context, "context");
630
631         if (prefix.equals(module.getPrefix())) {
632             return module;
633         }
634
635         final Set<ModuleImport> imports = module.getImports();
636         for (final ModuleImport mi : imports) {
637             if (prefix.equals(mi.getPrefix())) {
638                 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
639             }
640         }
641         return null;
642     }
643
644     /**
645      * Resolve a relative XPath into a set of QNames.
646      *
647      * @param context
648      *            Schema Context
649      * @param module
650      *            Yang Module
651      * @param relativeXPath
652      *            Non conditional Revision Aware Relative XPath
653      * @param actualSchemaNode
654      *            actual schema node
655      * @return target schema node
656      * @throws IllegalArgumentException if any arguments are null
657      */
658     private static @Nullable SchemaNode resolveRelativeXPath(final SchemaContext context, final Module module,
659             final PathExpression relativeXPath, final SchemaNode actualSchemaNode) {
660         checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
661                 + "for non relative Revision Aware XPath use findDataSchemaNode method");
662         checkState(actualSchemaNode.getPath() != null, "Schema Path reference for Leafref cannot be NULL");
663
664         final String orig = relativeXPath.getOriginalString();
665         return  orig.startsWith("deref(") ? resolveDerefPath(context, module, actualSchemaNode, orig)
666                 : findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode, doSplitXPath(orig)));
667     }
668
669     private static Iterable<QName> resolveRelativePath(final SchemaContext context, final Module module,
670             final SchemaNode actualSchemaNode, final List<String> steps) {
671         // Find out how many "parent" components there are and trim them
672         final int colCount = normalizeXPath(steps);
673         final List<String> xpaths = colCount == 0 ? steps : steps.subList(colCount, steps.size());
674
675         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
676         if (Iterables.size(schemaNodePath) - colCount >= 0) {
677             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
678                 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
679         }
680         return Iterables.concat(schemaNodePath,
681                 Iterables.transform(xpaths, input -> stringPathPartToQName(context, module, input)));
682     }
683
684     private static SchemaNode resolveDerefPath(final SchemaContext context, final Module module,
685             final SchemaNode actualSchemaNode, final String xpath) {
686         final int paren = xpath.indexOf(')', 6);
687         checkArgument(paren != -1, "Cannot find matching parentheses in %s", xpath);
688
689         final String derefArg = SPACE.trimFrom(xpath.substring(6, paren));
690         // Look up the node which we need to reference
691         final SchemaNode derefTarget = findTargetNode(context, resolveRelativePath(context, module, actualSchemaNode,
692             doSplitXPath(derefArg)));
693         checkArgument(derefTarget != null, "Cannot find deref(%s) target node %s in context of %s", derefArg,
694                 actualSchemaNode);
695         checkArgument(derefTarget instanceof TypedDataSchemaNode, "deref(%s) resolved to non-typed %s", derefArg,
696             derefTarget);
697
698         // We have a deref() target, decide what to do about it
699         final TypeDefinition<?> targetType = ((TypedDataSchemaNode) derefTarget).getType();
700         if (targetType instanceof InstanceIdentifierTypeDefinition) {
701             // Static inference breaks down, we cannot determine where this points to
702             // FIXME: dedicated exception, users can recover from it, derive from IAE
703             throw new UnsupportedOperationException("Cannot infer instance-identifier reference " + targetType);
704         }
705
706         // deref() is define only for instance-identifier and leafref types, handle the latter
707         checkArgument(targetType instanceof LeafrefTypeDefinition, "Illegal target type %s", targetType);
708
709         final PathExpression targetPath = ((LeafrefTypeDefinition) targetType).getPathStatement();
710         LOG.debug("Derefencing path {}", targetPath);
711
712         final SchemaNode deref = targetPath.isAbsolute()
713                 ? findTargetNode(context, actualSchemaNode.getQName().getModule(),
714                     ((LocationPathSteps) targetPath.getSteps()).getLocationPath())
715                         : findDataSchemaNodeForRelativeXPath(context, module, actualSchemaNode, targetPath);
716         if (deref == null) {
717             LOG.debug("Path {} could not be derefenced", targetPath);
718             return null;
719         }
720
721         checkArgument(deref instanceof LeafSchemaNode, "Unexpected %s reference in %s", deref, targetPath);
722
723         final List<String> qnames = doSplitXPath(SPACE.trimLeadingFrom(xpath.substring(paren + 1)));
724         return findTargetNode(context, resolveRelativePath(context, module, deref, qnames));
725     }
726
727     private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final QNameModule defaultModule,
728             final YangLocationPath path) {
729         final Deque<QName> ret = new ArrayDeque<>();
730         for (Step step : path.getSteps()) {
731             if (step instanceof AxisStep) {
732                 // We only support parent axis steps
733                 final YangXPathAxis axis = ((AxisStep) step).getAxis();
734                 checkState(axis == YangXPathAxis.PARENT, "Unexpected axis %s", axis);
735                 ret.removeLast();
736                 continue;
737             }
738
739             // This has to be a QNameStep
740             checkState(step instanceof QNameStep, "Unhandled step %s in %s", step, path);
741             final QName qname;
742             if (step instanceof ResolvedQNameStep) {
743                 qname = ((ResolvedQNameStep) step).getQName();
744             } else if (step instanceof UnresolvedQNameStep) {
745                 final AbstractQName toResolve = ((UnresolvedQNameStep) step).getQName();
746                 // TODO: should handle qualified QNames, too? parser should have resolved them when we get here...
747                 checkState(toResolve instanceof UnqualifiedQName, "Unhandled qname %s in %s", toResolve, path);
748                 qname = QName.create(defaultModule, toResolve.getLocalName());
749             } else {
750                 throw new IllegalStateException("Unhandled step " + step);
751             }
752
753             ret.addLast(qname);
754         }
755
756         return findTargetNode(context, ret);
757     }
758
759     private static @Nullable SchemaNode findTargetNode(final SchemaContext context, final Iterable<QName> qnamePath) {
760         // We do not have enough information about resolution context, hence cannot account for actions, RPCs
761         // and notifications. We therefore attempt to make a best estimate, but this can still fail.
762         final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
763         return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
764     }
765
766     @VisibleForTesting
767     static int normalizeXPath(final List<String> xpath) {
768         LOG.trace("Normalize {}", xpath);
769
770         // We need to make multiple passes here, as the leading XPaths as we can have "../abc/../../def", which really
771         // is "../../def"
772         while (true) {
773             // Next up: count leading ".." components
774             int leadingParents = 0;
775             while (true) {
776                 if (leadingParents == xpath.size()) {
777                     return leadingParents;
778                 }
779                 if (!"..".equals(xpath.get(leadingParents))) {
780                     break;
781                 }
782
783                 ++leadingParents;
784             }
785
786             // Now let's see if there there is a '..' in the rest
787             final int dots = findDots(xpath, leadingParents + 1);
788             if (dots == -1) {
789                 return leadingParents;
790             }
791
792             xpath.remove(dots - 1);
793             xpath.remove(dots - 1);
794             LOG.trace("Next iteration {}", xpath);
795         }
796     }
797
798     private static int findDots(final List<String> xpath, final int startIndex) {
799         for (int i = startIndex; i < xpath.size(); ++i) {
800             if ("..".equals(xpath.get(i))) {
801                 return i;
802             }
803         }
804
805         return -1;
806     }
807
808     private static List<String> doSplitXPath(final String xpath) {
809         return SLASH_SPLITTER.splitToList(xpath);
810     }
811
812     /**
813      * Extracts the base type of node on which schema node points to. If target node is again of type
814      * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
815      *
816      * @param typeDefinition
817      *            type of node which will be extracted
818      * @param schemaContext
819      *            Schema Context
820      * @param schema
821      *            Schema Node
822      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
823      *         is there to preserve backwards compatibility)
824      */
825     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
826             final SchemaContext schemaContext, final SchemaNode schema) {
827         PathExpression pathStatement = typeDefinition.getPathStatement();
828         pathStatement = new PathExpressionImpl(stripConditionsFromXPathString(pathStatement),
829             pathStatement.isAbsolute());
830
831         final DataSchemaNode dataSchemaNode;
832         if (pathStatement.isAbsolute()) {
833             SchemaNode baseSchema = schema;
834             while (baseSchema instanceof DerivableSchemaNode) {
835                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
836                 if (basePotential.isPresent()) {
837                     baseSchema = basePotential.get();
838                 } else {
839                     break;
840                 }
841             }
842
843             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
844             dataSchemaNode = (DataSchemaNode) findDataSchemaNode(schemaContext, parentModule, pathStatement);
845         } else {
846             Module parentModule = findParentModule(schemaContext, schema);
847             dataSchemaNode = (DataSchemaNode) findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema,
848                 pathStatement);
849         }
850
851         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
852         // and current expected behaviour for such cases is to just use pure string
853         // This should throw an exception about incorrect XPath in leafref
854         if (dataSchemaNode == null) {
855             return null;
856         }
857
858         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
859
860         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
861             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
862         }
863
864         return targetTypeDefinition;
865     }
866
867     /**
868      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
869      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
870      * module as typedef which is then imported to referenced module.
871      *
872      * <p>
873      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
874      */
875     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
876             final SchemaContext schemaContext, final QName qname) {
877         final PathExpression pathStatement = typeDefinition.getPathStatement();
878         if (!pathStatement.isAbsolute()) {
879             return null;
880         }
881
882         final PathExpression strippedPathStatement = new PathExpressionImpl(
883             stripConditionsFromXPathString(pathStatement), true);
884
885         final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
886         checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
887
888         final DataSchemaNode dataSchemaNode = (DataSchemaNode) findDataSchemaNode(schemaContext, parentModule.get(),
889             strippedPathStatement);
890         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
891         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
892             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
893         }
894
895         return targetTypeDefinition;
896     }
897
898     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
899             final SchemaNode schemaNode) {
900         checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
901         checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
902
903         TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
904         if (nodeType.getBaseType() != null) {
905             while (nodeType.getBaseType() != null) {
906                 nodeType = nodeType.getBaseType();
907             }
908
909             return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
910         }
911
912         return findParentModule(schemaContext, schemaNode);
913     }
914
915     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
916
917     /**
918      * Removes conditions from xPath pointed to target node.
919      *
920      * @param pathStatement
921      *            xPath to target node
922      * @return string representation of xPath without conditions
923      */
924     @VisibleForTesting
925     static String stripConditionsFromXPathString(final PathExpression pathStatement) {
926         return STRIP_PATTERN.matcher(pathStatement.getOriginalString()).replaceAll("");
927     }
928
929     /**
930      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
931      *
932      * @param node
933      *            a node representing LeafSchemaNode
934      * @return concrete type definition of node value
935      */
936     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
937         TypeDefinition<?> baseType = node.getType();
938         while (baseType.getBaseType() != null) {
939             baseType = baseType.getBaseType();
940         }
941         return baseType;
942     }
943
944     /**
945      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
946      *
947      * @param node
948      *            a node representing LeafListSchemaNode
949      * @return concrete type definition of node value
950      */
951     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
952         TypeDefinition<?> baseType = node.getType();
953         while (baseType.getBaseType() != null) {
954             baseType = baseType.getBaseType();
955         }
956         return baseType;
957     }
958
959     /**
960      * Gets the base type of DataSchemaNode value.
961      *
962      * @param node
963      *            a node representing DataSchemaNode
964      * @return concrete type definition of node value
965      */
966     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
967         if (node instanceof LeafListSchemaNode) {
968             return typeDefinition((LeafListSchemaNode) node);
969         } else if (node instanceof LeafSchemaNode) {
970             return typeDefinition((LeafSchemaNode) node);
971         } else {
972             throw new IllegalArgumentException("Unhandled parameter type: " + node);
973         }
974     }
975 }