Merge "Remove unused imports"
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / builder / impl / BuilderUtils.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.parser.builder.impl;
9
10 import com.google.common.base.Function;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Collections2;
15 import com.google.common.collect.Iterables;
16 import com.google.common.io.ByteSource;
17 import com.google.common.io.ByteStreams;
18 import java.io.File;
19 import java.io.FileNotFoundException;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.URI;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.LinkedHashSet;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Set;
33 import java.util.TreeMap;
34 import org.antlr.v4.runtime.tree.ParseTree;
35 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Belongs_to_stmtContext;
36 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_header_stmtsContext;
37 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
38 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Namespace_stmtContext;
39 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Revision_stmtsContext;
40 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Submodule_header_stmtsContext;
41 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Submodule_stmtContext;
42 import org.opendaylight.yangtools.yang.common.QName;
43 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
48 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
50 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
57 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
59 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
60 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
61 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationTargetBuilder;
62 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
63 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
64 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
65 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
66 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingMember;
67 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
68 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
69 import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuilder;
70 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
71 import org.opendaylight.yangtools.yang.parser.impl.ParserListenerUtils;
72 import org.opendaylight.yangtools.yang.parser.impl.util.YangModelDependencyInfo;
73 import org.opendaylight.yangtools.yang.parser.util.NamedByteArrayInputStream;
74 import org.opendaylight.yangtools.yang.parser.util.NamedFileInputStream;
75 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 public final class BuilderUtils {
80
81     private static final Logger LOG = LoggerFactory.getLogger(BuilderUtils.class);
82     private static final Splitter COLON_SPLITTER = Splitter.on(':');
83     private static final Date NULL_DATE = new Date(0L);
84     private static final String INPUT = "input";
85     private static final String OUTPUT = "output";
86
87     private BuilderUtils() {
88     }
89
90     public static Collection<ByteSource> streamsToByteSources(final Collection<InputStream> streams) throws IOException {
91         Collection<ByteSource> result = new HashSet<>();
92         for (InputStream stream : streams) {
93             result.add(new ByteSourceImpl(stream));
94         }
95         return result;
96     }
97
98     public static ByteSource fileToByteSource(final File file) {
99         return new ByteSource() {
100             @Override
101             public InputStream openStream() throws IOException {
102                 return new NamedFileInputStream(file, file.getAbsolutePath());
103             }
104         };
105     }
106
107     public static Collection<ByteSource> filesToByteSources(final Collection<File> streams)
108             throws FileNotFoundException {
109         return Collections2.transform(streams, new Function<File, ByteSource>() {
110             @Override
111             public ByteSource apply(final File input) {
112                 return new ByteSource() {
113                     @Override
114                     public InputStream openStream() throws IOException {
115                         return new NamedFileInputStream(input, input.getAbsolutePath());
116                     }
117                 };
118             }
119         });
120     }
121
122     /**
123      * Create new SchemaPath from given path and qname.
124      *
125      * @param schemaPath
126      *            base path
127      * @param qname
128      *            one or more qnames added to base path
129      * @return new SchemaPath from given path and qname
130      *
131      * @deprecated Use {@link SchemaPath#createChild(QName...)} instead.
132      */
133     @Deprecated
134     public static SchemaPath createSchemaPath(final SchemaPath schemaPath, final QName... qname) {
135         return schemaPath.createChild(qname);
136     }
137
138     /**
139      * Find dependent module based on given prefix
140      *
141      * @param modules
142      *            all available modules
143      * @param module
144      *            current module
145      * @param prefix
146      *            target module prefix
147      * @param line
148      *            current line in yang model
149      * @return module builder if found, null otherwise
150      */
151     public static ModuleBuilder findModuleFromBuilders(final Map<String, TreeMap<Date, ModuleBuilder>> modules,
152             final ModuleBuilder module, final String prefix, final int line) {
153         ModuleBuilder dependentModule;
154         Date dependentModuleRevision;
155
156         if (prefix == null) {
157             dependentModule = module;
158         } else if (prefix.equals(module.getPrefix())) {
159             dependentModule = module;
160         } else {
161             ModuleImport dependentModuleImport = module.getImport(prefix);
162             if (dependentModuleImport == null) {
163                 throw new YangParseException(module.getName(), line, "No import found with prefix '" + prefix + "'.");
164             }
165             String dependentModuleName = dependentModuleImport.getModuleName();
166             dependentModuleRevision = dependentModuleImport.getRevision();
167
168             TreeMap<Date, ModuleBuilder> moduleBuildersByRevision = modules.get(dependentModuleName);
169             if (moduleBuildersByRevision == null) {
170                 return null;
171             }
172             if (dependentModuleRevision == null) {
173                 dependentModule = moduleBuildersByRevision.lastEntry().getValue();
174             } else {
175                 dependentModule = moduleBuildersByRevision.get(dependentModuleRevision);
176             }
177         }
178         return dependentModule;
179     }
180
181     public static ModuleBuilder findModuleFromBuilders(ModuleImport imp, Iterable<ModuleBuilder> modules) {
182         String name = imp.getModuleName();
183         Date revision = imp.getRevision();
184         TreeMap<Date, ModuleBuilder> map = new TreeMap<>();
185         for (ModuleBuilder module : modules) {
186             if (module != null) {
187                 if (module.getName().equals(name)) {
188                     map.put(module.getRevision(), module);
189                 }
190             }
191         }
192         if (map.isEmpty()) {
193             return null;
194         }
195         if (revision == null) {
196             return map.lastEntry().getValue();
197         }
198         return map.get(revision);
199     }
200
201     /**
202      * Find module from context based on prefix.
203      *
204      * @param context
205      *            schema context
206      * @param currentModule
207      *            current module
208      * @param prefix
209      *            prefix used to reference dependent module
210      * @param line
211      *            current line in yang model
212      * @return module based on import with given prefix if found in context,
213      *         null otherwise
214      * @throws YangParseException
215      *             if no import found with given prefix
216      */
217     public static Module findModuleFromContext(final SchemaContext context, final ModuleBuilder currentModule,
218             final String prefix, final int line) {
219         TreeMap<Date, Module> modulesByRevision = new TreeMap<>();
220
221         ModuleImport dependentModuleImport = currentModule.getImport(prefix);
222         if (dependentModuleImport == null) {
223             throw new YangParseException(currentModule.getName(), line, "No import found with prefix '" + prefix + "'.");
224         }
225         String dependentModuleName = dependentModuleImport.getModuleName();
226         Date dependentModuleRevision = dependentModuleImport.getRevision();
227
228         for (Module contextModule : context.getModules()) {
229             if (contextModule.getName().equals(dependentModuleName)) {
230                 Date revision = contextModule.getRevision();
231                 if (revision == null) {
232                     revision = NULL_DATE;
233                 }
234                 modulesByRevision.put(revision, contextModule);
235             }
236         }
237
238         Module result;
239         if (dependentModuleRevision == null) {
240             result = modulesByRevision.get(modulesByRevision.firstKey());
241         } else {
242             result = modulesByRevision.get(dependentModuleRevision);
243         }
244         if (result == null) {
245             throw new YangParseException(currentModule.getName(), line, "Module not found for prefix " + prefix);
246         }
247
248         return result;
249     }
250
251     /**
252      * Add all augment's child nodes to given target.
253      *
254      * @param augment
255      *            builder of augment statement
256      * @param target
257      *            augmentation target node
258      */
259     public static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final Builder target) {
260         if (target instanceof DataNodeContainerBuilder) {
261             fillAugmentTarget(augment, (DataNodeContainerBuilder) target);
262         } else if (target instanceof ChoiceBuilder) {
263             fillAugmentTarget(augment, (ChoiceBuilder) target);
264         } else {
265             throw new YangParseException(
266                     augment.getModuleName(),
267                     augment.getLine(),
268                     "Error in augment parsing: The target node MUST be either a container, list, choice, case, input, output, or notification node.");
269         }
270     }
271
272     /**
273      * Add all augment's child nodes to given target.
274      *
275      * @param augment
276      *            builder of augment statement
277      * @param target
278      *            augmentation target node
279      */
280     private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final DataNodeContainerBuilder target) {
281         for (DataSchemaNodeBuilder child : augment.getChildNodeBuilders()) {
282             DataSchemaNodeBuilder childCopy = CopyUtils.copy(child, target, false);
283             if (augment.getParent() instanceof UsesNodeBuilder) {
284                 setNodeAddedByUses(childCopy);
285             }
286             setNodeAugmenting(childCopy);
287             try {
288                 target.addChildNode(childCopy);
289             } catch (YangParseException e) {
290
291                 // more descriptive message
292                 throw new YangParseException(augment.getModuleName(), augment.getLine(),
293                         "Failed to perform augmentation: " + e.getMessage());
294             }
295         }
296     }
297
298     /**
299      * Add all augment's child nodes to given target.
300      *
301      * @param augment
302      *            builder of augment statement
303      * @param target
304      *            augmentation target choice node
305      */
306     private static void fillAugmentTarget(final AugmentationSchemaBuilder augment, final ChoiceBuilder target) {
307         for (DataSchemaNodeBuilder builder : augment.getChildNodeBuilders()) {
308             DataSchemaNodeBuilder childCopy = CopyUtils.copy(builder, target, false);
309             if (augment.getParent() instanceof UsesNodeBuilder) {
310                 setNodeAddedByUses(childCopy);
311             }
312             setNodeAugmenting(childCopy);
313             target.addCase(childCopy);
314         }
315         for (UsesNodeBuilder usesNode : augment.getUsesNodeBuilders()) {
316             if (usesNode != null) {
317                 throw new YangParseException(augment.getModuleName(), augment.getLine(),
318                         "Error in augment parsing: cannot augment choice with nodes from grouping");
319             }
320         }
321     }
322
323     /**
324      * Set augmenting flag to true for node and all its child nodes.
325      *
326      * @param node
327      */
328     private static void setNodeAugmenting(final DataSchemaNodeBuilder node) {
329         node.setAugmenting(true);
330         if (node instanceof DataNodeContainerBuilder) {
331             DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
332             for (DataSchemaNodeBuilder inner : dataNodeChild.getChildNodeBuilders()) {
333                 setNodeAugmenting(inner);
334             }
335         } else if (node instanceof ChoiceBuilder) {
336             ChoiceBuilder choiceChild = (ChoiceBuilder) node;
337             for (ChoiceCaseBuilder inner : choiceChild.getCases()) {
338                 setNodeAugmenting(inner);
339             }
340         }
341     }
342
343     /**
344      * Set addedByUses flag to true for node and all its child nodes.
345      *
346      * @param node
347      */
348     public static void setNodeAddedByUses(final GroupingMember node) {
349         node.setAddedByUses(true);
350         if (node instanceof DataNodeContainerBuilder) {
351             DataNodeContainerBuilder dataNodeChild = (DataNodeContainerBuilder) node;
352             for (DataSchemaNodeBuilder inner : dataNodeChild.getChildNodeBuilders()) {
353                 setNodeAddedByUses(inner);
354             }
355         } else if (node instanceof ChoiceBuilder) {
356             ChoiceBuilder choiceChild = (ChoiceBuilder) node;
357             for (ChoiceCaseBuilder inner : choiceChild.getCases()) {
358                 setNodeAddedByUses(inner);
359             }
360         }
361     }
362
363     public static SchemaNodeBuilder findSchemaNode(final Iterable<QName> path, final SchemaNodeBuilder parentNode) {
364         SchemaNodeBuilder node = null;
365         SchemaNodeBuilder parent = parentNode;
366         int size = Iterables.size(path);
367         int i = 0;
368         for (QName qname : path) {
369             String name = qname.getLocalName();
370             if (parent instanceof DataNodeContainerBuilder) {
371                 node = ((DataNodeContainerBuilder) parent).getDataChildByName(name);
372                 if (node == null) {
373                     node = findUnknownNode(name, parent);
374                 }
375             } else if (parent instanceof ChoiceBuilder) {
376                 node = ((ChoiceBuilder) parent).getCaseNodeByName(name);
377                 if (node == null) {
378                     node = findUnknownNode(name, parent);
379                 }
380             } else if (parent instanceof RpcDefinitionBuilder) {
381                 if ("input".equals(name)) {
382                     node = ((RpcDefinitionBuilder) parent).getInput();
383                 } else if ("output".equals(name)) {
384                     node = ((RpcDefinitionBuilder) parent).getOutput();
385                 } else {
386                     if (node == null) {
387                         node = findUnknownNode(name, parent);
388                     }
389                 }
390             } else {
391                 node = findUnknownNode(name, parent);
392             }
393
394             if (i < size - 1) {
395                 parent = node;
396             }
397             i = i + 1;
398         }
399
400         return node;
401     }
402
403     private static UnknownSchemaNodeBuilder findUnknownNode(final String name, final Builder parent) {
404         for (UnknownSchemaNodeBuilder un : parent.getUnknownNodes()) {
405             if (un.getQName().getLocalName().equals(name)) {
406                 return un;
407             }
408         }
409         return null;
410     }
411
412     /**
413      *
414      * Find a builder for node in data namespace of YANG module.
415      *
416      * Search is performed on full QName equals, this means builders and schema
417      * path MUST be resolved against imports and their namespaces.
418      *
419      * Search is done in data namespace, this means notification, rpc
420      * definitions and top level data definitions are considered as top-level
421      * items, from which it is possible to traverse.
422      *
423      *
424      * @param schemaPath
425      *            Schema Path to node
426      * @param module
427      *            ModuleBuilder to start lookup in
428      * @return Node Builder if found, {@link Optional#absent()} otherwise.
429      */
430     public static Optional<SchemaNodeBuilder> findSchemaNodeInModule(final SchemaPath schemaPath,
431             final ModuleBuilder module) {
432         Iterator<QName> path = schemaPath.getPathFromRoot().iterator();
433         Preconditions.checkArgument(path.hasNext(), "Schema Path must contain at least one element.");
434         QName first = path.next();
435         Optional<SchemaNodeBuilder> currentNode = getDataNamespaceChild(module, first);
436
437         while (currentNode.isPresent() && path.hasNext()) {
438             SchemaNodeBuilder currentParent = currentNode.get();
439             QName currentPath = path.next();
440             currentNode = findDataChild(currentParent, currentPath);
441             if (!currentNode.isPresent()) {
442                 for (SchemaNodeBuilder un : currentParent.getUnknownNodes()) {
443                     if (un.getQName().equals(currentPath)) {
444                         currentNode = Optional.of(un);
445                     }
446                 }
447             }
448         }
449         return currentNode;
450     }
451
452     private static Optional<SchemaNodeBuilder> findDataChild(final SchemaNodeBuilder parent, final QName child) {
453         if (parent instanceof DataNodeContainerBuilder) {
454             return castOptional(SchemaNodeBuilder.class,
455                     findDataChildInDataNodeContainer((DataNodeContainerBuilder) parent, child));
456         } else if (parent instanceof ChoiceBuilder) {
457             return castOptional(SchemaNodeBuilder.class, findCaseInChoice((ChoiceBuilder) parent, child));
458         } else if (parent instanceof RpcDefinitionBuilder) {
459             return castOptional(SchemaNodeBuilder.class, findContainerInRpc((RpcDefinitionBuilder) parent, child));
460
461         } else {
462             LOG.trace("Child {} not found in node {}", child, parent);
463             return Optional.absent();
464         }
465     }
466
467     /**
468      * Casts optional from one argument to other.
469      *
470      * @param cls
471      *            Class to be checked
472      * @param optional
473      *            Original value
474      * @return Optional object with type argument casted as cls
475      */
476     private static <T> Optional<T> castOptional(final Class<T> cls, final Optional<?> optional) {
477         if (optional.isPresent()) {
478             Object value = optional.get();
479             if (cls.isInstance(value)) {
480                 @SuppressWarnings("unchecked")
481                 // Actually checked by outer if
482                 T casted = (T) value;
483                 return Optional.of(casted);
484             }
485         }
486         return Optional.absent();
487     }
488
489     // FIXME: if rpc does not define input or output, this method creates it
490     /**
491      *
492      * Gets input / output container from {@link RpcDefinitionBuilder} if QName
493      * is input/output.
494      *
495      *
496      * @param parent
497      *            RPC Definition builder
498      * @param child
499      *            Child QName
500      * @return Optional of input/output if defined and QName is input/output.
501      *         Otherwise {@link Optional#absent()}.
502      */
503     private static Optional<ContainerSchemaNodeBuilder> findContainerInRpc(final RpcDefinitionBuilder parent,
504             final QName child) {
505         if (INPUT.equals(child.getLocalName())) {
506             if (parent.getInput() == null) {
507                 QName qname = QName.create(parent.getQName().getModule(), "input");
508                 final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(parent.getModuleName(),
509                         parent.getLine(), qname, parent.getPath().createChild(qname));
510                 inputBuilder.setParent(parent);
511                 parent.setInput(inputBuilder);
512                 return Optional.of(inputBuilder);
513             }
514             return Optional.of(parent.getInput());
515         } else if (OUTPUT.equals(child.getLocalName())) {
516             if (parent.getOutput() == null) {
517                 QName qname = QName.create(parent.getQName().getModule(), "output");
518                 final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(parent.getModuleName(),
519                         parent.getLine(), qname, parent.getPath().createChild(qname));
520                 outputBuilder.setParent(parent);
521                 parent.setOutput(outputBuilder);
522                 return Optional.of(outputBuilder);
523             }
524             return Optional.of(parent.getOutput());
525         }
526         LOG.trace("Child {} not found in node {}", child, parent);
527         return Optional.absent();
528     }
529
530     /**
531      * Finds case by QName in {@link ChoiceBuilder}
532      *
533      *
534      * @param parent
535      *            DataNodeContainer in which lookup should be performed
536      * @param child
537      *            QName of child
538      * @return Optional of child if found.
539      */
540
541     private static Optional<ChoiceCaseBuilder> findCaseInChoice(final ChoiceBuilder parent, final QName child) {
542         for (ChoiceCaseBuilder caze : parent.getCases()) {
543             if (caze.getQName().equals(child)) {
544                 return Optional.of(caze);
545             }
546         }
547         LOG.trace("Child {} not found in node {}", child, parent);
548         return Optional.absent();
549     }
550
551     /**
552      * Finds direct child by QName in {@link DataNodeContainerBuilder}
553      *
554      *
555      * @param parent
556      *            DataNodeContainer in which lookup should be performed
557      * @param child
558      *            QName of child
559      * @return Optional of child if found.
560      */
561     private static Optional<DataSchemaNodeBuilder> findDataChildInDataNodeContainer(final DataNodeContainerBuilder parent,
562             final QName child) {
563         for (DataSchemaNodeBuilder childNode : parent.getChildNodeBuilders()) {
564             if (childNode.getQName().equals(child)) {
565                 return Optional.of(childNode);
566             }
567         }
568         LOG.trace("Child {} not found in node {}", child, parent);
569         return Optional.absent();
570     }
571
572     /**
573      *
574      * Find a child builder for node in data namespace of YANG module.
575      *
576      * Search is performed on full QName equals, this means builders and schema
577      * path MUST be resolved against imports and their namespaces.
578      *
579      * Search is done in data namespace, this means notification, rpc
580      * definitions and top level data definitions are considered as top-level
581      * items, from which it is possible to traverse.
582      *
583      *
584      * @param child
585      *            Child QName.
586      * @param module
587      *            ModuleBuilder to start lookup in
588      * @return Node Builder if found, {@link Optional#absent()} otherwise.
589      */
590     private static Optional<SchemaNodeBuilder> getDataNamespaceChild(final ModuleBuilder module, final QName child) {
591         /*
592          * First we do lookup in data tree, if node is found we return it.
593          */
594         final Optional<SchemaNodeBuilder> dataTreeNode = getDataChildByQName(module, child);
595         if (dataTreeNode.isPresent()) {
596             return dataTreeNode;
597         }
598
599         /*
600          * We lookup in notifications
601          */
602         Set<NotificationBuilder> notifications = module.getAddedNotifications();
603         for (NotificationBuilder notification : notifications) {
604             if (notification.getQName().equals(child)) {
605                 return Optional.<SchemaNodeBuilder> of(notification);
606             }
607         }
608
609         /*
610          * We lookup in RPCs
611          */
612         Set<RpcDefinitionBuilder> rpcs = module.getAddedRpcs();
613         for (RpcDefinitionBuilder rpc : rpcs) {
614             if (rpc.getQName().equals(child)) {
615                 return Optional.<SchemaNodeBuilder> of(rpc);
616             }
617         }
618         LOG.trace("Child {} not found in data namespace of module {}", child, module);
619         return Optional.absent();
620     }
621
622     private static Optional<SchemaNodeBuilder> getDataChildByQName(final DataNodeContainerBuilder builder, final QName child) {
623         for (DataSchemaNodeBuilder childNode : builder.getChildNodeBuilders()) {
624             if (childNode.getQName().equals(child)) {
625                 return Optional.<SchemaNodeBuilder> of(childNode);
626             }
627         }
628         LOG.trace("Child {} not found in node {}", child, builder);
629         return Optional.absent();
630     }
631
632     /**
633      * Find augment target node and perform augmentation.
634      *
635      * @param augment
636      *            augment builder to process
637      * @param firstNodeParent
638      *            parent of first node in path
639      * @return true if augmentation process succeed, false otherwise
640      */
641     public static boolean processAugmentation(final AugmentationSchemaBuilder augment,
642             final ModuleBuilder firstNodeParent) {
643         Optional<SchemaNodeBuilder> potentialTargetNode = findSchemaNodeInModule(augment.getTargetPath(),
644                 firstNodeParent);
645         if (!potentialTargetNode.isPresent()) {
646             return false;
647         } else if (potentialTargetNode.get() instanceof UnknownSchemaNodeBuilder) {
648             LOG.warn("Error in augment parsing: unsupported augment target: {}", potentialTargetNode.get());
649             return true;
650         }
651         SchemaNodeBuilder targetNode = potentialTargetNode.get();
652         fillAugmentTarget(augment, targetNode);
653         Preconditions.checkState(targetNode instanceof AugmentationTargetBuilder,
654                 "Node refered by augmentation must be valid augmentation target");
655         ((AugmentationTargetBuilder) targetNode).addAugmentation(augment);
656         augment.setResolved(true);
657         return true;
658     }
659
660     public static IdentitySchemaNodeBuilder findBaseIdentity(final ModuleBuilder module, final String baseString,
661             final int line) {
662
663         // FIXME: optimize indexOf() away?
664         if (baseString.indexOf(':') != -1) {
665             final Iterator<String> it = COLON_SPLITTER.split(baseString).iterator();
666             final String prefix = it.next();
667             final String name = it.next();
668
669             if (it.hasNext()) {
670                 throw new YangParseException(module.getName(), line, "Failed to parse identityref base: " + baseString);
671             }
672
673             ModuleBuilder dependentModule = getModuleByPrefix(module, prefix);
674             if (dependentModule == null) {
675                 return null;
676             }
677
678             return findIdentity(dependentModule.getAddedIdentities(), name);
679         } else {
680             return findIdentity(module.getAddedIdentities(), baseString);
681         }
682     }
683
684     public static IdentitySchemaNodeBuilder findIdentity(final Set<IdentitySchemaNodeBuilder> identities,
685             final String name) {
686         for (IdentitySchemaNodeBuilder identity : identities) {
687             if (identity.getQName().getLocalName().equals(name)) {
688                 return identity;
689             }
690         }
691         return null;
692     }
693
694     /**
695      * Get module in which this node is defined.
696      *
697      * @param node
698      * @return builder of module where this node is defined
699      */
700     public static ModuleBuilder getParentModule(final Builder node) {
701         if (node instanceof ModuleBuilder) {
702             return (ModuleBuilder) node;
703         }
704         Builder parent = node.getParent();
705         while (!(parent instanceof ModuleBuilder)) {
706             parent = parent.getParent();
707         }
708         ModuleBuilder parentModule = (ModuleBuilder) parent;
709         if (parentModule.isSubmodule()) {
710             parentModule = parentModule.getParent();
711         }
712         return parentModule;
713     }
714
715     public static Set<DataSchemaNodeBuilder> wrapChildNodes(final String moduleName, final int line,
716             final Collection<DataSchemaNode> nodes, final SchemaPath parentPath, final QName parentQName) {
717         Set<DataSchemaNodeBuilder> result = new LinkedHashSet<>(nodes.size());
718
719         for (DataSchemaNode node : nodes) {
720             QName qname = QName.create(parentQName, node.getQName().getLocalName());
721             DataSchemaNodeBuilder wrapped = wrapChildNode(moduleName, line, node, parentPath, qname);
722             result.add(wrapped);
723         }
724         return result;
725     }
726
727     public static DataSchemaNodeBuilder wrapChildNode(final String moduleName, final int line,
728             final DataSchemaNode node, final SchemaPath parentPath, final QName qname) {
729
730         final SchemaPath schemaPath = parentPath.createChild(qname);
731
732         if (node instanceof AnyXmlSchemaNode) {
733             return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
734         } else if (node instanceof ChoiceSchemaNode) {
735             return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceSchemaNode) node));
736         } else if (node instanceof ContainerSchemaNode) {
737             return new ContainerSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ContainerSchemaNode) node));
738         } else if (node instanceof LeafSchemaNode) {
739             return new LeafSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((LeafSchemaNode) node));
740         } else if (node instanceof LeafListSchemaNode) {
741             return new LeafListSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((LeafListSchemaNode) node));
742         } else if (node instanceof ListSchemaNode) {
743             return new ListSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ListSchemaNode) node));
744         } else if (node instanceof ChoiceCaseNode) {
745             return new ChoiceCaseBuilder(moduleName, line, qname, schemaPath, ((ChoiceCaseNode) node));
746         } else {
747             throw new YangParseException(moduleName, line, "Failed to copy node: Unknown type of DataSchemaNode: "
748                     + node);
749         }
750     }
751
752     public static Set<GroupingBuilder> wrapGroupings(final String moduleName, final int line,
753             final Set<GroupingDefinition> nodes, final SchemaPath parentPath, final QName parentQName) {
754         Set<GroupingBuilder> result = new HashSet<>();
755         for (GroupingDefinition node : nodes) {
756             QName qname = QName.create(parentQName, node.getQName().getLocalName());
757             SchemaPath schemaPath = parentPath.createChild(qname);
758             result.add(new GroupingBuilderImpl(moduleName, line, qname, schemaPath, node));
759         }
760         return result;
761     }
762
763     public static Set<TypeDefinitionBuilder> wrapTypedefs(final String moduleName, final int line,
764             final DataNodeContainer dataNode, final SchemaPath parentPath, final QName parentQName) {
765         Set<TypeDefinition<?>> nodes = dataNode.getTypeDefinitions();
766         Set<TypeDefinitionBuilder> result = new HashSet<>();
767         for (TypeDefinition<?> node : nodes) {
768             QName qname = QName.create(parentQName, node.getQName().getLocalName());
769             SchemaPath schemaPath = parentPath.createChild(qname);
770             result.add(new TypeDefinitionBuilderImpl(moduleName, line, qname, schemaPath, ((ExtendedType) node)));
771         }
772         return result;
773     }
774
775     public static List<UnknownSchemaNodeBuilderImpl> wrapUnknownNodes(final String moduleName, final int line,
776             final List<UnknownSchemaNode> nodes, final SchemaPath parentPath, final QName parentQName) {
777         List<UnknownSchemaNodeBuilderImpl> result = new ArrayList<>();
778         for (UnknownSchemaNode node : nodes) {
779             QName qname = QName.create(parentQName, node.getQName().getLocalName());
780             SchemaPath schemaPath = parentPath.createChild(qname);
781             result.add(new UnknownSchemaNodeBuilderImpl(moduleName, line, qname, schemaPath, node));
782         }
783         return result;
784     }
785
786     private static final class ByteSourceImpl extends ByteSource {
787         private final String toString;
788         private final byte[] data;
789
790         private ByteSourceImpl(final InputStream input) throws IOException {
791             toString = input.toString();
792             data = ByteStreams.toByteArray(input);
793         }
794
795         @Override
796         public InputStream openStream() throws IOException {
797             return new NamedByteArrayInputStream(data, toString);
798         }
799     }
800
801     public static ModuleBuilder getModuleByPrefix(final ModuleBuilder module, final String prefix) {
802         if (prefix == null || prefix.isEmpty() || prefix.equals(module.getPrefix())) {
803             return module;
804         } else {
805             return module.getImportedModule(prefix);
806         }
807     }
808
809     public static ModuleBuilder findModule(final QName qname, final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
810         TreeMap<Date, ModuleBuilder> map = modules.get(qname.getNamespace());
811         if (map == null) {
812             return null;
813         }
814         if (qname.getRevision() == null) {
815             return map.lastEntry().getValue();
816         }
817         return map.get(qname.getRevision());
818     }
819
820     public static Map<String, TreeMap<Date, URI>> createYangNamespaceContext(
821             final Collection<? extends ParseTree> modules, final Optional<SchemaContext> context) {
822         Map<String, TreeMap<Date, URI>> namespaceContext = new HashMap<>();
823         Set<Submodule_stmtContext> submodules = new HashSet<>();
824         // first read ParseTree collection and separate modules and submodules
825         for (ParseTree module : modules) {
826             for (int i = 0; i < module.getChildCount(); i++) {
827                 ParseTree moduleTree = module.getChild(i);
828                 if (moduleTree instanceof Submodule_stmtContext) {
829                     // put submodule context to separate collection
830                     submodules.add((Submodule_stmtContext) moduleTree);
831                 } else if (moduleTree instanceof Module_stmtContext) {
832                     // get name, revision and namespace from module
833                     Module_stmtContext moduleCtx = (Module_stmtContext) moduleTree;
834                     final String moduleName = ParserListenerUtils.stringFromNode(moduleCtx);
835                     Date rev = null;
836                     URI namespace = null;
837                     for (int j = 0; j < moduleCtx.getChildCount(); j++) {
838                         ParseTree moduleCtxChildTree = moduleCtx.getChild(j);
839                         if (moduleCtxChildTree instanceof Revision_stmtsContext) {
840                             String revisionDateStr = YangModelDependencyInfo
841                                     .getLatestRevision((Revision_stmtsContext) moduleCtxChildTree);
842                             if (revisionDateStr == null) {
843                                 rev = new Date(0);
844                             } else {
845                                 rev = QName.parseRevision(revisionDateStr);
846                             }
847                         }
848                         if (moduleCtxChildTree instanceof Module_header_stmtsContext) {
849                             Module_header_stmtsContext headerCtx = (Module_header_stmtsContext) moduleCtxChildTree;
850                             for (int k = 0; k < headerCtx.getChildCount(); k++) {
851                                 ParseTree ctx = headerCtx.getChild(k);
852                                 if (ctx instanceof Namespace_stmtContext) {
853                                     final String namespaceStr = ParserListenerUtils.stringFromNode(ctx);
854                                     namespace = URI.create(namespaceStr);
855                                     break;
856                                 }
857                             }
858                         }
859                     }
860                     // update namespaceContext
861                     TreeMap<Date, URI> revToNs = namespaceContext.get(moduleName);
862                     if (revToNs == null) {
863                         revToNs = new TreeMap<>();
864                         revToNs.put(rev, namespace);
865                         namespaceContext.put(moduleName, revToNs);
866                     }
867                     revToNs.put(rev, namespace);
868                 }
869             }
870         }
871         // after all ParseTree-s are parsed update namespaceContext with modules
872         // from SchemaContext
873         if (context.isPresent()) {
874             for (Module module : context.get().getModules()) {
875                 TreeMap<Date, URI> revToNs = namespaceContext.get(module.getName());
876                 if (revToNs == null) {
877                     revToNs = new TreeMap<>();
878                     revToNs.put(module.getRevision(), module.getNamespace());
879                     namespaceContext.put(module.getName(), revToNs);
880                 }
881                 revToNs.put(module.getRevision(), module.getNamespace());
882             }
883         }
884         // when all modules are processed, traverse submodules and update
885         // namespaceContext with mapping for submodules
886         for (Submodule_stmtContext submodule : submodules) {
887             final String moduleName = ParserListenerUtils.stringFromNode(submodule);
888             for (int i = 0; i < submodule.getChildCount(); i++) {
889                 ParseTree subHeaderCtx = submodule.getChild(i);
890                 if (subHeaderCtx instanceof Submodule_header_stmtsContext) {
891                     for (int j = 0; j < subHeaderCtx.getChildCount(); j++) {
892                         ParseTree belongsCtx = subHeaderCtx.getChild(j);
893                         if (belongsCtx instanceof Belongs_to_stmtContext) {
894                             final String belongsTo = ParserListenerUtils.stringFromNode(belongsCtx);
895                             TreeMap<Date, URI> ns = namespaceContext.get(belongsTo);
896                             if (ns == null) {
897                                 throw new YangParseException(moduleName, submodule.getStart().getLine(), String.format(
898                                         "Unresolved belongs-to statement: %s", belongsTo));
899                             }
900                             // submodule get namespace and revision from module
901                             TreeMap<Date, URI> subNs = new TreeMap<>();
902                             subNs.put(ns.firstKey(), ns.firstEntry().getValue());
903                             namespaceContext.put(moduleName, subNs);
904                         }
905                     }
906                 }
907             }
908         }
909         return namespaceContext;
910     }
911
912 }