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