BUG-944: convert SchemaContextUtil to use Iterable
[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.Preconditions;
11 import com.google.common.base.Splitter;
12 import com.google.common.collect.Iterables;
13
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
24 import org.opendaylight.yangtools.yang.common.QName;
25 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
26 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
27 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
28 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
29 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
31 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
32 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
33 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
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.UsesNode;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 /**
47  * The Schema Context Util contains support methods for searching through Schema
48  * Context modules for specified schema nodes via Schema Path or Revision Aware
49  * XPath. The Schema Context Util is designed as mixin, so it is not
50  * instantiable.
51  *
52  */
53 public final class SchemaContextUtil {
54     private static final Logger LOG = LoggerFactory.getLogger(SchemaContextUtil.class);
55     private static final Splitter COLON_SPLITTER = Splitter.on(':');
56     private static final Splitter SLASH_SPLITTER = Splitter.on('/');
57
58     private SchemaContextUtil() {
59     }
60
61     /**
62      * Method attempts to find DataSchemaNode in Schema Context via specified
63      * Schema Path. The returned DataSchemaNode from method will be the node at
64      * the end of the SchemaPath. If the DataSchemaNode is not present in the
65      * Schema Context the method will return <code>null</code>. <br>
66      * In case that Schema Context or Schema Path are not specified correctly
67      * (i.e. contains <code>null</code> values) the method will return
68      * IllegalArgumentException.
69      *
70      * @throws IllegalArgumentException
71      *
72      * @param context
73      *            Schema Context
74      * @param schemaPath
75      *            Schema Path to search for
76      * @return SchemaNode from the end of the Schema Path or <code>null</code>
77      *         if the Node is not present.
78      */
79     public static SchemaNode findDataSchemaNode(final SchemaContext context, final SchemaPath schemaPath) {
80         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
81         Preconditions.checkArgument(schemaPath != null, "Schema Path reference cannot be NULL");
82
83         final List<QName> prefixedPath = (schemaPath.getPath());
84         if (prefixedPath == null) {
85             LOG.debug("Schema path {} has null path", schemaPath);
86             return null;
87         }
88
89         LOG.trace("Looking for path {} in context {}", schemaPath, context);
90         return findNodeInSchemaContext(context, prefixedPath);
91     }
92
93     /**
94      * Method attempts to find DataSchemaNode inside of provided Schema Context
95      * and Yang Module accordingly to Non-conditional Revision Aware XPath. The
96      * specified Module MUST be present in Schema Context otherwise the
97      * operation would fail and return <code>null</code>. <br>
98      * The Revision Aware XPath MUST be specified WITHOUT the conditional
99      * statement (i.e. without [cond]) in path, because in this state the Schema
100      * Context is completely unaware of data state and will be not able to
101      * properly resolve XPath. If the XPath contains condition the method will
102      * return IllegalArgumentException. <br>
103      * In case that Schema Context or Module or Revision Aware XPath contains
104      * <code>null</code> references the method will throw
105      * IllegalArgumentException <br>
106      * If the Revision Aware XPath is correct and desired Data Schema Node is
107      * present in Yang module or in depending module in Schema Context the
108      * method will return specified Data Schema Node, otherwise the operation
109      * will fail and method will return <code>null</code>.
110      *
111      * @throws IllegalArgumentException
112      *
113      * @param context
114      *            Schema Context
115      * @param module
116      *            Yang Module
117      * @param nonCondXPath
118      *            Non Conditional Revision Aware XPath
119      * @return Returns Data Schema Node for specified Schema Context for given
120      *         Non-conditional Revision Aware XPath, or <code>null</code> if the
121      *         DataSchemaNode is not present in Schema Context.
122      */
123     public static SchemaNode findDataSchemaNode(final SchemaContext context, final Module module, final RevisionAwareXPath nonCondXPath) {
124         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
125         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
126         Preconditions.checkArgument(nonCondXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
127
128         String strXPath = nonCondXPath.toString();
129         if (strXPath != null) {
130             Preconditions.checkArgument(strXPath.indexOf('[') == -1, "Revision Aware XPath may not contain a condition");
131             if (nonCondXPath.isAbsolute()) {
132                 List<QName> qnamedPath = xpathToQNamePath(context, module, strXPath);
133                 if (qnamedPath != null) {
134                     return findNodeInSchemaContext(context, qnamedPath);
135                 }
136             }
137         }
138         return null;
139     }
140
141     /**
142      * Method attempts to find DataSchemaNode inside of provided Schema Context
143      * and Yang Module accordingly to Non-conditional relative Revision Aware
144      * XPath. The specified Module MUST be present in Schema Context otherwise
145      * the operation would fail and return <code>null</code>. <br>
146      * The relative Revision Aware XPath MUST be specified WITHOUT the
147      * conditional statement (i.e. without [cond]) in path, because in this
148      * state the Schema Context is completely unaware of data state and will be
149      * not able to properly resolve XPath. If the XPath contains condition the
150      * method will return IllegalArgumentException. <br>
151      * The Actual Schema Node MUST be specified correctly because from this
152      * Schema Node will search starts. If the Actual Schema Node is not correct
153      * the operation will simply fail, because it will be unable to find desired
154      * DataSchemaNode. <br>
155      * In case that Schema Context or Module or Actual Schema Node or relative
156      * Revision Aware XPath contains <code>null</code> references the method
157      * will throw IllegalArgumentException <br>
158      * If the Revision Aware XPath doesn't have flag
159      * <code>isAbsolute == false</code> the method will throw
160      * IllegalArgumentException. <br>
161      * If the relative Revision Aware XPath is correct and desired Data Schema
162      * Node is present in Yang module or in depending module in Schema Context
163      * the method will return specified Data Schema Node, otherwise the
164      * operation will fail and method will return <code>null</code>.
165      *
166      * @throws IllegalArgumentException
167      *
168      * @param context
169      *            Schema Context
170      * @param module
171      *            Yang Module
172      * @param actualSchemaNode
173      *            Actual Schema Node
174      * @param relativeXPath
175      *            Relative Non Conditional Revision Aware XPath
176      * @return DataSchemaNode if is present in specified Schema Context for
177      *         given relative Revision Aware XPath, otherwise will return
178      *         <code>null</code>.
179      */
180     public static SchemaNode findDataSchemaNodeForRelativeXPath(final SchemaContext context, final Module module,
181             final SchemaNode actualSchemaNode, final RevisionAwareXPath relativeXPath) {
182         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
183         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
184         Preconditions.checkArgument(actualSchemaNode != null, "Actual Schema Node reference cannot be NULL");
185         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
186         Preconditions.checkState(!relativeXPath.isAbsolute(),
187                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
188                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
189
190         SchemaPath actualNodePath = actualSchemaNode.getPath();
191         if (actualNodePath != null) {
192             Iterable<QName> qnamePath = resolveRelativeXPath(context, module, relativeXPath, actualSchemaNode);
193
194             if (qnamePath != null) {
195                 return findNodeInSchemaContext(context, qnamePath);
196             }
197         }
198         return null;
199     }
200
201     /**
202      * Returns parent Yang Module for specified Schema Context in which Schema
203      * Node is declared. If the Schema Node is not present in Schema Context the
204      * operation will return <code>null</code>. <br>
205      * If Schema Context or Schema Node contains <code>null</code> references
206      * the method will throw IllegalArgumentException
207      *
208      * @throws IllegalArgumentException
209      *
210      * @param context
211      *            Schema Context
212      * @param schemaNode
213      *            Schema Node
214      * @return Yang Module for specified Schema Context and Schema Node, if
215      *         Schema Node is NOT present, the method will returns
216      *         <code>null</code>
217      */
218     public static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
219         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL!");
220         Preconditions.checkArgument(schemaNode != null, "Schema Node cannot be NULL!");
221         Preconditions.checkState(schemaNode.getPath() != null, "Schema Path for Schema Node is not "
222                 + "set properly (Schema Path is NULL)");
223
224         final QName qname = Iterables.getFirst(schemaNode.getPath().getPathTowardsRoot(), null);
225         Preconditions.checkState(qname != null,
226                 "Schema Path contains invalid state of path parts. " +
227                 "The Schema Path MUST contain at least ONE QName which defines namespace and Local name of path.");
228         return context.findModuleByNamespaceAndRevision(qname.getNamespace(), qname.getRevision());
229     }
230
231     public static SchemaNode findNodeInSchemaContext(final SchemaContext context, final Iterable<QName> path) {
232         final QName current = path.iterator().next();
233
234         LOG.trace("Looking up module {} in context {}", current, path);
235         final Module module = context.findModuleByNamespaceAndRevision(current.getNamespace(), current.getRevision());
236         if (module == null) {
237             LOG.debug("Module {} not found", current);
238             return null;
239         }
240
241         return findNodeInModule(module, path);
242     }
243
244     public static GroupingDefinition findGrouping(final SchemaContext context, final Module module, final List<QName> path) {
245         QName first = path.get(0);
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().getPath());
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 (node.getPath().getPath().size() != 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 = findNodeInSchemaContext(ctx, u.getGroupingPath().getPath());
629
630         Preconditions.checkArgument(targetGrouping instanceof GroupingDefinition,
631                 "Failed to generate code for augment in %s", u);
632         GroupingDefinition gr = (GroupingDefinition) targetGrouping;
633         return gr.getDataChildByName(currentName);
634     }
635
636     private static Module getParentModule(final SchemaNode node, final SchemaContext ctx) {
637         QName qname = node.getPath().getPathFromRoot().iterator().next();
638         URI namespace = qname.getNamespace();
639         Date revision = qname.getRevision();
640         return ctx.findModuleByNamespaceAndRevision(namespace, revision);
641     }
642
643     private static DataSchemaNode getTargetNode(final List<QName> tmpPath, final DataSchemaNode node, final SchemaContext ctx) {
644         DataSchemaNode result = node;
645         if (tmpPath.size() == 1) {
646             if (result != null && result.isAddedByUses()) {
647                 result = findOriginal(result, ctx);
648             }
649             return result;
650         } else {
651             DataSchemaNode newParent = result;
652             Collections.reverse(tmpPath);
653
654             tmpPath.remove(0);
655             for (QName name : tmpPath) {
656                 // searching by local name is must, because node has different
657                 // namespace in its original location
658                 if (newParent == null) {
659                     break;
660                 }
661                 if (newParent instanceof DataNodeContainer) {
662                     newParent = ((DataNodeContainer) newParent).getDataChildByName(name.getLocalName());
663                 } else {
664                     newParent = ((ChoiceNode) newParent).getCaseNodeByName(name.getLocalName());
665                 }
666             }
667             if (newParent != null && newParent.isAddedByUses()) {
668                 newParent = findOriginal(newParent, ctx);
669             }
670             return newParent;
671         }
672     }
673
674     private static AugmentationSchema findNodeInAugment(final Collection<AugmentationSchema> augments, final QName name) {
675         for (AugmentationSchema augment : augments) {
676             DataSchemaNode node = augment.getDataChildByName(name);
677             if (node != null) {
678                 return augment;
679             }
680         }
681         return null;
682     }
683
684     private static DataSchemaNode findCorrectTargetFromAugmentGrouping(final DataSchemaNode node,
685             final AugmentationSchema parentNode, final List<SchemaNode> dataTree, final SchemaContext ctx) {
686
687         DataSchemaNode result = null;
688         QName currentName = node.getQName();
689         List<QName> tmpPath = new ArrayList<>();
690         tmpPath.add(currentName);
691         int i = 1;
692         Object parent = null;
693
694         do {
695             if (dataTree.size() < 2 || dataTree.size() == i) {
696                 parent = parentNode;
697             } else {
698                 parent = dataTree.get(dataTree.size() - (i + 1));
699                 tmpPath.add(((SchemaNode) parent).getQName());
700             }
701
702             if (parent instanceof DataNodeContainer) {
703                 DataNodeContainer dataNodeParent = (DataNodeContainer) parent;
704                 for (UsesNode u : dataNodeParent.getUses()) {
705                     if (result == null) {
706                         result = getResultFromUses(u, currentName.getLocalName(), ctx);
707                     }
708                 }
709             }
710
711             if (result == null) {
712                 i = i + 1;
713                 currentName = ((SchemaNode) parent).getQName();
714             }
715         } while (result == null);
716
717         if (result != null) {
718             result = getTargetNode(tmpPath, result, ctx);
719         }
720         return result;
721     }
722
723     /**
724      * Transforms string representation of XPath to Queue of QNames. The XPath
725      * is split by "/" and for each part of XPath is assigned correct module in
726      * Schema Path. <br>
727      * If Schema Context, Parent Module or XPath string contains
728      * <code>null</code> values, the method will throws IllegalArgumentException
729      *
730      * @throws IllegalArgumentException
731      *
732      * @param context
733      *            Schema Context
734      * @param parentModule
735      *            Parent Module
736      * @param xpath
737      *            XPath String
738      * @return return a list of QName
739      */
740     private static List<QName> xpathToQNamePath(final SchemaContext context, final Module parentModule, final String xpath) {
741         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
742         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
743         Preconditions.checkArgument(xpath != null, "XPath string reference cannot be NULL");
744
745         List<QName> path = new LinkedList<QName>();
746         for (String pathComponent : SLASH_SPLITTER.split(xpath)) {
747             if (!pathComponent.isEmpty()) {
748                 path.add(stringPathPartToQName(context, parentModule, pathComponent));
749             }
750         }
751         return path;
752     }
753
754     /**
755      * Transforms part of Prefixed Path as java String to QName. <br>
756      * If the string contains module prefix separated by ":" (i.e.
757      * mod:container) this module is provided from from Parent Module list of
758      * imports. If the Prefixed module is present in Schema Context the QName
759      * can be constructed. <br>
760      * If the Prefixed Path Part does not contains prefix the Parent's Module
761      * namespace is taken for construction of QName. <br>
762      * If Schema Context, Parent Module or Prefixed Path Part refers to
763      * <code>null</code> the method will throw IllegalArgumentException
764      *
765      * @throws IllegalArgumentException
766      *
767      * @param context
768      *            Schema Context
769      * @param parentModule
770      *            Parent Module
771      * @param prefixedPathPart
772      *            Prefixed Path Part string
773      * @return QName from prefixed Path Part String.
774      */
775     private static QName stringPathPartToQName(final SchemaContext context, final Module parentModule, final String prefixedPathPart) {
776         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
777         Preconditions.checkArgument(parentModule != null, "Parent Module reference cannot be NULL");
778         Preconditions.checkArgument(prefixedPathPart != null, "Prefixed Path Part cannot be NULL!");
779
780         if (prefixedPathPart.indexOf(':') != -1) {
781             final Iterator<String> prefixedName = COLON_SPLITTER.split(prefixedPathPart).iterator();
782             final String modulePrefix = prefixedName.next();
783
784             Module module = resolveModuleForPrefix(context, parentModule, modulePrefix);
785             Preconditions.checkArgument(module != null, "Failed to resolve xpath: no module found for prefix %s in module %s",
786                     modulePrefix, parentModule.getName());
787
788             // FIXME: Module should have a QNameModule handle
789             return QName.create(module.getNamespace(), module.getRevision(), prefixedName.next());
790         } else {
791             return QName.create(parentModule.getNamespace(), parentModule.getRevision(), prefixedPathPart);
792         }
793     }
794
795     /**
796      * Method will attempt to resolve and provide Module reference for specified
797      * module prefix. Each Yang module could contains multiple imports which
798      * MUST be associated with corresponding module prefix. The method simply
799      * looks into module imports and returns the module that is bounded with
800      * specified prefix. If the prefix is not present in module or the prefixed
801      * module is not present in specified Schema Context, the method will return
802      * <code>null</code>. <br>
803      * If String prefix is the same as prefix of the specified Module the
804      * reference to this module is returned. <br>
805      * If Schema Context, Module or Prefix are referring to <code>null</code>
806      * the method will return IllegalArgumentException
807      *
808      * @throws IllegalArgumentException
809      *
810      * @param context
811      *            Schema Context
812      * @param module
813      *            Yang Module
814      * @param prefix
815      *            Module Prefix
816      * @return Module for given prefix in specified Schema Context if is
817      *         present, otherwise returns <code>null</code>
818      */
819     private static Module resolveModuleForPrefix(final SchemaContext context, final Module module, final String prefix) {
820         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
821         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
822         Preconditions.checkArgument(prefix != null, "Prefix string cannot be NULL");
823
824         if (prefix.equals(module.getPrefix())) {
825             return module;
826         }
827
828         Set<ModuleImport> imports = module.getImports();
829         for (ModuleImport mi : imports) {
830             if (prefix.equals(mi.getPrefix())) {
831                 return context.findModuleByName(mi.getModuleName(), mi.getRevision());
832             }
833         }
834         return null;
835     }
836
837     /**
838      * @throws IllegalArgumentException
839      *
840      * @param context
841      *            Schema Context
842      * @param module
843      *            Yang Module
844      * @param relativeXPath
845      *            Non conditional Revision Aware Relative XPath
846      * @param leafrefSchemaPath
847      *            Schema Path for Leafref
848      * @return list of QName
849      */
850     private static Iterable<QName> resolveRelativeXPath(final SchemaContext context, final Module module,
851             final RevisionAwareXPath relativeXPath, final SchemaNode leafrefParentNode) {
852         Preconditions.checkArgument(context != null, "Schema Context reference cannot be NULL");
853         Preconditions.checkArgument(module != null, "Module reference cannot be NULL");
854         Preconditions.checkArgument(relativeXPath != null, "Non Conditional Revision Aware XPath cannot be NULL");
855         Preconditions.checkState(!relativeXPath.isAbsolute(),
856                 "Revision Aware XPath MUST be relative i.e. MUST contains ../, "
857                         + "for non relative Revision Aware XPath use findDataSchemaNode method");
858         Preconditions.checkState(leafrefParentNode.getPath() != null,
859                 "Schema Path reference for Leafref cannot be NULL");
860
861         final Iterable<String> xpaths = SLASH_SPLITTER.split(relativeXPath.toString());
862
863         // Find out how many "parent" components there are
864         // FIXME: is .contains() the right check here?
865         int colCount = 0;
866         for (Iterator<String> it = xpaths.iterator(); it.hasNext() && it.next().contains(".."); ) {
867             ++colCount;
868         }
869
870         final List<QName> absolutePath = new LinkedList<QName>();
871         final List<QName> path = leafrefParentNode.getPath().getPath();
872         if (path != null) {
873             int lenght = path.size() - colCount;
874             absolutePath.addAll(path.subList(0, lenght));
875             for (String s : Iterables.skip(xpaths, colCount)) {
876                 absolutePath.add(stringPathPartToQName(context, module, s));
877             }
878         }
879
880         return absolutePath;
881     }
882 }