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