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