Tighten childOf type
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / generator / impl / AbstractTypeGenerator.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o.  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.mdsal.binding.generator.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
14 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.computeDefaultSUID;
15 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.BASE_IDENTITY;
18 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_OBJECT;
19 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.DATA_ROOT;
20 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION;
21 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.NOTIFICATION_LISTENER;
22 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.ROUTING_CONTEXT;
23 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.RPC_SERVICE;
24 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.augmentable;
25 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.childOf;
26 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.choiceIn;
27 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifiable;
28 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.identifier;
29 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.rpcResult;
30 import static org.opendaylight.mdsal.binding.model.util.Types.BOOLEAN;
31 import static org.opendaylight.mdsal.binding.model.util.Types.FUTURE;
32 import static org.opendaylight.mdsal.binding.model.util.Types.typeForClass;
33 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
34 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
35 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
36
37 import com.google.common.base.Splitter;
38 import com.google.common.collect.Iterables;
39 import com.google.common.collect.Sets;
40 import java.util.AbstractMap.SimpleImmutableEntry;
41 import java.util.ArrayList;
42 import java.util.Collection;
43 import java.util.Comparator;
44 import java.util.HashMap;
45 import java.util.Iterator;
46 import java.util.List;
47 import java.util.Map;
48 import java.util.Optional;
49 import java.util.Set;
50 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
51 import org.opendaylight.mdsal.binding.model.api.Constant;
52 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
53 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
54 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
55 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
56 import org.opendaylight.mdsal.binding.model.api.Restrictions;
57 import org.opendaylight.mdsal.binding.model.api.Type;
58 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotableTypeBuilder;
59 import org.opendaylight.mdsal.binding.model.api.type.builder.AnnotationTypeBuilder;
60 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
61 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
62 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
63 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
64 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
65 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
66 import org.opendaylight.mdsal.binding.model.api.type.builder.TypeMemberBuilder;
67 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
68 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
69 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
70 import org.opendaylight.mdsal.binding.model.util.Types;
71 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
72 import org.opendaylight.mdsal.binding.yang.types.AbstractTypeProvider;
73 import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
74 import org.opendaylight.mdsal.binding.yang.types.GroupingDefinitionDependencySort;
75 import org.opendaylight.yangtools.yang.binding.BindingMapping;
76 import org.opendaylight.yangtools.yang.common.QName;
77 import org.opendaylight.yangtools.yang.common.QNameModule;
78 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
79 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
80 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
81 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
82 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
83 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
85 import org.opendaylight.yangtools.yang.model.api.DocumentedNode;
86 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
87 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
88 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.Module;
92 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
93 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
94 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
95 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
96 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
97 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
98 import org.opendaylight.yangtools.yang.model.api.Status;
99 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
100 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
101 import org.opendaylight.yangtools.yang.model.api.UsesNode;
102 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
103 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
105 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
107 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
108 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
109 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
112
113 abstract class AbstractTypeGenerator {
114     private static final Logger LOG = LoggerFactory.getLogger(BindingGeneratorImpl.class);
115     private static final Splitter COLON_SPLITTER = Splitter.on(':');
116     private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
117     private static final JavaTypeName OVERRIDE_ANNOTATION = JavaTypeName.create(Override.class);
118
119     /**
120      * Comparator based on augment target path.
121      */
122     private static final Comparator<AugmentationSchemaNode> AUGMENT_COMP = (o1, o2) -> {
123         final Iterator<QName> thisIt = o1.getTargetPath().getPathFromRoot().iterator();
124         final Iterator<QName> otherIt = o2.getTargetPath().getPathFromRoot().iterator();
125
126         while (thisIt.hasNext()) {
127             if (!otherIt.hasNext()) {
128                 return 1;
129             }
130
131             final int comp = thisIt.next().compareTo(otherIt.next());
132             if (comp != 0) {
133                 return comp;
134             }
135         }
136
137         return otherIt.hasNext() ? -1 : 0;
138     };
139
140     /**
141      * Constant with the concrete name of identifier.
142      */
143     private static final String AUGMENT_IDENTIFIER_NAME = "augment-identifier";
144
145     /**
146      * Constant with the concrete name of namespace.
147      */
148     private static final String YANG_EXT_NAMESPACE = "urn:opendaylight:yang:extension:yang-ext";
149
150     private final Map<QNameModule, ModuleContext> genCtx = new HashMap<>();
151
152     /**
153      * Outer key represents the package name. Outer value represents map of all
154      * builders in the same package. Inner key represents the schema node name
155      * (in JAVA class/interface name format). Inner value represents instance of
156      * builder for schema node specified in key part.
157      */
158     private final Map<String, Map<String, GeneratedTypeBuilder>> genTypeBuilders = new HashMap<>();
159
160     /**
161      * Provide methods for converting YANG types to JAVA types.
162      */
163     private final AbstractTypeProvider typeProvider;
164
165     /**
166      * Holds reference to schema context to resolve data of augmented element
167      * when creating augmentation builder
168      */
169     private final SchemaContext schemaContext;
170
171     AbstractTypeGenerator(final SchemaContext context, final AbstractTypeProvider typeProvider) {
172         this.schemaContext = requireNonNull(context);
173         this.typeProvider = requireNonNull(typeProvider);
174
175         final List<Module> contextModules = ModuleDependencySort.sort(schemaContext.getModules());
176         final List<ModuleContext> contexts = new ArrayList<>(contextModules.size());
177         for (final Module contextModule : contextModules) {
178             contexts.add(moduleToGenTypes(contextModule));
179         }
180
181         contexts.forEach(this::allAugmentsToGenTypes);
182     }
183
184     final Collection<ModuleContext> moduleContexts() {
185         return genCtx.values();
186     }
187
188     final ModuleContext moduleContext(final QNameModule module) {
189         return requireNonNull(genCtx.get(module), () -> "Module context not found for module " + module);
190     }
191
192     final AbstractTypeProvider typeProvider() {
193         return typeProvider;
194     }
195
196     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module);
197
198     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genType, Module module, SchemaNode node);
199
200     abstract void addCodegenInformation(GeneratedTypeBuilder interfaceBuilder, Module module, String description,
201             Set<? extends SchemaNode> nodes);
202
203     abstract void addComment(TypeMemberBuilder<?> genType, DocumentedNode node);
204
205     private ModuleContext moduleToGenTypes(final Module module) {
206         final ModuleContext context = new ModuleContext(module);
207         genCtx.put(module.getQNameModule(), context);
208         allTypeDefinitionsToGenTypes(context);
209         groupingsToGenTypes(context, module.getGroupings());
210         rpcMethodsToGenType(context);
211         allIdentitiesToGenTypes(context);
212         notificationsToGenType(context);
213
214         if (!module.getChildNodes().isEmpty()) {
215             final GeneratedTypeBuilder moduleType = moduleToDataType(context);
216             context.addModuleNode(moduleType);
217             resolveDataSchemaNodes(context, moduleType, moduleType, module.getChildNodes());
218         }
219         return context;
220     }
221
222     /**
223      * Converts all extended type definitions of module to the list of
224      * <code>Type</code> objects.
225      *
226      * @param module
227      *            module from which is obtained set of type definitions
228      * @throws IllegalArgumentException
229      *             <ul>
230      *             <li>if module is null</li>
231      *             <li>if name of module is null</li>
232      *             </ul>
233      * @throws IllegalStateException
234      *             if set of type definitions from module is null
235      */
236     private void allTypeDefinitionsToGenTypes(final ModuleContext context) {
237         final Module module = context.module();
238         checkArgument(module.getName() != null, "Module name cannot be NULL.");
239         final DataNodeIterator it = new DataNodeIterator(module);
240         final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
241         checkState(typeDefinitions != null, "Type Definitions for module %s cannot be NULL.", module.getName());
242
243         for (final TypeDefinition<?> typedef : typeDefinitions) {
244             if (typedef != null) {
245                 final Type type = typeProvider.generatedTypeForExtendedDefinitionType(typedef,  typedef);
246                 if (type != null) {
247                     context.addTypedefType(typedef.getPath(), type);
248                     context.addTypeToSchema(type,typedef);
249                 }
250             }
251         }
252     }
253
254     private GeneratedTypeBuilder processDataSchemaNode(final ModuleContext context, final Type childOf,
255             final DataSchemaNode node) {
256         if (node.isAugmenting() || node.isAddedByUses()) {
257             return null;
258         }
259         final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, node, childOf);
260         annotateDeprecatedIfNecessary(node.getStatus(), genType);
261
262         final Module module = context.module();
263         genType.setModuleName(module.getName());
264         addCodegenInformation(genType, module, node);
265         genType.setSchemaPath(node.getPath());
266         if (node instanceof DataNodeContainer) {
267             context.addChildNodeType(node, genType);
268             groupingsToGenTypes(context, ((DataNodeContainer) node).getGroupings());
269             processUsesAugments((DataNodeContainer) node, context);
270         }
271         return genType;
272     }
273
274     private void containerToGenType(final ModuleContext context, final GeneratedTypeBuilder parent,
275             final Type childOf, final ContainerSchemaNode node) {
276         final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
277         if (genType != null) {
278             constructGetter(parent, genType, node);
279             resolveDataSchemaNodes(context, genType, genType, node.getChildNodes());
280         }
281     }
282
283     private void listToGenType(final ModuleContext context, final GeneratedTypeBuilder parent, final Type childOf,
284             final ListSchemaNode node) {
285         final GeneratedTypeBuilder genType = processDataSchemaNode(context, childOf, node);
286         if (genType != null) {
287             constructGetter(parent, Types.listTypeFor(genType), node);
288
289             final List<String> listKeys = listKeys(node);
290             final GeneratedTOBuilder genTOBuilder = resolveListKeyTOBuilder(context, node);
291             if (genTOBuilder != null) {
292                 final Type identifierMarker = identifier(genType);
293                 final Type identifiableMarker = identifiable(genTOBuilder);
294                 genTOBuilder.addImplementsType(identifierMarker);
295                 genType.addImplementsType(identifiableMarker);
296             }
297
298             for (final DataSchemaNode schemaNode : node.getChildNodes()) {
299                 if (!schemaNode.isAugmenting()) {
300                     addSchemaNodeToListBuilders(context, schemaNode, genType, genTOBuilder, listKeys);
301                 }
302             }
303
304             // serialVersionUID
305             if (genTOBuilder != null) {
306                 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
307                 prop.setValue(Long.toString(computeDefaultSUID(genTOBuilder)));
308                 genTOBuilder.setSUID(prop);
309             }
310
311             typeBuildersToGenTypes(context, genType, genTOBuilder);
312         }
313     }
314
315     private void processUsesAugments(final DataNodeContainer node, final ModuleContext context) {
316         for (final UsesNode usesNode : node.getUses()) {
317             for (final AugmentationSchemaNode augment : usesNode.getAugmentations()) {
318                 usesAugmentationToGenTypes(context, augment, usesNode, node);
319                 processUsesAugments(augment, context);
320             }
321         }
322     }
323
324     /**
325      * Converts all <b>augmentation</b> of the module to the list
326      * <code>Type</code> objects.
327      *
328      * @param module
329      *            module from which is obtained list of all augmentation objects
330      *            to iterate over them
331      * @throws IllegalArgumentException
332      *             <ul>
333      *             <li>if the module is null</li>
334      *             <li>if the name of module is null</li>
335      *             </ul>
336      * @throws IllegalStateException
337      *             if set of augmentations from module is null
338      */
339     private void allAugmentsToGenTypes(final ModuleContext context) {
340         final Module module = context.module();
341         checkArgument(module != null, "Module reference cannot be NULL.");
342         checkArgument(module.getName() != null, "Module name cannot be NULL.");
343         checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
344
345         for (final AugmentationSchemaNode augment : resolveAugmentations(module)) {
346             augmentationToGenTypes(context, augment);
347         }
348     }
349
350     /**
351      * Returns list of <code>AugmentationSchema</code> objects. The objects are
352      * sorted according to the length of their target path from the shortest to
353      * the longest.
354      *
355      * @param module
356      *            module from which is obtained list of all augmentation objects
357      * @return list of sorted <code>AugmentationSchema</code> objects obtained
358      *         from <code>module</code>
359      * @throws IllegalArgumentException
360      *             if module is null
361      * @throws IllegalStateException
362      *             if set of module augmentations is null
363      */
364     private static List<AugmentationSchemaNode> resolveAugmentations(final Module module) {
365         checkArgument(module != null, "Module reference cannot be NULL.");
366         checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
367
368         final Set<AugmentationSchemaNode> augmentations = module.getAugmentations();
369         final List<AugmentationSchemaNode> sortedAugmentations = new ArrayList<>(augmentations);
370         sortedAugmentations.sort(AUGMENT_COMP);
371
372         return sortedAugmentations;
373     }
374
375     /**
376      * Create GeneratedTypeBuilder object from module argument.
377      *
378      * @param module
379      *            Module object from which builder will be created
380      * @return <code>GeneratedTypeBuilder</code> which is internal
381      *         representation of the module
382      * @throws IllegalArgumentException
383      *             if module is null
384      */
385     private GeneratedTypeBuilder moduleToDataType(final ModuleContext context) {
386         final GeneratedTypeBuilder moduleDataTypeBuilder = moduleTypeBuilder(context, "Data");
387         final Module module = context.module();
388         addImplementedInterfaceFromUses(module, moduleDataTypeBuilder);
389         moduleDataTypeBuilder.addImplementsType(DATA_ROOT);
390
391         addCodegenInformation(moduleDataTypeBuilder, module);
392         return moduleDataTypeBuilder;
393     }
394
395     /**
396      * Converts all <b>RPCs</b> input and output substatements of the module
397      * to the list of <code>Type</code> objects. In addition are to containers
398      * and lists which belong to input or output also part of returning list.
399      *
400      * @param module
401      *            module from which is obtained set of all rpc objects to
402      *            iterate over them
403      * @throws IllegalArgumentException
404      *             <ul>
405      *             <li>if the module is null</li>
406      *             <li>if the name of module is null</li>
407      *             </ul>
408      * @throws IllegalStateException
409      *             if set of rpcs from module is null
410      */
411     private void rpcMethodsToGenType(final ModuleContext context) {
412         final Module module = context.module();
413         checkArgument(module.getName() != null, "Module name cannot be NULL.");
414         final Set<RpcDefinition> rpcDefinitions = module.getRpcs();
415         checkState(rpcDefinitions != null, "Set of rpcs from module " + module.getName() + " cannot be NULL.");
416         if (rpcDefinitions.isEmpty()) {
417             return;
418         }
419
420         final GeneratedTypeBuilder interfaceBuilder = moduleTypeBuilder(context, "Service");
421         interfaceBuilder.addImplementsType(RPC_SERVICE);
422
423         addCodegenInformation(interfaceBuilder, module, "RPCs", rpcDefinitions);
424
425         for (final RpcDefinition rpc : rpcDefinitions) {
426             if (rpc != null) {
427                 final String rpcName = BindingMapping.getClassName(rpc.getQName());
428                 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
429                 final MethodSignatureBuilder method = interfaceBuilder.addMethod(rpcMethodName);
430
431                 // Do not refer to annotation class, as it may not be available at runtime
432                 method.addAnnotation("javax.annotation", "CheckReturnValue");
433                 addComment(method, rpc);
434                 method.addParameter(
435                     createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getInput())), "input");
436                 method.setReturnType(Types.parameterizedTypeFor(FUTURE,
437                     rpcResult(createRpcContainer(context, rpcName, rpc, verifyNotNull(rpc.getOutput())))));
438             }
439         }
440
441         context.addTopLevelNodeType(interfaceBuilder);
442     }
443
444     private Type createRpcContainer(final ModuleContext context, final String rpcName, final RpcDefinition rpc,
445             final ContainerSchemaNode schema) {
446         processUsesAugments(schema, context);
447         final GeneratedTypeBuilder outType = addRawInterfaceDefinition(
448             JavaTypeName.create(context.modulePackageName(), rpcName + BindingMapping.getClassName(schema.getQName())),
449             schema);
450         addImplementedInterfaceFromUses(schema, outType);
451         outType.addImplementsType(DATA_OBJECT);
452         outType.addImplementsType(augmentable(outType));
453         annotateDeprecatedIfNecessary(rpc.getStatus(), outType);
454         resolveDataSchemaNodes(context, outType, outType, schema.getChildNodes());
455         context.addChildNodeType(schema, outType);
456         return outType.build();
457     }
458
459     /**
460      * Converts all <b>notifications</b> of the module to the list of
461      * <code>Type</code> objects. In addition are to this list added containers
462      * and lists which are part of this notification.
463      *
464      * @param module
465      *            module from which is obtained set of all notification objects
466      *            to iterate over them
467      * @throws IllegalArgumentException
468      *             <ul>
469      *             <li>if the module equals null</li>
470      *             <li>if the name of module equals null</li>
471      *             </ul>
472      * @throws IllegalStateException
473      *             if set of notifications from module is null
474      */
475     private void notificationsToGenType(final ModuleContext context) {
476         final Module module = context.module();
477         checkArgument(module.getName() != null, "Module name cannot be NULL.");
478         final Set<NotificationDefinition> notifications = module.getNotifications();
479         if (notifications.isEmpty()) {
480             return;
481         }
482
483         final GeneratedTypeBuilder listenerInterface = moduleTypeBuilder(context, "Listener");
484         listenerInterface.addImplementsType(NOTIFICATION_LISTENER);
485
486         for (final NotificationDefinition notification : notifications) {
487             if (notification != null) {
488                 processUsesAugments(notification, context);
489
490                 final GeneratedTypeBuilder notificationInterface = addDefaultInterfaceDefinition(
491                     context.modulePackageName(), notification, null, context);
492                 annotateDeprecatedIfNecessary(notification.getStatus(), notificationInterface);
493                 notificationInterface.addImplementsType(NOTIFICATION);
494                 context.addChildNodeType(notification, notificationInterface);
495
496                 // Notification object
497                 resolveDataSchemaNodes(context, notificationInterface, notificationInterface,
498                     notification.getChildNodes());
499
500                 addComment(listenerInterface.addMethod("on" + notificationInterface.getName())
501                     .setAccessModifier(AccessModifier.PUBLIC).addParameter(notificationInterface, "notification")
502                     .setReturnType(Types.primitiveVoidType()), notification);
503             }
504         }
505
506         addCodegenInformation(listenerInterface, module, "notifications", notifications);
507         context.addTopLevelNodeType(listenerInterface);
508     }
509
510     /**
511      * Converts all <b>identities</b> of the module to the list of
512      * <code>Type</code> objects.
513      *
514      * @param module
515      *            module from which is obtained set of all identity objects to
516      *            iterate over them
517      * @param schemaContext
518      *            schema context only used as input parameter for method
519      *            {@link BindingGeneratorImpl#identityToGenType}
520      *
521      */
522     private void allIdentitiesToGenTypes(final ModuleContext context) {
523         final Set<IdentitySchemaNode> schemaIdentities = context.module().getIdentities();
524
525         if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
526             for (final IdentitySchemaNode identity : schemaIdentities) {
527                 identityToGenType(context, identity);
528             }
529         }
530     }
531
532     /**
533      * Converts the <b>identity</b> object to GeneratedType. Firstly it is
534      * created transport object builder. If identity contains base identity then
535      * reference to base identity is added to superior identity as its extend.
536      * If identity doesn't contain base identity then only reference to abstract
537      * class {@link org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode
538      * BaseIdentity} is added
539      *
540      * @param module
541      *            current module
542      * @param basePackageName
543      *            string contains the module package name
544      * @param identity
545      *            IdentitySchemaNode which contains data about identity
546      */
547     private void identityToGenType(final ModuleContext context,final IdentitySchemaNode identity) {
548         if (identity == null) {
549             return;
550         }
551         final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(JavaTypeName.create(
552             packageNameForGeneratedType(context.modulePackageName(), identity.getPath()),
553             BindingMapping.getClassName(identity.getQName())));
554         final Set<IdentitySchemaNode> baseIdentities = identity.getBaseIdentities();
555         if (!baseIdentities.isEmpty()) {
556             for (IdentitySchemaNode baseIdentity : baseIdentities) {
557                 final QName qname = baseIdentity.getQName();
558                 final GeneratedTransferObject gto = typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
559                     BindingMapping.getRootPackageName(qname.getModule()), BindingMapping.getClassName(qname))).build();
560                 newType.addImplementsType(gto);
561             }
562         } else {
563             newType.addImplementsType(BASE_IDENTITY);
564         }
565
566         final Module module = context.module();
567         addCodegenInformation(newType, module, identity);
568         newType.setModuleName(module.getName());
569         newType.setSchemaPath(identity.getPath());
570
571         qnameConstant(newType, JavaTypeName.create(context.modulePackageName(), BindingMapping.MODULE_INFO_CLASS_NAME),
572             identity.getQName().getLocalName());
573
574         context.addIdentityType(identity.getQName(), newType);
575     }
576
577     private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder,
578             final JavaTypeName yangModuleInfo, final String localName) {
579         return toBuilder.addConstant(typeForClass(QName.class), BindingMapping.QNAME_STATIC_FIELD_NAME,
580             new SimpleImmutableEntry<>(yangModuleInfo, localName));
581     }
582
583     /**
584      * Converts all <b>groupings</b> of the module to the list of
585      * <code>Type</code> objects. Firstly are groupings sorted according mutual
586      * dependencies. At least dependent (independent) groupings are in the list
587      * saved at first positions. For every grouping the record is added to map
588      * {@link ModuleContext#groupings allGroupings}
589      *
590      * @param module
591      *            current module
592      * @param groupings
593      *            collection of groupings from which types will be generated
594      *
595      */
596     private void groupingsToGenTypes(final ModuleContext context, final Collection<GroupingDefinition> groupings) {
597         for (final GroupingDefinition grouping : new GroupingDefinitionDependencySort().sort(groupings)) {
598             // Converts individual grouping to GeneratedType. Firstly generated type builder is created and every child
599             // node of grouping is resolved to the method.
600             final GeneratedTypeBuilder genType = addDefaultInterfaceDefinition(context, grouping);
601             annotateDeprecatedIfNecessary(grouping.getStatus(), genType);
602             context.addGroupingType(grouping.getPath(), genType);
603             resolveDataSchemaNodes(context, genType, genType, grouping.getChildNodes());
604             groupingsToGenTypes(context, grouping.getGroupings());
605             processUsesAugments(grouping, context);
606         }
607     }
608
609     /**
610      * Adds enumeration builder created from <code>enumTypeDef</code> to
611      * <code>typeBuilder</code>.
612      *
613      * Each <code>enumTypeDef</code> item is added to builder with its name and
614      * value.
615      *
616      * @param enumTypeDef
617      *            EnumTypeDefinition contains enum data
618      * @param enumName
619      *            string contains name which will be assigned to enumeration
620      *            builder
621      * @param typeBuilder
622      *            GeneratedTypeBuilder to which will be enum builder assigned
623      * @param module
624      *            Module in which type should be generated
625      * @return enumeration builder which contains data from
626      *         <code>enumTypeDef</code>
627      */
628     private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
629             final GeneratedTypeBuilder typeBuilder, final ModuleContext context) {
630         if (enumTypeDef != null && typeBuilder != null && enumTypeDef.getQName().getLocalName() != null) {
631             final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
632             typeProvider.addEnumDescription(enumBuilder, enumTypeDef);
633             enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
634             context.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
635             return enumBuilder;
636         }
637         return null;
638     }
639
640     /**
641      * Generates type builder for <code>module</code>.
642      *
643      * @param module
644      *            Module which is source of package name for generated type
645      *            builder
646      * @param postfix
647      *            string which is added to the module class name representation
648      *            as suffix
649      * @return instance of GeneratedTypeBuilder which represents
650      *         <code>module</code>.
651      * @throws IllegalArgumentException
652      *             if <code>module</code> is null
653      */
654     private GeneratedTypeBuilder moduleTypeBuilder(final ModuleContext context, final String postfix) {
655         final Module module = context.module();
656         final String moduleName = BindingMapping.getClassName(module.getName()) + postfix;
657         final GeneratedTypeBuilder moduleBuilder = typeProvider.newGeneratedTypeBuilder(
658             JavaTypeName.create(context.modulePackageName(), moduleName));
659
660         moduleBuilder.setModuleName(moduleName);
661         addCodegenInformation(moduleBuilder, module);
662         return moduleBuilder;
663     }
664
665     /**
666      * Converts <code>augSchema</code> to list of <code>Type</code> which
667      * contains generated type for augmentation. In addition there are also
668      * generated types for all containers, list and choices which are child of
669      * <code>augSchema</code> node or a generated types for cases are added if
670      * augmented node is choice.
671      *
672      * @param augmentPackageName
673      *            string with the name of the package to which the augmentation
674      *            belongs
675      * @param augSchema
676      *            AugmentationSchema which is contains data about augmentation
677      *            (target path, childs...)
678      * @param module
679      *            current module
680      * @throws IllegalArgumentException
681      *             <ul>
682      *             <li>if <code>augmentPackageName</code> equals null</li>
683      *             <li>if <code>augSchema</code> equals null</li>
684      *             </ul>
685      * @throws IllegalStateException
686      *             if augment target path is null
687      */
688     private void augmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema) {
689         checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
690         checkState(augSchema.getTargetPath() != null,
691                 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
692
693         processUsesAugments(augSchema, context);
694         final SchemaPath targetPath = augSchema.getTargetPath();
695         SchemaNode targetSchemaNode = null;
696
697         targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
698         if (targetSchemaNode instanceof DataSchemaNode && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
699             if (targetSchemaNode instanceof DerivableSchemaNode) {
700                 targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orElse(null);
701             }
702             if (targetSchemaNode == null) {
703                 throw new IllegalStateException("Failed to find target node from grouping in augmentation " + augSchema
704                         + " in module " + context.module().getName());
705             }
706         }
707         if (targetSchemaNode == null) {
708             throw new IllegalArgumentException("augment target not found: " + targetPath);
709         }
710
711         GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
712         if (targetTypeBuilder == null) {
713             targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
714         }
715         if (targetTypeBuilder == null) {
716             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
717         }
718
719         if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
720             final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getIdentifier());
721             addRawAugmentGenTypeDefinition(context, targetType, augSchema);
722
723         } else {
724             generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
725                     (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), null);
726         }
727     }
728
729     private void usesAugmentationToGenTypes(final ModuleContext context, final AugmentationSchemaNode augSchema,
730             final UsesNode usesNode, final DataNodeContainer usesNodeParent) {
731         checkArgument(augSchema != null, "Augmentation Schema cannot be NULL.");
732         checkState(augSchema.getTargetPath() != null,
733                 "Augmentation Schema does not contain Target Path (Target Path is NULL).");
734
735         processUsesAugments(augSchema, context);
736         final SchemaPath targetPath = augSchema.getTargetPath();
737         final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
738         if (targetSchemaNode == null) {
739             throw new IllegalArgumentException("augment target not found: " + targetPath);
740         }
741
742         GeneratedTypeBuilder targetTypeBuilder = findChildNodeByPath(targetSchemaNode.getPath());
743         if (targetTypeBuilder == null) {
744             targetTypeBuilder = findCaseByPath(targetSchemaNode.getPath());
745         }
746         if (targetTypeBuilder == null) {
747             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
748         }
749
750         if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
751             if (usesNodeParent instanceof SchemaNode) {
752                 addRawAugmentGenTypeDefinition(context,
753                     packageNameForAugmentedGeneratedType(context.modulePackageName(),
754                         ((SchemaNode) usesNodeParent).getPath()),
755                     targetTypeBuilder.build(), augSchema);
756             } else {
757                 addRawAugmentGenTypeDefinition(context, targetTypeBuilder.build(), augSchema);
758             }
759         } else {
760             generateTypesFromAugmentedChoiceCases(context, targetTypeBuilder.build(),
761                 (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes(), usesNodeParent);
762         }
763     }
764
765     /**
766      * Convenient method to find node added by uses statement.
767      *
768      * @param targetPath
769      *            node path
770      * @param parentUsesNode
771      *            parent of uses node
772      * @return node from its original location in grouping
773      */
774     private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
775         final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
776                 .getPathFromRoot());
777         if (!(targetGrouping instanceof GroupingDefinition)) {
778             throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
779         }
780
781         SchemaNode result = targetGrouping;
782         for (final QName node : targetPath.getPathFromRoot()) {
783             if (result instanceof DataNodeContainer) {
784                 final QName resultNode = node.withModule(result.getQName().getModule());
785                 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
786             } else if (result instanceof ChoiceSchemaNode) {
787                 result = findNamedCase((ChoiceSchemaNode) result, node.getLocalName());
788             }
789         }
790         if (result == null) {
791             return null;
792         }
793
794         if (result instanceof DerivableSchemaNode) {
795             DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
796             Optional<? extends SchemaNode> originalNode = castedResult.getOriginal();
797             if (castedResult.isAddedByUses() && originalNode.isPresent()) {
798                 result = originalNode.get();
799             }
800         }
801
802         if (result instanceof DataSchemaNode) {
803             DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
804             if (resultDataSchemaNode.isAddedByUses()) {
805                 // The original node is required, but we have only the copy of
806                 // the original node.
807                 // Maybe this indicates a bug in Yang parser.
808                 throw new IllegalStateException("Failed to generate code for augment in " + parentUsesNode);
809             }
810
811             return resultDataSchemaNode;
812         }
813
814         throw new IllegalStateException(
815             "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
816                     + parentUsesNode);
817     }
818
819     /**
820      * Returns a generated type builder for an augmentation.
821      *
822      * The name of the type builder is equal to the name of augmented node with
823      * serial number as suffix.
824      *
825      * @param context
826      *            current module
827      * @param augmentPackageName
828      *            string with contains the package name to which the augment
829      *            belongs
830      * @param basePackageName
831      *            string with the package name to which the augmented node
832      *            belongs
833      * @param targetTypeRef
834      *            target type
835      * @param augSchema
836      *            augmentation schema which contains data about the child nodes
837      *            and uses of augment
838      * @return generated type builder for augment
839      */
840     private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context,
841             final String augmentPackageName, final Type targetTypeRef,
842             final AugmentationSchemaNode augSchema) {
843         Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
844         if (augmentBuilders == null) {
845             augmentBuilders = new HashMap<>();
846             genTypeBuilders.put(augmentPackageName, augmentBuilders);
847         }
848         final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
849
850         String augTypeName;
851         if (augIdentifier != null) {
852             augTypeName = BindingMapping.getClassName(augIdentifier);
853         } else {
854             augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
855         }
856
857         final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
858             JavaTypeName.create(augmentPackageName, augTypeName));
859
860         augTypeBuilder.addImplementsType(DATA_OBJECT);
861         augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
862         annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
863         addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
864
865         augSchemaNodeToMethods(context, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
866         augmentBuilders.put(augTypeName, augTypeBuilder);
867
868         if (!augSchema.getChildNodes().isEmpty()) {
869             context.addTypeToAugmentation(augTypeBuilder, augSchema);
870
871         }
872         context.addAugmentType(augTypeBuilder);
873         return augTypeBuilder;
874     }
875
876     private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
877             final AugmentationSchemaNode augSchema) {
878         return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
879     }
880
881     /**
882      *
883      * @param unknownSchemaNodes
884      * @return nodeParameter of UnknownSchemaNode
885      */
886     private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
887         for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
888             final QName nodeType = unknownSchemaNode.getNodeType();
889             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
890                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
891                 return unknownSchemaNode.getNodeParameter();
892             }
893         }
894         return null;
895     }
896
897     /**
898      * Returns first unique name for the augment generated type builder. The
899      * generated type builder name for augment consists from name of augmented
900      * node and serial number of its augmentation.
901      *
902      * @param builders
903      *            map of builders which were created in the package to which the
904      *            augmentation belongs
905      * @param genTypeName
906      *            string with name of augmented node
907      * @return string with unique name for augmentation builder
908      */
909     private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
910         int index = 1;
911         if (builders != null) {
912             while (builders.containsKey(genTypeName + index)) {
913                 index = index + 1;
914             }
915         }
916         return genTypeName + index;
917     }
918
919     /**
920      * Adds the methods to <code>typeBuilder</code> which represent subnodes of
921      * node for which <code>typeBuilder</code> was created.
922      *
923      * The subnodes aren't mapped to the methods if they are part of grouping or
924      * augment (in this case are already part of them).
925      *
926      * @param module
927      *            current module
928      * @param parent
929      *            generated type builder which represents any node. The subnodes
930      *            of this node are added to the <code>typeBuilder</code> as
931      *            methods. The subnode can be of type leaf, leaf-list, list,
932      *            container, choice.
933      * @param childOf
934      *            parent type
935      * @param schemaNodes
936      *            set of data schema nodes which are the children of the node
937      *            for which <code>typeBuilder</code> was created
938      * @return generated type builder which is the same builder as input
939      *         parameter. The getter methods (representing child nodes) could be
940      *         added to it.
941      */
942     private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
943             final Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
944         if (schemaNodes != null && parent != null) {
945             for (final DataSchemaNode schemaNode : schemaNodes) {
946                 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
947                     addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, childOf);
948                 }
949             }
950         }
951         return parent;
952     }
953
954     /**
955      * Adds the methods to <code>typeBuilder</code> what represents subnodes of
956      * node for which <code>typeBuilder</code> was created.
957      *
958      * @param module
959      *            current module
960      * @param typeBuilder
961      *            generated type builder which represents any node. The subnodes
962      *            of this node are added to the <code>typeBuilder</code> as
963      *            methods. The subnode can be of type leaf, leaf-list, list,
964      *            container, choice.
965      * @param childOf
966      *            parent type
967      * @param schemaNodes
968      *            set of data schema nodes which are the children of the node
969      *            for which <code>typeBuilder</code> was created
970      * @return generated type builder which is the same object as the input
971      *         parameter <code>typeBuilder</code>. The getter method could be
972      *         added to it.
973      */
974     private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
975             final GeneratedTypeBuilder typeBuilder, final Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
976         if (schemaNodes != null && typeBuilder != null) {
977             for (final DataSchemaNode schemaNode : schemaNodes) {
978                 if (!schemaNode.isAugmenting()) {
979                     addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, childOf);
980                 }
981             }
982         }
983         return typeBuilder;
984     }
985
986     /**
987      * Adds to <code>typeBuilder</code> a method which is derived from
988      * <code>schemaNode</code>.
989      *
990      * @param node
991      *            data schema node which is added to <code>typeBuilder</code> as
992      *            a method
993      * @param typeBuilder
994      *            generated type builder to which is <code>schemaNode</code>
995      *            added as a method.
996      * @param childOf
997      *            parent type
998      * @param module
999      *            current module
1000      */
1001     private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1002             final GeneratedTypeBuilder typeBuilder, final Type childOf) {
1003         if (node != null && typeBuilder != null) {
1004             if (node instanceof LeafSchemaNode) {
1005                 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1006             } else if (node instanceof LeafListSchemaNode) {
1007                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1008             } else if (node instanceof ContainerSchemaNode) {
1009                 containerToGenType(context, typeBuilder, childOf, (ContainerSchemaNode) node);
1010             } else if (node instanceof ListSchemaNode) {
1011                 listToGenType(context, typeBuilder, childOf, (ListSchemaNode) node);
1012             } else if (node instanceof ChoiceSchemaNode) {
1013                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1014             } else {
1015                 // TODO: anyxml not yet supported
1016                 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1017                         typeBuilder.getFullyQualifiedName());
1018             }
1019         }
1020     }
1021
1022     /**
1023      * Converts <code>choiceNode</code> to the list of generated types for
1024      * choice and its cases.
1025      *
1026      * The package names for choice and for its cases are created as
1027      * concatenation of the module package (<code>basePackageName</code>) and
1028      * names of all parents node.
1029      *
1030      * @param context
1031      *            current module
1032      * @param basePackageName
1033      *            string with the module package name
1034      * @param parent
1035      *            parent type
1036      * @param choiceNode
1037      *            choice node which is mapped to generated type. Also child
1038      *            nodes - cases are mapped to generated types.
1039      * @throws IllegalArgumentException
1040      *             <ul>
1041      *             <li>if <code>basePackageName</code> is null</li>
1042      *             <li>if <code>choiceNode</code> is null</li>
1043      *             </ul>
1044      */
1045     private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1046             final ChoiceSchemaNode choiceNode) {
1047         checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1048
1049         if (!choiceNode.isAddedByUses()) {
1050             final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1051                 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1052                 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1053             choiceTypeBuilder.addImplementsType(choiceIn(parent));
1054             annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1055             context.addChildNodeType(choiceNode, choiceTypeBuilder);
1056
1057             final GeneratedType choiceType = choiceTypeBuilder.build();
1058             generateTypesFromChoiceCases(context, choiceType, choiceNode);
1059
1060             constructGetter(parent, choiceType, choiceNode);
1061         }
1062     }
1063
1064     /**
1065      * Converts <code>caseNodes</code> set to list of corresponding generated types.
1066      *
1067      * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1068      * The package names for the builder is created as concatenation of the module package and names of all parents
1069      * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1070      * and <i>choice</i> type
1071      *
1072      * @param context
1073      *            current module context
1074      * @param refChoiceType
1075      *            type which represents superior <i>case</i>
1076      * @param choiceNode
1077      *            choice case node which is mapped to generated type
1078      * @throws IllegalArgumentException
1079      *             <ul>
1080      *             <li>if <code>refChoiceType</code> equals null</li>
1081      *             <li>if <code>caseNodes</code> equals null</li>
1082      *             </ul>
1083      */
1084     private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1085             final ChoiceSchemaNode choiceNode) {
1086         checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1087         checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1088
1089         for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1090             if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1091                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1092                 caseTypeBuilder.addImplementsType(refChoiceType);
1093                 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1094                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1095                 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1096                 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1097                 if (caseChildNodes != null) {
1098                     final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1099
1100                     if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1101                         SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1102
1103                         if (parent instanceof AugmentationSchemaNode) {
1104                             final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1105                             final SchemaPath targetPath = augSchema.getTargetPath();
1106                             SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1107                             if (targetSchemaNode instanceof DataSchemaNode
1108                                     && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1109                                 if (targetSchemaNode instanceof DerivableSchemaNode) {
1110                                     targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1111                                             .orElse(null);
1112                                 }
1113                                 if (targetSchemaNode == null) {
1114                                     throw new IllegalStateException(
1115                                             "Failed to find target node from grouping for augmentation " + augSchema
1116                                                     + " in module " + context.module().getName());
1117                                 }
1118                             }
1119                             parent = targetSchemaNode;
1120                         }
1121
1122                         checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1123                         Type childOfType = findChildNodeByPath(parent.getPath());
1124                         if (childOfType == null) {
1125                             childOfType = findGroupingByPath(parent.getPath());
1126                         }
1127                         resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1128                     } else {
1129                         resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1130                     }
1131                }
1132             }
1133             processUsesAugments(caseNode, context);
1134         }
1135     }
1136
1137     /**
1138      * Generates list of generated types for all the cases of a choice which are
1139      * added to the choice through the augment.
1140      *
1141      * @param module
1142      *            current module
1143      * @param basePackageName
1144      *            string contains name of package to which augment belongs. If
1145      *            an augmented choice is from an other package (pcg1) than an
1146      *            augmenting choice (pcg2) then case's of the augmenting choice
1147      *            will belong to pcg2.
1148      * @param targetType
1149      *            Type which represents target choice
1150      * @param targetNode
1151      *            node which represents target choice
1152      * @param augmentedNodes
1153      *            set of choice case nodes for which is checked if are/aren't
1154      *            added to choice through augmentation
1155      * @throws IllegalArgumentException
1156      *             <ul>
1157      *             <li>if <code>basePackageName</code> is null</li>
1158      *             <li>if <code>targetType</code> is null</li>
1159      *             <li>if <code>augmentedNodes</code> is null</li>
1160      *             </ul>
1161      */
1162     private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1163             final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1164             final DataNodeContainer usesNodeParent) {
1165         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1166         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1167
1168         for (final DataSchemaNode caseNode : augmentedNodes) {
1169             if (caseNode != null) {
1170                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1171                 caseTypeBuilder.addImplementsType(targetType);
1172
1173                 final Type childOfType = findChildOfType(targetNode);
1174                 CaseSchemaNode node = null;
1175                 final String caseLocalName = caseNode.getQName().getLocalName();
1176                 if (caseNode instanceof CaseSchemaNode) {
1177                     node = (CaseSchemaNode) caseNode;
1178                 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1179                     final String targetNodeLocalName = targetNode.getQName().getLocalName();
1180                     for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1181                         if (dataSchemaNode instanceof ChoiceSchemaNode
1182                                 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1183                             node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1184                             break;
1185                         }
1186                     }
1187                 } else {
1188                     node = findNamedCase(targetNode, caseLocalName);
1189                 }
1190                 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1191                 if (childNodes != null) {
1192                     resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, childNodes);
1193                 }
1194                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1195                 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1196             }
1197         }
1198     }
1199
1200     private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1201         final SchemaPath nodePath = targetNode.getPath();
1202         final SchemaPath parentSp = nodePath.getParent();
1203         if (parentSp.getParent() == null) {
1204             return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1205         }
1206
1207         final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1208         GeneratedTypeBuilder childOfType = null;
1209         if (parent instanceof CaseSchemaNode) {
1210             childOfType = findCaseByPath(parent.getPath());
1211         } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1212             childOfType = findChildNodeByPath(parent.getPath());
1213         } else if (parent instanceof GroupingDefinition) {
1214             childOfType = findGroupingByPath(parent.getPath());
1215         }
1216
1217         if (childOfType == null) {
1218             throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1219         }
1220
1221         return childOfType;
1222     }
1223
1224     private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1225         final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1226         return cases.isEmpty() ? null : cases.get(0);
1227     }
1228
1229     private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1230         // New parser with encapsulated type
1231         if (leaf.getPath().equals(type.getPath())) {
1232             return true;
1233         }
1234
1235         // Embedded type definition with new parser. Also takes care of the old parser with bits
1236         if (leaf.getPath().equals(type.getPath().getParent())) {
1237             return true;
1238         }
1239
1240         return false;
1241     }
1242
1243     private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1244             final List<PatternConstraint> patternConstraints) {
1245         if (!patternConstraints.isEmpty()) {
1246             final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1247                 .append(BindingMapping.getPropertyName(leafName));
1248             typeBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), field.toString(),
1249                 typeProvider.resolveRegExpressions(patternConstraints));
1250         }
1251     }
1252
1253     /**
1254      * Converts <code>leaf</code> to the getter method which is added to
1255      * <code>typeBuilder</code>.
1256      *
1257      * @param typeBuilder
1258      *            generated type builder to which is added getter method as
1259      *            <code>leaf</code> mapping
1260      * @param leaf
1261      *            leaf schema node which is mapped as getter method which is
1262      *            added to <code>typeBuilder</code>
1263      * @param module
1264      *            Module in which type was defined
1265      * @return boolean value
1266      *         <ul>
1267      *         <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1268      *         null</li>
1269      *         <li>true - in other cases</li>
1270      *         </ul>
1271      */
1272     private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1273             final ModuleContext context) {
1274         if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1275             return null;
1276         }
1277
1278         final Module parentModule = findParentModule(schemaContext, leaf);
1279         Type returnType = null;
1280
1281         final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1282         if (isInnerType(leaf, typeDef)) {
1283             if (typeDef instanceof EnumTypeDefinition) {
1284                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1285                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1286                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1287                     typeBuilder, context);
1288                 if (enumBuilder != null) {
1289                     returnType = enumBuilder.toInstance(typeBuilder);
1290                 }
1291                 typeProvider.putReferencedType(leaf.getPath(), returnType);
1292             } else if (typeDef instanceof UnionTypeDefinition) {
1293                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1294                     parentModule);
1295                 if (genTOBuilder != null) {
1296                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1297                     // Store the inner type within the union so that we can find the reference for it
1298                     context.addInnerTypedefType(typeDef.getPath(), returnType);
1299                 }
1300             } else if (typeDef instanceof BitsTypeDefinition) {
1301                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1302                     parentModule);
1303                 if (genTOBuilder != null) {
1304                     returnType = genTOBuilder.build();
1305                 }
1306             } else {
1307                 // It is constrained version of already declared type (inner declared type exists,
1308                 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1309                 // In order to get proper class we need to look up closest derived type
1310                 // and apply restrictions from leaf type
1311                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1312                 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1313                         restrictions);
1314                 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1315             }
1316         } else {
1317             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1318             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1319             addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1320         }
1321
1322         if (returnType == null) {
1323             return null;
1324         }
1325
1326         if (typeDef instanceof EnumTypeDefinition) {
1327             typeProvider.putReferencedType(leaf.getPath(), returnType);
1328         }
1329
1330         final MethodSignatureBuilder getter = constructGetter(typeBuilder,  returnType, leaf);
1331         processContextRefExtension(leaf, getter, parentModule);
1332         return returnType;
1333     }
1334
1335     private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1336         // Returns DerivedType in case of new parser.
1337         final TypeDefinition<?> baseType = typeDef.getBaseType();
1338         return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1339     }
1340
1341     private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1342             final Module module) {
1343         for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1344             final QName nodeType = node.getNodeType();
1345             if ("context-reference".equals(nodeType.getLocalName())) {
1346                 final String nodeParam = node.getNodeParameter();
1347                 IdentitySchemaNode identity = null;
1348                 String basePackageName = null;
1349                 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1350                 final Iterator<String> iterator = splittedElement.iterator();
1351                 final int length = Iterables.size(splittedElement);
1352                 if (length == 1) {
1353                     identity = findIdentityByName(module.getIdentities(), iterator.next());
1354                     basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1355                 } else if (length == 2) {
1356                     final String prefix = iterator.next();
1357                     final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1358                     if (dependentModule == null) {
1359                         throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1360                                 + prefix);
1361                     }
1362                     identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1363                     basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1364                 } else {
1365                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1366                             + nodeParam);
1367                 }
1368                 if (identity == null) {
1369                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1370                             + nodeParam);
1371                 }
1372
1373                 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1374                 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1375                 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1376                 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1377             }
1378         }
1379     }
1380
1381     private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1382         for (final IdentitySchemaNode id : identities) {
1383             if (id.getQName().getLocalName().equals(name)) {
1384                 return id;
1385             }
1386         }
1387         return null;
1388     }
1389
1390     private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1391         for (final ModuleImport imp : imports) {
1392             if (imp.getPrefix().equals(prefix)) {
1393                 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1394             }
1395         }
1396         return null;
1397     }
1398
1399     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1400             final boolean isReadOnly) {
1401         if (leaf != null && toBuilder != null) {
1402             Type returnType;
1403             final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1404             if (typeDef instanceof UnionTypeDefinition) {
1405                 // GeneratedType for this type definition should have be already created
1406                 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1407                 returnType = mc.getTypedefs().get(typeDef.getPath());
1408                 if (returnType == null) {
1409                     // This may still be an inner type, try to find it
1410                     returnType = mc.getInnerType(typeDef.getPath());
1411                 }
1412             } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1413                 // Annonymous enumeration (already generated, since it is inherited via uses).
1414                 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1415                 QName qname = originalLeaf.getQName();
1416                 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1417             } else {
1418                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1419             }
1420             return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1421         }
1422         return false;
1423     }
1424
1425     /**
1426      * Converts <code>leaf</code> schema node to property of generated TO
1427      * builder.
1428      *
1429      * @param toBuilder
1430      *            generated TO builder to which is <code>leaf</code> added as
1431      *            property
1432      * @param leaf
1433      *            leaf schema node which is added to <code>toBuilder</code> as
1434      *            property
1435      * @param returnType
1436      *            property type
1437      * @param isReadOnly
1438      *            boolean value which says if leaf property is|isn't read only
1439      * @return boolean value
1440      *         <ul>
1441      *         <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1442      *         name equals null or if leaf is added by <i>uses</i>.</li>
1443      *         <li>true - other cases</li>
1444      *         </ul>
1445      */
1446     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1447             final Type returnType, final boolean isReadOnly) {
1448         if (returnType == null) {
1449             return false;
1450         }
1451         final String leafName = leaf.getQName().getLocalName();
1452         final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1453         propBuilder.setReadOnly(isReadOnly);
1454         propBuilder.setReturnType(returnType);
1455         addComment(propBuilder, leaf);
1456
1457         toBuilder.addEqualsIdentity(propBuilder);
1458         toBuilder.addHashIdentity(propBuilder);
1459         toBuilder.addToStringProperty(propBuilder);
1460         return true;
1461     }
1462
1463     /**
1464      * Converts <code>node</code> leaf list schema node to getter method of
1465      * <code>typeBuilder</code>.
1466      *
1467      * @param typeBuilder
1468      *            generated type builder to which is <code>node</code> added as
1469      *            getter method
1470      * @param node
1471      *            leaf list schema node which is added to
1472      *            <code>typeBuilder</code> as getter method
1473      * @param module module
1474      * @return boolean value
1475      *         <ul>
1476      *         <li>true - if <code>node</code>, <code>typeBuilder</code>,
1477      *         nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1478      *         <li>false - other cases</li>
1479      *         </ul>
1480      */
1481     private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1482             final ModuleContext context) {
1483         if (node == null || typeBuilder == null || node.isAddedByUses()) {
1484             return false;
1485         }
1486
1487         final QName nodeName = node.getQName();
1488
1489         final TypeDefinition<?> typeDef = node.getType();
1490         final Module parentModule = findParentModule(schemaContext, node);
1491
1492         Type returnType = null;
1493         if (typeDef.getBaseType() == null) {
1494             if (typeDef instanceof EnumTypeDefinition) {
1495                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1496                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1497                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1498                     typeBuilder, context);
1499                 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1500                 typeProvider.putReferencedType(node.getPath(), returnType);
1501             } else if (typeDef instanceof UnionTypeDefinition) {
1502                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1503                     node, parentModule);
1504                 if (genTOBuilder != null) {
1505                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1506                 }
1507             } else if (typeDef instanceof BitsTypeDefinition) {
1508                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1509                     node, parentModule);
1510                 returnType = genTOBuilder.build();
1511             } else {
1512                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1513                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1514                 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1515             }
1516         } else {
1517             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1518             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1519             addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1520         }
1521
1522         final ParameterizedType listType = Types.listTypeFor(returnType);
1523         constructGetter(typeBuilder, listType, node);
1524         return true;
1525     }
1526
1527     private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1528             final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1529         final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1530
1531         addCodegenInformation(returnType, parentModule, typeDef);
1532         returnType.setSchemaPath(typeDef.getPath());
1533         returnType.setModuleName(parentModule.getName());
1534
1535         genTOBuilder.setTypedef(true);
1536         genTOBuilder.setIsUnion(true);
1537         AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1538
1539
1540
1541         final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1542
1543
1544         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1545         method.setReturnType(returnType);
1546         method.addParameter(Types.STRING, "defaultValue");
1547         method.setAccessModifier(AccessModifier.PUBLIC);
1548         method.setStatic(true);
1549
1550         final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1551         if (types == null) {
1552             typeProvider.getAdditionalTypes().put(parentModule,
1553                     Sets.newHashSet(unionBuilder.build()));
1554         } else {
1555             types.add(unionBuilder.build());
1556         }
1557         return returnType.build();
1558     }
1559
1560     private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1561             final GeneratedTypeBuilder typeBuilder) {
1562         // Append enclosing path hierarchy without dots
1563         final StringBuilder sb = new StringBuilder();
1564         genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1565         final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1566             JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1567         unionBuilder.setIsUnionBuilder(true);
1568         return unionBuilder;
1569     }
1570
1571     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1572             final SchemaNode schemaNode) {
1573         return addDefaultInterfaceDefinition(context, schemaNode, null);
1574     }
1575
1576     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1577             final SchemaNode schemaNode, final Type childOf) {
1578         final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1579         return addDefaultInterfaceDefinition(packageName, schemaNode, childOf, context);
1580     }
1581
1582
1583     /**
1584      * Instantiates generated type builder with <code>packageName</code> and
1585      * <code>schemaNode</code>.
1586      *
1587      * The new builder always implements
1588      * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1589      * If <code>schemaNode</code> is instance of GroupingDefinition it also
1590      * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1591      * Augmentable}.<br>
1592      * If <code>schemaNode</code> is instance of
1593      * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1594      * DataNodeContainer} it can also implement nodes which are specified in
1595      * <i>uses</i>.
1596      *
1597      * @param packageName
1598      *            string with the name of the package to which
1599      *            <code>schemaNode</code> belongs.
1600      * @param schemaNode
1601      *            schema node for which is created generated type builder
1602      * @param parent
1603      *            parent type (can be null)
1604      * @return generated type builder <code>schemaNode</code>
1605      */
1606     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1607             final Type parent, final ModuleContext context) {
1608         final GeneratedTypeBuilder it = addRawInterfaceDefinition(
1609             JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1610
1611         it.addImplementsType(parent == null ? DATA_OBJECT : childOf(parent));
1612         if (!(schemaNode instanceof GroupingDefinition)) {
1613             it.addImplementsType(augmentable(it));
1614         }
1615         if (schemaNode instanceof DataNodeContainer) {
1616             final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1617             groupingsToGenTypes(context, containerSchema.getGroupings());
1618             addImplementedInterfaceFromUses(containerSchema, it);
1619         }
1620
1621         return it;
1622     }
1623
1624     /**
1625      * Wraps the calling of the same overloaded method.
1626      *
1627      * @param packageName
1628      *            string with the package name to which returning generated type
1629      *            builder belongs
1630      * @param schemaNode
1631      *            schema node which provide data about the schema node name
1632      * @return generated type builder for <code>schemaNode</code>
1633      */
1634     private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1635             final String prefix) {
1636         return addRawInterfaceDefinition(
1637             JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1638                 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1639     }
1640
1641     /**
1642      * Returns reference to generated type builder for specified
1643      * <code>schemaNode</code> with <code>packageName</code>.
1644      *
1645      * Firstly the generated type builder is searched in
1646      * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1647      * found it is created and added to <code>genTypeBuilders</code>.
1648      *
1649      * @param packageName
1650      *            string with the package name to which returning generated type
1651      *            builder belongs
1652      * @param schemaNode
1653      *            schema node which provide data about the schema node name
1654      * @param prefix
1655      *            return type name prefix
1656      * @return generated type builder for <code>schemaNode</code>
1657      * @throws IllegalArgumentException
1658      *             <ul>
1659      *             <li>if <code>schemaNode</code> is null</li>
1660      *             <li>if <code>packageName</code> is null</li>
1661      *             <li>if QName of schema node is null</li>
1662      *             <li>if schemaNode name is null</li>
1663      *             </ul>
1664      *
1665      */
1666     private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1667         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1668         checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1669         final String schemaNodeName = schemaNode.getQName().getLocalName();
1670         checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1671
1672         // FIXME: Validation of name conflict
1673         final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1674         final Module module = findParentModule(schemaContext, schemaNode);
1675         qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1676             BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1677
1678         addCodegenInformation(newType, module, schemaNode);
1679         newType.setSchemaPath(schemaNode.getPath());
1680         newType.setModuleName(module.getName());
1681
1682         final String packageName = identifier.packageName();
1683         final String simpleName = identifier.simpleName();
1684         if (!genTypeBuilders.containsKey(packageName)) {
1685             final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1686             builders.put(simpleName, newType);
1687             genTypeBuilders.put(packageName, builders);
1688         } else {
1689             final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1690             if (!builders.containsKey(simpleName)) {
1691                 builders.put(simpleName, newType);
1692             }
1693         }
1694         return newType;
1695     }
1696
1697     /**
1698      * Creates the name of the getter method name from <code>localName</code>.
1699      *
1700      * @param localName
1701      *            string with the name of the getter method
1702      * @param returnType
1703      *            return type
1704      * @return string with the name of the getter method for
1705      *         <code>methodName</code> in JAVA method format
1706      */
1707     public static String getterMethodName(final String localName, final Type returnType) {
1708         final StringBuilder method = new StringBuilder();
1709         if (BOOLEAN.equals(returnType)) {
1710             method.append("is");
1711         } else {
1712             method.append("get");
1713         }
1714         final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1715         method.append(name);
1716         return method.toString();
1717     }
1718
1719     /**
1720      * Created a method signature builder as part of <code>interfaceBuilder</code>.
1721      *
1722      * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1723      * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1724      *
1725      * @param interfaceBuilder generated type builder for which the getter method should be created
1726      * @param returnType type which represents the return type of the getter method
1727      * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1728      * @param comment string with comment for the getter method
1729      * @param status status from yang file, for deprecated annotation
1730      * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1731      */
1732     private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1733             final SchemaNode node) {
1734         final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1735             getterMethodName(node.getQName().getLocalName(), returnType));
1736         getMethod.setReturnType(returnType);
1737
1738         annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1739         if (!returnType.getPackageName().isEmpty()) {
1740             // The return type has a package, so it's not a primitive type
1741             getMethod.addAnnotation("javax.annotation", "Nullable");
1742         }
1743         addComment(getMethod, node);
1744
1745         return getMethod;
1746     }
1747
1748     /**
1749      * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1750      * or to <code>genTOBuilder</code> as property.
1751      *
1752      * @param basePackageName
1753      *            string contains the module package name
1754      * @param schemaNode
1755      *            data schema node which should be added as getter method to
1756      *            <code>typeBuilder</code> or as a property to
1757      *            <code>genTOBuilder</code> if is part of the list key
1758      * @param typeBuilder
1759      *            generated type builder for the list schema node
1760      * @param genTOBuilder
1761      *            generated TO builder for the list keys
1762      * @param listKeys
1763      *            list of string which contains names of the list keys
1764      * @param module
1765      *            current module
1766      * @throws IllegalArgumentException
1767      *             <ul>
1768      *             <li>if <code>schemaNode</code> equals null</li>
1769      *             <li>if <code>typeBuilder</code> equals null</li>
1770      *             </ul>
1771      */
1772     private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1773             final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1774             final List<String> listKeys) {
1775         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1776         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1777
1778         if (schemaNode instanceof LeafSchemaNode) {
1779             final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1780             final String leafName = leaf.getQName().getLocalName();
1781             Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1782             if (listKeys.contains(leafName)) {
1783                 if (type == null) {
1784                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1785                 } else {
1786                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1787                 }
1788             }
1789         } else if (!schemaNode.isAddedByUses()) {
1790             if (schemaNode instanceof LeafListSchemaNode) {
1791                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1792             } else if (schemaNode instanceof ContainerSchemaNode) {
1793                 containerToGenType(context, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1794             } else if (schemaNode instanceof ChoiceSchemaNode) {
1795                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1796             } else if (schemaNode instanceof ListSchemaNode) {
1797                 listToGenType(context, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1798             }
1799         }
1800     }
1801
1802     private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1803             final GeneratedTOBuilder genTOBuilder) {
1804         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1805
1806         if (genTOBuilder != null) {
1807             final GeneratedTransferObject genTO = genTOBuilder.build();
1808             // Add Identifiable.getKey() for items
1809             typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1810                 .addAnnotation(OVERRIDE_ANNOTATION);
1811             context.addGeneratedTOBuilder(genTOBuilder);
1812         }
1813     }
1814
1815     /**
1816      * Selects the names of the list keys from <code>list</code> and returns
1817      * them as the list of the strings
1818      *
1819      * @param list
1820      *            of string with names of the list keys
1821      * @return list of string which represents names of the list keys. If the
1822      *         <code>list</code> contains no keys then the empty list is
1823      *         returned.
1824      */
1825     private static List<String> listKeys(final ListSchemaNode list) {
1826         final List<String> listKeys = new ArrayList<>();
1827
1828         final List<QName> keyDefinition = list.getKeyDefinition();
1829         if (keyDefinition != null) {
1830             for (final QName keyDef : keyDefinition) {
1831                 listKeys.add(keyDef.getLocalName());
1832             }
1833         }
1834         return listKeys;
1835     }
1836
1837     /**
1838      * Generates for the <code>list</code> which contains any list keys special
1839      * generated TO builder.
1840      *
1841      * @param packageName
1842      *            string with package name to which the list belongs
1843      * @param list
1844      *            list schema node which is source of data about the list name
1845      * @return generated TO builder which represents the keys of the
1846      *         <code>list</code> or null if <code>list</code> is null or list of
1847      *         key definitions is null or empty.
1848      */
1849     private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1850         if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1851             return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1852                 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1853                 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1854         }
1855         return null;
1856     }
1857
1858     /**
1859      * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1860      *
1861      * If more then one generated TO builder is created for enclosing then all
1862      * of the generated TO builders are added to <code>typeBuilder</code> as
1863      * enclosing transfer objects.
1864      *
1865      * @param typeDef
1866      *            type definition which can be of type <code>UnionType</code> or
1867      *            <code>BitsTypeDefinition</code>
1868      * @param typeBuilder
1869      *            generated type builder to which is added generated TO created
1870      *            from <code>typeDef</code>
1871      * @param leaf
1872      *            string with name for generated TO builder
1873      * @param parentModule
1874      *            parent module
1875      * @return generated TO builder for <code>typeDef</code>
1876      */
1877     private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1878             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1879         final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1880             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1881             typeDef, leaf);
1882
1883         checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1884         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1885         final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1886         for (final GeneratedTOBuilder genTOBuilder : types) {
1887             resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1888         }
1889
1890         final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
1891         genPropBuilder.setReturnType(Types.CHAR_ARRAY);
1892         resultTOBuilder.addEqualsIdentity(genPropBuilder);
1893         resultTOBuilder.addHashIdentity(genPropBuilder);
1894         resultTOBuilder.addToStringProperty(genPropBuilder);
1895         processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1896         return resultTOBuilder;
1897     }
1898
1899     /**
1900      * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1901      * also added to <code>typeBuilder</code> as enclosing transfer object.
1902      *
1903      * If more then one generated TO builder is created for enclosing then all
1904      * of the generated TO builders are added to <code>typeBuilder</code> as
1905      * enclosing transfer objects.
1906      *
1907      * @param typeDef
1908      *            type definition which can be of type <code>UnionType</code> or
1909      *            <code>BitsTypeDefinition</code>
1910      * @param typeBuilder
1911      *            generated type builder to which is added generated TO created
1912      *            from <code>typeDef</code>
1913      * @param leaf
1914      *            string with name for generated TO builder
1915      * @param parentModule
1916      *            parent module
1917      * @return generated TO builder for <code>typeDef</code>
1918      */
1919     private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
1920             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1921         final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
1922             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1923             typeDef, parentModule.getName());
1924         typeBuilder.addEnclosingTransferObject(genTOBuilder);
1925         return genTOBuilder;
1926
1927     }
1928
1929     private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
1930             final List<GeneratedTOBuilder> genTOBuilders) {
1931         for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
1932             typeBuilder.addEnclosingTransferObject(genTOBuilder);
1933         }
1934         return genTOBuilders.get(0);
1935     }
1936
1937     /**
1938      * Adds the implemented types to type builder.
1939      *
1940      * The method passes through the list of <i>uses</i> in
1941      * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
1942      * generated type from {@link ModuleContext#groupings
1943      * allGroupings} which is added as <i>implements type</i> to
1944      * <code>builder</code>
1945      *
1946      * @param dataNodeContainer
1947      *            element which contains the list of used YANG groupings
1948      * @param builder
1949      *            builder to which are added implemented types according to
1950      *            <code>dataNodeContainer</code>
1951      * @return generated type builder with all implemented types
1952      */
1953     private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
1954             final GeneratedTypeBuilder builder) {
1955         for (final UsesNode usesNode : dataNodeContainer.getUses()) {
1956             final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
1957             if (genType == null) {
1958                 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
1959                         + builder.getName());
1960             }
1961
1962             builder.addImplementsType(genType);
1963         }
1964         return builder;
1965     }
1966
1967     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
1968         for (final ModuleContext ctx : genCtx.values()) {
1969             final GeneratedTypeBuilder result = ctx.getChildNode(path);
1970             if (result != null) {
1971                 return result;
1972             }
1973         }
1974         return null;
1975     }
1976
1977     private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
1978         for (final ModuleContext ctx : genCtx.values()) {
1979             final GeneratedTypeBuilder result = ctx.getGrouping(path);
1980             if (result != null) {
1981                 return result;
1982             }
1983         }
1984         return null;
1985     }
1986
1987     private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
1988         for (final ModuleContext ctx : genCtx.values()) {
1989             final GeneratedTypeBuilder result = ctx.getCase(path);
1990             if (result != null) {
1991                 return result;
1992             }
1993         }
1994         return null;
1995     }
1996
1997     private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
1998         if (status == Status.DEPRECATED) {
1999             builder.addAnnotation(DEPRECATED_ANNOTATION);
2000         }
2001     }
2002 }