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