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