Minor code style improvements to eliminate eclipse warnings.
[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  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.parser.builder.impl;
9
10 import java.net.URI;
11 import java.util.*;
12
13 import org.opendaylight.yangtools.yang.common.QName;
14 import org.opendaylight.yangtools.yang.model.api.*;
15 import org.opendaylight.yangtools.yang.parser.builder.api.*;
16 import org.opendaylight.yangtools.yang.parser.util.Comparators;
17 import org.opendaylight.yangtools.yang.parser.util.ModuleImportImpl;
18 import org.opendaylight.yangtools.yang.parser.util.RefineHolder;
19 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
20
21 /**
22  * Builder of Module object. If this module is dependent on external
23  * module/modules, these dependencies must be resolved before module is built,
24  * otherwise result may not be valid.
25  */
26 public class ModuleBuilder extends AbstractDataNodeContainerBuilder {
27
28     private final ModuleImpl instance;
29     private final String name;
30     private final String sourcePath;
31     private final SchemaPath schemaPath;
32     private URI namespace;
33     private String prefix;
34     private Date revision;
35
36     private final boolean submodule;
37     private String belongsTo;
38     private ModuleBuilder parent;
39
40     public ModuleBuilder getParent() {
41         return parent;
42     }
43
44     public void setParent(ModuleBuilder parent) {
45         this.parent = parent;
46     }
47
48     private final Deque<Builder> actualPath = new LinkedList<>();
49     private final Set<TypeAwareBuilder> dirtyNodes = new HashSet<>();
50
51     private final Set<ModuleImport> imports = new HashSet<ModuleImport>();
52
53     private final Set<AugmentationSchema> augments = new HashSet<>();
54     private final List<AugmentationSchemaBuilder> augmentBuilders = new ArrayList<>();
55     private final List<AugmentationSchemaBuilder> allAugments = new ArrayList<>();
56
57     private final List<GroupingBuilder> allGroupings = new ArrayList<>();
58
59     private final List<UsesNodeBuilder> allUsesNodes = new ArrayList<>();
60
61     private final Set<RpcDefinition> rpcs = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
62     private final Set<RpcDefinitionBuilder> addedRpcs = new HashSet<>();
63
64     private final Set<NotificationDefinition> notifications = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
65     private final Set<NotificationBuilder> addedNotifications = new HashSet<>();
66
67     private final Set<IdentitySchemaNode> identities = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
68     private final Set<IdentitySchemaNodeBuilder> addedIdentities = new HashSet<>();
69
70     private final Set<FeatureDefinition> features = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
71     private final Set<FeatureBuilder> addedFeatures = new HashSet<>();
72
73     private final Set<Deviation> deviations = new HashSet<>();
74     private final Set<DeviationBuilder> deviationBuilders = new HashSet<>();
75
76     private final List<ExtensionDefinition> extensions = new ArrayList<>();
77     private final List<ExtensionBuilder> addedExtensions = new ArrayList<>();
78
79     private final List<UnknownSchemaNodeBuilder> allUnknownNodes = new ArrayList<UnknownSchemaNodeBuilder>();
80
81     private final List<ListSchemaNodeBuilder> allLists = new ArrayList<ListSchemaNodeBuilder>();
82
83     public ModuleBuilder(final String name, final String sourcePath) {
84         this(name, false, sourcePath);
85     }
86
87     public ModuleBuilder(final String name, final boolean submodule, final String sourcePath) {
88         super(name, 0, null);
89         this.name = name;
90         this.sourcePath = sourcePath;
91         schemaPath = new SchemaPath(Collections.<QName> emptyList(), true);
92         this.submodule = submodule;
93         instance = new ModuleImpl(name, sourcePath);
94         actualPath.push(this);
95     }
96
97     public ModuleBuilder(Module base) {
98         super(base.getName(), 0, null);
99         this.name = base.getName();
100         this.sourcePath = base.getModuleSourcePath();
101         schemaPath = new SchemaPath(Collections.<QName> emptyList(), true);
102         submodule = false;
103         instance = new ModuleImpl(base.getName(), base.getModuleSourcePath());
104         actualPath.push(this);
105         namespace = base.getNamespace();
106         prefix = base.getPrefix();
107         revision = base.getRevision();
108
109         for (DataSchemaNode childNode : base.getChildNodes()) {
110             childNodes.add(childNode);
111         }
112
113         typedefs.addAll(base.getTypeDefinitions());
114         groupings.addAll(base.getGroupings());
115         usesNodes.addAll(base.getUses());
116         augments.addAll(base.getAugmentations());
117         rpcs.addAll(base.getRpcs());
118         notifications.addAll(base.getNotifications());
119         identities.addAll(base.getIdentities());
120         features.addAll(base.getFeatures());
121         deviations.addAll(base.getDeviations());
122         extensions.addAll(base.getExtensionSchemaNodes());
123         unknownNodes.addAll(base.getUnknownSchemaNodes());
124     }
125
126     /**
127      * Build new Module object based on this builder.
128      */
129     @Override
130     public Module build() {
131         instance.setPrefix(prefix);
132         instance.setRevision(revision);
133         instance.setImports(imports);
134         instance.setNamespace(namespace);
135
136         // TYPEDEFS
137         for (TypeDefinitionBuilder tdb : addedTypedefs) {
138             typedefs.add(tdb.build());
139         }
140         instance.setTypeDefinitions(typedefs);
141
142         // CHILD NODES
143         for (DataSchemaNodeBuilder child : addedChildNodes) {
144             childNodes.add(child.build());
145         }
146         instance.addChildNodes(childNodes);
147
148         // GROUPINGS
149         for (GroupingBuilder gb : addedGroupings) {
150             groupings.add(gb.build());
151         }
152         instance.setGroupings(groupings);
153
154         // USES
155         for (UsesNodeBuilder unb : addedUsesNodes) {
156             usesNodes.add(unb.build());
157         }
158         instance.setUses(usesNodes);
159
160         // FEATURES
161         for (FeatureBuilder fb : addedFeatures) {
162             features.add(fb.build());
163         }
164         instance.setFeatures(features);
165
166         // NOTIFICATIONS
167         for (NotificationBuilder entry : addedNotifications) {
168             notifications.add(entry.build());
169         }
170         instance.setNotifications(notifications);
171
172         // AUGMENTATIONS
173         for (AugmentationSchemaBuilder builder : augmentBuilders) {
174             augments.add(builder.build());
175         }
176         instance.setAugmentations(augments);
177
178         // RPCs
179         for (RpcDefinitionBuilder rpc : addedRpcs) {
180             rpcs.add(rpc.build());
181         }
182         instance.setRpcs(rpcs);
183
184         // DEVIATIONS
185         for (DeviationBuilder entry : deviationBuilders) {
186             deviations.add(entry.build());
187         }
188         instance.setDeviations(deviations);
189
190         // EXTENSIONS
191         for (ExtensionBuilder eb : addedExtensions) {
192             extensions.add(eb.build());
193         }
194         Collections.sort(extensions, Comparators.SCHEMA_NODE_COMP);
195         instance.setExtensionSchemaNodes(extensions);
196
197         // IDENTITIES
198         for (IdentitySchemaNodeBuilder id : addedIdentities) {
199             identities.add(id.build());
200         }
201         instance.setIdentities(identities);
202
203         // UNKNOWN NODES
204         for (UnknownSchemaNodeBuilder unb : addedUnknownNodes) {
205             unknownNodes.add(unb.build());
206         }
207         Collections.sort(unknownNodes, Comparators.SCHEMA_NODE_COMP);
208         instance.setUnknownSchemaNodes(unknownNodes);
209
210         return instance;
211     }
212
213     public String getModuleSourcePath() {
214         return sourcePath;
215     }
216
217     @Override
218     public void setParent(Builder parent) {
219         throw new YangParseException(name, 0, "Can not set parent to module");
220     }
221
222     @Override
223     public SchemaPath getPath() {
224         return schemaPath;
225     }
226
227     @Override
228     public Set<TypeDefinitionBuilder> getTypeDefinitionBuilders() {
229         return addedTypedefs;
230     }
231
232     public void enterNode(final Builder node) {
233         actualPath.push(node);
234     }
235
236     public void exitNode() {
237         actualPath.pop();
238     }
239
240     public Builder getActualNode() {
241         if (actualPath.isEmpty()) {
242             return null;
243         } else {
244             return actualPath.peekFirst();
245         }
246     }
247
248     public Builder getActualParent() {
249         if (actualPath.size() < 2) {
250             return null;
251         } else {
252             Builder builderChild = actualPath.removeFirst();
253             Builder builderParent = actualPath.peekFirst();
254             actualPath.addFirst(builderChild);
255             return builderParent;
256         }
257     }
258
259     public Set<TypeAwareBuilder> getDirtyNodes() {
260         return dirtyNodes;
261     }
262
263     public Set<AugmentationSchema> getAugments() {
264         return augments;
265     }
266
267     public List<AugmentationSchemaBuilder> getAugmentBuilders() {
268         return augmentBuilders;
269     }
270
271     public List<AugmentationSchemaBuilder> getAllAugments() {
272         return allAugments;
273     }
274
275     public Set<IdentitySchemaNode> getIdentities() {
276         return identities;
277     }
278
279     public Set<IdentitySchemaNodeBuilder> getAddedIdentities() {
280         return addedIdentities;
281     }
282
283     public Set<FeatureDefinition> getFeatures() {
284         return features;
285     }
286
287     public Set<FeatureBuilder> getAddedFeatures() {
288         return addedFeatures;
289     }
290
291     public List<GroupingBuilder> getAllGroupings() {
292         return allGroupings;
293     }
294
295     public List<UsesNodeBuilder> getAllUsesNodes() {
296         return allUsesNodes;
297     }
298
299     public Set<Deviation> getDeviations() {
300         return deviations;
301     }
302
303     public Set<DeviationBuilder> getDeviationBuilders() {
304         return deviationBuilders;
305     }
306
307     public List<ExtensionDefinition> getExtensions() {
308         return extensions;
309     }
310
311     public List<ExtensionBuilder> getAddedExtensions() {
312         return addedExtensions;
313     }
314
315     public List<UnknownSchemaNodeBuilder> getAllUnknownNodes() {
316         return allUnknownNodes;
317     }
318
319     public List<ListSchemaNodeBuilder> getAllLists() {
320         return allLists;
321     }
322
323     public String getName() {
324         return name;
325     }
326
327     public URI getNamespace() {
328         return namespace;
329     }
330
331     public void setNamespace(final URI namespace) {
332         this.namespace = namespace;
333     }
334
335     public String getPrefix() {
336         return prefix;
337     }
338
339     public Date getRevision() {
340         return revision;
341     }
342
343     public boolean isSubmodule() {
344         return submodule;
345     }
346
347     public String getBelongsTo() {
348         return belongsTo;
349     }
350
351     public void setBelongsTo(String belongsTo) {
352         this.belongsTo = belongsTo;
353     }
354
355     public void markActualNodeDirty() {
356         final TypeAwareBuilder nodeBuilder = (TypeAwareBuilder) getActualNode();
357         dirtyNodes.add(nodeBuilder);
358     }
359
360     public void setRevision(final Date revision) {
361         this.revision = revision;
362     }
363
364     public void setPrefix(final String prefix) {
365         this.prefix = prefix;
366     }
367
368     public void setYangVersion(final String yangVersion) {
369         instance.setYangVersion(yangVersion);
370     }
371
372     public void setDescription(final String description) {
373         instance.setDescription(description);
374     }
375
376     public void setReference(final String reference) {
377         instance.setReference(reference);
378     }
379
380     public void setOrganization(final String organization) {
381         instance.setOrganization(organization);
382     }
383
384     public void setContact(final String contact) {
385         instance.setContact(contact);
386     }
387
388     public boolean addModuleImport(final String moduleName, final Date revision, final String prefix) {
389         final ModuleImport moduleImport = createModuleImport(moduleName, revision, prefix);
390         return imports.add(moduleImport);
391     }
392
393     public Set<ModuleImport> getModuleImports() {
394         return imports;
395     }
396
397     public ExtensionBuilder addExtension(final QName qname, final int line, final SchemaPath path) {
398         Builder parent = getActualNode();
399         if (!(parent.equals(this))) {
400             throw new YangParseException(name, line, "extension can be defined only in module or submodule");
401         }
402
403         final String extName = qname.getLocalName();
404         for (ExtensionBuilder addedExtension : addedExtensions) {
405             if (addedExtension.getQName().getLocalName().equals(extName)) {
406                 raiseYangParserException("extension", "node", extName, line, addedExtension.getLine());
407             }
408         }
409         final ExtensionBuilder builder = new ExtensionBuilder(name, line, qname, path);
410         builder.setParent(parent);
411         addedExtensions.add(builder);
412         return builder;
413     }
414
415     public ContainerSchemaNodeBuilder addContainerNode(final int line, final QName qname, final SchemaPath schemaPath) {
416         final ContainerSchemaNodeBuilder builder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
417
418         Builder parent = getActualNode();
419         builder.setParent(parent);
420         addChildToParent(parent, builder, qname.getLocalName());
421
422         return builder;
423     }
424
425     public ListSchemaNodeBuilder addListNode(final int line, final QName qname, final SchemaPath schemaPath) {
426         final ListSchemaNodeBuilder builder = new ListSchemaNodeBuilder(name, line, qname, schemaPath);
427
428         Builder parent = getActualNode();
429         builder.setParent(parent);
430         addChildToParent(parent, builder, qname.getLocalName());
431         allLists.add(builder);
432
433         return builder;
434     }
435
436     public LeafSchemaNodeBuilder addLeafNode(final int line, final QName qname, final SchemaPath schemaPath) {
437         final LeafSchemaNodeBuilder builder = new LeafSchemaNodeBuilder(name, line, qname, schemaPath);
438
439         Builder parent = getActualNode();
440         builder.setParent(parent);
441         addChildToParent(parent, builder, qname.getLocalName());
442
443         return builder;
444     }
445
446     public LeafListSchemaNodeBuilder addLeafListNode(final int line, final QName qname, final SchemaPath schemaPath) {
447         final LeafListSchemaNodeBuilder builder = new LeafListSchemaNodeBuilder(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 GroupingBuilder addGrouping(final int line, final QName qname, final SchemaPath path) {
457         final GroupingBuilder builder = new GroupingBuilderImpl(name, line, qname, path);
458
459         Builder parent = getActualNode();
460         builder.setParent(parent);
461
462         String groupingName = qname.getLocalName();
463         if (parent.equals(this)) {
464             for (GroupingBuilder addedGrouping : addedGroupings) {
465                 if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
466                     raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
467                 }
468             }
469             addedGroupings.add(builder);
470         } else {
471             if (parent instanceof DataNodeContainerBuilder) {
472                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
473                 for (GroupingBuilder addedGrouping : parentNode.getGroupingBuilders()) {
474                     if (addedGrouping.getQName().getLocalName().equals(groupingName)) {
475                         raiseYangParserException("", "Grouping", groupingName, line, addedGrouping.getLine());
476                     }
477                 }
478                 parentNode.addGrouping(builder);
479             } else if (parent instanceof RpcDefinitionBuilder) {
480                 RpcDefinitionBuilder parentNode = (RpcDefinitionBuilder) parent;
481                 for (GroupingBuilder child : parentNode.getGroupings()) {
482                     if (child.getQName().getLocalName().equals(groupingName)) {
483                         raiseYangParserException("", "Grouping", groupingName, line, child.getLine());
484                     }
485                 }
486                 parentNode.addGrouping(builder);
487             } else {
488                 throw new YangParseException(name, line, "Unresolved parent of grouping " + groupingName);
489             }
490         }
491
492         allGroupings.add(builder);
493         return builder;
494     }
495
496     public AugmentationSchemaBuilder addAugment(final int line, final String augmentTargetStr) {
497         final AugmentationSchemaBuilder builder = new AugmentationSchemaBuilderImpl(name, line, augmentTargetStr);
498
499         Builder parent = getActualNode();
500         builder.setParent(parent);
501
502         if (parent.equals(this)) {
503             // augment can be declared only under 'module' ...
504             if (!(augmentTargetStr.startsWith("/"))) {
505                 throw new YangParseException(
506                         name,
507                         line,
508                         "If the 'augment' statement is on the top level in a module, the absolute form of a schema node identifier MUST be used.");
509             }
510             augmentBuilders.add(builder);
511         } else {
512             // ... or 'uses' statement
513             if (parent instanceof UsesNodeBuilder) {
514                 if (augmentTargetStr.startsWith("/")) {
515                     throw new YangParseException(name, line,
516                             "If 'augment' statement is a substatement to the 'uses' statement, it cannot contain absolute path ("
517                                     + augmentTargetStr + ")");
518                 }
519                 ((UsesNodeBuilder) parent).addAugment(builder);
520             } else {
521                 throw new YangParseException(name, line, "Augment can be declared only under module or uses statement.");
522             }
523         }
524         allAugments.add(builder);
525
526         return builder;
527     }
528
529     @Override
530     public void addUsesNode(UsesNodeBuilder usesBuilder) {
531         addedUsesNodes.add(usesBuilder);
532         allUsesNodes.add(usesBuilder);
533     }
534
535     public UsesNodeBuilder addUsesNode(final int line, final String groupingPathStr) {
536         final UsesNodeBuilder usesBuilder = new UsesNodeBuilderImpl(name, line, groupingPathStr);
537
538         Builder parent = getActualNode();
539         usesBuilder.setParent(parent);
540
541         if (parent.equals(this)) {
542             addedUsesNodes.add(usesBuilder);
543         } else {
544             if (!(parent instanceof DataNodeContainerBuilder)) {
545                 throw new YangParseException(name, line, "Unresolved parent of uses '" + groupingPathStr + "'.");
546             }
547             ((DataNodeContainerBuilder) parent).addUsesNode(usesBuilder);
548         }
549         if (parent instanceof AugmentationSchemaBuilder) {
550             usesBuilder.setAugmenting(true);
551         }
552
553         allUsesNodes.add(usesBuilder);
554         return usesBuilder;
555     }
556
557     public void addRefine(final RefineHolder refine) {
558         final Builder parent = getActualNode();
559         if (!(parent instanceof UsesNodeBuilder)) {
560             throw new YangParseException(name, refine.getLine(), "refine can be defined only in uses statement");
561         }
562         ((UsesNodeBuilder) parent).addRefine(refine);
563         refine.setParent(parent);
564     }
565
566     public RpcDefinitionBuilder addRpc(final int line, final QName qname, final SchemaPath path) {
567         Builder parent = getActualNode();
568         if (!(parent.equals(this))) {
569             throw new YangParseException(name, line, "rpc can be defined only in module or submodule");
570         }
571
572         final RpcDefinitionBuilder rpcBuilder = new RpcDefinitionBuilder(name, line, qname, path);
573         rpcBuilder.setParent(parent);
574
575         String rpcName = qname.getLocalName();
576         for (RpcDefinitionBuilder rpc : addedRpcs) {
577             if (rpc.getQName().getLocalName().equals(rpcName)) {
578                 raiseYangParserException("", "rpc", rpcName, line, rpc.getLine());
579             }
580         }
581         for (DataSchemaNodeBuilder addedChild : addedChildNodes) {
582             if (addedChild.getQName().getLocalName().equals(rpcName)) {
583                 raiseYangParserException("rpc", "node", rpcName, line, addedChild.getLine());
584             }
585         }
586         for (NotificationBuilder addedNotification : addedNotifications) {
587             if (addedNotification.getQName().getLocalName().equals(rpcName)) {
588                 raiseYangParserException("rpc", "notification", rpcName, line, addedNotification.getLine());
589             }
590         }
591         addedRpcs.add(rpcBuilder);
592         return rpcBuilder;
593     }
594
595     public ContainerSchemaNodeBuilder addRpcInput(final int line, final QName qname, final SchemaPath schemaPath) {
596         final Builder parent = getActualNode();
597         if (!(parent instanceof RpcDefinitionBuilder)) {
598             throw new YangParseException(name, line, "input can be defined only in rpc statement");
599         }
600         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
601
602         final ContainerSchemaNodeBuilder inputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
603         inputBuilder.setParent(rpc);
604
605         rpc.setInput(inputBuilder);
606         return inputBuilder;
607     }
608
609     public ContainerSchemaNodeBuilder addRpcOutput(final SchemaPath schemaPath, final QName qname, final int line) {
610         final Builder parent = getActualNode();
611         if (!(parent instanceof RpcDefinitionBuilder)) {
612             throw new YangParseException(name, line, "output can be defined only in rpc statement");
613         }
614         final RpcDefinitionBuilder rpc = (RpcDefinitionBuilder) parent;
615
616         final ContainerSchemaNodeBuilder outputBuilder = new ContainerSchemaNodeBuilder(name, line, qname, schemaPath);
617         outputBuilder.setParent(rpc);
618
619         rpc.setOutput(outputBuilder);
620         return outputBuilder;
621     }
622
623     public void addNotification(NotificationDefinition notification) {
624         notifications.add(notification);
625     }
626
627     public NotificationBuilder addNotification(final int line, final QName qname, final SchemaPath path) {
628         final Builder parent = getActualNode();
629         if (!(parent.equals(this))) {
630             throw new YangParseException(name, line, "notification can be defined only in module or submodule");
631         }
632
633         String notificationName = qname.getLocalName();
634         for (NotificationBuilder nb : addedNotifications) {
635             if (nb.getQName().equals(qname)) {
636                 raiseYangParserException("", "notification", notificationName, line, nb.getLine());
637             }
638         }
639         for (RpcDefinitionBuilder rpc : addedRpcs) {
640             if (rpc.getQName().getLocalName().equals(notificationName)) {
641                 raiseYangParserException("notification", "rpc", notificationName, line, rpc.getLine());
642             }
643         }
644         for (DataSchemaNodeBuilder addedChild : addedChildNodes) {
645             if (addedChild.getQName().getLocalName().equals(notificationName)) {
646                 raiseYangParserException("notification", "node", notificationName, line, addedChild.getLine());
647             }
648         }
649
650         final NotificationBuilder builder = new NotificationBuilder(name, line, qname, path);
651         builder.setParent(parent);
652         addedNotifications.add(builder);
653
654         return builder;
655     }
656
657     public FeatureBuilder addFeature(final int line, final QName qname, final SchemaPath path) {
658         Builder parent = getActualNode();
659         if (!(parent.equals(this))) {
660             throw new YangParseException(name, line, "feature can be defined only in module or submodule");
661         }
662
663         final FeatureBuilder builder = new FeatureBuilder(name, line, qname, path);
664         builder.setParent(parent);
665
666         String featureName = qname.getLocalName();
667         for (FeatureBuilder addedFeature : addedFeatures) {
668             if (addedFeature.getQName().getLocalName().equals(featureName)) {
669                 raiseYangParserException("", "feature", featureName, line, addedFeature.getLine());
670             }
671         }
672         addedFeatures.add(builder);
673         return builder;
674     }
675
676     public ChoiceBuilder addChoice(final int line, final QName qname, final SchemaPath path) {
677         final ChoiceBuilder builder = new ChoiceBuilder(name, line, qname, path);
678
679         Builder parent = getActualNode();
680         builder.setParent(parent);
681         addChildToParent(parent, builder, qname.getLocalName());
682
683         return builder;
684     }
685
686     public ChoiceCaseBuilder addCase(final int line, final QName qname, final SchemaPath path) {
687         Builder parent = getActualNode();
688         if (parent == null || parent.equals(this)) {
689             throw new YangParseException(name, line, "'case' parent not found");
690         }
691
692         final ChoiceCaseBuilder builder = new ChoiceCaseBuilder(name, line, qname, path);
693         builder.setParent(parent);
694
695         if (parent instanceof ChoiceBuilder) {
696             ((ChoiceBuilder) parent).addCase(builder);
697         } else if (parent instanceof AugmentationSchemaBuilder) {
698             ((AugmentationSchemaBuilder) parent).addChildNode(builder);
699         } else {
700             throw new YangParseException(name, line, "Unresolved parent of 'case' " + qname.getLocalName());
701         }
702
703         return builder;
704     }
705
706     public AnyXmlBuilder addAnyXml(final int line, final QName qname, final SchemaPath schemaPath) {
707         final AnyXmlBuilder builder = new AnyXmlBuilder(name, line, qname, schemaPath);
708
709         Builder parent = getActualNode();
710         builder.setParent(parent);
711         addChildToParent(parent, builder, qname.getLocalName());
712
713         return builder;
714     }
715
716     @Override
717     public void addTypedef(TypeDefinitionBuilder typedefBuilder) {
718         String nodeName = typedefBuilder.getQName().getLocalName();
719         for (TypeDefinitionBuilder tdb : addedTypedefs) {
720             if (tdb.getQName().getLocalName().equals(nodeName)) {
721                 raiseYangParserException("", "typedef", nodeName, typedefBuilder.getLine(), tdb.getLine());
722             }
723         }
724         addedTypedefs.add(typedefBuilder);
725     }
726
727     public TypeDefinitionBuilderImpl addTypedef(final int line, final QName qname, final SchemaPath path) {
728         final TypeDefinitionBuilderImpl builder = new TypeDefinitionBuilderImpl(name, line, qname, path);
729
730         Builder parent = getActualNode();
731         builder.setParent(parent);
732
733         String typedefName = qname.getLocalName();
734         if (parent.equals(this)) {
735             for (TypeDefinitionBuilder tdb : addedTypedefs) {
736                 if (tdb.getQName().getLocalName().equals(typedefName)) {
737                     raiseYangParserException("", "typedef", typedefName, line, tdb.getLine());
738                 }
739             }
740             addedTypedefs.add(builder);
741         } else {
742             if (parent instanceof DataNodeContainerBuilder) {
743                 DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
744                 for (TypeDefinitionBuilder child : parentNode.getTypeDefinitionBuilders()) {
745                     if (child.getQName().getLocalName().equals(typedefName)) {
746                         raiseYangParserException("", "typedef", typedefName, line, child.getLine());
747                     }
748                 }
749                 parentNode.addTypedef(builder);
750             } else if (parent instanceof RpcDefinitionBuilder) {
751                 RpcDefinitionBuilder rpcParent = (RpcDefinitionBuilder) parent;
752                 for (TypeDefinitionBuilder tdb : rpcParent.getTypeDefinitions()) {
753                     if (tdb.getQName().getLocalName().equals(builder.getQName().getLocalName())) {
754                         raiseYangParserException("", "typedef", typedefName, line, tdb.getLine());
755                     }
756                 }
757                 rpcParent.addTypedef(builder);
758             } else {
759                 throw new YangParseException(name, line, "Unresolved parent of typedef " + typedefName);
760             }
761         }
762
763         return builder;
764     }
765
766     public void setType(final TypeDefinition<?> type) {
767         Builder parent = getActualNode();
768         if (!(parent instanceof TypeAwareBuilder)) {
769             throw new YangParseException("Failed to set type '" + type.getQName().getLocalName()
770                     + "'. Invalid parent node: " + parent);
771         }
772         ((TypeAwareBuilder) parent).setType(type);
773     }
774
775     public UnionTypeBuilder addUnionType(final int line, final URI namespace, final Date revision) {
776         final Builder parent = getActualNode();
777         if (parent == null) {
778             throw new YangParseException(name, line, "Unresolved parent of union type");
779         } else {
780             final UnionTypeBuilder union = new UnionTypeBuilder(name, line);
781             if (parent instanceof TypeAwareBuilder) {
782                 ((TypeAwareBuilder) parent).setTypedef(union);
783                 return union;
784             } else {
785                 throw new YangParseException(name, line, "Invalid parent of union type.");
786             }
787         }
788     }
789
790     public void addIdentityrefType(final int line, final SchemaPath schemaPath, final String baseString) {
791         final IdentityrefTypeBuilder identityref = new IdentityrefTypeBuilder(name, line, baseString, schemaPath);
792
793         final Builder parent = getActualNode();
794         if (parent == null) {
795             throw new YangParseException(name, line, "Unresolved parent of identityref type.");
796         } else {
797             if (parent instanceof TypeAwareBuilder) {
798                 final TypeAwareBuilder typeParent = (TypeAwareBuilder) parent;
799                 typeParent.setTypedef(identityref);
800                 dirtyNodes.add(typeParent);
801             } else {
802                 throw new YangParseException(name, line, "Invalid parent of identityref type.");
803             }
804         }
805     }
806
807     public DeviationBuilder addDeviation(final int line, final String targetPath) {
808         Builder parent = getActualNode();
809         if (!(parent.equals(this))) {
810             throw new YangParseException(name, line, "deviation can be defined only in module or submodule");
811         }
812
813         final DeviationBuilder builder = new DeviationBuilder(name, line, targetPath);
814         builder.setParent(parent);
815         deviationBuilders.add(builder);
816         return builder;
817     }
818
819     public IdentitySchemaNodeBuilder addIdentity(final QName qname, final int line, final SchemaPath path) {
820         Builder parent = getActualNode();
821         if (!(parent.equals(this))) {
822             throw new YangParseException(name, line, "identity can be defined only in module or submodule");
823         }
824         String identityName = qname.getLocalName();
825         for (IdentitySchemaNodeBuilder idBuilder : addedIdentities) {
826             if (idBuilder.getQName().equals(qname)) {
827                 raiseYangParserException("", "identity", identityName, line, idBuilder.getLine());
828             }
829         }
830
831         final IdentitySchemaNodeBuilder builder = new IdentitySchemaNodeBuilder(name, line, qname, path);
832         builder.setParent(parent);
833         addedIdentities.add(builder);
834         return builder;
835     }
836
837     @Override
838     public void addUnknownNodeBuilder(final UnknownSchemaNodeBuilder builder) {
839         addedUnknownNodes.add(builder);
840         allUnknownNodes.add(builder);
841     }
842
843     public UnknownSchemaNodeBuilder addUnknownSchemaNode(final int line, final QName qname, final SchemaPath path) {
844         final Builder parent = getActualNode();
845         final UnknownSchemaNodeBuilder builder = new UnknownSchemaNodeBuilder(name, line, qname, path);
846         builder.setParent(parent);
847         allUnknownNodes.add(builder);
848
849         if (parent.equals(this)) {
850             addedUnknownNodes.add(builder);
851         } else {
852             if (parent instanceof SchemaNodeBuilder) {
853                 ((SchemaNodeBuilder) parent).addUnknownNodeBuilder(builder);
854             } else if (parent instanceof DataNodeContainerBuilder) {
855                 ((DataNodeContainerBuilder) parent).addUnknownNodeBuilder(builder);
856             } else if (parent instanceof RefineHolder) {
857                 ((RefineHolder) parent).addUnknownNodeBuilder(builder);
858             } else {
859                 throw new YangParseException(name, line, "Unresolved parent of unknown node '" + qname.getLocalName()
860                         + "'");
861             }
862         }
863
864         return builder;
865     }
866
867     public Set<RpcDefinition> getRpcs() {
868         return rpcs;
869     }
870
871     public Set<RpcDefinitionBuilder> getAddedRpcs() {
872         return addedRpcs;
873     }
874
875     public Set<NotificationDefinition> getNotifications() {
876         return notifications;
877     }
878
879     public Set<NotificationBuilder> getAddedNotifications() {
880         return addedNotifications;
881     }
882
883     @Override
884     public String toString() {
885         return "module " + name;
886     }
887
888     private static final class ModuleImpl implements Module {
889         private URI namespace;
890         private final String name;
891         private final String sourcePath;
892         private Date revision;
893         private String prefix;
894         private String yangVersion;
895         private String description;
896         private String reference;
897         private String organization;
898         private String contact;
899         private final Set<ModuleImport> imports = new HashSet<>();
900         private final Set<FeatureDefinition> features = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
901         private final Set<TypeDefinition<?>> typeDefinitions = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
902         private final Set<NotificationDefinition> notifications = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
903         private final Set<AugmentationSchema> augmentations = new HashSet<>();
904         private final Set<RpcDefinition> rpcs = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
905         private final Set<Deviation> deviations = new HashSet<>();
906         private final Set<DataSchemaNode> childNodes = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
907         private final Set<GroupingDefinition> groupings = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
908         private final Set<UsesNode> uses = new HashSet<>();
909         private final List<ExtensionDefinition> extensionNodes = new ArrayList<>();
910         private final Set<IdentitySchemaNode> identities = new TreeSet<>(Comparators.SCHEMA_NODE_COMP);
911         private final List<UnknownSchemaNode> unknownNodes = new ArrayList<>();
912
913         private ModuleImpl(String name, String sourcePath) {
914             this.name = name;
915             this.sourcePath = sourcePath;
916         }
917
918         @Override
919         public String getModuleSourcePath() {
920             return sourcePath;
921         }
922
923         @Override
924         public URI getNamespace() {
925             return namespace;
926         }
927
928         private void setNamespace(URI namespace) {
929             this.namespace = namespace;
930         }
931
932         @Override
933         public String getName() {
934             return name;
935         }
936
937         @Override
938         public Date getRevision() {
939             return revision;
940         }
941
942         private void setRevision(Date revision) {
943             this.revision = revision;
944         }
945
946         @Override
947         public String getPrefix() {
948             return prefix;
949         }
950
951         private void setPrefix(String prefix) {
952             this.prefix = prefix;
953         }
954
955         @Override
956         public String getYangVersion() {
957             return yangVersion;
958         }
959
960         private void setYangVersion(String yangVersion) {
961             this.yangVersion = yangVersion;
962         }
963
964         @Override
965         public String getDescription() {
966             return description;
967         }
968
969         private void setDescription(String description) {
970             this.description = description;
971         }
972
973         @Override
974         public String getReference() {
975             return reference;
976         }
977
978         private void setReference(String reference) {
979             this.reference = reference;
980         }
981
982         @Override
983         public String getOrganization() {
984             return organization;
985         }
986
987         private void setOrganization(String organization) {
988             this.organization = organization;
989         }
990
991         @Override
992         public String getContact() {
993             return contact;
994         }
995
996         private void setContact(String contact) {
997             this.contact = contact;
998         }
999
1000         @Override
1001         public Set<ModuleImport> getImports() {
1002             return imports;
1003         }
1004
1005         private void setImports(Set<ModuleImport> imports) {
1006             if (imports != null) {
1007                 this.imports.addAll(imports);
1008             }
1009         }
1010
1011         @Override
1012         public Set<FeatureDefinition> getFeatures() {
1013             return features;
1014         }
1015
1016         private void setFeatures(Set<FeatureDefinition> features) {
1017             if (features != null) {
1018                 this.features.addAll(features);
1019             }
1020         }
1021
1022         @Override
1023         public Set<TypeDefinition<?>> getTypeDefinitions() {
1024             return typeDefinitions;
1025         }
1026
1027         private void setTypeDefinitions(Set<TypeDefinition<?>> typeDefinitions) {
1028             if (typeDefinitions != null) {
1029                 this.typeDefinitions.addAll(typeDefinitions);
1030             }
1031         }
1032
1033         @Override
1034         public Set<NotificationDefinition> getNotifications() {
1035             return notifications;
1036         }
1037
1038         private void setNotifications(Set<NotificationDefinition> notifications) {
1039             if (notifications != null) {
1040                 this.notifications.addAll(notifications);
1041             }
1042         }
1043
1044         @Override
1045         public Set<AugmentationSchema> getAugmentations() {
1046             return augmentations;
1047         }
1048
1049         private void setAugmentations(Set<AugmentationSchema> augmentations) {
1050             if (augmentations != null) {
1051                 this.augmentations.addAll(augmentations);
1052             }
1053         }
1054
1055         @Override
1056         public Set<RpcDefinition> getRpcs() {
1057             return rpcs;
1058         }
1059
1060         private void setRpcs(Set<RpcDefinition> rpcs) {
1061             if (rpcs != null) {
1062                 this.rpcs.addAll(rpcs);
1063             }
1064         }
1065
1066         @Override
1067         public Set<Deviation> getDeviations() {
1068             return deviations;
1069         }
1070
1071         private void setDeviations(Set<Deviation> deviations) {
1072             if (deviations != null) {
1073                 this.deviations.addAll(deviations);
1074             }
1075         }
1076
1077         @Override
1078         public Set<DataSchemaNode> getChildNodes() {
1079             return Collections.unmodifiableSet(childNodes);
1080         }
1081
1082         private void addChildNodes(Set<DataSchemaNode> childNodes) {
1083             if (childNodes != null) {
1084                 this.childNodes.addAll(childNodes);
1085             }
1086         }
1087
1088         @Override
1089         public Set<GroupingDefinition> getGroupings() {
1090             return groupings;
1091         }
1092
1093         private void setGroupings(Set<GroupingDefinition> groupings) {
1094             if (groupings != null) {
1095                 this.groupings.addAll(groupings);
1096             }
1097         }
1098
1099         @Override
1100         public Set<UsesNode> getUses() {
1101             return uses;
1102         }
1103
1104         private void setUses(Set<UsesNode> uses) {
1105             if (uses != null) {
1106                 this.uses.addAll(uses);
1107             }
1108         }
1109
1110         @Override
1111         public List<ExtensionDefinition> getExtensionSchemaNodes() {
1112             Collections.sort(extensionNodes, Comparators.SCHEMA_NODE_COMP);
1113             return extensionNodes;
1114         }
1115
1116         private void setExtensionSchemaNodes(final List<ExtensionDefinition> extensionNodes) {
1117             if (extensionNodes != null) {
1118                 this.extensionNodes.addAll(extensionNodes);
1119             }
1120         }
1121
1122         @Override
1123         public Set<IdentitySchemaNode> getIdentities() {
1124             return identities;
1125         }
1126
1127         private void setIdentities(final Set<IdentitySchemaNode> identities) {
1128             if (identities != null) {
1129                 this.identities.addAll(identities);
1130             }
1131         }
1132
1133         @Override
1134         public List<UnknownSchemaNode> getUnknownSchemaNodes() {
1135             return unknownNodes;
1136         }
1137
1138         private void setUnknownSchemaNodes(final List<UnknownSchemaNode> unknownNodes) {
1139             if (unknownNodes != null) {
1140                 this.unknownNodes.addAll(unknownNodes);
1141             }
1142         }
1143
1144         @Override
1145         public DataSchemaNode getDataChildByName(QName name) {
1146             return getChildNode(childNodes, name);
1147         }
1148
1149         @Override
1150         public DataSchemaNode getDataChildByName(String name) {
1151             return getChildNode(childNodes, name);
1152         }
1153
1154         @Override
1155         public int hashCode() {
1156             final int prime = 31;
1157             int result = 1;
1158             result = prime * result + ((namespace == null) ? 0 : namespace.hashCode());
1159             result = prime * result + ((name == null) ? 0 : name.hashCode());
1160             result = prime * result + ((revision == null) ? 0 : revision.hashCode());
1161             result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());
1162             result = prime * result + ((yangVersion == null) ? 0 : yangVersion.hashCode());
1163             return result;
1164         }
1165
1166         @Override
1167         public boolean equals(Object obj) {
1168             if (this == obj) {
1169                 return true;
1170             }
1171             if (obj == null) {
1172                 return false;
1173             }
1174             if (getClass() != obj.getClass()) {
1175                 return false;
1176             }
1177             ModuleImpl other = (ModuleImpl) obj;
1178             if (namespace == null) {
1179                 if (other.namespace != null) {
1180                     return false;
1181                 }
1182             } else if (!namespace.equals(other.namespace)) {
1183                 return false;
1184             }
1185             if (name == null) {
1186                 if (other.name != null) {
1187                     return false;
1188                 }
1189             } else if (!name.equals(other.name)) {
1190                 return false;
1191             }
1192             if (revision == null) {
1193                 if (other.revision != null) {
1194                     return false;
1195                 }
1196             } else if (!revision.equals(other.revision)) {
1197                 return false;
1198             }
1199             if (prefix == null) {
1200                 if (other.prefix != null) {
1201                     return false;
1202                 }
1203             } else if (!prefix.equals(other.prefix)) {
1204                 return false;
1205             }
1206             if (yangVersion == null) {
1207                 if (other.yangVersion != null) {
1208                     return false;
1209                 }
1210             } else if (!yangVersion.equals(other.yangVersion)) {
1211                 return false;
1212             }
1213             return true;
1214         }
1215
1216         @Override
1217         public String toString() {
1218             StringBuilder sb = new StringBuilder(ModuleImpl.class.getSimpleName());
1219             sb.append("[");
1220             sb.append("name=" + name);
1221             sb.append(", namespace=" + namespace);
1222             sb.append(", revision=" + revision);
1223             sb.append(", prefix=" + prefix);
1224             sb.append(", yangVersion=" + yangVersion);
1225             sb.append("]");
1226             return sb.toString();
1227         }
1228     }
1229
1230     /**
1231      * Add child to parent. Method checks for duplicates and add given child
1232      * node to parent. If node with same name is found, throws exception. If
1233      * parent is null, child node will be added directly to module.
1234      *
1235      * @param parent
1236      * @param child
1237      * @param childName
1238      */
1239     private void addChildToParent(final Builder parent, final DataSchemaNodeBuilder child, final String childName) {
1240         final int lineNum = child.getLine();
1241         if (parent.equals(this)) {
1242             addChildToModule(child, childName, lineNum);
1243         } else {
1244             addChildToSubnodeOfModule(parent, child, childName, lineNum);
1245         }
1246     }
1247
1248     /**
1249      * Adds child node <code>child</code> to the set of nodes child nodes.
1250      *
1251      * The method reduces the complexity of the method
1252      * {@link #addChildToParent(Builder, DataSchemaNodeBuilder, String)
1253      * addChildToParent}.
1254      *
1255      * @param child
1256      *            data schema node builder for child node
1257      * @param childName
1258      *            string with name of child node
1259      * @param lineNum
1260      *            line number in YANG file where is the node with the name equal
1261      *            to <code>childName</code> is defined
1262      */
1263     private void addChildToModule(final DataSchemaNodeBuilder child, final String childName, final int lineNum) {
1264         // if parent == null => node is defined under module
1265         // All leafs, leaf-lists, lists, containers, choices, rpcs,
1266         // notifications, and anyxmls defined within a parent node or at the
1267         // top level of the module or its submodules share the same
1268         // identifier namespace.
1269         for (DataSchemaNodeBuilder childNode : addedChildNodes) {
1270             if (childNode.getQName().getLocalName().equals(childName)) {
1271                 raiseYangParserException("'" + child + "'", "node", childName, lineNum, childNode.getLine());
1272             }
1273         }
1274         for (RpcDefinitionBuilder rpc : addedRpcs) {
1275             if (rpc.getQName().getLocalName().equals(childName)) {
1276                 raiseYangParserException("'" + child + "'", "rpc", childName, lineNum, rpc.getLine());
1277             }
1278         }
1279         for (NotificationBuilder notification : addedNotifications) {
1280             if (notification.getQName().getLocalName().equals(childName)) {
1281                 raiseYangParserException("'" + child + "'", "notification", childName, lineNum, notification.getLine());
1282             }
1283         }
1284         addedChildNodes.add(child);
1285     }
1286
1287     /**
1288      * Adds child node <code>child</code> to the group of child nodes of the
1289      * <code>parent</code>
1290      *
1291      * The method reduces the complexity of the method
1292      * {@link #addChildToParent(Builder, DataSchemaNodeBuilder, String)
1293      * addChildToParent}. *
1294      *
1295      * @param parent
1296      *            builder of node which is parent for <code>child</code>
1297      * @param child
1298      *            data schema node builder for child node
1299      * @param childName
1300      *            string with name of child node
1301      * @param lineNum
1302      *            line number in YANG file where is the node with the name equal
1303      *            to <code>childName</code> is defined
1304      */
1305     private void addChildToSubnodeOfModule(final Builder parent, final DataSchemaNodeBuilder child,
1306             final String childName, final int lineNum) {
1307         // no need for checking rpc and notification because they can be
1308         // defined only under module or submodule
1309         if (parent instanceof DataNodeContainerBuilder) {
1310             DataNodeContainerBuilder parentNode = (DataNodeContainerBuilder) parent;
1311             for (DataSchemaNodeBuilder childNode : parentNode.getChildNodeBuilders()) {
1312                 if (childNode.getQName().getLocalName().equals(childName)) {
1313                     raiseYangParserException("'" + child + "'", "node", childName, lineNum, childNode.getLine());
1314                 }
1315             }
1316             parentNode.addChildNode(child);
1317         } else if (parent instanceof ChoiceBuilder) {
1318             ChoiceBuilder parentNode = (ChoiceBuilder) parent;
1319             for (ChoiceCaseBuilder caseBuilder : parentNode.getCases()) {
1320                 if (caseBuilder.getQName().getLocalName().equals(childName)) {
1321                     raiseYangParserException("'" + child + "'", "node", childName, lineNum, caseBuilder.getLine());
1322                 }
1323             }
1324             parentNode.addCase(child);
1325         } else {
1326             throw new YangParseException(name, lineNum, "Unresolved parent of node '" + childName + "'.");
1327         }
1328     }
1329
1330     private ModuleImport createModuleImport(final String moduleName, final Date revision, final String prefix) {
1331         final ModuleImport moduleImport = new ModuleImportImpl(moduleName, revision, prefix);
1332         return moduleImport;
1333     }
1334
1335     private void raiseYangParserException(final String cantAddType, final String type, final String name,
1336             final int currentLine, final int duplicateLine) {
1337
1338         StringBuilder msgPrefix = new StringBuilder("");
1339         if (cantAddType != null && !cantAddType.isEmpty()) {
1340             msgPrefix.append("Can not add ");
1341             msgPrefix.append(cantAddType);
1342             msgPrefix.append(": ");
1343         }
1344
1345         String msg = String.format("%s%s with same name '%s' already declared at line %d.", msgPrefix, type, name,
1346                 duplicateLine);
1347         throw new YangParseException(moduleName, currentLine, msg);
1348     }
1349
1350     @Override
1351     public int hashCode() {
1352         final int prime = 31;
1353         int result = 1;
1354         result = prime * result + ((name == null) ? 0 : name.hashCode());
1355         result = prime * result + ((namespace == null) ? 0 : namespace.hashCode());
1356         result = prime * result + ((revision == null) ? 0 : revision.hashCode());
1357         result = prime * result + ((prefix == null) ? 0 : prefix.hashCode());
1358
1359         return result;
1360     }
1361
1362     @Override
1363     public boolean equals(Object obj) {
1364         if (this == obj) {
1365             return true;
1366         }
1367         if (obj == null) {
1368             return false;
1369         }
1370         if (getClass() != obj.getClass()) {
1371             return false;
1372         }
1373         ModuleBuilder other = (ModuleBuilder) obj;
1374         if (name == null) {
1375             if (other.name != null) {
1376                 return false;
1377             }
1378         } else if (!name.equals(other.name)) {
1379             return false;
1380         }
1381         if (namespace == null) {
1382             if (other.namespace != null) {
1383                 return false;
1384             }
1385         } else if (!namespace.equals(other.namespace)) {
1386             return false;
1387         }
1388         if (prefix == null) {
1389             if (other.prefix != null) {
1390                 return false;
1391             }
1392         } else if (!prefix.equals(other.prefix)) {
1393             return false;
1394         }
1395         if (revision == null) {
1396             if (other.revision != null) {
1397                 return false;
1398             }
1399         } else if (!revision.equals(other.revision)) {
1400             return false;
1401         }
1402         return true;
1403     }
1404
1405 }