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