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