Merge "BUG-868: do not use InstanceIdentifier constructor"
[yangtools.git] / yang / yang-parser-impl / src / main / java / org / opendaylight / yangtools / yang / parser / builder / impl / ModuleBuilder.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
3  * This program and the accompanying materials are made available under the
4  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
5  * and is available at http://www.eclipse.org/legal/epl-v10.html
6  */
7 package org.opendaylight.yangtools.yang.parser.builder.impl;
8
9 import com.google.common.io.ByteSource;
10 import java.io.IOException;
11 import java.io.InputStream;
12 import java.net.URI;
13 import java.util.ArrayList;
14 import java.util.Collections;
15 import java.util.Date;
16 import java.util.Deque;
17 import java.util.HashSet;
18 import java.util.LinkedHashSet;
19 import java.util.LinkedList;
20 import java.util.List;
21 import java.util.Set;
22 import java.util.TreeSet;
23 import org.apache.commons.io.IOUtils;
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.Deviation;
27 import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
28 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
29 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
30 import org.opendaylight.yangtools.yang.model.api.Module;
31 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
32 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
33 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
34 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
35 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
36 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
37 import org.opendaylight.yangtools.yang.model.util.ModuleImportImpl;
38 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
39 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
40 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
41 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
42 import org.opendaylight.yangtools.yang.parser.builder.api.DocumentedNodeBuilder;
43 import org.opendaylight.yangtools.yang.parser.builder.api.ExtensionBuilder;
44 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
45 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
46 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
47 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
48 import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuilder;
49 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
50 import org.opendaylight.yangtools.yang.parser.builder.util.AbstractDocumentedDataNodeContainerBuilder;
51 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
52 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
53
54 /**
55  * Builder of Module object. If this module is dependent on external
56  * module/modules, these dependencies must be resolved before module is built,
57  * otherwise result may not be valid.
58  */
59 public class ModuleBuilder extends AbstractDocumentedDataNodeContainerBuilder implements DocumentedNodeBuilder {
60
61     private ModuleImpl instance;
62     private final String name;
63     private final String sourcePath;
64     private static final SchemaPath SCHEMA_PATH = SchemaPath.create(Collections.<QName> emptyList(), true);
65     private URI namespace;
66     private String prefix;
67     private Date revision;
68
69     private final boolean submodule;
70     private String belongsTo;
71     private ModuleBuilder parent;
72
73     private final Deque<Builder> actualPath = new LinkedList<>();
74     private final Set<TypeAwareBuilder> dirtyNodes = new HashSet<>();
75
76     final Set<ModuleImport> imports = new HashSet<>();
77
78     private final Set<AugmentationSchema> augments = new LinkedHashSet<>();
79     private final List<AugmentationSchemaBuilder> augmentBuilders = new ArrayList<>();
80     private final List<AugmentationSchemaBuilder> allAugments = new ArrayList<>();
81
82     private final List<GroupingBuilder> allGroupings = new ArrayList<>();
83
84     private final List<UsesNodeBuilder> allUsesNodes = new ArrayList<>();
85
86     private final Set<RpcDefinition> rpcs = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
87     private final Set<RpcDefinitionBuilder> addedRpcs = new HashSet<>();
88
89     private final Set<NotificationDefinition> notifications = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
90     private final Set<NotificationBuilder> addedNotifications = new HashSet<>();
91
92     private final Set<IdentitySchemaNode> identities = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
93     private final Set<IdentitySchemaNodeBuilder> addedIdentities = new HashSet<>();
94
95     private final Set<FeatureDefinition> features = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
96     private final Set<FeatureBuilder> addedFeatures = new HashSet<>();
97
98     private final Set<Deviation> deviations = new HashSet<>();
99     private final Set<DeviationBuilder> deviationBuilders = new HashSet<>();
100
101     private final List<ExtensionDefinition> extensions = new ArrayList<>();
102     private final List<ExtensionBuilder> addedExtensions = new ArrayList<>();
103
104     private final List<UnknownSchemaNodeBuilder> allUnknownNodes = new ArrayList<>();
105
106     private final List<ListSchemaNodeBuilder> allLists = new ArrayList<>();
107
108     private String source;
109     private String yangVersion;
110     private String organization;
111     private String contact;
112
113     public ModuleBuilder(final String name, final String sourcePath) {
114         this(name, false, sourcePath);
115     }
116
117     public ModuleBuilder(final String name, final boolean submodule, final String sourcePath) {
118         super(name, 0, null);
119         this.name = name;
120         this.sourcePath = sourcePath;
121         this.submodule = submodule;
122         actualPath.push(this);//FIXME: this escapes constructor
123     }
124
125     public ModuleBuilder(final Module base) {
126         super(base.getName(), 0, new QName(base.getNamespace(), base.getRevision(), base.getPrefix(), base.getName()),
127                 SCHEMA_PATH, base);
128         this.name = base.getName();
129         this.sourcePath = base.getModuleSourcePath();
130
131         submodule = false;
132         yangVersion = base.getYangVersion();
133         actualPath.push(this);//FIXME: this escapes constructor
134         namespace = base.getNamespace();
135         prefix = base.getPrefix();
136         revision = base.getRevision();
137
138         augments.addAll(base.getAugmentations());
139         rpcs.addAll(base.getRpcs());
140         notifications.addAll(base.getNotifications());
141
142         for (IdentitySchemaNode identityNode : base.getIdentities()) {
143             addedIdentities.add(new IdentitySchemaNodeBuilder(name, identityNode));
144         }
145
146         features.addAll(base.getFeatures());
147         deviations.addAll(base.getDeviations());
148         extensions.addAll(base.getExtensionSchemaNodes());
149         unknownNodes.addAll(base.getUnknownSchemaNodes());
150         source = base.getSource();
151     }
152
153     @Override
154     protected String getStatementName() {
155         return "module";
156     }
157
158     /**
159      * Build new Module object based on this builder.
160      */
161     @Override
162     public Module build() {
163         if(instance != null) {
164             return instance;
165         }
166
167         buildChildren();
168
169         // FEATURES
170         for (FeatureBuilder fb : addedFeatures) {
171             features.add(fb.build());
172         }
173
174         // NOTIFICATIONS
175         for (NotificationBuilder entry : addedNotifications) {
176             notifications.add(entry.build());
177         }
178
179         // AUGMENTATIONS
180         for (AugmentationSchemaBuilder builder : augmentBuilders) {
181             augments.add(builder.build());
182         }
183
184         // RPCs
185         for (RpcDefinitionBuilder rpc : addedRpcs) {
186             rpcs.add(rpc.build());
187         }
188
189         // DEVIATIONS
190         for (DeviationBuilder entry : deviationBuilders) {
191             deviations.add(entry.build());
192         }
193
194         // EXTENSIONS
195         for (ExtensionBuilder eb : addedExtensions) {
196             extensions.add(eb.build());
197         }
198         Collections.sort(extensions, Comparators.SCHEMA_NODE_COMP);
199
200
201         // IDENTITIES
202         for (IdentitySchemaNodeBuilder id : addedIdentities) {
203             identities.add(id.build());
204         }
205
206         // UNKNOWN NODES
207         for (UnknownSchemaNodeBuilder unb : addedUnknownNodes) {
208             unknownNodes.add(unb.build());
209         }
210         Collections.sort(unknownNodes, Comparators.SCHEMA_NODE_COMP);
211
212         instance = new ModuleImpl(name, sourcePath, this);
213         return instance;
214     }
215
216     public String getModuleSourcePath() {
217         return sourcePath;
218     }
219
220     @Override
221     public ModuleBuilder getParent() {
222         return parent;
223     }
224
225     public void setParent(final ModuleBuilder parent) {
226         this.parent = parent;
227     }
228
229     @Override
230     public void setParent(final Builder parent) {
231         throw new YangParseException(name, 0, "Can not set parent to module");
232     }
233
234     @Override
235     public SchemaPath getPath() {
236         return SCHEMA_PATH;
237     }
238
239     public void enterNode(final Builder node) {
240         actualPath.push(node);
241     }
242
243     public void exitNode() {
244         actualPath.pop();
245     }
246
247     public Builder getActualNode() {
248         if (actualPath.isEmpty()) {
249             return null;
250         } else {
251             return actualPath.peekFirst();
252         }
253     }
254
255     public Set<TypeAwareBuilder> getDirtyNodes() {
256         return dirtyNodes;
257     }
258
259     public Set<AugmentationSchema> getAugments() {
260         return augments;
261     }
262
263     public List<AugmentationSchemaBuilder> getAugmentBuilders() {
264         return augmentBuilders;
265     }
266
267     public List<AugmentationSchemaBuilder> getAllAugments() {
268         return allAugments;
269     }
270
271     public Set<IdentitySchemaNode> getIdentities() {
272         return identities;
273     }
274
275     public Set<IdentitySchemaNodeBuilder> getAddedIdentities() {
276         return addedIdentities;
277     }
278
279     public Set<FeatureDefinition> getFeatures() {
280         return features;
281     }
282
283     public Set<FeatureBuilder> getAddedFeatures() {
284         return addedFeatures;
285     }
286
287     public List<GroupingBuilder> getAllGroupings() {
288         return allGroupings;
289     }
290
291     public List<UsesNodeBuilder> getAllUsesNodes() {
292         return allUsesNodes;
293     }
294
295     public Set<Deviation> getDeviations() {
296         return deviations;
297     }
298
299     public Set<DeviationBuilder> getDeviationBuilders() {
300         return deviationBuilders;
301     }
302
303     public List<ExtensionDefinition> getExtensions() {
304         return extensions;
305     }
306
307     public List<ExtensionBuilder> getAddedExtensions() {
308         return addedExtensions;
309     }
310
311     public List<UnknownSchemaNodeBuilder> getAllUnknownNodes() {
312         return allUnknownNodes;
313     }
314
315     public List<ListSchemaNodeBuilder> getAllLists() {
316         return allLists;
317     }
318
319     public String getName() {
320         return name;
321     }
322
323     public URI getNamespace() {
324         return namespace;
325     }
326
327     public void setNamespace(final URI namespace) {
328         this.namespace = namespace;
329     }
330
331     public String getPrefix() {
332         return prefix;
333     }
334
335     public Date getRevision() {
336         return revision;
337     }
338
339     protected Set<ModuleImport> getImports() {
340         return imports;
341     }
342
343     protected String getSource() {
344         return source;
345     }
346
347     public boolean isSubmodule() {
348         return submodule;
349     }
350
351     public String getBelongsTo() {
352         return belongsTo;
353     }
354
355     public void setBelongsTo(final String belongsTo) {
356         this.belongsTo = belongsTo;
357     }
358
359     public void markActualNodeDirty() {
360         final TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) getActualNode();
361         dirtyNodes.add(nodeBuilder);
362     }
363
364     public void setRevision(final Date revision) {
365         this.revision = revision;
366     }
367
368     public void setPrefix(final String prefix) {
369         this.prefix = prefix;
370     }
371
372     public void setYangVersion(final String yangVersion) {
373         this.yangVersion = yangVersion;
374     }
375
376     public void setOrganization(final String organization) {
377         this.organization = organization;
378     }
379
380     public void setContact(final String contact) {
381         this.contact = contact;
382     }
383
384     public boolean addModuleImport(final String moduleName, final Date revision, final String prefix) {
385         checkNotSealed();
386         final ModuleImport moduleImport = createModuleImport(moduleName, revision, prefix);
387         return imports.add(moduleImport);
388     }
389
390     public Set<ModuleImport> getModuleImports() {
391         return imports;
392     }
393
394     public ExtensionBuilder addExtension(final QName qname, final int line, final SchemaPath path) {
395         checkNotSealed();
396         Builder parent = getActualNode();
397         if (!(parent.equals(this))) {
398             throw new YangParseException(name, line, "extension can be defined only in module or submodule");
399         }
400
401         final String extName = qname.getLocalName();
402         for (ExtensionBuilder addedExtension : addedExtensions) {
403             if (addedExtension.getQName().getLocalName().equals(extName)) {
404                 raiseYangParserException("extension", "node", extName, line, addedExtension.getLine());
405             }
406         }
407         final ExtensionBuilder builder = new ExtensionBuilderImpl(name, line, qname, path);
408         builder.setParent(parent);
409         addedExtensions.add(builder);
410         return builder;
411     }
412
413     public ContainerSchemaNodeBuilder addContainerNode(final int line, final QName qname, final SchemaPath schemaPath) {
414         checkNotSealed();
415         final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
416
417         Builder parent = getActualNode();
418         builder.setParent(parent);
419         addChildToParent(parent, builder, qname.getLocalName());
420
421         return builder;
422     }
423
424     public ListSchemaNodeBuilder addListNode(final int line, final QName qname, final SchemaPath schemaPath) {
425         checkNotSealed();
426         final ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(name, line, qname, schemaPath);
427
428         Builder parent = getActualNode();
429         builder.setParent(parent);
430         addChildToParent(parent, builder, qname.getLocalName());
431         allLists.add(builder);
432
433         return builder;
434     }
435
436     public LeafSchemaNodeBuilder addLeafNode(final int line, final QName qname, final SchemaPath schemaPath) {
437         checkNotSealed();
438         final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(name, line, qname, schemaPath);
439
440         Builder parent = getActualNode();
441         builder.setParent(parent);
442         addChildToParent(parent, builder, qname.getLocalName());
443
444         return builder;
445     }
446
447     public LeafListSchemaNodeBuilder addLeafListNode(final int line, final QName qname, final SchemaPath schemaPath) {
448         checkNotSealed();
449         final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(name, line, qname, schemaPath);
450
451         Builder parent = getActualNode();
452         builder.setParent(parent);
453         addChildToParent(parent, builder, qname.getLocalName());
454
455         return builder;
456     }
457
458     public GroupingBuilder addGrouping(final int line, final QName qname, final SchemaPath path) {
459         checkNotSealed();
460         final GroupingBuilder builder = new GroupingBuilderImpl(name, line, qname, path);
461
462         Builder parent = getActualNode();
463         builder.setParent(parent);
464
465         String groupingName = qname.getLocalName();
466         if (parent.equals(this)) {
467             for (GroupingBuilder addedGrouping : getGroupingBuilders()) {
468                 if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
469                     raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
470                 }
471             }
472             addGrouping(builder);
473         } else {
474             if (parent instanceof DataNodeContainerBuilder) {
475                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
476                 for (GroupingBuilder addedGrouping : parentNode.getGroupingBuilders()) {
477                     if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
478                         raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
479                     }
480                 }
481                 parentNode.addGrouping(builder);
482             } else if (parent instanceof RpcDefinitionBuilder) {
483                 RpcDefinitionBuilder parentNode = (RpcDefinitionBuilder) parent;
484                 for (GroupingBuilder child : parentNode.getGroupings()) {
485                     if (child.getQName().getLocalName().equals(groupingName)) {
486                         raiseYangParserException("", "Grouping", groupingName, line, child.getLine());
487                     }
488                 }
489                 parentNode.addGrouping(builder);
490             } else {
491                 throw new YangParseException(name, line, "Unresolved parent of grouping " + groupingName);
492             }
493         }
494
495         allGroupings.add(builder);
496         return builder;
497     }
498
499     public AugmentationSchemaBuilder addAugment(final int line, final String augmentTargetStr, final int order) {
500         checkNotSealed();
501         final AugmentationSchemaBuilder builder = new AugmentationSchemaBuilderImpl(name, line, augmentTargetStr, order);
502
503         Builder parent = getActualNode();
504         builder.setParent(parent);
505
506         if (parent.equals(this)) {
507             // augment can be declared only under 'module' ...
508             if (!(augmentTargetStr.startsWith("/"))) {
509                 throw new YangParseException(
510                         name,
511                         line,
512                         "If the 'augment' statement is on the top level in a module, the absolute form of a schema node identifier MUST be used.");
513             }
514             augmentBuilders.add(builder);
515         } else {
516             // ... or 'uses' statement
517             if (parent instanceof UsesNodeBuilder) {
518                 if (augmentTargetStr.startsWith("/")) {
519                     throw new YangParseException(name, line,
520                             "If 'augment' statement is a substatement to the 'uses' statement, it cannot contain absolute path ("
521                                     + augmentTargetStr + ")");
522                 }
523                 ((UsesNodeBuilder) parent).addAugment(builder);
524             } else {
525                 throw new YangParseException(name, line, "Augment can be declared only under module or uses statement.");
526             }
527         }
528         allAugments.add(builder);
529
530         return builder;
531     }
532
533     public UsesNodeBuilder addUsesNode(final int line, final String groupingPathStr) {
534         checkNotSealed();
535         final UsesNodeBuilder usesBuilder = new UsesNodeBuilderImpl(name, line, groupingPathStr);
536
537         Builder parent = getActualNode();
538         usesBuilder.setParent(parent);
539
540         if (parent.equals(this)) {
541             addUsesNode(usesBuilder);
542         } else {
543             if (!(parent instanceof DataNodeContainerBuilder)) {
544                 throw new YangParseException(name, line, "Unresolved parent of uses '" + groupingPathStr + "'.");
545             }
546             ((DataNodeContainerBuilder) parent).addUsesNode(usesBuilder);
547         }
548         if (parent instanceof AugmentationSchemaBuilder) {
549             usesBuilder.setAugmenting(true);
550         }
551
552         allUsesNodes.add(usesBuilder);
553         return usesBuilder;
554     }
555
556     public void addRefine(final RefineHolderImpl refine) {
557         checkNotSealed();
558         final Builder parent = getActualNode();
559         if (!(parent instanceof UsesNodeBuilder)) {
560             throw new YangParseException(name, refine.getLine(), "refine can be defined only in uses statement");
561         }
562         ((UsesNodeBuilder) parent).addRefine(refine);
563         refine.setParent(parent);
564     }
565
566     public RpcDefinitionBuilder addRpc(final int line, final QName qname, final SchemaPath path) {
567         checkNotSealed();
568         Builder parent = getActualNode();
569         if (!(parent.equals(this))) {
570             throw new YangParseException(name, line, "rpc can be defined only in module or submodule");
571         }
572
573         final RpcDefinitionBuilder rpcBuilder = new RpcDefinitionBuilder(name, line, qname, path);
574         rpcBuilder.setParent(parent);
575
576         String rpcName = qname.getLocalName();
577         checkNotConflictingInDataNamespace(rpcName, line);
578         addedRpcs.add(rpcBuilder);
579         return rpcBuilder;
580     }
581
582     private void checkNotConflictingInDataNamespace(final String rpcName, final int line) {
583         for (DataSchemaNodeBuilder addedChild : getChildNodeBuilders()) {
584             if (addedChild.getQName().getLocalName().equals(rpcName)) {
585                 raiseYangParserException("rpc", "node", rpcName, line, addedChild.getLine());
586             }
587         }
588         for (RpcDefinitionBuilder rpc : addedRpcs) {
589             if (rpc.getQName().getLocalName().equals(rpcName)) {
590                 raiseYangParserException("", "rpc", rpcName, line, rpc.getLine());
591             }
592         }
593         for (NotificationBuilder addedNotification : addedNotifications) {
594             if (addedNotification.getQName().getLocalName().equals(rpcName)) {
595                 raiseYangParserException("rpc", "notification", rpcName, line, addedNotification.getLine());
596             }
597         }
598     }
599
600     public ContainerSchemaNodeBuilder addRpcInput(final int line, final QName qname, final SchemaPath schemaPath) {
601         checkNotSealed();
602         final Builder parent = getActualNode();
603         if (!(parent instanceof RpcDefinitionBuilder)) {
604             throw new YangParseException(name, line, "input can be defined only in rpc statement");
605         }
606         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
607
608         final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
609         inputBuilder.setParent(rpc);
610
611         rpc.setInput(inputBuilder);
612         return inputBuilder;
613     }
614
615     public ContainerSchemaNodeBuilder addRpcOutput(final SchemaPath schemaPath, final QName qname, final int line) {
616         checkNotSealed();
617         final Builder parent = getActualNode();
618         if (!(parent instanceof RpcDefinitionBuilder)) {
619             throw new YangParseException(name, line, "output can be defined only in rpc statement");
620         }
621         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
622
623         final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
624         outputBuilder.setParent(rpc);
625
626         rpc.setOutput(outputBuilder);
627         return outputBuilder;
628     }
629
630     public void addNotification(final NotificationDefinition notification) {
631         checkNotSealed();
632         notifications.add(notification);
633     }
634
635     public NotificationBuilder addNotification(final int line, final QName qname, final SchemaPath path) {
636         checkNotSealed();
637         final Builder parent = getActualNode();
638         if (!(parent.equals(this))) {
639             throw new YangParseException(name, line, "notification can be defined only in module or submodule");
640         }
641
642         String notificationName = qname.getLocalName();
643         checkNotConflictingInDataNamespace(notificationName, line);
644
645         final NotificationBuilder builder = new NotificationBuilder(name, line, qname, path);
646         builder.setParent(parent);
647         addedNotifications.add(builder);
648
649         return builder;
650     }
651
652     public FeatureBuilder addFeature(final int line, final QName qname, final SchemaPath path) {
653         Builder parent = getActualNode();
654         if (!(parent.equals(this))) {
655             throw new YangParseException(name, line, "feature can be defined only in module or submodule");
656         }
657
658         final FeatureBuilder builder = new FeatureBuilder(name, line, qname, path);
659         builder.setParent(parent);
660
661         String featureName = qname.getLocalName();
662         for (FeatureBuilder addedFeature : addedFeatures) {
663             if (addedFeature.getQName().getLocalName().equals(featureName)) {
664                 raiseYangParserException("", "feature", featureName, line, addedFeature.getLine());
665             }
666         }
667         addedFeatures.add(builder);
668         return builder;
669     }
670
671     public ChoiceBuilder addChoice(final int line, final QName qname, final SchemaPath path) {
672         final ChoiceBuilder builder = new ChoiceBuilder(name, line, qname, path);
673
674         Builder parent = getActualNode();
675         builder.setParent(parent);
676         addChildToParent(parent, builder, qname.getLocalName());
677
678         return builder;
679     }
680
681     public ChoiceCaseBuilder addCase(final int line, final QName qname, final SchemaPath path) {
682         Builder parent = getActualNode();
683         if (parent == null || parent.equals(this)) {
684             throw new YangParseException(name, line, "'case' parent not found");
685         }
686
687         final ChoiceCaseBuilder builder = new ChoiceCaseBuilder(name, line, qname, path);
688         builder.setParent(parent);
689
690         if (parent instanceof ChoiceBuilder) {
691             ((ChoiceBuilder) parent).addCase(builder);
692         } else if (parent instanceof AugmentationSchemaBuilder) {
693             ((AugmentationSchemaBuilder) parent).addChildNode(builder);
694         } else {
695             throw new YangParseException(name, line, "Unresolved parent of 'case' " + qname.getLocalName());
696         }
697
698         return builder;
699     }
700
701     public AnyXmlBuilder addAnyXml(final int line, final QName qname, final SchemaPath schemaPath) {
702         final AnyXmlBuilder builder = new AnyXmlBuilder(name, line, qname, schemaPath);
703
704         Builder parent = getActualNode();
705         builder.setParent(parent);
706         addChildToParent(parent, builder, qname.getLocalName());
707
708         return builder;
709     }
710
711     @Override
712     public void addTypedef(final TypeDefinitionBuilder typedefBuilder) {
713         String nodeName = typedefBuilder.getQName().getLocalName();
714         for (TypeDefinitionBuilder tdb : getTypeDefinitionBuilders()) {
715             if (tdb.getQName().getLocalName().equals(nodeName)) {
716                 raiseYangParserException("", "typedef", nodeName, typedefBuilder.getLine(), tdb.getLine());
717             }
718         }
719         super.addTypedef(typedefBuilder);
720     }
721
722     public TypeDefinitionBuilderImpl addTypedef(final int line, final QName qname, final SchemaPath path) {
723         final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(name, line, qname, path);
724
725         Builder parent = getActualNode();
726         builder.setParent(parent);
727
728         String typedefName = qname.getLocalName();
729         if (parent.equals(this)) {
730             addTypedef(builder);
731         } else {
732             if (parent instanceof DataNodeContainerBuilder) {
733                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
734                 for (TypeDefinitionBuilder child : parentNode.getTypeDefinitionBuilders()) {
735                     if (child.getQName().getLocalName().equals(typedefName)) {
736                         raiseYangParserException("", "typedef", typedefName, line, child.getLine());
737                     }
738                 }
739                 parentNode.addTypedef(builder);
740             } else if (parent instanceof RpcDefinitionBuilder) {
741                 RpcDefinitionBuilder rpcParent = (RpcDefinitionBuilder) parent;
742                 for (TypeDefinitionBuilder tdb : rpcParent.getTypeDefinitions()) {
743                     if (tdb.getQName().getLocalName().equals(builder.getQName().getLocalName())) {
744                         raiseYangParserException("", "typedef", typedefName, line, tdb.getLine());
745                     }
746                 }
747                 rpcParent.addTypedef(builder);
748             } else {
749                 throw new YangParseException(name, line, "Unresolved parent of typedef " + typedefName);
750             }
751         }
752
753         return builder;
754     }
755
756     public void setType(final TypeDefinition<?> type) {
757         Builder parent = getActualNode();
758         if (!(parent instanceof TypeAwareBuilder)) {
759             throw new YangParseException("Failed to set type '" + type.getQName().getLocalName()
760                     + "'. Invalid parent node: " + parent);
761         }
762         ((TypeAwareBuilder) parent).setType(type);
763     }
764
765     public UnionTypeBuilder addUnionType(final int line, final URI namespace, final Date revision) {
766         final Builder parent = getActualNode();
767         if (parent == null) {
768             throw new YangParseException(name, line, "Unresolved parent of union type");
769         } else {
770             final UnionTypeBuilder union = new UnionTypeBuilder(name, line);
771             if (parent instanceof TypeAwareBuilder) {
772                 ((TypeAwareBuilder) parent).setTypedef(union);
773                 return union;
774             } else {
775                 throw new YangParseException(name, line, "Invalid parent of union type.");
776             }
777         }
778     }
779
780     public void addIdentityrefType(final int line, final SchemaPath schemaPath, final String baseString) {
781         final IdentityrefTypeBuilder identityref = new IdentityrefTypeBuilder(name, line, baseString, schemaPath);
782
783         final Builder parent = getActualNode();
784         if (parent == null) {
785             throw new YangParseException(name, line, "Unresolved parent of identityref type.");
786         } else {
787             if (parent instanceof TypeAwareBuilder) {
788                 final TypeAwareBuilder typeParent = (TypeAwareBuilder) parent;
789                 typeParent.setTypedef(identityref);
790                 dirtyNodes.add(typeParent);
791             } else {
792                 throw new YangParseException(name, line, "Invalid parent of identityref type.");
793             }
794         }
795     }
796
797     public DeviationBuilder addDeviation(final int line, final String targetPath) {
798         Builder parent = getActualNode();
799         if (!(parent.equals(this))) {
800             throw new YangParseException(name, line, "deviation can be defined only in module or submodule");
801         }
802
803         final DeviationBuilder builder = new DeviationBuilder(name, line, targetPath);
804         builder.setParent(parent);
805         deviationBuilders.add(builder);
806         return builder;
807     }
808
809     public IdentitySchemaNodeBuilder addIdentity(final QName qname, final int line, final SchemaPath path) {
810         Builder parent = getActualNode();
811         if (!(parent.equals(this))) {
812             throw new YangParseException(name, line, "identity can be defined only in module or submodule");
813         }
814         String identityName = qname.getLocalName();
815         for (IdentitySchemaNodeBuilder idBuilder : addedIdentities) {
816             if (idBuilder.getQName().equals(qname)) {
817                 raiseYangParserException("", "identity", identityName, line, idBuilder.getLine());
818             }
819         }
820
821         final IdentitySchemaNodeBuilder builder = new IdentitySchemaNodeBuilder(name, line, qname, path);
822         builder.setParent(parent);
823         addedIdentities.add(builder);
824         return builder;
825     }
826
827     @Override
828     public void addUnknownNodeBuilder(final UnknownSchemaNodeBuilder builder) {
829         addedUnknownNodes.add(builder);
830         allUnknownNodes.add(builder);
831     }
832
833     public UnknownSchemaNodeBuilderImpl addUnknownSchemaNode(final int line, final QName qname, final SchemaPath path) {
834         final Builder parent = getActualNode();
835         final UnknownSchemaNodeBuilderImpl builder = new UnknownSchemaNodeBuilderImpl(name, line, qname, path);
836         builder.setParent(parent);
837         allUnknownNodes.add(builder);
838
839         if (parent.equals(this)) {
840             addedUnknownNodes.add(builder);
841         } else {
842             if (parent instanceof SchemaNodeBuilder) {
843                 parent.addUnknownNodeBuilder(builder);
844             } else if (parent instanceof DataNodeContainerBuilder) {
845                 parent.addUnknownNodeBuilder(builder);
846             } else if (parent instanceof RefineHolderImpl) {
847                 parent.addUnknownNodeBuilder(builder);
848             } else {
849                 throw new YangParseException(name, line, "Unresolved parent of unknown node '" + qname.getLocalName()
850                         + "'");
851             }
852         }
853
854         return builder;
855     }
856
857     public Set<RpcDefinition> getRpcs() {
858         return rpcs;
859     }
860
861     public Set<RpcDefinitionBuilder> getAddedRpcs() {
862         return addedRpcs;
863     }
864
865     public Set<NotificationDefinition> getNotifications() {
866         return notifications;
867     }
868
869     public Set<NotificationBuilder> getAddedNotifications() {
870         return addedNotifications;
871     }
872
873     @Override
874     public String toString() {
875         return "module " + name;
876     }
877
878     public void setSource(ByteSource byteSource) throws IOException {
879         try (InputStream stream = byteSource.openStream()) {
880             setSource(IOUtils.toString(stream));
881         }
882     }
883
884     public void setSource(final String source) {
885         this.source = source;
886     }
887
888     /**
889      * Add child to parent. Method checks for duplicates and add given child
890      * node to parent. If node with same name is found, throws exception. If
891      * parent is null, child node will be added directly to module.
892      *
893      * @param parent
894      * @param child
895      * @param childName
896      */
897     private void addChildToParent(final Builder parent, final DataSchemaNodeBuilder child, final String childName) {
898         final int lineNum = child.getLine();
899         if (parent.equals(this)) {
900             addChildToModule(child, childName, lineNum);
901         } else {
902             addChildToSubnodeOfModule(parent, child, childName, lineNum);
903         }
904     }
905
906     public String getYangVersion() {
907         return yangVersion;
908     }
909
910     public String getContact() {
911         return contact;
912     }
913
914     public String getOrganization() {
915         return organization;
916     }
917
918     /**
919      * Adds child node <code>child</code> to the set of nodes child nodes.
920      *
921      * The method reduces the complexity of the method
922      * {@link #addChildToParent(Builder, DataSchemaNodeBuilder, String)
923      * addChildToParent}.
924      *
925      * @param child
926      *            data schema node builder for child node
927      * @param childName
928      *            string with name of child node
929      * @param lineNum
930      *            line number in YANG file where is the node with the name equal
931      *            to <code>childName</code> is defined
932      */
933     private void addChildToModule(final DataSchemaNodeBuilder child, final String childName, final int lineNum) {
934         // if parent == null => node is defined under module
935         // All leafs, leaf-lists, lists, containers, choices, rpcs,
936         // notifications, and anyxmls defined within a parent node or at the
937         // top level of the module or its submodules share the same
938         // identifier namespace.
939         for (DataSchemaNodeBuilder childNode : getChildNodeBuilders()) {
940             if (childNode.getQName().getLocalName().equals(childName)) {
941                 raiseYangParserException("'" + child + "'", "node", childName, lineNum, childNode.getLine());
942             }
943         }
944         for (RpcDefinitionBuilder rpc : addedRpcs) {
945             if (rpc.getQName().getLocalName().equals(childName)) {
946                 raiseYangParserException("'" + child + "'", "rpc", childName, lineNum, rpc.getLine());
947             }
948         }
949         for (NotificationBuilder notification : addedNotifications) {
950             if (notification.getQName().getLocalName().equals(childName)) {
951                 raiseYangParserException("'" + child + "'", "notification", childName, lineNum, notification.getLine());
952             }
953         }
954         addChildNode(child);
955     }
956
957     /**
958      * Adds child node <code>child</code> to the group of child nodes of the
959      * <code>parent</code>
960      *
961      * The method reduces the complexity of the method
962      * {@link #addChildToParent(Builder, DataSchemaNodeBuilder, String)
963      * addChildToParent}. *
964      *
965      * @param parent
966      *            builder of node which is parent for <code>child</code>
967      * @param child
968      *            data schema node builder for child node
969      * @param childName
970      *            string with name of child node
971      * @param lineNum
972      *            line number in YANG file where is the node with the name equal
973      *            to <code>childName</code> is defined
974      */
975     private void addChildToSubnodeOfModule(final Builder parent, final DataSchemaNodeBuilder child,
976             final String childName, final int lineNum) {
977         // no need for checking rpc and notification because they can be
978         // defined only under module or submodule
979         if (parent instanceof DataNodeContainerBuilder) {
980             DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
981             for (DataSchemaNodeBuilder childNode : parentNode.getChildNodeBuilders()) {
982                 if (childNode.getQName().getLocalName().equals(childName)) {
983                     raiseYangParserException("'" + child + "'", "node", childName, lineNum, childNode.getLine());
984                 }
985             }
986             parentNode.addChildNode(child);
987         } else if (parent instanceof ChoiceBuilder) {
988             ChoiceBuilder parentNode = (ChoiceBuilder) parent;
989             for (ChoiceCaseBuilder caseBuilder : parentNode.getCases()) {
990                 if (caseBuilder.getQName().getLocalName().equals(childName)) {
991                     raiseYangParserException("'" + child + "'", "node", childName, lineNum, caseBuilder.getLine());
992                 }
993             }
994             parentNode.addCase(child);
995         } else {
996             throw new YangParseException(name, lineNum, "Unresolved parent of node '" + childName + "'.");
997         }
998     }
999
1000     private ModuleImport createModuleImport(final String moduleName, final Date revision, final String prefix) {
1001         return new ModuleImportImpl(moduleName, revision, prefix);
1002     }
1003
1004     private void raiseYangParserException(final String cantAddType, final String type, final String name,
1005             final int currentLine, final int duplicateLine) {
1006
1007         StringBuilder msgPrefix = new StringBuilder("");
1008         if (cantAddType != null && !cantAddType.isEmpty()) {
1009             msgPrefix.append("Can not add ");
1010             msgPrefix.append(cantAddType);
1011             msgPrefix.append(": ");
1012         }
1013
1014         String msg = String.format("%s%s with same name '%s' already declared at line %d.", msgPrefix, type, name,
1015                 duplicateLine);
1016         throw new YangParseException(getModuleName(), currentLine, msg);
1017     }
1018
1019     @Override
1020     public int hashCode() {
1021         final int prime = 31;
1022         int result = 1;
1023         result = prime * result + ((name == null) ? 0 : name.hashCode());
1024         result = prime * result + ((namespace == null) ? 0 : namespace.hashCode());
1025         result = prime * result + ((revision == null) ? 0 : revision.hashCode());
1026         result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());
1027
1028         return result;
1029     }
1030
1031     @Override
1032     public boolean equals(final Object obj) {
1033         if (this == obj) {
1034             return true;
1035         }
1036         if (obj == null) {
1037             return false;
1038         }
1039         if (getClass() != obj.getClass()) {
1040             return false;
1041         }
1042         ModuleBuilder other = (ModuleBuilder) obj;
1043         if (name == null) {
1044             if (other.name != null) {
1045                 return false;
1046             }
1047         } else if (!name.equals(other.name)) {
1048             return false;
1049         }
1050         if (namespace == null) {
1051             if (other.namespace != null) {
1052                 return false;
1053             }
1054         } else if (!namespace.equals(other.namespace)) {
1055             return false;
1056         }
1057         if (prefix == null) {
1058             if (other.prefix != null) {
1059                 return false;
1060             }
1061         } else if (!prefix.equals(other.prefix)) {
1062             return false;
1063         }
1064         if (revision == null) {
1065             if (other.revision != null) {
1066                 return false;
1067             }
1068         } else if (!revision.equals(other.revision)) {
1069             return false;
1070         }
1071         return true;
1072     }
1073
1074     public List<UnknownSchemaNode> getExtensionInstances() {
1075         return unknownNodes;
1076     }
1077 }