Merge "BUG-579: improve code readability in RestconfUtils."
[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
12 import java.io.IOException;
13 import java.io.InputStream;
14 import java.net.URI;
15 import java.util.ArrayList;
16 import java.util.Collections;
17 import java.util.Date;
18 import java.util.Deque;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.LinkedHashSet;
22 import java.util.LinkedList;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Set;
26 import java.util.TreeSet;
27
28 import org.apache.commons.io.IOUtils;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.common.QNameModule;
31 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
32 import org.opendaylight.yangtools.yang.model.api.Deviation;
33 import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
34 import org.opendaylight.yangtools.yang.model.api.FeatureDefinition;
35 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.Module;
37 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
38 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
39 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
40 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
41 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
42 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
43 import org.opendaylight.yangtools.yang.model.util.ModuleImportImpl;
44 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
45 import org.opendaylight.yangtools.yang.parser.builder.api.Builder;
46 import org.opendaylight.yangtools.yang.parser.builder.api.DataNodeContainerBuilder;
47 import org.opendaylight.yangtools.yang.parser.builder.api.DataSchemaNodeBuilder;
48 import org.opendaylight.yangtools.yang.parser.builder.api.DocumentedNodeBuilder;
49 import org.opendaylight.yangtools.yang.parser.builder.api.ExtensionBuilder;
50 import org.opendaylight.yangtools.yang.parser.builder.api.GroupingBuilder;
51 import org.opendaylight.yangtools.yang.parser.builder.api.SchemaNodeBuilder;
52 import org.opendaylight.yangtools.yang.parser.builder.api.TypeAwareBuilder;
53 import org.opendaylight.yangtools.yang.parser.builder.api.TypeDefinitionBuilder;
54 import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuilder;
55 import org.opendaylight.yangtools.yang.parser.builder.api.UsesNodeBuilder;
56 import org.opendaylight.yangtools.yang.parser.builder.util.AbstractDocumentedDataNodeContainerBuilder;
57 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
58 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
59
60 /**
61  * Builder of Module object. If this module is dependent on external
62  * module/modules, these dependencies must be resolved before module is built,
63  * otherwise result may not be valid.
64  */
65 public class ModuleBuilder extends AbstractDocumentedDataNodeContainerBuilder implements DocumentedNodeBuilder {
66
67     private ModuleImpl instance;
68     private final String name;
69     private final String sourcePath;
70     private static final SchemaPath SCHEMA_PATH = SchemaPath.create(Collections.<QName> emptyList(), true);
71     private String prefix;
72     private QNameModule qnameModule = QNameModule.create(null, null);
73
74     private final boolean submodule;
75     private String belongsTo;
76     private ModuleBuilder parent;
77
78     private final Deque<Builder> actualPath = new LinkedList<>();
79     private final Set<TypeAwareBuilder> dirtyNodes = new HashSet<>();
80
81     final Map<String, ModuleImport> imports = new HashMap<>();
82     final Map<String, ModuleBuilder> importedModules = 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, new QName(base.getNamespace(), base.getRevision(), 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     protected String getSource() {
370         return source;
371     }
372
373     public boolean isSubmodule() {
374         return submodule;
375     }
376
377     public String getBelongsTo() {
378         return belongsTo;
379     }
380
381     public void setBelongsTo(final String belongsTo) {
382         this.belongsTo = belongsTo;
383     }
384
385     public void markActualNodeDirty() {
386         final TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) getActualNode();
387         dirtyNodes.add(nodeBuilder);
388     }
389
390     public void setRevision(final Date revision) {
391         this.qnameModule = QNameModule.create(qnameModule.getNamespace(), revision);
392     }
393
394     public void setPrefix(final String prefix) {
395         this.prefix = prefix;
396     }
397
398     public void setYangVersion(final String yangVersion) {
399         this.yangVersion = yangVersion;
400     }
401
402     public void setOrganization(final String organization) {
403         this.organization = organization;
404     }
405
406     public void setContact(final String contact) {
407         this.contact = contact;
408     }
409
410     public void addModuleImport(final String moduleName, final Date revision, final String prefix) {
411         checkPrefix(prefix);
412         checkNotSealed();
413         final ModuleImport moduleImport = createModuleImport(moduleName, revision, prefix);
414         imports.put(prefix, moduleImport);
415     }
416
417     private void checkPrefix(final String prefix) {
418         if (prefix == null || prefix.isEmpty()) {
419             throw new IllegalArgumentException("Cannot add imported module with undefined prefix");
420         }
421         if (prefix.equals(this.prefix)) {
422             throw new IllegalArgumentException("Cannot add imported module with prefix equals to module prefix");
423         }
424     }
425
426     public ExtensionBuilder addExtension(final QName qname, final int line, final SchemaPath path) {
427         checkNotSealed();
428         Builder parent = getActualNode();
429         if (!(parent.equals(this))) {
430             throw new YangParseException(name, line, "extension can be defined only in module or submodule");
431         }
432
433         final String extName = qname.getLocalName();
434         for (ExtensionBuilder addedExtension : addedExtensions) {
435             if (addedExtension.getQName().getLocalName().equals(extName)) {
436                 raiseYangParserException("extension", "node", extName, line, addedExtension.getLine());
437             }
438         }
439         final ExtensionBuilder builder = new ExtensionBuilderImpl(name, line, qname, path);
440         builder.setParent(parent);
441         addedExtensions.add(builder);
442         return builder;
443     }
444
445     public ContainerSchemaNodeBuilder addContainerNode(final int line, final QName qname, final SchemaPath schemaPath) {
446         checkNotSealed();
447         final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
448
449         Builder parent = getActualNode();
450         builder.setParent(parent);
451         addChildToParent(parent, builder, qname.getLocalName());
452
453         return builder;
454     }
455
456     public ListSchemaNodeBuilder addListNode(final int line, final QName qname, final SchemaPath schemaPath) {
457         checkNotSealed();
458         final ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(name, line, qname, schemaPath);
459
460         Builder parent = getActualNode();
461         builder.setParent(parent);
462         addChildToParent(parent, builder, qname.getLocalName());
463         allLists.add(builder);
464
465         return builder;
466     }
467
468     public LeafSchemaNodeBuilder addLeafNode(final int line, final QName qname, final SchemaPath schemaPath) {
469         checkNotSealed();
470         final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(name, line, qname, schemaPath);
471
472         Builder parent = getActualNode();
473         builder.setParent(parent);
474         addChildToParent(parent, builder, qname.getLocalName());
475
476         return builder;
477     }
478
479     public LeafListSchemaNodeBuilder addLeafListNode(final int line, final QName qname, final SchemaPath schemaPath) {
480         checkNotSealed();
481         final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(name, line, qname, schemaPath);
482
483         Builder parent = getActualNode();
484         builder.setParent(parent);
485         addChildToParent(parent, builder, qname.getLocalName());
486
487         return builder;
488     }
489
490     public GroupingBuilder addGrouping(final int line, final QName qname, final SchemaPath path) {
491         checkNotSealed();
492         final GroupingBuilder builder = new GroupingBuilderImpl(name, line, qname, path);
493
494         Builder parent = getActualNode();
495         builder.setParent(parent);
496
497         String groupingName = qname.getLocalName();
498         if (parent.equals(this)) {
499             for (GroupingBuilder addedGrouping : getGroupingBuilders()) {
500                 if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
501                     raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
502                 }
503             }
504             addGrouping(builder);
505         } else {
506             if (parent instanceof DataNodeContainerBuilder) {
507                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
508                 for (GroupingBuilder addedGrouping : parentNode.getGroupingBuilders()) {
509                     if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
510                         raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
511                     }
512                 }
513                 parentNode.addGrouping(builder);
514             } else if (parent instanceof RpcDefinitionBuilder) {
515                 RpcDefinitionBuilder parentNode = (RpcDefinitionBuilder) parent;
516                 for (GroupingBuilder child : parentNode.getGroupings()) {
517                     if (child.getQName().getLocalName().equals(groupingName)) {
518                         raiseYangParserException("", "Grouping", groupingName, line, child.getLine());
519                     }
520                 }
521                 parentNode.addGrouping(builder);
522             } else {
523                 throw new YangParseException(name, line, "Unresolved parent of grouping " + groupingName);
524             }
525         }
526
527         allGroupings.add(builder);
528         return builder;
529     }
530
531     public AugmentationSchemaBuilder addAugment(final int line, final String augmentTargetStr, final int order) {
532         checkNotSealed();
533         final AugmentationSchemaBuilder builder = new AugmentationSchemaBuilderImpl(name, line, augmentTargetStr, order);
534
535         Builder parent = getActualNode();
536         builder.setParent(parent);
537
538         if (parent.equals(this)) {
539             // augment can be declared only under 'module' ...
540             if (!(augmentTargetStr.startsWith("/"))) {
541                 throw new YangParseException(
542                         name,
543                         line,
544                         "If the 'augment' statement is on the top level in a module, the absolute form of a schema node identifier MUST be used.");
545             }
546             augmentBuilders.add(builder);
547         } else {
548             // ... or 'uses' statement
549             if (parent instanceof UsesNodeBuilder) {
550                 if (augmentTargetStr.startsWith("/")) {
551                     throw new YangParseException(name, line,
552                             "If 'augment' statement is a substatement to the 'uses' statement, it cannot contain absolute path ("
553                                     + augmentTargetStr + ")");
554                 }
555                 ((UsesNodeBuilder) parent).addAugment(builder);
556             } else {
557                 throw new YangParseException(name, line, "Augment can be declared only under module or uses statement.");
558             }
559         }
560         allAugments.add(builder);
561
562         return builder;
563     }
564
565     public UsesNodeBuilder addUsesNode(final int line, final String groupingPathStr) {
566         checkNotSealed();
567         final UsesNodeBuilder usesBuilder = new UsesNodeBuilderImpl(name, line, groupingPathStr);
568
569         Builder parent = getActualNode();
570         usesBuilder.setParent(parent);
571
572         if (parent.equals(this)) {
573             addUsesNode(usesBuilder);
574         } else {
575             if (!(parent instanceof DataNodeContainerBuilder)) {
576                 throw new YangParseException(name, line, "Unresolved parent of uses '" + groupingPathStr + "'.");
577             }
578             ((DataNodeContainerBuilder) parent).addUsesNode(usesBuilder);
579         }
580         if (parent instanceof AugmentationSchemaBuilder) {
581             usesBuilder.setAugmenting(true);
582         }
583
584         allUsesNodes.add(usesBuilder);
585         return usesBuilder;
586     }
587
588     public void addRefine(final RefineHolderImpl refine) {
589         checkNotSealed();
590         final Builder parent = getActualNode();
591         if (!(parent instanceof UsesNodeBuilder)) {
592             throw new YangParseException(name, refine.getLine(), "refine can be defined only in uses statement");
593         }
594         ((UsesNodeBuilder) parent).addRefine(refine);
595         refine.setParent(parent);
596     }
597
598     public RpcDefinitionBuilder addRpc(final int line, final QName qname, final SchemaPath path) {
599         checkNotSealed();
600         Builder parent = getActualNode();
601         if (!(parent.equals(this))) {
602             throw new YangParseException(name, line, "rpc can be defined only in module or submodule");
603         }
604
605         final RpcDefinitionBuilder rpcBuilder = new RpcDefinitionBuilder(name, line, qname, path);
606         rpcBuilder.setParent(parent);
607
608         String rpcName = qname.getLocalName();
609         checkNotConflictingInDataNamespace(rpcName, line);
610         addedRpcs.add(rpcBuilder);
611         return rpcBuilder;
612     }
613
614     private void checkNotConflictingInDataNamespace(final String rpcName, final int line) {
615         for (DataSchemaNodeBuilder addedChild : getChildNodeBuilders()) {
616             if (addedChild.getQName().getLocalName().equals(rpcName)) {
617                 raiseYangParserException("rpc", "node", rpcName, line, addedChild.getLine());
618             }
619         }
620         for (RpcDefinitionBuilder rpc : addedRpcs) {
621             if (rpc.getQName().getLocalName().equals(rpcName)) {
622                 raiseYangParserException("", "rpc", rpcName, line, rpc.getLine());
623             }
624         }
625         for (NotificationBuilder addedNotification : addedNotifications) {
626             if (addedNotification.getQName().getLocalName().equals(rpcName)) {
627                 raiseYangParserException("rpc", "notification", rpcName, line, addedNotification.getLine());
628             }
629         }
630     }
631
632     public ContainerSchemaNodeBuilder addRpcInput(final int line, final QName qname, final SchemaPath schemaPath) {
633         checkNotSealed();
634         final Builder parent = getActualNode();
635         if (!(parent instanceof RpcDefinitionBuilder)) {
636             throw new YangParseException(name, line, "input can be defined only in rpc statement");
637         }
638         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
639
640         final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
641         inputBuilder.setParent(rpc);
642
643         rpc.setInput(inputBuilder);
644         return inputBuilder;
645     }
646
647     public ContainerSchemaNodeBuilder addRpcOutput(final SchemaPath schemaPath, final QName qname, final int line) {
648         checkNotSealed();
649         final Builder parent = getActualNode();
650         if (!(parent instanceof RpcDefinitionBuilder)) {
651             throw new YangParseException(name, line, "output can be defined only in rpc statement");
652         }
653         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
654
655         final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
656         outputBuilder.setParent(rpc);
657
658         rpc.setOutput(outputBuilder);
659         return outputBuilder;
660     }
661
662     public void addNotification(final NotificationDefinition notification) {
663         checkNotSealed();
664         notifications.add(notification);
665     }
666
667     public NotificationBuilder addNotification(final int line, final QName qname, final SchemaPath path) {
668         checkNotSealed();
669         final Builder parent = getActualNode();
670         if (!(parent.equals(this))) {
671             throw new YangParseException(name, line, "notification can be defined only in module or submodule");
672         }
673
674         String notificationName = qname.getLocalName();
675         checkNotConflictingInDataNamespace(notificationName, line);
676
677         final NotificationBuilder builder = new NotificationBuilder(name, line, qname, path);
678         builder.setParent(parent);
679         addedNotifications.add(builder);
680
681         return builder;
682     }
683
684     public FeatureBuilder addFeature(final int line, final QName qname, final SchemaPath path) {
685         Builder parent = getActualNode();
686         if (!(parent.equals(this))) {
687             throw new YangParseException(name, line, "feature can be defined only in module or submodule");
688         }
689
690         final FeatureBuilder builder = new FeatureBuilder(name, line, qname, path);
691         builder.setParent(parent);
692
693         String featureName = qname.getLocalName();
694         for (FeatureBuilder addedFeature : addedFeatures) {
695             if (addedFeature.getQName().getLocalName().equals(featureName)) {
696                 raiseYangParserException("", "feature", featureName, line, addedFeature.getLine());
697             }
698         }
699         addedFeatures.add(builder);
700         return builder;
701     }
702
703     public ChoiceBuilder addChoice(final int line, final QName qname, final SchemaPath path) {
704         final ChoiceBuilder builder = new ChoiceBuilder(name, line, qname, path);
705
706         Builder parent = getActualNode();
707         builder.setParent(parent);
708         addChildToParent(parent, builder, qname.getLocalName());
709
710         return builder;
711     }
712
713     public ChoiceCaseBuilder addCase(final int line, final QName qname, final SchemaPath path) {
714         Builder parent = getActualNode();
715         if (parent == null || parent.equals(this)) {
716             throw new YangParseException(name, line, "'case' parent not found");
717         }
718
719         final ChoiceCaseBuilder builder = new ChoiceCaseBuilder(name, line, qname, path);
720         builder.setParent(parent);
721
722         if (parent instanceof ChoiceBuilder) {
723             ((ChoiceBuilder) parent).addCase(builder);
724         } else if (parent instanceof AugmentationSchemaBuilder) {
725             ((AugmentationSchemaBuilder) parent).addChildNode(builder);
726         } else {
727             throw new YangParseException(name, line, "Unresolved parent of 'case' " + qname.getLocalName());
728         }
729
730         return builder;
731     }
732
733     public AnyXmlBuilder addAnyXml(final int line, final QName qname, final SchemaPath schemaPath) {
734         final AnyXmlBuilder builder = new AnyXmlBuilder(name, line, qname, schemaPath);
735
736         Builder parent = getActualNode();
737         builder.setParent(parent);
738         addChildToParent(parent, builder, qname.getLocalName());
739
740         return builder;
741     }
742
743     @Override
744     public void addTypedef(final TypeDefinitionBuilder typedefBuilder) {
745         String nodeName = typedefBuilder.getQName().getLocalName();
746         for (TypeDefinitionBuilder tdb : getTypeDefinitionBuilders()) {
747             if (tdb.getQName().getLocalName().equals(nodeName)) {
748                 raiseYangParserException("", "typedef", nodeName, typedefBuilder.getLine(), tdb.getLine());
749             }
750         }
751         super.addTypedef(typedefBuilder);
752     }
753
754     public TypeDefinitionBuilderImpl addTypedef(final int line, final QName qname, final SchemaPath path) {
755         final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(name, line, qname, path);
756
757         Builder parent = getActualNode();
758         builder.setParent(parent);
759
760         String typedefName = qname.getLocalName();
761         if (parent.equals(this)) {
762             addTypedef(builder);
763         } else {
764             if (parent instanceof DataNodeContainerBuilder) {
765                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
766                 for (TypeDefinitionBuilder child : parentNode.getTypeDefinitionBuilders()) {
767                     if (child.getQName().getLocalName().equals(typedefName)) {
768                         raiseYangParserException("", "typedef", typedefName, line, child.getLine());
769                     }
770                 }
771                 parentNode.addTypedef(builder);
772             } else if (parent instanceof RpcDefinitionBuilder) {
773                 RpcDefinitionBuilder rpcParent = (RpcDefinitionBuilder) parent;
774                 for (TypeDefinitionBuilder tdb : rpcParent.getTypeDefinitions()) {
775                     if (tdb.getQName().getLocalName().equals(builder.getQName().getLocalName())) {
776                         raiseYangParserException("", "typedef", typedefName, line, tdb.getLine());
777                     }
778                 }
779                 rpcParent.addTypedef(builder);
780             } else {
781                 throw new YangParseException(name, line, "Unresolved parent of typedef " + typedefName);
782             }
783         }
784
785         return builder;
786     }
787
788     public void setType(final TypeDefinition<?> type) {
789         Builder parent = getActualNode();
790         if (!(parent instanceof TypeAwareBuilder)) {
791             throw new YangParseException("Failed to set type '" + type.getQName().getLocalName()
792                     + "'. Invalid parent node: " + parent);
793         }
794         ((TypeAwareBuilder) parent).setType(type);
795     }
796
797     public UnionTypeBuilder addUnionType(final int line, final QNameModule module) {
798         final Builder parent = getActualNode();
799         if (parent == null) {
800             throw new YangParseException(name, line, "Unresolved parent of union type");
801         } else {
802             final UnionTypeBuilder union = new UnionTypeBuilder(name, line);
803             if (parent instanceof TypeAwareBuilder) {
804                 ((TypeAwareBuilder) parent).setTypedef(union);
805                 return union;
806             } else {
807                 throw new YangParseException(name, line, "Invalid parent of union type.");
808             }
809         }
810     }
811
812     public void addIdentityrefType(final int line, final SchemaPath schemaPath, final String baseString) {
813         final IdentityrefTypeBuilder identityref = new IdentityrefTypeBuilder(name, line, baseString, schemaPath);
814
815         final Builder parent = getActualNode();
816         if (parent == null) {
817             throw new YangParseException(name, line, "Unresolved parent of identityref type.");
818         } else {
819             if (parent instanceof TypeAwareBuilder) {
820                 final TypeAwareBuilder typeParent = (TypeAwareBuilder) parent;
821                 typeParent.setTypedef(identityref);
822                 dirtyNodes.add(typeParent);
823             } else {
824                 throw new YangParseException(name, line, "Invalid parent of identityref type.");
825             }
826         }
827     }
828
829     public DeviationBuilder addDeviation(final int line, final String targetPath) {
830         Builder parent = getActualNode();
831         if (!(parent.equals(this))) {
832             throw new YangParseException(name, line, "deviation can be defined only in module or submodule");
833         }
834
835         final DeviationBuilder builder = new DeviationBuilder(name, line, targetPath);
836         builder.setParent(parent);
837         deviationBuilders.add(builder);
838         return builder;
839     }
840
841     public IdentitySchemaNodeBuilder addIdentity(final QName qname, final int line, final SchemaPath path) {
842         Builder parent = getActualNode();
843         if (!(parent.equals(this))) {
844             throw new YangParseException(name, line, "identity can be defined only in module or submodule");
845         }
846         String identityName = qname.getLocalName();
847         for (IdentitySchemaNodeBuilder idBuilder : addedIdentities) {
848             if (idBuilder.getQName().equals(qname)) {
849                 raiseYangParserException("", "identity", identityName, line, idBuilder.getLine());
850             }
851         }
852
853         final IdentitySchemaNodeBuilder builder = new IdentitySchemaNodeBuilder(name, line, qname, path);
854         builder.setParent(parent);
855         addedIdentities.add(builder);
856         return builder;
857     }
858
859     @Override
860     public void addUnknownNodeBuilder(final UnknownSchemaNodeBuilder builder) {
861         addedUnknownNodes.add(builder);
862         allUnknownNodes.add(builder);
863     }
864
865     public UnknownSchemaNodeBuilderImpl addUnknownSchemaNode(final int line, final QName qname, final SchemaPath path) {
866         final Builder parent = getActualNode();
867         final UnknownSchemaNodeBuilderImpl builder = new UnknownSchemaNodeBuilderImpl(name, line, qname, path);
868         builder.setParent(parent);
869         allUnknownNodes.add(builder);
870
871         if (parent.equals(this)) {
872             addedUnknownNodes.add(builder);
873         } else {
874             if (parent instanceof SchemaNodeBuilder) {
875                 parent.addUnknownNodeBuilder(builder);
876             } else if (parent instanceof DataNodeContainerBuilder) {
877                 parent.addUnknownNodeBuilder(builder);
878             } else if (parent instanceof RefineHolderImpl) {
879                 parent.addUnknownNodeBuilder(builder);
880             } else {
881                 throw new YangParseException(name, line, "Unresolved parent of unknown node '" + qname.getLocalName()
882                         + "'");
883             }
884         }
885
886         return builder;
887     }
888
889     public Set<RpcDefinition> getRpcs() {
890         return rpcs;
891     }
892
893     public Set<RpcDefinitionBuilder> getAddedRpcs() {
894         return addedRpcs;
895     }
896
897     public Set<NotificationDefinition> getNotifications() {
898         return notifications;
899     }
900
901     public Set<NotificationBuilder> getAddedNotifications() {
902         return addedNotifications;
903     }
904
905     @Override
906     public String toString() {
907         return "module " + name;
908     }
909
910     public void setSource(final ByteSource byteSource) throws IOException {
911         try (InputStream stream = byteSource.openStream()) {
912             setSource(IOUtils.toString(stream));
913         }
914     }
915
916     public void setSource(final String source) {
917         this.source = source;
918     }
919
920     /**
921      * Add child to parent. Method checks for duplicates and add given child
922      * node to parent. If node with same name is found, throws exception. If
923      * parent is null, child node will be added directly to module.
924      *
925      * @param parent
926      * @param child
927      * @param childName
928      */
929     private void addChildToParent(final Builder parent, final DataSchemaNodeBuilder child, final String childName) {
930         final int lineNum = child.getLine();
931         if (parent.equals(this)) {
932             addChildToModule(child, childName, lineNum);
933         } else {
934             addChildToSubnodeOfModule(parent, child, childName, lineNum);
935         }
936     }
937
938     public String getYangVersion() {
939         return yangVersion;
940     }
941
942     public String getContact() {
943         return contact;
944     }
945
946     public String getOrganization() {
947         return organization;
948     }
949
950     /**
951      * Adds child node <code>child</code> to the set of nodes child nodes.
952      *
953      * The method reduces the complexity of the method
954      * {@link #addChildToParent(Builder, DataSchemaNodeBuilder, String)
955      * addChildToParent}.
956      *
957      * @param child
958      *            data schema node builder for child node
959      * @param childName
960      *            string with name of child node
961      * @param lineNum
962      *            line number in YANG file where is the node with the name equal
963      *            to <code>childName</code> is defined
964      */
965     private void addChildToModule(final DataSchemaNodeBuilder child, final String childName, final int lineNum) {
966         // if parent == null => node is defined under module
967         // All leafs, leaf-lists, lists, containers, choices, rpcs,
968         // notifications, and anyxmls defined within a parent node or at the
969         // top level of the module or its submodules share the same
970         // identifier namespace.
971         for (DataSchemaNodeBuilder childNode : getChildNodeBuilders()) {
972             if (childNode.getQName().getLocalName().equals(childName)) {
973                 raiseYangParserException("'" + child + "'", "node", childName, lineNum, childNode.getLine());
974             }
975         }
976         for (RpcDefinitionBuilder rpc : addedRpcs) {
977             if (rpc.getQName().getLocalName().equals(childName)) {
978                 raiseYangParserException("'" + child + "'", "rpc", childName, lineNum, rpc.getLine());
979             }
980         }
981         for (NotificationBuilder notification : addedNotifications) {
982             if (notification.getQName().getLocalName().equals(childName)) {
983                 raiseYangParserException("'" + child + "'", "notification", childName, lineNum, notification.getLine());
984             }
985         }
986         addChildNode(child);
987     }
988
989     /**
990      * Adds child node <code>child</code> to the group of child nodes of the
991      * <code>parent</code>
992      *
993      * The method reduces the complexity of the method
994      * {@link #addChildToParent(Builder, DataSchemaNodeBuilder, String)
995      * addChildToParent}. *
996      *
997      * @param parent
998      *            builder of node which is parent for <code>child</code>
999      * @param child
1000      *            data schema node builder for child node
1001      * @param childName
1002      *            string with name of child node
1003      * @param lineNum
1004      *            line number in YANG file where is the node with the name equal
1005      *            to <code>childName</code> is defined
1006      */
1007     private void addChildToSubnodeOfModule(final Builder parent, final DataSchemaNodeBuilder child,
1008             final String childName, final int lineNum) {
1009         // no need for checking rpc and notification because they can be
1010         // defined only under module or submodule
1011         if (parent instanceof DataNodeContainerBuilder) {
1012             DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
1013             for (DataSchemaNodeBuilder childNode : parentNode.getChildNodeBuilders()) {
1014                 if (childNode.getQName().getLocalName().equals(childName)) {
1015                     raiseYangParserException("'" + child + "'", "node", childName, lineNum, childNode.getLine());
1016                 }
1017             }
1018             parentNode.addChildNode(child);
1019         } else if (parent instanceof ChoiceBuilder) {
1020             ChoiceBuilder parentNode = (ChoiceBuilder) parent;
1021             for (ChoiceCaseBuilder caseBuilder : parentNode.getCases()) {
1022                 if (caseBuilder.getQName().getLocalName().equals(childName)) {
1023                     raiseYangParserException("'" + child + "'", "node", childName, lineNum, caseBuilder.getLine());
1024                 }
1025             }
1026             parentNode.addCase(child);
1027         } else {
1028             throw new YangParseException(name, lineNum, "Unresolved parent of node '" + childName + "'.");
1029         }
1030     }
1031
1032     private ModuleImport createModuleImport(final String moduleName, final Date revision, final String prefix) {
1033         return new ModuleImportImpl(moduleName, revision, prefix);
1034     }
1035
1036     private void raiseYangParserException(final String cantAddType, final String type, final String name,
1037             final int currentLine, final int duplicateLine) {
1038
1039         StringBuilder msgPrefix = new StringBuilder("");
1040         if (cantAddType != null && !cantAddType.isEmpty()) {
1041             msgPrefix.append("Can not add ");
1042             msgPrefix.append(cantAddType);
1043             msgPrefix.append(": ");
1044         }
1045
1046         String msg = String.format("%s%s with same name '%s' already declared at line %d.", msgPrefix, type, name,
1047                 duplicateLine);
1048         throw new YangParseException(getModuleName(), currentLine, msg);
1049     }
1050
1051     @Override
1052     public int hashCode() {
1053         final int prime = 31;
1054         int result = 1;
1055         result = prime * result + ((name == null) ? 0 : name.hashCode());
1056         result = prime * result + qnameModule.hashCode();
1057         result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());
1058
1059         return result;
1060     }
1061
1062     @Override
1063     public boolean equals(final Object obj) {
1064         if (this == obj) {
1065             return true;
1066         }
1067         if (obj == null) {
1068             return false;
1069         }
1070         if (getClass() != obj.getClass()) {
1071             return false;
1072         }
1073         ModuleBuilder other = (ModuleBuilder) obj;
1074         if (name == null) {
1075             if (other.name != null) {
1076                 return false;
1077             }
1078         } else if (!name.equals(other.name)) {
1079             return false;
1080         }
1081         if (!qnameModule.equals(other.qnameModule)) {
1082             return false;
1083         }
1084         if (prefix == null) {
1085             if (other.prefix != null) {
1086                 return false;
1087             }
1088         } else if (!prefix.equals(other.prefix)) {
1089             return false;
1090         }
1091         return true;
1092     }
1093
1094     public List<UnknownSchemaNode> getExtensionInstances() {
1095         return unknownNodes;
1096     }
1097 }