BUG-1342: fixed bug in resolving augments with target added by uses.
[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.net.URI;
15 import java.util.ArrayList;
16 import java.util.Collection;
17 import java.util.Collections;
18 import java.util.Date;
19 import java.util.Iterator;
20 import java.util.LinkedList;
21 import java.util.List;
22 import java.util.Set;
23 import org.opendaylight.yangtools.yang.common.QName;
24 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
25 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
26 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
27 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
28 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
29 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
30 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
31 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
32 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
33 import org.opendaylight.yangtools.yang.model.api.Module;
34 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
35 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
36 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
37 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
38 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
39 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.UsesNode;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * The Schema Context Util contains support methods for searching through Schema
47  * Context modules for specified schema nodes via Schema Path or Revision Aware
48  * XPath. The Schema Context Util is designed as mixin, so it is not
49  * instantiable.
50  *
51  */
52 public final class SchemaContextUtil {
53     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
54     private static final Splitter COLON_SPLITTER = Splitter.on(':');
55     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
56
57     private SchemaContextUtil() {
58     }
59
60     /**
61      * Method attempts to find DataSchemaNode in Schema Context via specified
62      * Schema Path. The returned DataSchemaNode from method will be the node at
63      * the end of the SchemaPath. If the DataSchemaNode is not present in the
64      * Schema Context the method will return <code>null</code>. <br>
65      * In case that Schema Context or Schema Path are not specified correctly
66      * (i.e. contains <code>null</code> values) the method will return
67      * IllegalArgumentException.
68      *
69      * @throws IllegalArgumentException
70      *
71      * @param context
72      *            Schema Context
73      * @param schemaPath
74      *            Schema Path to search for
75      * @return SchemaNode from the end of the Schema Path or <code>null</code>
76      *         if the Node is not present.
77      */
78     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
79         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
80         Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
81
82         final Iterable<QName> prefixedPath = schemaPath.getPathFromRoot();
83         if (prefixedPath == null) {
84             LOG.debug("Schema path {} has null path", schemaPath);
85             return null;
86         }
87
88         LOG.trace("Looking for path {} in context {}", schemaPath, context);
89         return findNodeInSchemaContext(context, prefixedPath);
90     }
91
92     /**
93      * Method attempts to find DataSchemaNode inside of provided Schema Context
94      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
95      * specified Module MUST be present in Schema Context otherwise the
96      * operation would fail and return <code>null</code>. <br>
97      * The Revision Aware XPath MUST be specified WITHOUT the conditional
98      * statement (i.e. without [cond]) in path, because in this state the Schema
99      * Context is completely unaware of data state and will be not able to
100      * properly resolve XPath. If the XPath contains condition the method will
101      * return IllegalArgumentException. <br>
102      * In case that Schema Context or Module or Revision Aware XPath contains
103      * <code>null</code> references the method will throw
104      * IllegalArgumentException <br>
105      * If the Revision Aware XPath is correct and desired Data Schema Node is
106      * present in Yang module or in depending module in Schema Context the
107      * method will return specified Data Schema Node, otherwise the operation
108      * will fail and method will return <code>null</code>.
109      *
110      * @throws IllegalArgumentException
111      *
112      * @param context
113      *            Schema Context
114      * @param module
115      *            Yang Module
116      * @param nonCondXPath
117      *            Non Conditional Revision Aware XPath
118      * @return Returns Data Schema Node for specified Schema Context for given
119      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
120      *         DataSchemaNode is not present in Schema Context.
121      */
122     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
123         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
124         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
125         Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
126
127         String strXPath = nonCondXPath.toString();
128         if (strXPath != null) {
129             Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
130             if (nonCondXPath.isAbsolute()) {
131                 List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
132                 if (qnamedPath != null) {
133                     return findNodeInSchemaContext(context, qnamedPath);
134                 }
135             }
136         }
137         return null;
138     }
139
140     /**
141      * Method attempts to find DataSchemaNode inside of provided Schema Context
142      * and Yang Module accordingly to Non-conditional relative Revision Aware
143      * XPath. The specified Module MUST be present in Schema Context otherwise
144      * the operation would fail and return <code>null</code>. <br>
145      * The relative Revision Aware XPath MUST be specified WITHOUT the
146      * conditional statement (i.e. without [cond]) in path, because in this
147      * state the Schema Context is completely unaware of data state and will be
148      * not able to properly resolve XPath. If the XPath contains condition the
149      * method will return IllegalArgumentException. <br>
150      * The Actual Schema Node MUST be specified correctly because from this
151      * Schema Node will search starts. If the Actual Schema Node is not correct
152      * the operation will simply fail, because it will be unable to find desired
153      * DataSchemaNode. <br>
154      * In case that Schema Context or Module or Actual Schema Node or relative
155      * Revision Aware XPath contains <code>null</code> references the method
156      * will throw IllegalArgumentException <br>
157      * If the Revision Aware XPath doesn't have flag
158      * <code>isAbsolute == false</code> the method will throw
159      * IllegalArgumentException. <br>
160      * If the relative Revision Aware XPath is correct and desired Data Schema
161      * Node is present in Yang module or in depending module in Schema Context
162      * the method will return specified Data Schema Node, otherwise the
163      * operation will fail and method will return <code>null</code>.
164      *
165      * @throws IllegalArgumentException
166      *
167      * @param context
168      *            Schema Context
169      * @param module
170      *            Yang Module
171      * @param actualSchemaNode
172      *            Actual Schema Node
173      * @param relativeXPath
174      *            Relative Non Conditional Revision Aware XPath
175      * @return DataSchemaNode if is present in specified Schema Context for
176      *         given relative Revision Aware XPath, otherwise will return
177      *         <code>null</code>.
178      */
179     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
180             final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
181         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
182         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
183         Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
184         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
185         Preconditions.checkState(!relativeXPath.isAbsolute(),
186                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
187                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
188
189         SchemaPath actualNodePath = actualSchemaNode.getPath();
190         if (actualNodePath != null) {
191             Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
192
193             if (qnamePath != null) {
194                 return findNodeInSchemaContext(context, qnamePath);
195             }
196         }
197         return null;
198     }
199
200     /**
201      * Returns parent Yang Module for specified Schema Context in which Schema
202      * Node is declared. If the Schema Node is not present in Schema Context the
203      * operation will return <code>null</code>. <br>
204      * If Schema Context or Schema Node contains <code>null</code> references
205      * the method will throw IllegalArgumentException
206      *
207      * @throws IllegalArgumentException
208      *
209      * @param context
210      *            Schema Context
211      * @param schemaNode
212      *            Schema Node
213      * @return Yang Module for specified Schema Context and Schema Node, if
214      *         Schema Node is NOT present, the method will returns
215      *         <code>null</code>
216      */
217     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
218         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
219         Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
220         Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
221                 + "set properly (Schema Path is NULL)");
222
223         final QName qname = Iterables.getFirst(schemaNode.getPath().getPathTowardsRoot(), null);
224         Preconditions.checkState(qname != null,
225                 "Schema Path contains invalid state of path parts. " +
226                 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
227         return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
228     }
229
230     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
231         final QName current = path.iterator().next();
232
233         LOG.trace("Looking up module {} in context {}", current, path);
234         final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
235         if (module == null) {
236             LOG.debug("Module {} not found", current);
237             return null;
238         }
239
240         return findNodeInModule(module, path);
241     }
242
243     public static GroupingDefinition findGrouping(final SchemaContext context, final Module module, final Iterable<QName> path) {
244         Iterator<QName> iterator = path.iterator();
245         QName first = iterator.next();
246         Module m = context.findModuleByNamespace(first.getNamespace()).iterator().next();
247         DataNodeContainer currentParent = m;
248         for (QName qname : path) {
249             boolean found = false;
250             DataNodeContainer node = (DataNodeContainer) currentParent.getDataChildByName(qname.getLocalName());
251             if (node == null) {
252                 Set<GroupingDefinition> groupings = currentParent.getGroupings();
253                 for (GroupingDefinition gr : groupings) {
254                     if (gr.getQName().getLocalName().equals(qname.getLocalName())) {
255                         currentParent = gr;
256                         found = true;
257                     }
258                 }
259             } else {
260                 found = true;
261                 currentParent = node;
262             }
263
264             Preconditions.checkArgument(found, "Failed to find referenced grouping: %s(%s)", path, qname.getLocalName());
265         }
266
267         return (GroupingDefinition) currentParent;
268     }
269
270     private static SchemaNode findNodeInModule(final Module module, final Iterable<QName> path) {
271         final QName current = path.iterator().next();
272
273         LOG.trace("Looking for data container {} in module {}", current, module);
274         SchemaNode parent = module.getDataChildByName(current);
275         if (parent != null) {
276             final SchemaNode ret = findNode((DataSchemaNode) parent, nextLevel(path));
277             if (ret != null) {
278                 return ret;
279             }
280         }
281
282         LOG.trace("Looking for RPC {} in module {}", current, module);
283         parent = getRpcByName(module, current);
284         if (parent != null) {
285             final SchemaNode ret = findNodeInRpc((RpcDefinition) parent, nextLevel(path));
286             if (ret != null) {
287                 return ret;
288             }
289         }
290
291         LOG.trace("Looking for notification {} in module {}", current, module);
292         parent = getNotificationByName(module, current);
293         if (parent != null) {
294             final SchemaNode ret = findNodeInNotification((NotificationDefinition) parent, nextLevel(path));
295             if (ret != null) {
296                 return ret;
297             }
298         }
299
300         LOG.trace("Looking for grouping {} in module {}", current, module);
301         parent = getGroupingByName(module, current);
302         if (parent != null) {
303             final SchemaNode ret = findNodeInGrouping((GroupingDefinition) parent, nextLevel(path));
304             if (ret != null) {
305                 return ret;
306             }
307         }
308
309         LOG.debug("No node matching {} found in module {}", path, module);
310         return null;
311     }
312
313     private static SchemaNode findNodeInGrouping(final GroupingDefinition grouping, final Iterable<QName> path) {
314         final QName current = Iterables.getFirst(path, null);
315         if (current == null) {
316             LOG.debug("Found grouping {}", grouping);
317             return grouping;
318         }
319
320         LOG.trace("Looking for path {} in grouping {}", path, grouping);
321         final DataSchemaNode node = grouping.getDataChildByName(current);
322         if (node == null) {
323             LOG.debug("No node matching {} found in grouping {}", current, grouping);
324             return null;
325         }
326
327         return findNode(node, nextLevel(path));
328     }
329
330     private static SchemaNode findNodeInRpc(final RpcDefinition rpc, final Iterable<QName> path) {
331         final QName current = Iterables.getFirst(path, null);
332         if (current == null) {
333             LOG.debug("Found RPC {}", rpc);
334             return rpc;
335         }
336
337         LOG.trace("Looking for path {} in rpc {}", path, rpc);
338         switch (current.getLocalName()) {
339         case "input":
340             return findNode(rpc.getInput(), nextLevel(path));
341         case "output":
342             return findNode(rpc.getOutput(), nextLevel(path));
343         default:
344             LOG.debug("Invalid component {} of path {} in RPC {}", current, path, rpc);
345             return null;
346         }
347     }
348
349     private static SchemaNode findNodeInNotification(final NotificationDefinition ntf, final Iterable<QName> path) {
350         final QName current = Iterables.getFirst(path, null);
351         if (current == null) {
352             LOG.debug("Found notification {}", ntf);
353             return ntf;
354         }
355
356         LOG.trace("Looking for path {} in notification {}", path, ntf);
357         DataSchemaNode node = ntf.getDataChildByName(current);
358         if (node == null) {
359             LOG.debug("No node matching {} found in notification {}", current, ntf);
360             return null;
361         }
362
363         return findNode(node, nextLevel(path));
364     }
365
366     private static SchemaNode findNode(final ChoiceNode parent, final Iterable<QName> path) {
367         final QName current = Iterables.getFirst(path, null);
368         if (current == null) {
369             return parent;
370         }
371         ChoiceCaseNode node = parent.getCaseNodeByName(current);
372         if (node != null) {
373             return findNodeInCase(node, nextLevel(path));
374         }
375         return null;
376     }
377
378     private static SchemaNode findNode(final ContainerSchemaNode parent, final Iterable<QName> path) {
379         final QName current = Iterables.getFirst(path, null);
380         if (current == null) {
381             return parent;
382         }
383
384         final DataSchemaNode node = parent.getDataChildByName(current);
385         if (node == null) {
386             LOG.debug("Failed to find {} in parent {}", path, parent);
387             return null;
388         }
389
390         return findNode(node, nextLevel(path));
391     }
392
393     private static SchemaNode findNode(final ListSchemaNode parent, final Iterable<QName> path) {
394         final QName current = Iterables.getFirst(path, null);
395         if (current == null) {
396             return parent;
397         }
398
399         DataSchemaNode node = parent.getDataChildByName(current);
400         if (node == null) {
401             LOG.debug("Failed to find {} in parent {}", path, parent);
402             return null;
403         }
404         return findNode(node, nextLevel(path));
405     }
406
407     private static SchemaNode findNode(final DataSchemaNode parent, final Iterable<QName> path) {
408         final SchemaNode node;
409         if (!Iterables.isEmpty(path)) {
410             if (parent instanceof ContainerSchemaNode) {
411                 node = findNode((ContainerSchemaNode) parent, path);
412             } else if (parent instanceof ListSchemaNode) {
413                 node = findNode((ListSchemaNode) parent, path);
414             } else if (parent instanceof ChoiceNode) {
415                 node = findNode((ChoiceNode) parent, path);
416             } else {
417                 throw new IllegalArgumentException(
418                         String.format("Path nesting violation in parent %s path %s", parent, path));
419             }
420         } else {
421             node = parent;
422         }
423
424         if (node == null) {
425             LOG.debug("Failed to find {} in parent {}", path, parent);
426             return null;
427         }
428         return node;
429     }
430
431     public static SchemaNode findNodeInCase(final ChoiceCaseNode parent, final Iterable<QName> path) {
432         final QName current = Iterables.getFirst(path, null);
433         if (current == null) {
434             return parent;
435         }
436
437         DataSchemaNode node = parent.getDataChildByName(current);
438         if (node == null) {
439             LOG.debug("Failed to find {} in parent {}", path, parent);
440             return null;
441         }
442         return findNode(node, nextLevel(path));
443     }
444
445     public static RpcDefinition getRpcByName(final Module module, final QName name) {
446         for (RpcDefinition rpc : module.getRpcs()) {
447             if (rpc.getQName().equals(name)) {
448                 return rpc;
449             }
450         }
451         return null;
452     }
453
454     private static Iterable<QName> nextLevel(final Iterable<QName> path) {
455         return Iterables.skip(path, 1);
456     }
457
458     public static NotificationDefinition getNotificationByName(final Module module, final QName name) {
459         for (NotificationDefinition notification : module.getNotifications()) {
460             if (notification.getQName().equals(name)) {
461                 return notification;
462             }
463         }
464         return null;
465     }
466
467     public static GroupingDefinition getGroupingByName(final Module module, final QName name) {
468         for (GroupingDefinition grouping : module.getGroupings()) {
469             if (grouping.getQName().equals(name)) {
470                 return grouping;
471             }
472         }
473         return null;
474     }
475
476     /**
477      * Utility method which search for original node defined in grouping.
478      *
479      * @param node
480      * @return
481      */
482     public static DataSchemaNode findOriginal(final DataSchemaNode node, final SchemaContext ctx) {
483         DataSchemaNode result = findCorrectTargetFromGrouping(node, ctx);
484         if (result == null) {
485             result = findCorrectTargetFromAugment(node, ctx);
486             if (result != null) {
487                 if (result.isAddedByUses()) {
488                     result = findOriginal(result, ctx);
489                 }
490             }
491         }
492         return result;
493     }
494
495     private static DataSchemaNode findCorrectImmediateTargetFromGrouping(final DataSchemaNode node, final SchemaContext ctx) {
496         // uses is under module statement
497         final Module m = findParentModule(ctx, node);
498         Preconditions.checkArgument(m != null, "Failed to find module for node {} in context {}", node, ctx);
499
500         for (final UsesNode u : m.getUses()) {
501             final SchemaNode targetGrouping = findNodeInSchemaContext(ctx, u.getGroupingPath().getPathFromRoot());
502             Preconditions.checkArgument(targetGrouping instanceof GroupingDefinition,
503                     "Failed to generate code for augment in %s", u);
504
505             LOG.trace("Checking grouping {} for node {}", targetGrouping, node);
506             final GroupingDefinition gr = (GroupingDefinition) targetGrouping;
507             final DataSchemaNode result = gr.getDataChildByName(node.getQName().getLocalName());
508             if (result != null) {
509                 return result;
510             }
511
512             LOG.debug("Skipped grouping {}, no matching node found", gr);
513         }
514
515         throw new IllegalArgumentException(
516                 String.format("Failed to find uses node matching {} in context {}", node, ctx));
517     }
518
519     private static DataSchemaNode findCorrectTargetFromGrouping(final DataSchemaNode node, final SchemaContext ctx) {
520         if (Iterables.size(node.getPath().getPathTowardsRoot()) != 1) {
521             QName currentName = node.getQName();
522             // tmpPath is used to track level of nesting
523             List<QName> tmpPath = new ArrayList<>();
524             Object parent = null;
525
526             // create schema path of parent node
527             SchemaPath sp = node.getPath().getParent();
528             parent = findDataSchemaNode(ctx, sp);
529
530             do {
531                 tmpPath.add(currentName);
532
533                 DataSchemaNode result = null;
534                 // search parent node's used groupings for presence of wanted
535                 // node
536                 if (parent instanceof DataNodeContainer) {
537                     DataNodeContainer dataNodeParent = (DataNodeContainer) parent;
538                     for (UsesNode u : dataNodeParent.getUses()) {
539                         result = getResultFromUses(u, currentName.getLocalName(), ctx);
540                         if (result != null) {
541                             break;
542                         }
543                     }
544                 }
545
546                 // if node is not found in any of current parent's used
547                 // groupings => parent is added by grouping too, so repeat same
548                 // process for parent
549                 if (result == null) {
550                     final SchemaNode sn = (SchemaNode) parent;
551
552                     // set current name to name of parent node
553                     currentName = sn.getQName();
554                     Preconditions.checkArgument(parent instanceof SchemaNode,
555                             "Failed to generate code for augmend node {} at parent {}", node, parent);
556
557                     // create schema path for parent of current parent
558                     final SchemaPath parentSp = sn.getPath().getParent();
559                     parent = parentSp.getPathFromRoot().iterator().hasNext() ? findDataSchemaNode(ctx, parentSp)
560                             : getParentModule(sn, ctx);
561                 } else {
562                     // if wanted node was found in grouping, traverse this node
563                     // based on level of nesting
564                     return getTargetNode(tmpPath, result, ctx);
565                 }
566             } while (!(parent instanceof Module));
567
568             return null;
569         } else {
570             return findCorrectImmediateTargetFromGrouping(node, ctx);
571         }
572     }
573
574     private static DataSchemaNode findCorrectTargetFromAugment(final DataSchemaNode node, final SchemaContext ctx) {
575         if (!node.isAugmenting()) {
576             return null;
577         }
578
579         QName currentName = node.getQName();
580         Object currentNode = node;
581         Object parent = node;
582         List<QName> tmpPath = new ArrayList<QName>();
583         List<SchemaNode> tmpTree = new ArrayList<SchemaNode>();
584
585         AugmentationSchema augment = null;
586         do {
587             SchemaPath sp = ((SchemaNode) parent).getPath();
588             parent = findDataSchemaNode(ctx, sp.getParent());
589             if (parent instanceof AugmentationTarget) {
590                 tmpPath.add(currentName);
591                 tmpTree.add((SchemaNode) currentNode);
592                 augment = findNodeInAugment(((AugmentationTarget) parent).getAvailableAugmentations(), currentName);
593                 if (augment == null) {
594                     currentName = ((DataSchemaNode) parent).getQName();
595                     currentNode = parent;
596                 }
597             }
598         } while (((DataSchemaNode) parent).isAugmenting() && augment == null);
599
600         if (augment == null) {
601             return null;
602         } else {
603             Collections.reverse(tmpPath);
604             Collections.reverse(tmpTree);
605             Object actualParent = augment;
606             DataSchemaNode result = null;
607             for (QName name : tmpPath) {
608                 if (actualParent instanceof DataNodeContainer) {
609                     result = ((DataNodeContainer) actualParent).getDataChildByName(name.getLocalName());
610                     actualParent = ((DataNodeContainer) actualParent).getDataChildByName(name.getLocalName());
611                 } else {
612                     if (actualParent instanceof ChoiceNode) {
613                         result = ((ChoiceNode) actualParent).getCaseNodeByName(name.getLocalName());
614                         actualParent = ((ChoiceNode) actualParent).getCaseNodeByName(name.getLocalName());
615                     }
616                 }
617             }
618
619             if (result.isAddedByUses()) {
620                 result = findCorrectTargetFromAugmentGrouping(result, augment, tmpTree, ctx);
621             }
622
623             return result;
624         }
625     }
626
627     private static DataSchemaNode getResultFromUses(final UsesNode u, final String currentName, final SchemaContext ctx) {
628         SchemaNode targetGrouping = SchemaContextUtil.findNodeInSchemaContext(ctx, u.getGroupingPath()
629                 .getPathFromRoot());
630         if (!(targetGrouping instanceof GroupingDefinition)) {
631             targetGrouping = findGrouping(ctx, getParentModule(targetGrouping, ctx), u.getGroupingPath()
632                     .getPathFromRoot());
633         }
634         Preconditions.checkArgument(targetGrouping instanceof GroupingDefinition,
635                 "Failed to generate code for augment in %s", u);
636         GroupingDefinition gr = (GroupingDefinition) targetGrouping;
637         return gr.getDataChildByName(currentName);
638     }
639
640     private static Module getParentModule(final SchemaNode node, final SchemaContext ctx) {
641         QName qname = node.getPath().getPathFromRoot().iterator().next();
642         URI namespace = qname.getNamespace();
643         Date revision = qname.getRevision();
644         return ctx.findModuleByNamespaceAndRevision(namespace, revision);
645     }
646
647     private static DataSchemaNode getTargetNode(final List<QName> tmpPath, final DataSchemaNode node, final SchemaContext ctx) {
648         DataSchemaNode result = node;
649         if (tmpPath.size() == 1) {
650             if (result != null && result.isAddedByUses()) {
651                 result = findOriginal(result, ctx);
652             }
653             return result;
654         } else {
655             DataSchemaNode newParent = result;
656             Collections.reverse(tmpPath);
657
658             tmpPath.remove(0);
659             for (QName name : tmpPath) {
660                 // searching by local name is must, because node has different
661                 // namespace in its original location
662                 if (newParent == null) {
663                     break;
664                 }
665                 if (newParent instanceof DataNodeContainer) {
666                     newParent = ((DataNodeContainer) newParent).getDataChildByName(name.getLocalName());
667                 } else {
668                     newParent = ((ChoiceNode) newParent).getCaseNodeByName(name.getLocalName());
669                 }
670             }
671             if (newParent != null && newParent.isAddedByUses()) {
672                 newParent = findOriginal(newParent, ctx);
673             }
674             return newParent;
675         }
676     }
677
678     private static AugmentationSchema findNodeInAugment(final Collection<AugmentationSchema> augments, final QName name) {
679         for (AugmentationSchema augment : augments) {
680             DataSchemaNode node = augment.getDataChildByName(name);
681             if (node != null) {
682                 return augment;
683             }
684         }
685         return null;
686     }
687
688     private static DataSchemaNode findCorrectTargetFromAugmentGrouping(final DataSchemaNode node,
689             final AugmentationSchema parentNode, final List<SchemaNode> dataTree, final SchemaContext ctx) {
690
691         DataSchemaNode result = null;
692         QName currentName = node.getQName();
693         List<QName> tmpPath = new ArrayList<>();
694         tmpPath.add(currentName);
695         int i = 1;
696         Object parent = null;
697
698         do {
699             if (dataTree.size() < 2 || dataTree.size() == i) {
700                 parent = parentNode;
701             } else {
702                 parent = dataTree.get(dataTree.size() - (i + 1));
703                 tmpPath.add(((SchemaNode) parent).getQName());
704             }
705
706             if (parent instanceof DataNodeContainer) {
707                 DataNodeContainer dataNodeParent = (DataNodeContainer) parent;
708                 for (UsesNode u : dataNodeParent.getUses()) {
709                     if (result == null) {
710                         result = getResultFromUses(u, currentName.getLocalName(), ctx);
711                     }
712                 }
713             }
714
715             if (result == null) {
716                 i = i + 1;
717                 currentName = ((SchemaNode) parent).getQName();
718             }
719         } while (result == null);
720
721         if (result != null) {
722             result = getTargetNode(tmpPath, result, ctx);
723         }
724         return result;
725     }
726
727     /**
728      * Transforms string representation of XPath to Queue of QNames. The XPath
729      * is split by "/" and for each part of XPath is assigned correct module in
730      * Schema Path. <br>
731      * If Schema Context, Parent Module or XPath string contains
732      * <code>null</code> values, the method will throws IllegalArgumentException
733      *
734      * @throws IllegalArgumentException
735      *
736      * @param context
737      *            Schema Context
738      * @param parentModule
739      *            Parent Module
740      * @param xpath
741      *            XPath String
742      * @return return a list of QName
743      */
744     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
745         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
746         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
747         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
748
749         List<QName> path = new LinkedList<QName>();
750         for (String pathComponent : SLASH_SPLITTER.split(xpath)) {
751             if (!pathComponent.isEmpty()) {
752                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
753             }
754         }
755         return path;
756     }
757
758     /**
759      * Transforms part of Prefixed Path as java String to QName. <br>
760      * If the string contains module prefix separated by ":" (i.e.
761      * mod:container) this module is provided from from Parent Module list of
762      * imports. If the Prefixed module is present in Schema Context the QName
763      * can be constructed. <br>
764      * If the Prefixed Path Part does not contains prefix the Parent's Module
765      * namespace is taken for construction of QName. <br>
766      * If Schema Context, Parent Module or Prefixed Path Part refers to
767      * <code>null</code> the method will throw IllegalArgumentException
768      *
769      * @throws IllegalArgumentException
770      *
771      * @param context
772      *            Schema Context
773      * @param parentModule
774      *            Parent Module
775      * @param prefixedPathPart
776      *            Prefixed Path Part string
777      * @return QName from prefixed Path Part String.
778      */
779     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
780         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
781         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
782         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
783
784         if (prefixedPathPart.indexOf(':') != -1) {
785             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
786             final String modulePrefix = prefixedName.next();
787
788             Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
789             Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
790                     modulePrefix, parentModule.getName());
791
792             // FIXME: Module should have a QNameModule handle
793             return QName.create(module.getNamespace(), module.getRevision(), prefixedName.next());
794         } else {
795             return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
796         }
797     }
798
799     /**
800      * Method will attempt to resolve and provide Module reference for specified
801      * module prefix. Each Yang module could contains multiple imports which
802      * MUST be associated with corresponding module prefix. The method simply
803      * looks into module imports and returns the module that is bounded with
804      * specified prefix. If the prefix is not present in module or the prefixed
805      * module is not present in specified Schema Context, the method will return
806      * <code>null</code>. <br>
807      * If String prefix is the same as prefix of the specified Module the
808      * reference to this module is returned. <br>
809      * If Schema Context, Module or Prefix are referring to <code>null</code>
810      * the method will return IllegalArgumentException
811      *
812      * @throws IllegalArgumentException
813      *
814      * @param context
815      *            Schema Context
816      * @param module
817      *            Yang Module
818      * @param prefix
819      *            Module Prefix
820      * @return Module for given prefix in specified Schema Context if is
821      *         present, otherwise returns <code>null</code>
822      */
823     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
824         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
825         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
826         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
827
828         if (prefix.equals(module.getPrefix())) {
829             return module;
830         }
831
832         Set<ModuleImport> imports = module.getImports();
833         for (ModuleImport mi : imports) {
834             if (prefix.equals(mi.getPrefix())) {
835                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
836             }
837         }
838         return null;
839     }
840
841     /**
842      * @throws IllegalArgumentException
843      *
844      * @param context
845      *            Schema Context
846      * @param module
847      *            Yang Module
848      * @param relativeXPath
849      *            Non conditional Revision Aware Relative XPath
850      * @param leafrefSchemaPath
851      *            Schema Path for Leafref
852      * @return list of QName
853      */
854     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
855             final RevisionAwareXPath relativeXPath, final SchemaNode leafrefParentNode) {
856         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
857         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
858         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
859         Preconditions.checkState(!relativeXPath.isAbsolute(),
860                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
861                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
862         Preconditions.checkState(leafrefParentNode.getPath() != null,
863                 "Schema Path reference for Leafref cannot be NULL");
864
865         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
866
867         // Find out how many "parent" components there are
868         // FIXME: is .contains() the right check here?
869         int colCount = 0;
870         for (Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
871             ++colCount;
872         }
873
874         final Iterable<QName> parent = leafrefParentNode.getPath().getPathFromRoot();
875         return Iterables.concat(Iterables.limit(parent, Iterables.size(parent) - colCount),
876                 Iterables.transform(Iterables.skip(xpaths, colCount), new Function<String, QName>() {
877                     @Override
878                     public QName apply(final String input) {
879                         return stringPathPartToQName(context, module, input);
880                     }
881                 }));
882     }
883 }