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