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