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