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