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