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