98fe8694db6ae04a68dd16429e566df850134b12
[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.base.Function;
11 import com.google.common.base.Preconditions;
12 import com.google.common.base.Splitter;
13 import com.google.common.collect.Iterables;
14 import java.util.Arrays;
15 import java.util.Iterator;
16 import java.util.LinkedList;
17 import java.util.List;
18 import java.util.Set;
19
20 import org.opendaylight.yangtools.yang.common.QName;
21 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
22 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
23 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
24 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
25 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
26 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
27 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
28 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
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         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                 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         SchemaPath actualNodePath = actualSchemaNode.getPath();
188         if (actualNodePath != null) {
189             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     private static SchemaNode findNodeInModule(Module module, Iterable<QName> path) {
242
243         Preconditions.checkArgument(module != null, "Parent reference cannot be NULL");
244         Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
245
246         if (!path.iterator().hasNext()) {
247             LOG.debug("No node matching {} found in node {}", path, module);
248             return null;
249         }
250
251         QName current = path.iterator().next();
252         LOG.trace("Looking for node {} in module {}", current, module);
253
254         SchemaNode foundNode = null;
255         Iterable<QName> nextPath = nextLevel(path);
256
257         foundNode = module.getDataChildByName(current);
258         if (foundNode != null && nextPath.iterator().hasNext()) {
259             foundNode = findNodeIn(foundNode, nextPath);
260         }
261
262         if (foundNode == null) {
263             foundNode = getGroupingByName(module, current);
264             if (foundNode != null && nextPath.iterator().hasNext()) {
265                 foundNode = findNodeIn(foundNode, nextPath);
266             }
267         }
268
269         if (foundNode == null) {
270             foundNode = getRpcByName(module, current);
271             if (foundNode != null && nextPath.iterator().hasNext()) {
272                 foundNode = findNodeIn(foundNode, nextPath);
273             }
274         }
275
276         if (foundNode == null) {
277             foundNode = getNotificationByName(module, current);
278             if (foundNode != null && nextPath.iterator().hasNext()) {
279                 foundNode = findNodeIn(foundNode, nextPath);
280             }
281         }
282
283         if (foundNode == null) {
284             LOG.debug("No node matching {} found in node {}", path, module);
285         }
286
287         return foundNode;
288
289     }
290
291     private static SchemaNode findNodeIn(SchemaNode parent, Iterable<QName> path) {
292
293         Preconditions.checkArgument(parent != null, "Parent reference cannot be NULL");
294         Preconditions.checkArgument(path != null, "Path reference cannot be NULL");
295
296         if (!path.iterator().hasNext()) {
297             LOG.debug("No node matching {} found in node {}", path, parent);
298             return null;
299         }
300
301         QName current = path.iterator().next();
302         LOG.trace("Looking for node {} in node {}", current, parent);
303
304         SchemaNode foundNode = null;
305         Iterable<QName> nextPath = nextLevel(path);
306
307         if (parent instanceof DataNodeContainer) {
308             DataNodeContainer parentDataNodeContainer = (DataNodeContainer) parent;
309
310             foundNode = parentDataNodeContainer.getDataChildByName(current);
311             if (foundNode != null && nextPath.iterator().hasNext()) {
312                 foundNode = findNodeIn(foundNode, nextPath);
313             }
314
315             if (foundNode == null) {
316                 foundNode = getGroupingByName(parentDataNodeContainer, current);
317                 if (foundNode != null && nextPath.iterator().hasNext()) {
318                     foundNode = findNodeIn(foundNode, nextPath);
319                 }
320             }
321         }
322
323         if (foundNode == null && parent instanceof RpcDefinition) {
324             RpcDefinition parentRpcDefinition = (RpcDefinition) parent;
325
326             if (current.getLocalName().equals("input")) {
327                 foundNode = parentRpcDefinition.getInput();
328                 if (foundNode != null && nextPath.iterator().hasNext()) {
329                     foundNode = findNodeIn(foundNode, nextPath);
330                 }
331             }
332
333             if (current.getLocalName().equals("output")) {
334                 foundNode = parentRpcDefinition.getOutput();
335                 if (foundNode != null && nextPath.iterator().hasNext()) {
336                     foundNode = findNodeIn(foundNode, nextPath);
337                 }
338             }
339
340             if (foundNode == null) {
341                 foundNode = getGroupingByName(parentRpcDefinition, current);
342                 if (foundNode != null && nextPath.iterator().hasNext()) {
343                     foundNode = findNodeIn(foundNode, nextPath);
344                 }
345             }
346         }
347
348         if (foundNode == null && parent instanceof ChoiceNode) {
349             foundNode = ((ChoiceNode) parent).getCaseNodeByName(current);
350             if (foundNode != null && nextPath.iterator().hasNext()) {
351                 foundNode = findNodeIn(foundNode, nextPath);
352             }
353         }
354
355         if (foundNode == null) {
356             LOG.debug("No node matching {} found in node {}", path, parent);
357         }
358
359         return foundNode;
360
361     }
362
363     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
364         return Iterables.skip(path, 1);
365     }
366
367     private static RpcDefinition getRpcByName(final Module module, final QName name) {
368         for (RpcDefinition rpc : module.getRpcs()) {
369             if (rpc.getQName().equals(name)) {
370                 return rpc;
371             }
372         }
373         return null;
374     }
375
376     private static NotificationDefinition getNotificationByName(final Module module, final QName name) {
377         for (NotificationDefinition notification : module.getNotifications()) {
378             if (notification.getQName().equals(name)) {
379                 return notification;
380             }
381         }
382         return null;
383     }
384
385     private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final QName name) {
386         for (GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
387             if (grouping.getQName().equals(name)) {
388                 return grouping;
389             }
390         }
391         return null;
392     }
393
394     private static GroupingDefinition getGroupingByName(final RpcDefinition rpc, final QName name) {
395         for (GroupingDefinition grouping : rpc.getGroupings()) {
396             if (grouping.getQName().equals(name)) {
397                 return grouping;
398             }
399         }
400         return null;
401     }
402
403     /**
404      * Transforms string representation of XPath to Queue of QNames. The XPath
405      * is split by "/" and for each part of XPath is assigned correct module in
406      * Schema Path. <br>
407      * If Schema Context, Parent Module or XPath string contains
408      * <code>null</code> values, the method will throws IllegalArgumentException
409      *
410      * @throws IllegalArgumentException
411      *
412      * @param context
413      *            Schema Context
414      * @param parentModule
415      *            Parent Module
416      * @param xpath
417      *            XPath String
418      * @return return a list of QName
419      */
420     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
421         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
422         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
423         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
424
425         List<QName> path = new LinkedList<QName>();
426         for (String pathComponent : SLASH_SPLITTER.split(xpath)) {
427             if (!pathComponent.isEmpty()) {
428                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
429             }
430         }
431         return path;
432     }
433
434     /**
435      * Transforms part of Prefixed Path as java String to QName. <br>
436      * If the string contains module prefix separated by ":" (i.e.
437      * mod:container) this module is provided from from Parent Module list of
438      * imports. If the Prefixed module is present in Schema Context the QName
439      * can be constructed. <br>
440      * If the Prefixed Path Part does not contains prefix the Parent's Module
441      * namespace is taken for construction of QName. <br>
442      * If Schema Context, Parent Module or Prefixed Path Part refers to
443      * <code>null</code> the method will throw IllegalArgumentException
444      *
445      * @throws IllegalArgumentException
446      *
447      * @param context
448      *            Schema Context
449      * @param parentModule
450      *            Parent Module
451      * @param prefixedPathPart
452      *            Prefixed Path Part string
453      * @return QName from prefixed Path Part String.
454      */
455     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
456         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
457         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
458         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
459
460         if (prefixedPathPart.indexOf(':') != -1) {
461             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
462             final String modulePrefix = prefixedName.next();
463
464             Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
465             Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
466                     modulePrefix, parentModule.getName());
467
468             return QName.create(module.getQNameModule(), prefixedName.next());
469         } else {
470             return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
471         }
472     }
473
474     /**
475      * Method will attempt to resolve and provide Module reference for specified
476      * module prefix. Each Yang module could contains multiple imports which
477      * MUST be associated with corresponding module prefix. The method simply
478      * looks into module imports and returns the module that is bounded with
479      * specified prefix. If the prefix is not present in module or the prefixed
480      * module is not present in specified Schema Context, the method will return
481      * <code>null</code>. <br>
482      * If String prefix is the same as prefix of the specified Module the
483      * reference to this module is returned. <br>
484      * If Schema Context, Module or Prefix are referring to <code>null</code>
485      * the method will return IllegalArgumentException
486      *
487      * @throws IllegalArgumentException
488      *
489      * @param context
490      *            Schema Context
491      * @param module
492      *            Yang Module
493      * @param prefix
494      *            Module Prefix
495      * @return Module for given prefix in specified Schema Context if is
496      *         present, otherwise returns <code>null</code>
497      */
498     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
499         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
500         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
501         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
502
503         if (prefix.equals(module.getPrefix())) {
504             return module;
505         }
506
507         Set<ModuleImport> imports = module.getImports();
508         for (ModuleImport mi : imports) {
509             if (prefix.equals(mi.getPrefix())) {
510                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
511             }
512         }
513         return null;
514     }
515
516     /**
517      * @throws IllegalArgumentException
518      *
519      * @param context
520      *            Schema Context
521      * @param module
522      *            Yang Module
523      * @param relativeXPath
524      *            Non conditional Revision Aware Relative XPath
525      * @param actualSchemaNode
526      *            actual schema node
527      * @return list of QName
528      */
529     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
530             final RevisionAwareXPath relativeXPath, final SchemaNode actualSchemaNode) {
531         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
532         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
533         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
534         Preconditions.checkState(!relativeXPath.isAbsolute(),
535                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
536                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
537         Preconditions.checkState(actualSchemaNode.getPath() != null,
538                 "Schema Path reference for Leafref cannot be NULL");
539
540         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
541
542         // Find out how many "parent" components there are
543         // FIXME: is .contains() the right check here?
544         // FIXME: case ../../node1/node2/../node3/../node4
545         int colCount = 0;
546         for (Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
547             ++colCount;
548         }
549
550         final Iterable<QName> schemaNodePath = actualSchemaNode.getPath().getPathFromRoot();
551
552         if (Iterables.size(schemaNodePath) - colCount >= 0) {
553             return Iterables.concat(Iterables.limit(schemaNodePath, Iterables.size(schemaNodePath) - colCount),
554                     Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
555                         @Override
556                         public QName apply(final String input) {
557                             return stringPathPartToQName(context, module, input);
558                         }
559                     }));
560         }
561         return Iterables.concat(schemaNodePath,
562                 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
563                     @Override
564                     public QName apply(final String input) {
565                         return stringPathPartToQName(context, module, input);
566                     }
567                 }));
568     }
569
570     /**
571      * 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
572      * type definition.
573      *
574      * @param typeDefinition
575      *            type of node which will be extracted
576      * @param schemaContext
577      *            Schema Context
578      * @param schema
579      *            Schema Node
580      * @return recursively found type definition this leafref is pointing to or null if the xpath is incorrect (null is there to preserve backwards compatibility)
581      */
582     public static TypeDefinition<?> getBaseTypeForLeafRef(final LeafrefTypeDefinition typeDefinition, final SchemaContext schemaContext, final SchemaNode schema) {
583         RevisionAwareXPath pathStatement = typeDefinition.getPathStatement();
584         pathStatement = new RevisionAwareXPathImpl(stripConditionsFromXPathString(pathStatement), pathStatement.isAbsolute());
585
586         final Module parentModule = SchemaContextUtil.findParentModule(schemaContext, schema);
587
588         final DataSchemaNode dataSchemaNode;
589         if(pathStatement.isAbsolute()) {
590             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, pathStatement);
591         } else {
592             dataSchemaNode = (DataSchemaNode) SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule, schema, pathStatement);
593         }
594
595         // FIXME this is just to preserve backwards compatibility since yangtools do not mind wrong leafref xpaths
596         // and current expected behaviour for such cases is to just use pure string
597         // This should throw an exception about incorrect XPath in leafref
598         if(dataSchemaNode == null) {
599             return null;
600         }
601
602         final TypeDefinition<?> targetTypeDefinition = typeDefinition(dataSchemaNode);
603
604         if(targetTypeDefinition instanceof LeafrefTypeDefinition) {
605             return getBaseTypeForLeafRef(((LeafrefTypeDefinition) targetTypeDefinition), schemaContext, dataSchemaNode);
606         } else {
607             return targetTypeDefinition;
608         }
609     }
610
611     /**
612      * Removes conditions from xPath pointed to target node.
613      *
614      * @param pathStatement
615      *            xPath to target node
616      * @return string representation of xPath without conditions
617      *
618      */
619     private static String stripConditionsFromXPathString(final RevisionAwareXPath pathStatement) {
620         return pathStatement.toString().replaceAll("\\[.*\\]", "");
621     }
622
623     /**
624      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
625      *
626      * @param node
627      *            a node representing LeafSchemaNode
628      * @return concrete type definition of node value
629      */
630     private static TypeDefinition<? extends Object> typeDefinition(final LeafSchemaNode node) {
631         TypeDefinition<?> baseType = node.getType();
632         while (baseType.getBaseType() != null) {
633             baseType = baseType.getBaseType();
634         }
635         return baseType;
636     }
637
638     /**
639      * Extracts the base type of leaf schema node until it reach concrete type of TypeDefinition.
640      *
641      * @param node
642      *            a node representing LeafListSchemaNode
643      * @return concrete type definition of node value
644      */
645     private static TypeDefinition<? extends Object> typeDefinition(final LeafListSchemaNode node) {
646         TypeDefinition<?> baseType = node.getType();
647         while (baseType.getBaseType() != null) {
648             baseType = baseType.getBaseType();
649         }
650         return baseType;
651     }
652
653     /**
654      * Gets the base type of DataSchemaNode value.
655      *
656      * @param node
657      *            a node representing DataSchemaNode
658      * @return concrete type definition of node value
659      */
660     private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
661         if (node instanceof LeafListSchemaNode) {
662             return typeDefinition((LeafListSchemaNode) node);
663         } else if (node instanceof LeafSchemaNode) {
664             return typeDefinition((LeafSchemaNode) node);
665         } else {
666             throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
667         }
668     }
669 }