6eb4062712c3d0833f08879834ece069ee3c849e
[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.common.QNameModule;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
27 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
33 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
34 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.Module;
36 import org.opendaylight.yangtools.yang.model.api.ModuleIdentifier;
37 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
38 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
39 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
40 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
41 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
42 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
44 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
45 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
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.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
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 Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
233         if (module == null) {
234             LOG.debug("Module {} not found", current);
235             return null;
236         }
237
238         return findNodeInModule(module, 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<ModuleIdentifier> getConstituentModuleIdentifiers(final SchemaContext context) {
295         final Set<ModuleIdentifier> 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 ModuleIdentifier moduleToIdentifier(final Module module) {
309         return ModuleIdentifierImpl.create(module.getName(), Optional.of(module.getNamespace()),
310             Optional.of(module.getRevision()));
311     }
312
313     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
314
315         Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
316         Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
317
318         if (!path.iterator().hasNext()) {
319             LOG.debug("No node matching {} found in node {}", path, module);
320             return null;
321         }
322
323         final QName current = path.iterator().next();
324         LOG.trace("Looking for node {} in module {}", current, module);
325
326         SchemaNode foundNode = null;
327         final Iterable<QName> nextPath = nextLevel(path);
328
329         foundNode = module.getDataChildByName(current);
330         if (foundNode != null && nextPath.iterator().hasNext()) {
331             foundNode = findNodeIn(foundNode, nextPath);
332         }
333
334         if (foundNode == null) {
335             foundNode = getGroupingByName(module, current);
336             if (foundNode != null && nextPath.iterator().hasNext()) {
337                 foundNode = findNodeIn(foundNode, nextPath);
338             }
339         }
340
341         if (foundNode == null) {
342             foundNode = getRpcByName(module, current);
343             if (foundNode != null && nextPath.iterator().hasNext()) {
344                 foundNode = findNodeIn(foundNode, nextPath);
345             }
346         }
347
348         if (foundNode == null) {
349             foundNode = getNotificationByName(module, current);
350             if (foundNode != null && nextPath.iterator().hasNext()) {
351                 foundNode = findNodeIn(foundNode, nextPath);
352             }
353         }
354
355         if (foundNode == null) {
356             LOG.debug("No node matching {} found in node {}", path, module);
357         }
358
359         return foundNode;
360
361     }
362
363     private static SchemaNode findNodeIn(final SchemaNode parent, final Iterable<QName> path) {
364
365         Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
366         Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
367
368         if (!path.iterator().hasNext()) {
369             LOG.debug("No node matching {} found in node {}", path, parent);
370             return null;
371         }
372
373         final QName current = path.iterator().next();
374         LOG.trace("Looking for node {} in node {}", current, parent);
375
376         SchemaNode foundNode = null;
377         final Iterable<QName> nextPath = nextLevel(path);
378
379         if (parent instanceof DataNodeContainer) {
380             final DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
381
382             foundNode = parentDataNodeContainer.getDataChildByName(current);
383             if (foundNode != null && nextPath.iterator().hasNext()) {
384                 foundNode = findNodeIn(foundNode, nextPath);
385             }
386
387             if (foundNode == null) {
388                 foundNode = getGroupingByName(parentDataNodeContainer, current);
389                 if (foundNode != null && nextPath.iterator().hasNext()) {
390                     foundNode = findNodeIn(foundNode, nextPath);
391                 }
392             }
393         }
394
395         if (foundNode == null && parent instanceof RpcDefinition) {
396             final RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
397
398             if (current.getLocalName().equals("input")) {
399                 foundNode = parentRpcDefinition.getInput();
400                 if (foundNode != null && nextPath.iterator().hasNext()) {
401                     foundNode = findNodeIn(foundNode, nextPath);
402                 }
403             }
404
405             if (current.getLocalName().equals("output")) {
406                 foundNode = parentRpcDefinition.getOutput();
407                 if (foundNode != null && nextPath.iterator().hasNext()) {
408                     foundNode = findNodeIn(foundNode, nextPath);
409                 }
410             }
411
412             if (foundNode == null) {
413                 foundNode = getGroupingByName(parentRpcDefinition, current);
414                 if (foundNode != null && nextPath.iterator().hasNext()) {
415                     foundNode = findNodeIn(foundNode, nextPath);
416                 }
417             }
418         }
419
420         if (foundNode == null && parent instanceof ChoiceSchemaNode) {
421             foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
422
423             if (foundNode != null && nextPath.iterator().hasNext()) {
424                 foundNode = findNodeIn(foundNode, nextPath);
425             }
426
427             if (foundNode == null) {
428                 // fallback that tries to map into one of the child cases
429                 for (final ChoiceCaseNode caseNode : ((ChoiceSchemaNode) parent).getCases()) {
430                     final DataSchemaNode maybeChild = caseNode.getDataChildByName(current);
431                     if (maybeChild != null) {
432                         foundNode = findNodeIn(maybeChild, nextPath);
433                         break;
434                     }
435                 }
436             }
437         }
438
439         if (foundNode == null) {
440             LOG.debug("No node matching {} found in node {}", path, parent);
441         }
442
443         return foundNode;
444
445     }
446
447     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
448         return Iterables.skip(path, 1);
449     }
450
451     private static RpcDefinition getRpcByName(final Module module, final QName name) {
452         for (final RpcDefinition rpc : module.getRpcs()) {
453             if (rpc.getQName().equals(name)) {
454                 return rpc;
455             }
456         }
457         return null;
458     }
459
460     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
461         for (final NotificationDefinition notification : module.getNotifications()) {
462             if (notification.getQName().equals(name)) {
463                 return notification;
464             }
465         }
466         return null;
467     }
468
469     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
470         for (final GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
471             if (grouping.getQName().equals(name)) {
472                 return grouping;
473             }
474         }
475         return null;
476     }
477
478     private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
479         for (final GroupingDefinition grouping : rpc.getGroupings()) {
480             if (grouping.getQName().equals(name)) {
481                 return grouping;
482             }
483         }
484         return null;
485     }
486
487     /**
488      * Transforms string representation of XPath to Queue of QNames. The XPath
489      * is split by "/" and for each part of XPath is assigned correct module in
490      * Schema Path. <br>
491      * If Schema Context, Parent Module or XPath string contains
492      * <code>null</code> values, the method will throws IllegalArgumentException
493      *
494      * @param context
495      *            Schema Context
496      * @param parentModule
497      *            Parent Module
498      * @param xpath
499      *            XPath String
500      * @return return a list of QName
501      *
502      * @throws IllegalArgumentException if any arguments are null
503      *
504      */
505     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
506             final String xpath) {
507         // FIXME: 2.0.0: this should throw NPE, not IAE
508         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
509         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
510         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
511
512         final List<QName> path = new LinkedList<>();
513         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
514             if (!pathComponent.isEmpty()) {
515                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
516             }
517         }
518         return path;
519     }
520
521     /**
522      * Transforms part of Prefixed Path as java String to QName. <br>
523      * If the string contains module prefix separated by ":" (i.e.
524      * mod:container) this module is provided from from Parent Module list of
525      * imports. If the Prefixed module is present in Schema Context the QName
526      * can be constructed. <br>
527      * If the Prefixed Path Part does not contains prefix the Parent's Module
528      * namespace is taken for construction of QName. <br>
529      * If Schema Context, Parent Module or Prefixed Path Part refers to
530      * <code>null</code> the method will throw IllegalArgumentException
531      *
532      * @param context
533      *            Schema Context
534      * @param parentModule
535      *            Parent Module
536      * @param prefixedPathPart
537      *            Prefixed Path Part string
538      * @return QName from prefixed Path Part String.
539      * @throws IllegalArgumentException if any arguments are null
540      */
541     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
542             final String prefixedPathPart) {
543         // FIXME: 2.0.0: this should throw NPE, not IAE
544         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
545         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
546         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
547
548         if (prefixedPathPart.indexOf(':') != -1) {
549             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
550             final String modulePrefix = prefixedName.next();
551
552             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
553             Preconditions.checkArgument(module != null,
554                     "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
555                     parentModule.getName());
556
557             return QName.create(module.getQNameModule(), prefixedName.next());
558         }
559
560         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
561     }
562
563     /**
564      * Method will attempt to resolve and provide Module reference for specified
565      * module prefix. Each Yang module could contains multiple imports which
566      * MUST be associated with corresponding module prefix. The method simply
567      * looks into module imports and returns the module that is bounded with
568      * specified prefix. If the prefix is not present in module or the prefixed
569      * module is not present in specified Schema Context, the method will return
570      * <code>null</code>. <br>
571      * If String prefix is the same as prefix of the specified Module the
572      * reference to this module is returned. <br>
573      * If Schema Context, Module or Prefix are referring to <code>null</code>
574      * the method will return IllegalArgumentException
575      *
576      * @param context
577      *            Schema Context
578      * @param module
579      *            Yang Module
580      * @param prefix
581      *            Module Prefix
582      * @return Module for given prefix in specified Schema Context if is
583      *         present, otherwise returns <code>null</code>
584      * @throws IllegalArgumentException if any arguments are null
585      */
586     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
587             final String prefix) {
588         // FIXME: 2.0.0: this should throw NPE, not IAE
589         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
590         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
591         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
592
593         if (prefix.equals(module.getPrefix())) {
594             return module;
595         }
596
597         final Set<ModuleImport> imports = module.getImports();
598         for (final ModuleImport mi : imports) {
599             if (prefix.equals(mi.getPrefix())) {
600                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
601             }
602         }
603         return null;
604     }
605
606     /**
607      * Resolve a relative XPath into a set of QNames.
608      *
609      * @param context
610      *            Schema Context
611      * @param module
612      *            Yang Module
613      * @param relativeXPath
614      *            Non conditional Revision Aware Relative XPath
615      * @param actualSchemaNode
616      *            actual schema node
617      * @return list of QName
618      * @throws IllegalArgumentException if any arguments are null
619      */
620     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
621             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
622         // FIXME: 2.0.0: this should throw NPE, not IAE
623         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
624         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
625         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
626         Preconditions.checkState(!relativeXPath.isAbsolute(),
627                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
628                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
629         Preconditions.checkState(actualSchemaNode.getPath() != null,
630                 "Schema Path reference for Leafref cannot be NULL");
631
632         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
633
634         // Find out how many "parent" components there are
635         // FIXME: is .contains() the right check here?
636         // FIXME: case ../../node1/node2/../node3/../node4
637         int colCount = 0;
638         for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
639             ++colCount;
640         }
641
642         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
643
644         if (Iterables.size(schemaNodePath) - colCount >= 0) {
645             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
646                 Iterables.transform(Iterables.skip(xpaths, colCount),
647                     input -> stringPathPartToQName(context, module, input)));
648         }
649         return Iterables.concat(schemaNodePath,
650                 Iterables.transform(Iterables.skip(xpaths, colCount),
651                     input -> stringPathPartToQName(context, module, input)));
652     }
653
654     /**
655      * Extracts the base type of node on which schema node points to. If target node is again of type
656      * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
657      *
658      * @param typeDefinition
659      *            type of node which will be extracted
660      * @param schemaContext
661      *            Schema Context
662      * @param schema
663      *            Schema Node
664      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
665      *         is there to preserve backwards compatibility)
666      */
667     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
668             final SchemaContext schemaContext, final SchemaNode schema) {
669         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
670         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
671             pathStatement.isAbsolute());
672
673         final DataSchemaNode dataSchemaNode;
674         if (pathStatement.isAbsolute()) {
675             SchemaNode baseSchema = schema;
676             while (baseSchema instanceof DerivableSchemaNode) {
677                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
678                 if (basePotential.isPresent()) {
679                     baseSchema = basePotential.get();
680                 } else {
681                     break;
682                 }
683             }
684
685             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
686             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
687                     pathStatement);
688         } else {
689             Module parentModule = findParentModule(schemaContext, schema);
690             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
691                     parentModule, schema, pathStatement);
692         }
693
694         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
695         // and current expected behaviour for such cases is to just use pure string
696         // This should throw an exception about incorrect XPath in leafref
697         if (dataSchemaNode == null) {
698             return null;
699         }
700
701         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
702
703         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
704             return getBaseTypeForLeafRef((LeafrefTypeDefinition) targetTypeDefinition, schemaContext, dataSchemaNode);
705         }
706
707         return targetTypeDefinition;
708     }
709
710     /**
711      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qname}. This handle
712      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
713      * module as typedef which is then imported to referenced module.
714      *
715      * <p>
716      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
717      */
718     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
719             final SchemaContext schemaContext, final QName qname) {
720         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
721         final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
722             stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
723         if (!strippedPathStatement.isAbsolute()) {
724             return null;
725         }
726
727         final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
728                 qname.getRevision());
729         final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
730             parentModule, 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             final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
751             return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
752                     typeDefModuleQname.getRevision());
753         }
754
755         return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
756     }
757
758     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
759
760     /**
761      * Removes conditions from xPath pointed to target node.
762      *
763      * @param pathStatement
764      *            xPath to target node
765      * @return string representation of xPath without conditions
766      */
767     @VisibleForTesting
768     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
769         return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
770     }
771
772     /**
773      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
774      *
775      * @param node
776      *            a node representing LeafSchemaNode
777      * @return concrete type definition of node value
778      */
779     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
780         TypeDefinition<?> baseType = node.getType();
781         while (baseType.getBaseType() != null) {
782             baseType = baseType.getBaseType();
783         }
784         return baseType;
785     }
786
787     /**
788      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
789      *
790      * @param node
791      *            a node representing LeafListSchemaNode
792      * @return concrete type definition of node value
793      */
794     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
795         TypeDefinition<?> baseType = node.getType();
796         while (baseType.getBaseType() != null) {
797             baseType = baseType.getBaseType();
798         }
799         return baseType;
800     }
801
802     /**
803      * Gets the base type of DataSchemaNode value.
804      *
805      * @param node
806      *            a node representing DataSchemaNode
807      * @return concrete type definition of node value
808      */
809     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
810         if (node instanceof LeafListSchemaNode) {
811             return typeDefinition((LeafListSchemaNode) node);
812         } else if (node instanceof LeafSchemaNode) {
813             return typeDefinition((LeafSchemaNode) node);
814         } else {
815             throw new IllegalArgumentException("Unhandled parameter type: " + node);
816         }
817     }
818 }