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