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