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