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