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