Migrate yang-model-util annotations
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / SchemaContextUtil.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.model.util;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.annotations.VisibleForTesting;
16 import com.google.common.base.Splitter;
17 import com.google.common.collect.Iterables;
18 import java.util.HashSet;
19 import java.util.Iterator;
20 import java.util.LinkedList;
21 import java.util.List;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.regex.Pattern;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.yangtools.yang.common.QName;
28 import org.opendaylight.yangtools.yang.model.api.ActionNodeContainer;
29 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
33 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
40 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
41 import org.opendaylight.yangtools.yang.model.api.NotificationNodeContainer;
42 import org.opendaylight.yangtools.yang.model.api.OperationDefinition;
43 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
44 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
45 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
46 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
48 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
52 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * The Schema Context Util contains support methods for searching through Schema Context modules for specified schema
58  * nodes via Schema Path or Revision Aware XPath. The Schema Context Util is designed as mixin, so it is not
59  * instantiable.
60  */
61 public final class SchemaContextUtil {
62     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
63     private static final Splitter COLON_SPLITTER = Splitter.on(':');
64     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
65
66     private SchemaContextUtil() {
67     }
68
69     /**
70      * Method attempts to find DataSchemaNode in Schema Context via specified
71      * Schema Path. The returned DataSchemaNode from method will be the node at
72      * the end of the SchemaPath. If the DataSchemaNode is not present in the
73      * Schema Context the method will return <code>null</code>. <br>
74      * In case that Schema Context or Schema Path are not specified correctly
75      * (i.e. contains <code>null</code> values) the method will throw
76      * IllegalArgumentException.
77      *
78      * @param context
79      *            Schema Context
80      * @param schemaPath
81      *            Schema Path to search for
82      * @return SchemaNode from the end of the Schema Path or <code>null</code>
83      *         if the Node is not present.
84      * @throws IllegalArgumentException if context or schemaPath is not correct.
85      */
86     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
87         checkArgument(context != null, "Schema Context reference cannot be NULL");
88         checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
89
90         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
91         if (prefixedPath == null) {
92             LOG.debug("Schema path {} has null path", schemaPath);
93             return null;
94         }
95
96         LOG.trace("Looking for path {} in context {}", schemaPath, context);
97         return findNodeInSchemaContext(context, prefixedPath);
98     }
99
100     /**
101      * Method attempts to find DataSchemaNode inside of provided Schema Context
102      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
103      * specified Module MUST be present in Schema Context otherwise the
104      * operation would fail and return <code>null</code>. <br>
105      * The Revision Aware XPath MUST be specified WITHOUT the conditional
106      * statement (i.e. without [cond]) in path, because in this state the Schema
107      * Context is completely unaware of data state and will be not able to
108      * properly resolve XPath. If the XPath contains condition the method will
109      * return IllegalArgumentException. <br>
110      * In case that Schema Context or Module or Revision Aware XPath contains
111      * <code>null</code> references the method will throw
112      * IllegalArgumentException <br>
113      * If the Revision Aware XPath is correct and desired Data Schema Node is
114      * present in Yang module or in depending module in Schema Context the
115      * method will return specified Data Schema Node, otherwise the operation
116      * will fail and method will return <code>null</code>.
117      *
118      * @param context
119      *            Schema Context
120      * @param module
121      *            Yang Module
122      * @param nonCondXPath
123      *            Non Conditional Revision Aware XPath
124      * @return Returns Data Schema Node for specified Schema Context for given
125      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
126      *         DataSchemaNode is not present in Schema Context.
127      */
128     // FIXME: This entire method is ill-defined, as the resolution process depends on  where the XPath is defined --
129     //        notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
130     //        of RFC7950.
131     //
132     //        Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
133     //        a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
134     //        via a derived SchemaContext (i.e. this class would have to have a
135     //
136     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
137     //
138     //        which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
139     //        that feels like an overkill.
140     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
141             final RevisionAwareXPath nonCondXPath) {
142         checkArgument(context != null, "Schema Context reference cannot be NULL");
143         checkArgument(module != null, "Module reference cannot be NULL");
144         checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
145
146         final String strXPath = nonCondXPath.toString();
147         if (strXPath != null) {
148             checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
149             if (nonCondXPath.isAbsolute()) {
150                 final List<QName> path = xpathToQNamePath(context, module, strXPath);
151
152                 // We do not have enough information about resolution context, hence cannot account for actions, RPCs
153                 // and notifications. We therefore attempt to make a best estimate, but this can still fail.
154                 final Optional<DataSchemaNode> pureData = context.findDataTreeChild(path);
155                 return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, path);
156             }
157         }
158         return null;
159     }
160
161     /**
162      * Method attempts to find DataSchemaNode inside of provided Schema Context
163      * and Yang Module accordingly to Non-conditional relative Revision Aware
164      * XPath. The specified Module MUST be present in Schema Context otherwise
165      * the operation would fail and return <code>null</code>. <br>
166      * The relative Revision Aware XPath MUST be specified WITHOUT the
167      * conditional statement (i.e. without [cond]) in path, because in this
168      * state the Schema Context is completely unaware of data state and will be
169      * not able to properly resolve XPath. If the XPath contains condition the
170      * method will return IllegalArgumentException. <br>
171      * The Actual Schema Node MUST be specified correctly because from this
172      * Schema Node will search starts. If the Actual Schema Node is not correct
173      * the operation will simply fail, because it will be unable to find desired
174      * DataSchemaNode. <br>
175      * In case that Schema Context or Module or Actual Schema Node or relative
176      * Revision Aware XPath contains <code>null</code> references the method
177      * will throw IllegalArgumentException <br>
178      * If the Revision Aware XPath doesn't have flag
179      * <code>isAbsolute == false</code> the method will throw
180      * IllegalArgumentException. <br>
181      * If the relative Revision Aware XPath is correct and desired Data Schema
182      * Node is present in Yang module or in depending module in Schema Context
183      * the method will return specified Data Schema Node, otherwise the
184      * operation will fail and method will return <code>null</code>.
185      *
186      * @param context
187      *            Schema Context
188      * @param module
189      *            Yang Module
190      * @param actualSchemaNode
191      *            Actual Schema Node
192      * @param relativeXPath
193      *            Relative Non Conditional Revision Aware XPath
194      * @return DataSchemaNode if is present in specified Schema Context for
195      *         given relative Revision Aware XPath, otherwise will return
196      *         <code>null</code>.
197      */
198     // FIXME: This entire method is ill-defined, as the resolution process depends on  where the XPath is defined --
199     //        notably RPCs, actions and notifications modify the data tree temporarily. See sections 6.4.1 and 9.9.2
200     //        of RFC7950.
201     //
202     //        Most notably we need to understand whether the XPath is being resolved in the data tree, or as part of
203     //        a notification/action/RPC, as then the SchemaContext grows tentative nodes ... which could be addressed
204     //        via a derived SchemaContext (i.e. this class would have to have a
205     //
206     //            SchemaContext notificationSchemaContext(SchemaContext delegate, NotificationDefinition notif)
207     //
208     //        which would then be passed in to a method similar to this one. In static contexts, like MD-SAL codegen,
209     //        that feels like an overkill.
210     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
211             final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
212         checkArgument(context != null, "Schema Context reference cannot be NULL");
213         checkArgument(module != null, "Module reference cannot be NULL");
214         checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
215         checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
216         checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
217                 + "for non relative Revision Aware XPath use findDataSchemaNode method");
218
219         final SchemaPath actualNodePath = actualSchemaNode.getPath();
220         if (actualNodePath != null) {
221             final Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
222
223             // We do not have enough information about resolution context, hence cannot account for actions, RPCs
224             // and notifications. We therefore attempt to make a best estimate, but this can still fail.
225             final Optional<DataSchemaNode> pureData = context.findDataTreeChild(qnamePath);
226             return pureData.isPresent() ? pureData.get() : findNodeInSchemaContext(context, qnamePath);
227         }
228         return null;
229     }
230
231     /**
232      * Returns parent Yang Module for specified Schema Context in which Schema
233      * Node is declared. If the Schema Node is not present in Schema Context the
234      * operation will return <code>null</code>. <br>
235      * If Schema Context or Schema Node contains <code>null</code> references
236      * the method will throw IllegalArgumentException
237      *
238      * @param context
239      *            Schema Context
240      * @param schemaNode
241      *            Schema Node
242      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
243      *         return <code>null</code>
244      */
245     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
246         checkArgument(context != null, "Schema Context reference cannot be NULL!");
247         checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
248         checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not set properly (Schema Path is "
249                 + "NULL)");
250
251         final QName qname = schemaNode.getPath().getLastComponent();
252         checkState(qname != null, "Schema Path contains invalid state of path parts. "
253                 + "The Schema Path MUST contain at least ONE QName  which defines namespace and Local name of path.");
254         return context.findModule(qname.getModule()).orElse(null);
255     }
256
257     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
258         final QName current = path.iterator().next();
259
260         LOG.trace("Looking up module {} in context {}", current, path);
261         final Optional<Module> module = context.findModule(current.getModule());
262         if (!module.isPresent()) {
263             LOG.debug("Module {} not found", current);
264             return null;
265         }
266
267         return findNodeInModule(module.get(), path);
268     }
269
270     /**
271      * Returns NotificationDefinition from Schema Context.
272      *
273      * @param schema SchemaContext in which lookup should be performed.
274      * @param path Schema Path of notification
275      * @return Notification schema or null, if notification is not present in schema context.
276      */
277     @Beta
278     public static @Nullable NotificationDefinition getNotificationSchema(final @NonNull SchemaContext schema,
279             final @NonNull SchemaPath path) {
280         requireNonNull(schema, "Schema context must not be null.");
281         requireNonNull(path, "Schema path must not be null.");
282         for (final NotificationDefinition potential : schema.getNotifications()) {
283             if (path.equals(potential.getPath())) {
284                 return potential;
285             }
286         }
287         return null;
288     }
289
290     /**
291      * Returns RPC Input or Output Data container from RPC definition.
292      *
293      * @param schema SchemaContext in which lookup should be performed.
294      * @param path Schema path of RPC input/output data container
295      * @return Notification schema or null, if notification is not present in schema context.
296      */
297     @Beta
298     public static @Nullable ContainerSchemaNode getRpcDataSchema(final @NonNull SchemaContext schema,
299             final @NonNull SchemaPath path) {
300         requireNonNull(schema, "Schema context must not be null.");
301         requireNonNull(path, "Schema path must not be null.");
302         final Iterator<QName> it = path.getPathFromRoot().iterator();
303         checkArgument(it.hasNext(), "Rpc must have QName.");
304         final QName rpcName = it.next();
305         checkArgument(it.hasNext(), "input or output must be part of path.");
306         final QName inOrOut = it.next();
307         for (final RpcDefinition potential : schema.getOperations()) {
308             if (rpcName.equals(potential.getQName())) {
309                 return SchemaNodeUtils.getRpcDataSchema(potential, inOrOut);
310             }
311         }
312         return null;
313     }
314
315     /**
316      * Extract the identifiers of all modules and submodules which were used to create a particular SchemaContext.
317      *
318      * @param context SchemaContext to be examined
319      * @return Set of ModuleIdentifiers.
320      */
321     public static Set<SourceIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
322         final Set<SourceIdentifier> ret = new HashSet<>();
323
324         for (Module module : context.getModules()) {
325             ret.add(moduleToIdentifier(module));
326
327             for (Module submodule : module.getSubmodules()) {
328                 ret.add(moduleToIdentifier(submodule));
329             }
330         }
331
332         return ret;
333     }
334
335     private static SourceIdentifier moduleToIdentifier(final Module module) {
336         return RevisionSourceIdentifier.create(module.getName(), module.getRevision());
337     }
338
339     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
340         checkArgument(module != null, "Parent reference cannot be NULL");
341         checkArgument(path != null, "Path reference cannot be NULL");
342
343         if (!path.iterator().hasNext()) {
344             LOG.debug("No node matching {} found in node {}", path, module);
345             return null;
346         }
347
348         final QName current = path.iterator().next();
349         LOG.trace("Looking for node {} in module {}", current, module);
350
351         SchemaNode foundNode = null;
352         final Iterable<QName> nextPath = nextLevel(path);
353
354         foundNode = module.getDataChildByName(current);
355         if (foundNode != null && nextPath.iterator().hasNext()) {
356             foundNode = findNodeIn(foundNode, nextPath);
357         }
358
359         if (foundNode == null) {
360             foundNode = getGroupingByName(module, current);
361             if (foundNode != null && nextPath.iterator().hasNext()) {
362                 foundNode = findNodeIn(foundNode, nextPath);
363             }
364         }
365
366         if (foundNode == null) {
367             foundNode = getRpcByName(module, current);
368             if (foundNode != null && nextPath.iterator().hasNext()) {
369                 foundNode = findNodeIn(foundNode, nextPath);
370             }
371         }
372
373         if (foundNode == null) {
374             foundNode = getNotificationByName(module, current);
375             if (foundNode != null && nextPath.iterator().hasNext()) {
376                 foundNode = findNodeIn(foundNode, nextPath);
377             }
378         }
379
380         if (foundNode == null) {
381             LOG.debug("No node matching {} found in node {}", path, module);
382         }
383
384         return foundNode;
385
386     }
387
388     private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
389         checkArgument(parent != null, "Parent reference cannot be NULL");
390         checkArgument(path != null, "Path reference cannot be NULL");
391
392         if (!path.iterator().hasNext()) {
393             LOG.debug("No node matching {} found in node {}", path, parent);
394             return null;
395         }
396
397         final QName current = path.iterator().next();
398         LOG.trace("Looking for node {} in node {}", current, parent);
399
400         SchemaNode foundNode = null;
401         final Iterable<QName> nextPath = nextLevel(path);
402
403         if (parent instanceof DataNodeContainer) {
404             final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
405
406             foundNode = parentDataNodeContainer.getDataChildByName(current);
407             if (foundNode != null && nextPath.iterator().hasNext()) {
408                 foundNode = findNodeIn(foundNode, nextPath);
409             }
410
411             if (foundNode == null) {
412                 foundNode = getGroupingByName(parentDataNodeContainer, current);
413                 if (foundNode != null && nextPath.iterator().hasNext()) {
414                     foundNode = findNodeIn(foundNode, nextPath);
415                 }
416             }
417         }
418
419         if (foundNode == null && parent instanceof ActionNodeContainer) {
420             foundNode = ((ActionNodeContainer) parent).getActions().stream()
421                     .filter(act -> current.equals(act.getQName())).findFirst().orElse(null);
422             if (foundNode != null && nextPath.iterator().hasNext()) {
423                 foundNode = findNodeIn(foundNode, nextPath);
424             }
425         }
426
427         if (foundNode == null && parent instanceof NotificationNodeContainer) {
428             foundNode = ((NotificationNodeContainer) parent).getNotifications().stream()
429                     .filter(notif -> current.equals(notif.getQName())).findFirst().orElse(null);
430             if (foundNode != null && nextPath.iterator().hasNext()) {
431                 foundNode = findNodeIn(foundNode, nextPath);
432             }
433         }
434
435         if (foundNode == null && parent instanceof OperationDefinition) {
436             final OperationDefinition parentRpcDefinition = (OperationDefinition) parent;
437
438             if (current.getLocalName().equals("input")) {
439                 foundNode = parentRpcDefinition.getInput();
440                 if (foundNode != null && nextPath.iterator().hasNext()) {
441                     foundNode = findNodeIn(foundNode, nextPath);
442                 }
443             }
444
445             if (current.getLocalName().equals("output")) {
446                 foundNode = parentRpcDefinition.getOutput();
447                 if (foundNode != null && nextPath.iterator().hasNext()) {
448                     foundNode = findNodeIn(foundNode, nextPath);
449                 }
450             }
451
452             if (foundNode == null) {
453                 foundNode = getGroupingByName(parentRpcDefinition, current);
454                 if (foundNode != null && nextPath.iterator().hasNext()) {
455                     foundNode = findNodeIn(foundNode, nextPath);
456                 }
457             }
458         }
459
460         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
461             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
462
463             if (foundNode != null && nextPath.iterator().hasNext()) {
464                 foundNode = findNodeIn(foundNode, nextPath);
465             }
466
467             if (foundNode == null) {
468                 // fallback that tries to map into one of the child cases
469                 for (final CaseSchemaNode caseNode : ((ChoiceSchemaNode) parent).getCases().values()) {
470                     final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
471                     if (maybeChild != null) {
472                         foundNode = findNodeIn(maybeChild, nextPath);
473                         break;
474                     }
475                 }
476             }
477         }
478
479         if (foundNode == null) {
480             LOG.debug("No node matching {} found in node {}", path, parent);
481         }
482
483         return foundNode;
484
485     }
486
487     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
488         return Iterables.skip(path, 1);
489     }
490
491     private static RpcDefinition getRpcByName(final Module module, final QName name) {
492         for (final RpcDefinition rpc : module.getRpcs()) {
493             if (rpc.getQName().equals(name)) {
494                 return rpc;
495             }
496         }
497         return null;
498     }
499
500     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
501         for (final NotificationDefinition notification : module.getNotifications()) {
502             if (notification.getQName().equals(name)) {
503                 return notification;
504             }
505         }
506         return null;
507     }
508
509     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
510         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
511             if (grouping.getQName().equals(name)) {
512                 return grouping;
513             }
514         }
515         return null;
516     }
517
518     private static GroupingDefinition getGroupingByName(final OperationDefinition rpc, final QName name) {
519         for (final GroupingDefinition grouping : rpc.getGroupings()) {
520             if (grouping.getQName().equals(name)) {
521                 return grouping;
522             }
523         }
524         return null;
525     }
526
527     /**
528      * Transforms string representation of XPath to Queue of QNames. The XPath
529      * is split by "/" and for each part of XPath is assigned correct module in
530      * Schema Path. <br>
531      * If Schema Context, Parent Module or XPath string contains
532      * <code>null</code> values, the method will throws IllegalArgumentException
533      *
534      * @param context
535      *            Schema Context
536      * @param parentModule
537      *            Parent Module
538      * @param xpath
539      *            XPath String
540      * @return return a list of QName
541      *
542      * @throws IllegalArgumentException if any arguments are null
543      *
544      */
545     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
546             final String xpath) {
547         // FIXME: 3.0.0: this should throw NPE, not IAE
548         checkArgument(context != null, "Schema Context reference cannot be NULL");
549         checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
550         checkArgument(xpath != null, "XPath string reference cannot be NULL");
551
552         final List<QName> path = new LinkedList<>();
553         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
554             if (!pathComponent.isEmpty()) {
555                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
556             }
557         }
558         return path;
559     }
560
561     /**
562      * Transforms part of Prefixed Path as java String to QName. <br>
563      * If the string contains module prefix separated by ":" (i.e.
564      * mod:container) this module is provided from from Parent Module list of
565      * imports. If the Prefixed module is present in Schema Context the QName
566      * can be constructed. <br>
567      * If the Prefixed Path Part does not contains prefix the Parent's Module
568      * namespace is taken for construction of QName. <br>
569      * If Schema Context, Parent Module or Prefixed Path Part refers to
570      * <code>null</code> the method will throw IllegalArgumentException
571      *
572      * @param context Schema Context
573      * @param parentModule Parent Module
574      * @param prefixedPathPart Prefixed Path Part string
575      * @return QName from prefixed Path Part String.
576      * @throws IllegalArgumentException if any arguments are null
577      */
578     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
579             final String prefixedPathPart) {
580         // FIXME: 3.0.0: this should throw NPE, not IAE
581         checkArgument(context != null, "Schema Context reference cannot be NULL");
582         checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
583         checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
584
585         if (prefixedPathPart.indexOf(':') != -1) {
586             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
587             final String modulePrefix = prefixedName.next();
588
589             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
590             checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
591                     modulePrefix, parentModule.getName());
592
593             return QName.create(module.getQNameModule(), prefixedName.next());
594         }
595
596         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
597     }
598
599     /**
600      * Method will attempt to resolve and provide Module reference for specified module prefix. Each Yang module could
601      * contains multiple imports which MUST be associated with corresponding module prefix. The method simply looks into
602      * module imports and returns the module that is bounded with specified prefix. If the prefix is not present
603      * in module or the prefixed module is not present in specified Schema Context, the method will return {@code null}.
604      * <br>
605      * If String prefix is the same as prefix of the specified Module the reference to this module is returned.<br>
606      * If Schema Context, Module or Prefix are referring to {@code null} the method will throw IllegalArgumentException.
607      *
608      * @param context Schema Context
609      * @param module Yang Module
610      * @param prefix Module Prefix
611      * @return Module for given prefix in specified Schema Context if is present, otherwise returns <code>null</code>
612      * @throws IllegalArgumentException if any arguments are null
613      */
614     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
615             final String prefix) {
616         // FIXME: 3.0.0: this should throw NPE, not IAE
617         checkArgument(context != null, "Schema Context reference cannot be NULL");
618         checkArgument(module != null, "Module reference cannot be NULL");
619         checkArgument(prefix != null, "Prefix string cannot be NULL");
620
621         if (prefix.equals(module.getPrefix())) {
622             return module;
623         }
624
625         final Set<ModuleImport> imports = module.getImports();
626         for (final ModuleImport mi : imports) {
627             if (prefix.equals(mi.getPrefix())) {
628                 return context.findModule(mi.getModuleName(), mi.getRevision()).orElse(null);
629             }
630         }
631         return null;
632     }
633
634     /**
635      * Resolve a relative XPath into a set of QNames.
636      *
637      * @param context
638      *            Schema Context
639      * @param module
640      *            Yang Module
641      * @param relativeXPath
642      *            Non conditional Revision Aware Relative XPath
643      * @param actualSchemaNode
644      *            actual schema node
645      * @return list of QName
646      * @throws IllegalArgumentException if any arguments are null
647      */
648     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
649             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
650         // FIXME: 3.0.0: this should throw NPE, not IAE
651         checkArgument(context != null, "Schema Context reference cannot be NULL");
652         checkArgument(module != null, "Module reference cannot be NULL");
653         checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
654         checkState(!relativeXPath.isAbsolute(), "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
655                 + "for non relative Revision Aware XPath use findDataSchemaNode method");
656         checkState(actualSchemaNode.getPath() != null,
657                 "Schema Path reference for Leafref cannot be NULL");
658
659         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
660
661         // Find out how many "parent" components there are
662         // FIXME: is .contains() the right check here?
663         // FIXME: case ../../node1/node2/../node3/../node4
664         int colCount = 0;
665         for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
666             ++colCount;
667         }
668
669         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
670
671         if (Iterables.size(schemaNodePath) - colCount >= 0) {
672             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
673                 Iterables.transform(Iterables.skip(xpaths, colCount),
674                     input -> stringPathPartToQName(context, module, input)));
675         }
676         return Iterables.concat(schemaNodePath,
677                 Iterables.transform(Iterables.skip(xpaths, colCount),
678                     input -> stringPathPartToQName(context, module, input)));
679     }
680
681     /**
682      * Extracts the base type of node on which schema node points to. If target node is again of type
683      * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
684      *
685      * @param typeDefinition
686      *            type of node which will be extracted
687      * @param schemaContext
688      *            Schema Context
689      * @param schema
690      *            Schema Node
691      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
692      *         is there to preserve backwards compatibility)
693      */
694     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
695             final SchemaContext schemaContext, final SchemaNode schema) {
696         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
697         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
698             pathStatement.isAbsolute());
699
700         final DataSchemaNode dataSchemaNode;
701         if (pathStatement.isAbsolute()) {
702             SchemaNode baseSchema = schema;
703             while (baseSchema instanceof DerivableSchemaNode) {
704                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
705                 if (basePotential.isPresent()) {
706                     baseSchema = basePotential.get();
707                 } else {
708                     break;
709                 }
710             }
711
712             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
713             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
714                     pathStatement);
715         } else {
716             Module parentModule = findParentModule(schemaContext, schema);
717             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
718                     parentModule, schema, pathStatement);
719         }
720
721         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
722         // and current expected behaviour for such cases is to just use pure string
723         // This should throw an exception about incorrect XPath in leafref
724         if (dataSchemaNode == null) {
725             return null;
726         }
727
728         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
729
730         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
731             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
732         }
733
734         return targetTypeDefinition;
735     }
736
737     /**
738      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
739      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
740      * module as typedef which is then imported to referenced module.
741      *
742      * <p>
743      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
744      */
745     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
746             final SchemaContext schemaContext, final QName qname) {
747         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
748         final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
749             stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
750         if (!strippedPathStatement.isAbsolute()) {
751             return null;
752         }
753
754         final Optional<Module> parentModule = schemaContext.findModule(qname.getModule());
755         checkArgument(parentModule.isPresent(), "Failed to find parent module for %s", qname);
756
757         final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
758             parentModule.get(), strippedPathStatement);
759         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
760         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
761             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
762         }
763
764         return targetTypeDefinition;
765     }
766
767     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
768             final SchemaNode schemaNode) {
769         checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
770         checkArgument(schemaNode instanceof TypedDataSchemaNode, "Unsupported node %s", schemaNode);
771
772         TypeDefinition<?> nodeType = ((TypedDataSchemaNode) schemaNode).getType();
773         if (nodeType.getBaseType() != null) {
774             while (nodeType.getBaseType() != null) {
775                 nodeType = nodeType.getBaseType();
776             }
777
778             return schemaContext.findModule(nodeType.getQName().getModule()).orElse(null);
779         }
780
781         return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
782     }
783
784     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
785
786     /**
787      * Removes conditions from xPath pointed to target node.
788      *
789      * @param pathStatement
790      *            xPath to target node
791      * @return string representation of xPath without conditions
792      */
793     @VisibleForTesting
794     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
795         return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
796     }
797
798     /**
799      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
800      *
801      * @param node
802      *            a node representing LeafSchemaNode
803      * @return concrete type definition of node value
804      */
805     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
806         TypeDefinition<?> baseType = node.getType();
807         while (baseType.getBaseType() != null) {
808             baseType = baseType.getBaseType();
809         }
810         return baseType;
811     }
812
813     /**
814      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
815      *
816      * @param node
817      *            a node representing LeafListSchemaNode
818      * @return concrete type definition of node value
819      */
820     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
821         TypeDefinition<?> baseType = node.getType();
822         while (baseType.getBaseType() != null) {
823             baseType = baseType.getBaseType();
824         }
825         return baseType;
826     }
827
828     /**
829      * Gets the base type of DataSchemaNode value.
830      *
831      * @param node
832      *            a node representing DataSchemaNode
833      * @return concrete type definition of node value
834      */
835     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
836         if (node instanceof LeafListSchemaNode) {
837             return typeDefinition((LeafListSchemaNode) node);
838         } else if (node instanceof LeafSchemaNode) {
839             return typeDefinition((LeafSchemaNode) node);
840         } else {
841             throw new IllegalArgumentException("Unhandled parameter type: " + node);
842         }
843     }
844 }