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