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