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