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