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