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