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