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