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