Cleanup SchemaContextUtil
[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.Iterator;
17 import java.util.LinkedList;
18 import java.util.List;
19 import java.util.Set;
20 import java.util.regex.Pattern;
21 import javax.annotation.Nonnull;
22 import javax.annotation.Nullable;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.common.QNameModule;
25 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
27 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
28 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
31 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
35 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
36 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
37 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.TypedSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 /**
48  * The Schema Context Util contains support methods for searching through Schema
49  * Context modules for specified schema nodes via Schema Path or Revision Aware
50  * XPath. The Schema Context Util is designed as mixin, so it is not
51  * instantiable.
52  *
53  */
54 public final class SchemaContextUtil {
55     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
56     private static final Splitter COLON_SPLITTER = Splitter.on(':');
57     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
58
59     private SchemaContextUtil() {
60     }
61
62     /**
63      * Method attempts to find DataSchemaNode in Schema Context via specified
64      * Schema Path. The returned DataSchemaNode from method will be the node at
65      * the end of the SchemaPath. If the DataSchemaNode is not present in the
66      * Schema Context the method will return <code>null</code>. <br>
67      * In case that Schema Context or Schema Path are not specified correctly
68      * (i.e. contains <code>null</code> values) the method will return
69      * IllegalArgumentException.
70      *
71      * @param context
72      *            Schema Context
73      * @param schemaPath
74      *            Schema Path to search for
75      * @return SchemaNode from the end of the Schema Path or <code>null</code>
76      *         if the Node is not present.
77      *
78      * @throws IllegalArgumentException
79      */
80     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
81         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
82         Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
83
84         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
85         if (prefixedPath == null) {
86             LOG.debug("Schema path {} has null path", schemaPath);
87             return null;
88         }
89
90         LOG.trace("Looking for path {} in context {}", schemaPath, context);
91         return findNodeInSchemaContext(context, prefixedPath);
92     }
93
94     /**
95      * Method attempts to find DataSchemaNode inside of provided Schema Context
96      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
97      * specified Module MUST be present in Schema Context otherwise the
98      * operation would fail and return <code>null</code>. <br>
99      * The Revision Aware XPath MUST be specified WITHOUT the conditional
100      * statement (i.e. without [cond]) in path, because in this state the Schema
101      * Context is completely unaware of data state and will be not able to
102      * properly resolve XPath. If the XPath contains condition the method will
103      * return IllegalArgumentException. <br>
104      * In case that Schema Context or Module or Revision Aware XPath contains
105      * <code>null</code> references the method will throw
106      * IllegalArgumentException <br>
107      * If the Revision Aware XPath is correct and desired Data Schema Node is
108      * present in Yang module or in depending module in Schema Context the
109      * method will return specified Data Schema Node, otherwise the operation
110      * will fail and method will return <code>null</code>.
111      *
112      * @param context
113      *            Schema Context
114      * @param module
115      *            Yang Module
116      * @param nonCondXPath
117      *            Non Conditional Revision Aware XPath
118      * @return Returns Data Schema Node for specified Schema Context for given
119      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
120      *         DataSchemaNode is not present in Schema Context.
121      * @throws IllegalArgumentException
122      */
123     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module,
124             final RevisionAwareXPath nonCondXPath) {
125         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
126         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
127         Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
128
129         final String strXPath = nonCondXPath.toString();
130         if (strXPath != null) {
131             Preconditions.checkArgument(strXPath.indexOf('[') == -1,
132                     "Revision Aware XPath may not contain a condition");
133             if (nonCondXPath.isAbsolute()) {
134                 final List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
135                 if (qnamedPath != null) {
136                     return findNodeInSchemaContext(context, qnamedPath);
137                 }
138             }
139         }
140         return null;
141     }
142
143     /**
144      * Method attempts to find DataSchemaNode inside of provided Schema Context
145      * and Yang Module accordingly to Non-conditional relative Revision Aware
146      * XPath. The specified Module MUST be present in Schema Context otherwise
147      * the operation would fail and return <code>null</code>. <br>
148      * The relative Revision Aware XPath MUST be specified WITHOUT the
149      * conditional statement (i.e. without [cond]) in path, because in this
150      * state the Schema Context is completely unaware of data state and will be
151      * not able to properly resolve XPath. If the XPath contains condition the
152      * method will return IllegalArgumentException. <br>
153      * The Actual Schema Node MUST be specified correctly because from this
154      * Schema Node will search starts. If the Actual Schema Node is not correct
155      * the operation will simply fail, because it will be unable to find desired
156      * DataSchemaNode. <br>
157      * In case that Schema Context or Module or Actual Schema Node or relative
158      * Revision Aware XPath contains <code>null</code> references the method
159      * will throw IllegalArgumentException <br>
160      * If the Revision Aware XPath doesn't have flag
161      * <code>isAbsolute == false</code> the method will throw
162      * IllegalArgumentException. <br>
163      * If the relative Revision Aware XPath is correct and desired Data Schema
164      * Node is present in Yang module or in depending module in Schema Context
165      * the method will return specified Data Schema Node, otherwise the
166      * operation will fail and method will return <code>null</code>.
167      *
168      * @param context
169      *            Schema Context
170      * @param module
171      *            Yang Module
172      * @param actualSchemaNode
173      *            Actual Schema Node
174      * @param relativeXPath
175      *            Relative Non Conditional Revision Aware XPath
176      * @return DataSchemaNode if is present in specified Schema Context for
177      *         given relative Revision Aware XPath, otherwise will return
178      *         <code>null</code>.
179      *
180      * @throws IllegalArgumentException
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      * @param context
211      *            Schema Context
212      * @param schemaNode
213      *            Schema Node
214      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
215      *         return <code>null</code>
216      *
217      * @throws IllegalArgumentException
218      */
219     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
220         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
221         Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
222         Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
223                 + "set properly (Schema Path is NULL)");
224
225         final QName qname = schemaNode.getPath().getLastComponent();
226         Preconditions.checkState(qname != null, "Schema Path contains invalid state of path parts. "
227                 + "The Schema Path MUST contain at least ONE QName  which defines namespace and Local name of path.");
228         return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
229     }
230
231     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
232         final QName current = path.iterator().next();
233
234         LOG.trace("Looking up module {} in context {}", current, path);
235         final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
236         if (module == null) {
237             LOG.debug("Module {} not found", current);
238             return null;
239         }
240
241         return findNodeInModule(module, path);
242     }
243
244     /**
245      * Returns NotificationDefinition from Schema Context
246      *
247      * @param schema SchemaContext in which lookup should be performed.
248      * @param path Schema Path of notification
249      * @return Notification schema or null, if notification is not present in schema context.
250      */
251     @Beta
252     @Nullable public static NotificationDefinition getNotificationSchema(@Nonnull final SchemaContext schema,
253             @Nonnull final SchemaPath path) {
254         Preconditions.checkNotNull(schema, "Schema context must not be null.");
255         Preconditions.checkNotNull(path, "Schema path must not be null.");
256         for (final NotificationDefinition potential : schema.getNotifications()) {
257             if (path.equals(potential.getPath())) {
258                return potential;
259             }
260         }
261         return null;
262     }
263
264     /**
265      * Returns RPC Input or Output Data container from RPC definition.
266      *
267      * @param schema SchemaContext in which lookup should be performed.
268      * @param path Schema path of RPC input/output data container
269      * @return Notification schema or null, if notification is not present in schema context.
270      */
271     @Beta
272     @Nullable public static ContainerSchemaNode getRpcDataSchema(@Nonnull final SchemaContext schema,
273             @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      * @param context
459      *            Schema Context
460      * @param parentModule
461      *            Parent Module
462      * @param xpath
463      *            XPath String
464      * @return return a list of QName
465      *
466      * @throws IllegalArgumentException
467      */
468     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule,
469             final String xpath) {
470         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
471         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
472         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
473
474         final List<QName> path = new LinkedList<>();
475         for (final String pathComponent : SLASH_SPLITTER.split(xpath)) {
476             if (!pathComponent.isEmpty()) {
477                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
478             }
479         }
480         return path;
481     }
482
483     /**
484      * Transforms part of Prefixed Path as java String to QName. <br>
485      * If the string contains module prefix separated by ":" (i.e.
486      * mod:container) this module is provided from from Parent Module list of
487      * imports. If the Prefixed module is present in Schema Context the QName
488      * can be constructed. <br>
489      * If the Prefixed Path Part does not contains prefix the Parent's Module
490      * namespace is taken for construction of QName. <br>
491      * If Schema Context, Parent Module or Prefixed Path Part refers to
492      * <code>null</code> the method will throw IllegalArgumentException
493      *
494      * @param context
495      *            Schema Context
496      * @param parentModule
497      *            Parent Module
498      * @param prefixedPathPart
499      *            Prefixed Path Part string
500      * @return QName from prefixed Path Part String.
501      *
502      * @throws IllegalArgumentException
503      */
504     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule,
505             final String prefixedPathPart) {
506         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
507         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
508         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
509
510         if (prefixedPathPart.indexOf(':') != -1) {
511             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
512             final String modulePrefix = prefixedName.next();
513
514             final Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
515             Preconditions.checkArgument(module != null,
516                     "Failed to resolve xpath: no module found for prefix %s in module %s", modulePrefix,
517                     parentModule.getName());
518
519             return QName.create(module.getQNameModule(), prefixedName.next());
520         }
521
522         return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
523     }
524
525     /**
526      * Method will attempt to resolve and provide Module reference for specified
527      * module prefix. Each Yang module could contains multiple imports which
528      * MUST be associated with corresponding module prefix. The method simply
529      * looks into module imports and returns the module that is bounded with
530      * specified prefix. If the prefix is not present in module or the prefixed
531      * module is not present in specified Schema Context, the method will return
532      * <code>null</code>. <br>
533      * If String prefix is the same as prefix of the specified Module the
534      * reference to this module is returned. <br>
535      * If Schema Context, Module or Prefix are referring to <code>null</code>
536      * the method will return IllegalArgumentException
537      *
538      * @param context
539      *            Schema Context
540      * @param module
541      *            Yang Module
542      * @param prefix
543      *            Module Prefix
544      * @return Module for given prefix in specified Schema Context if is
545      *         present, otherwise returns <code>null</code>
546      *
547      * @throws IllegalArgumentException
548      */
549     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module,
550             final String prefix) {
551         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
552         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
553         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
554
555         if (prefix.equals(module.getPrefix())) {
556             return module;
557         }
558
559         final Set<ModuleImport> imports = module.getImports();
560         for (final ModuleImport mi : imports) {
561             if (prefix.equals(mi.getPrefix())) {
562                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
563             }
564         }
565         return null;
566     }
567
568     /**
569      * @param context
570      *            Schema Context
571      * @param module
572      *            Yang Module
573      * @param relativeXPath
574      *            Non conditional Revision Aware Relative XPath
575      * @param actualSchemaNode
576      *            actual schema node
577      * @return list of QName
578      *
579      * @throws IllegalArgumentException
580      */
581     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
582             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
583         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
584         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
585         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
586         Preconditions.checkState(!relativeXPath.isAbsolute(),
587                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
588                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
589         Preconditions.checkState(actualSchemaNode.getPath() != null,
590                 "Schema Path reference for Leafref cannot be NULL");
591
592         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
593
594         // Find out how many "parent" components there are
595         // FIXME: is .contains() the right check here?
596         // FIXME: case ../../node1/node2/../node3/../node4
597         int colCount = 0;
598         for (final Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
599             ++colCount;
600         }
601
602         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
603
604         if (Iterables.size(schemaNodePath) - colCount >= 0) {
605             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
606                 Iterables.transform(Iterables.skip(xpaths, colCount),
607                     input -> stringPathPartToQName(context, module, input)));
608         }
609         return Iterables.concat(schemaNodePath,
610                 Iterables.transform(Iterables.skip(xpaths, colCount),
611                     input -> stringPathPartToQName(context, module, input)));
612     }
613
614     /**
615      * Extracts the base type of node on which schema node points to. If target node is again of type
616      * LeafrefTypeDefinition, methods will be call recursively until it reach concrete type definition.
617      *
618      * @param typeDefinition
619      *            type of node which will be extracted
620      * @param schemaContext
621      *            Schema Context
622      * @param schema
623      *            Schema Node
624      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null
625      *         is there to preserve backwards compatibility)
626      */
627     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
628             final SchemaContext schemaContext, final SchemaNode schema) {
629         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
630         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement),
631             pathStatement.isAbsolute());
632
633         final DataSchemaNode dataSchemaNode;
634         if (pathStatement.isAbsolute()) {
635             SchemaNode baseSchema = schema;
636             while (baseSchema instanceof DerivableSchemaNode) {
637                 final Optional<? extends SchemaNode> basePotential = ((DerivableSchemaNode) baseSchema).getOriginal();
638                 if (basePotential.isPresent()) {
639                     baseSchema = basePotential.get();
640                 } else {
641                     break;
642                 }
643             }
644
645             Module parentModule = findParentModuleOfReferencingType(schemaContext, baseSchema);
646             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule,
647                     pathStatement);
648         } else {
649             Module parentModule = findParentModule(schemaContext, schema);
650             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext,
651                     parentModule, schema, pathStatement);
652         }
653
654         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
655         // and current expected behaviour for such cases is to just use pure string
656         // This should throw an exception about incorrect XPath in leafref
657         if (dataSchemaNode == null) {
658             return null;
659         }
660
661         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
662
663         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
664             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
665         }
666
667         return targetTypeDefinition;
668     }
669
670     private static Module findParentModuleOfReferencingType(final SchemaContext schemaContext,
671             final SchemaNode schemaNode) {
672         Preconditions.checkArgument(schemaContext != null, "Schema Context reference cannot be NULL!");
673         Preconditions.checkArgument(schemaNode instanceof TypedSchemaNode, "Unsupported node %s", schemaNode);
674
675         TypeDefinition<?> nodeType = ((TypedSchemaNode) schemaNode).getType();
676         if (nodeType.getBaseType() != null) {
677             while (nodeType.getBaseType() != null) {
678                 nodeType = nodeType.getBaseType();
679             }
680
681             final QNameModule typeDefModuleQname = nodeType.getQName().getModule();
682             return schemaContext.findModuleByNamespaceAndRevision(typeDefModuleQname.getNamespace(),
683                     typeDefModuleQname.getRevision());
684         }
685
686         return SchemaContextUtil.findParentModule(schemaContext, schemaNode);
687     }
688
689     /**
690      * Returns base type for {@code typeDefinition} which belongs to module specified via {@code qName}. This handle
691      * the case when leafref type isn't specified as type substatement of leaf or leaf-list but is defined in other
692      * module as typedef which is then imported to referenced module.
693      *
694      * Because {@code typeDefinition} is definied via typedef statement, only absolute path is meaningful.
695      *
696      * @param typeDefinition
697      * @param schemaContext
698      * @param qName
699      */
700     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition,
701             final SchemaContext schemaContext, final QName qName) {
702         final RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
703         final RevisionAwareXPath strippedPathStatement = new RevisionAwareXPathImpl(
704             stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
705         if (!strippedPathStatement.isAbsolute()) {
706             return null;
707         }
708
709         final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(qName.getNamespace()
710             ,qName.getRevision());
711         final DataSchemaNode dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext,
712             parentModule, strippedPathStatement);
713         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
714         if (targetTypeDefinition instanceof LeafrefTypeDefinition) {
715             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
716         }
717
718         return targetTypeDefinition;
719     }
720
721     private static final Pattern STRIP_PATTERN = Pattern.compile("\\[[^\\[\\]]*\\]");
722
723     /**
724      * Removes conditions from xPath pointed to target node.
725      *
726      * @param pathStatement
727      *            xPath to target node
728      * @return string representation of xPath without conditions
729      *
730      */
731     @VisibleForTesting
732     static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
733         return STRIP_PATTERN.matcher(pathStatement.toString()).replaceAll("");
734     }
735
736     /**
737      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
738      *
739      * @param node
740      *            a node representing LeafSchemaNode
741      * @return concrete type definition of node value
742      */
743     private static TypeDefinition<?> typeDefinition(final LeafSchemaNode node) {
744         TypeDefinition<?> baseType = node.getType();
745         while (baseType.getBaseType() != null) {
746             baseType = baseType.getBaseType();
747         }
748         return baseType;
749     }
750
751     /**
752      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
753      *
754      * @param node
755      *            a node representing LeafListSchemaNode
756      * @return concrete type definition of node value
757      */
758     private static TypeDefinition<?> typeDefinition(final LeafListSchemaNode node) {
759         TypeDefinition<?> baseType = node.getType();
760         while (baseType.getBaseType() != null) {
761             baseType = baseType.getBaseType();
762         }
763         return baseType;
764     }
765
766     /**
767      * Gets the base type of DataSchemaNode value.
768      *
769      * @param node
770      *            a node representing DataSchemaNode
771      * @return concrete type definition of node value
772      */
773     private static TypeDefinition<?> typeDefinition(final DataSchemaNode node) {
774         if (node instanceof LeafListSchemaNode) {
775             return typeDefinition((LeafListSchemaNode) node);
776         } else if (node instanceof LeafSchemaNode) {
777             return typeDefinition((LeafSchemaNode) node);
778         } else {
779             throw new IllegalArgumentException("Unhandled parameter type: " + node);
780         }
781     }
782 }