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