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