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