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