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