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