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