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