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