Use lambdas instead of anonymous classes
[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.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Splitter;
15 import com.google.common.collect.Iterables;
16 import java.util.Collections;
17 import java.util.Iterator;
18 import java.util.LinkedList;
19 import java.util.List;
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.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.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<>();
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),
603                     input -> stringPathPartToQName(context, module, input)));
604         }
605         return Iterables.concat(schemaNodePath,
606                 Iterables.transform(Iterables.skip(xpaths, colCount),
607                     input -> stringPathPartToQName(context, module, input)));
608     }
609
610     /**
611      * 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
612      * type definition.
613      *
614      * @param typeDefinition
615      *            type of node which will be extracted
616      * @param schemaContext
617      *            Schema Context
618      * @param schema
619      *            Schema Node
620      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
621      */
622     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
623         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
624         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
625
626         final DataSchemaNode dataSchemaNode;
627         if (pathStatement.isAbsolute()) {
628             SchemaNode baseSchema = schema;
629             while (baseSchema instanceof DerivableSchemaNode) {
630                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
631                 if (basePotential.isPresent()) {
632                     baseSchema = basePotential.get();
633                 } else {
634                     break;
635                 }
636             }
637
638             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
639             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
640                     pathStatement);
641         } else {
642             Module parentModule = findParentModule(schemaContext, schema);
643             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
644                     parentModule, schema, pathStatement);
645         }
646
647         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
648         // and current expected behaviour for such cases is to just use pure string
649         // This should throw an exception about incorrect XPath in leafref
650         if (dataSchemaNode == null) {
651             return null;
652         }
653
654         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
655
656         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
657             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
658         } else {
659             return targetTypeDefinition;
660         }
661     }
662
663     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
664             final SchemaNode schemaNode) {
665         Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
666         Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
667
668         TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
669         if (nodeType.getBaseType() != null) {
670             while (nodeType.getBaseType() != null) {
671                 nodeType = nodeType.getBaseType();
672             }
673
674             final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
675             return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
676                     typeDefModuleQname.getRevision());
677         }
678
679         return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
680     }
681
682     /**
683      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle case
684      * when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other module as typedef
685      * which is then imported to referenced module.
686      *
687      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
688      *
689      * @param typeDefinition
690      * @param schemaContext
691      * @param qName
692      * @return
693      */
694     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
695             final SchemaContext schemaContext, final QName qName) {
696         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
697         final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
698         if (!strippedPathStatement.isAbsolute()) {
699             return null;
700         }
701
702         final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace(),qName.getRevision());
703         final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, strippedPathStatement);
704         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
705         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
706             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
707         } else {
708             return targetTypeDefinition;
709         }
710     }
711
712     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
713
714     /**
715      * Removes conditions from xPath pointed to target node.
716      *
717      * @param pathStatement
718      *            xPath to target node
719      * @return string representation of xPath without conditions
720      *
721      */
722     @VisibleForTesting
723     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
724         return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
725     }
726
727     /**
728      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
729      *
730      * @param node
731      *            a node representing LeafSchemaNode
732      * @return concrete type definition of node value
733      */
734     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
735         TypeDefinition<?> baseType = node.getType();
736         while (baseType.getBaseType() != null) {
737             baseType = baseType.getBaseType();
738         }
739         return baseType;
740     }
741
742     /**
743      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
744      *
745      * @param node
746      *            a node representing LeafListSchemaNode
747      * @return concrete type definition of node value
748      */
749     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
750         TypeDefinition<?> baseType = node.getType();
751         while (baseType.getBaseType() != null) {
752             baseType = baseType.getBaseType();
753         }
754         return baseType;
755     }
756
757     /**
758      * Gets the base type of DataSchemaNode value.
759      *
760      * @param node
761      *            a node representing DataSchemaNode
762      * @return concrete type definition of node value
763      */
764     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
765         if (node instanceof LeafListSchemaNode) {
766             return typeDefinition((LeafListSchemaNode) node);
767         } else if (node instanceof LeafSchemaNode) {
768             return typeDefinition((LeafSchemaNode) node);
769         } else {
770             throw new IllegalArgumentException("Unhandled parameter types: " + Collections.<Object>singletonList(node).toString());
771         }
772     }
773 }