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