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