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