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