306726b674f6751f58ad51b25efcfb1105fdd46d
[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 = genTypeBuilders.get(augmentPackageName);
934         if (augmentBuilders == null) {
935             augmentBuilders = new HashMap<>();
936             genTypeBuilders.put(augmentPackageName, augmentBuilders);
937         }
938         final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
939
940         String augTypeName;
941         if (augIdentifier != null) {
942             augTypeName = BindingMapping.getClassName(augIdentifier);
943         } else {
944             augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
945         }
946
947         final GeneratedTypeBuilder augTypeBuilder = typeProvider.newGeneratedTypeBuilder(
948             JavaTypeName.create(augmentPackageName, augTypeName));
949
950         augTypeBuilder.addImplementsType(DATA_OBJECT);
951         augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
952         annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
953         addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
954
955         augSchemaNodeToMethods(context, augTypeBuilder, augSchema.getChildNodes());
956         augmentBuilders.put(augTypeName, augTypeBuilder);
957
958         if (!augSchema.getChildNodes().isEmpty()) {
959             context.addTypeToAugmentation(augTypeBuilder, augSchema);
960
961         }
962         context.addAugmentType(augTypeBuilder);
963         return augTypeBuilder;
964     }
965
966     private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final ModuleContext context, final Type targetTypeRef,
967             final AugmentationSchemaNode augSchema) {
968         return addRawAugmentGenTypeDefinition(context, context.modulePackageName(), targetTypeRef, augSchema);
969     }
970
971     /**
972      *
973      * @param unknownSchemaNodes
974      * @return nodeParameter of UnknownSchemaNode
975      */
976     private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
977         for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
978             final QName nodeType = unknownSchemaNode.getNodeType();
979             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
980                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
981                 return unknownSchemaNode.getNodeParameter();
982             }
983         }
984         return null;
985     }
986
987     /**
988      * Returns first unique name for the augment generated type builder. The
989      * generated type builder name for augment consists from name of augmented
990      * node and serial number of its augmentation.
991      *
992      * @param builders
993      *            map of builders which were created in the package to which the
994      *            augmentation belongs
995      * @param genTypeName
996      *            string with name of augmented node
997      * @return string with unique name for augmentation builder
998      */
999     private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1000         int index = 1;
1001         if (builders != null) {
1002             while (builders.containsKey(genTypeName + index)) {
1003                 index = index + 1;
1004             }
1005         }
1006         return genTypeName + index;
1007     }
1008
1009     /**
1010      * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1011      * node for which <code>typeBuilder</code> was created.
1012      *
1013      * The subnodes aren't mapped to the methods if they are part of grouping or
1014      * augment (in this case are already part of them).
1015      *
1016      * @param module
1017      *            current module
1018      * @param parent
1019      *            generated type builder which represents any node. The subnodes
1020      *            of this node are added to the <code>typeBuilder</code> as
1021      *            methods. The subnode can be of type leaf, leaf-list, list,
1022      *            container, choice.
1023      * @param childOf
1024      *            parent type
1025      * @param schemaNodes
1026      *            set of data schema nodes which are the children of the node
1027      *            for which <code>typeBuilder</code> was created
1028      * @return generated type builder which is the same builder as input
1029      *         parameter. The getter methods (representing child nodes) could be
1030      *         added to it.
1031      */
1032     private GeneratedTypeBuilder resolveDataSchemaNodes(final ModuleContext context, final GeneratedTypeBuilder parent,
1033             final @Nullable Type childOf, final Iterable<DataSchemaNode> schemaNodes) {
1034         if (schemaNodes != null && parent != null) {
1035             final Type baseInterface = childOf == null ? DATA_OBJECT : childOf(childOf);
1036             for (final DataSchemaNode schemaNode : schemaNodes) {
1037                 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1038                     addSchemaNodeToBuilderAsMethod(context, schemaNode, parent, baseInterface);
1039                 }
1040             }
1041         }
1042         return parent;
1043     }
1044
1045     /**
1046      * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1047      * node for which <code>typeBuilder</code> was created.
1048      *
1049      * @param module
1050      *            current module
1051      * @param typeBuilder
1052      *            generated type builder which represents any node. The subnodes
1053      *            of this node are added to the <code>typeBuilder</code> as
1054      *            methods. The subnode can be of type leaf, leaf-list, list,
1055      *            container, choice.
1056      * @param childOf
1057      *            parent type
1058      * @param schemaNodes
1059      *            set of data schema nodes which are the children of the node
1060      *            for which <code>typeBuilder</code> was created
1061      * @return generated type builder which is the same object as the input
1062      *         parameter <code>typeBuilder</code>. The getter method could be
1063      *         added to it.
1064      */
1065     private GeneratedTypeBuilder augSchemaNodeToMethods(final ModuleContext context,
1066             final GeneratedTypeBuilder typeBuilder, final Iterable<DataSchemaNode> schemaNodes) {
1067         if (schemaNodes != null && typeBuilder != null) {
1068             final Type baseInterface = childOf(typeBuilder);
1069             for (final DataSchemaNode schemaNode : schemaNodes) {
1070                 if (!schemaNode.isAugmenting()) {
1071                     addSchemaNodeToBuilderAsMethod(context, schemaNode, typeBuilder, baseInterface);
1072                 }
1073             }
1074         }
1075         return typeBuilder;
1076     }
1077
1078     /**
1079      * Adds to <code>typeBuilder</code> a method which is derived from
1080      * <code>schemaNode</code>.
1081      *
1082      * @param node
1083      *            data schema node which is added to <code>typeBuilder</code> as
1084      *            a method
1085      * @param typeBuilder
1086      *            generated type builder to which is <code>schemaNode</code>
1087      *            added as a method.
1088      * @param childOf
1089      *            parent type
1090      * @param module
1091      *            current module
1092      */
1093     private void addSchemaNodeToBuilderAsMethod(final ModuleContext context, final DataSchemaNode node,
1094             final GeneratedTypeBuilder typeBuilder, final Type baseInterface) {
1095         if (node != null && typeBuilder != null) {
1096             if (node instanceof LeafSchemaNode) {
1097                 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, context);
1098             } else if (node instanceof LeafListSchemaNode) {
1099                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node, context);
1100             } else if (node instanceof ContainerSchemaNode) {
1101                 containerToGenType(context, typeBuilder, baseInterface, (ContainerSchemaNode) node);
1102             } else if (node instanceof ListSchemaNode) {
1103                 listToGenType(context, typeBuilder, baseInterface, (ListSchemaNode) node);
1104             } else if (node instanceof ChoiceSchemaNode) {
1105                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) node);
1106             } else {
1107                 // TODO: anyxml not yet supported
1108                 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1109                         typeBuilder.getFullyQualifiedName());
1110             }
1111         }
1112     }
1113
1114     /**
1115      * Converts <code>choiceNode</code> to the list of generated types for
1116      * choice and its cases.
1117      *
1118      * The package names for choice and for its cases are created as
1119      * concatenation of the module package (<code>basePackageName</code>) and
1120      * names of all parents node.
1121      *
1122      * @param context
1123      *            current module
1124      * @param basePackageName
1125      *            string with the module package name
1126      * @param parent
1127      *            parent type
1128      * @param choiceNode
1129      *            choice node which is mapped to generated type. Also child
1130      *            nodes - cases are mapped to generated types.
1131      * @throws IllegalArgumentException
1132      *             <ul>
1133      *             <li>if <code>basePackageName</code> is null</li>
1134      *             <li>if <code>choiceNode</code> is null</li>
1135      *             </ul>
1136      */
1137     private void choiceToGeneratedType(final ModuleContext context, final GeneratedTypeBuilder parent,
1138             final ChoiceSchemaNode choiceNode) {
1139         checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1140
1141         if (!choiceNode.isAddedByUses()) {
1142             final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(
1143                 JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), choiceNode.getPath()),
1144                 BindingMapping.getClassName(choiceNode.getQName())), choiceNode);
1145             choiceTypeBuilder.addImplementsType(choiceIn(parent));
1146             annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1147             context.addChildNodeType(choiceNode, choiceTypeBuilder);
1148
1149             final GeneratedType choiceType = choiceTypeBuilder.build();
1150             generateTypesFromChoiceCases(context, choiceType, choiceNode);
1151
1152             constructGetter(parent, choiceType, choiceNode);
1153         }
1154     }
1155
1156     /**
1157      * Converts <code>caseNodes</code> set to list of corresponding generated types.
1158      *
1159      * For every <i>case</i> which isn't added through augment or <i>uses</i> is created generated type builder.
1160      * The package names for the builder is created as concatenation of the module package and names of all parents
1161      * nodes of the concrete <i>case</i>. There is also relation "<i>implements type</i>" between every case builder
1162      * and <i>choice</i> type
1163      *
1164      * @param context
1165      *            current module context
1166      * @param refChoiceType
1167      *            type which represents superior <i>case</i>
1168      * @param choiceNode
1169      *            choice case node which is mapped to generated type
1170      * @throws IllegalArgumentException
1171      *             <ul>
1172      *             <li>if <code>refChoiceType</code> equals null</li>
1173      *             <li>if <code>caseNodes</code> equals null</li>
1174      *             </ul>
1175      */
1176     private void generateTypesFromChoiceCases(final ModuleContext context, final Type refChoiceType,
1177             final ChoiceSchemaNode choiceNode) {
1178         checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1179         checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1180
1181         for (final CaseSchemaNode caseNode : choiceNode.getCases().values()) {
1182             if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1183                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1184                 caseTypeBuilder.addImplementsType(refChoiceType);
1185                 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1186                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1187                 context.addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1188                 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1189                 if (caseChildNodes != null) {
1190                     final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1191
1192                     if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1193                         SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1194
1195                         if (parent instanceof AugmentationSchemaNode) {
1196                             final AugmentationSchemaNode augSchema = (AugmentationSchemaNode) parent;
1197                             final SchemaPath targetPath = augSchema.getTargetPath();
1198                             SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1199                             if (targetSchemaNode instanceof DataSchemaNode
1200                                     && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1201                                 if (targetSchemaNode instanceof DerivableSchemaNode) {
1202                                     targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal()
1203                                             .orElse(null);
1204                                 }
1205                                 if (targetSchemaNode == null) {
1206                                     throw new IllegalStateException(
1207                                             "Failed to find target node from grouping for augmentation " + augSchema
1208                                                     + " in module " + context.module().getName());
1209                                 }
1210                             }
1211                             parent = targetSchemaNode;
1212                         }
1213
1214                         checkState(parent != null, "Could not find Choice node parent %s", choiceNodeParentPath);
1215                         Type childOfType = findChildNodeByPath(parent.getPath());
1216                         if (childOfType == null) {
1217                             childOfType = findGroupingByPath(parent.getPath());
1218                         }
1219                         resolveDataSchemaNodes(context, caseTypeBuilder, childOfType, caseChildNodes);
1220                     } else {
1221                         resolveDataSchemaNodes(context, caseTypeBuilder, moduleToDataType(context), caseChildNodes);
1222                     }
1223                }
1224             }
1225             processUsesAugments(caseNode, context);
1226         }
1227     }
1228
1229     /**
1230      * Generates list of generated types for all the cases of a choice which are
1231      * added to the choice through the augment.
1232      *
1233      * @param module
1234      *            current module
1235      * @param basePackageName
1236      *            string contains name of package to which augment belongs. If
1237      *            an augmented choice is from an other package (pcg1) than an
1238      *            augmenting choice (pcg2) then case's of the augmenting choice
1239      *            will belong to pcg2.
1240      * @param targetType
1241      *            Type which represents target choice
1242      * @param targetNode
1243      *            node which represents target choice
1244      * @param augmentedNodes
1245      *            set of choice case nodes for which is checked if are/aren't
1246      *            added to choice through augmentation
1247      * @throws IllegalArgumentException
1248      *             <ul>
1249      *             <li>if <code>basePackageName</code> is null</li>
1250      *             <li>if <code>targetType</code> is null</li>
1251      *             <li>if <code>augmentedNodes</code> is null</li>
1252      *             </ul>
1253      */
1254     private void generateTypesFromAugmentedChoiceCases(final ModuleContext context,
1255             final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1256             final DataNodeContainer usesNodeParent) {
1257         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1258         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1259
1260         for (final DataSchemaNode caseNode : augmentedNodes) {
1261             if (caseNode != null) {
1262                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(context, caseNode);
1263                 caseTypeBuilder.addImplementsType(targetType);
1264
1265                 CaseSchemaNode node = null;
1266                 final String caseLocalName = caseNode.getQName().getLocalName();
1267                 if (caseNode instanceof CaseSchemaNode) {
1268                     node = (CaseSchemaNode) caseNode;
1269                 } else if (findNamedCase(targetNode, caseLocalName) == null) {
1270                     final String targetNodeLocalName = targetNode.getQName().getLocalName();
1271                     for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1272                         if (dataSchemaNode instanceof ChoiceSchemaNode
1273                                 && targetNodeLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
1274                             node = findNamedCase((ChoiceSchemaNode) dataSchemaNode, caseLocalName);
1275                             break;
1276                         }
1277                     }
1278                 } else {
1279                     node = findNamedCase(targetNode, caseLocalName);
1280                 }
1281                 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1282                 if (childNodes != null) {
1283                     resolveDataSchemaNodes(context, caseTypeBuilder, findChildOfType(targetNode), childNodes);
1284                 }
1285                 context.addCaseType(caseNode.getPath(), caseTypeBuilder);
1286                 context.addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1287             }
1288         }
1289     }
1290
1291     private GeneratedTypeBuilder findChildOfType(final ChoiceSchemaNode targetNode) {
1292         final SchemaPath nodePath = targetNode.getPath();
1293         final SchemaPath parentSp = nodePath.getParent();
1294         if (parentSp.getParent() == null) {
1295             return moduleContext(nodePath.getLastComponent().getModule()).getModuleNode();
1296         }
1297
1298         final SchemaNode parent = findDataSchemaNode(schemaContext, parentSp);
1299         GeneratedTypeBuilder childOfType = null;
1300         if (parent instanceof CaseSchemaNode) {
1301             childOfType = findCaseByPath(parent.getPath());
1302         } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1303             childOfType = findChildNodeByPath(parent.getPath());
1304         } else if (parent instanceof GroupingDefinition) {
1305             childOfType = findGroupingByPath(parent.getPath());
1306         }
1307
1308         if (childOfType == null) {
1309             throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1310         }
1311
1312         return childOfType;
1313     }
1314
1315     private static CaseSchemaNode findNamedCase(final ChoiceSchemaNode choice, final String caseName) {
1316         final List<CaseSchemaNode> cases = choice.findCaseNodes(caseName);
1317         return cases.isEmpty() ? null : cases.get(0);
1318     }
1319
1320     private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1321         // New parser with encapsulated type
1322         if (leaf.getPath().equals(type.getPath())) {
1323             return true;
1324         }
1325
1326         // Embedded type definition with new parser. Also takes care of the old parser with bits
1327         if (leaf.getPath().equals(type.getPath().getParent())) {
1328             return true;
1329         }
1330
1331         return false;
1332     }
1333
1334     private void addPatternConstant(final GeneratedTypeBuilder typeBuilder, final String leafName,
1335             final List<PatternConstraint> patternConstraints) {
1336         if (!patternConstraints.isEmpty()) {
1337             final StringBuilder field = new StringBuilder().append(TypeConstants.PATTERN_CONSTANT_NAME).append("_")
1338                 .append(BindingMapping.getPropertyName(leafName));
1339             typeBuilder.addConstant(LIST_STRING_TYPE, field.toString(),
1340                 typeProvider.resolveRegExpressions(patternConstraints));
1341         }
1342     }
1343
1344     /**
1345      * Converts <code>leaf</code> to the getter method which is added to
1346      * <code>typeBuilder</code>.
1347      *
1348      * @param typeBuilder
1349      *            generated type builder to which is added getter method as
1350      *            <code>leaf</code> mapping
1351      * @param leaf
1352      *            leaf schema node which is mapped as getter method which is
1353      *            added to <code>typeBuilder</code>
1354      * @param module
1355      *            Module in which type was defined
1356      * @return boolean value
1357      *         <ul>
1358      *         <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1359      *         null</li>
1360      *         <li>true - in other cases</li>
1361      *         </ul>
1362      */
1363     private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf,
1364             final ModuleContext context) {
1365         if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1366             return null;
1367         }
1368
1369         final Module parentModule = findParentModule(schemaContext, leaf);
1370         Type returnType = null;
1371
1372         final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1373         if (isInnerType(leaf, typeDef)) {
1374             if (typeDef instanceof EnumTypeDefinition) {
1375                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1376                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1377                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1378                     typeBuilder, context);
1379                 if (enumBuilder != null) {
1380                     returnType = enumBuilder.toInstance(typeBuilder);
1381                 }
1382                 typeProvider.putReferencedType(leaf.getPath(), returnType);
1383             } else if (typeDef instanceof UnionTypeDefinition) {
1384                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition) typeDef, typeBuilder, leaf,
1385                     parentModule);
1386                 if (genTOBuilder != null) {
1387                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1388                     // Store the inner type within the union so that we can find the reference for it
1389                     context.addInnerTypedefType(typeDef.getPath(), returnType);
1390                 }
1391             } else if (typeDef instanceof BitsTypeDefinition) {
1392                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition) typeDef, typeBuilder, leaf,
1393                     parentModule);
1394                 if (genTOBuilder != null) {
1395                     returnType = genTOBuilder.build();
1396                 }
1397             } else {
1398                 // It is constrained version of already declared type (inner declared type exists,
1399                 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1400                 // In order to get proper class we need to look up closest derived type
1401                 // and apply restrictions from leaf type
1402                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1403                 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1404                         restrictions);
1405                 addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1406             }
1407         } else {
1408             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1409             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1410             addPatternConstant(typeBuilder, leaf.getQName().getLocalName(), restrictions.getPatternConstraints());
1411         }
1412
1413         if (returnType == null) {
1414             return null;
1415         }
1416
1417         if (typeDef instanceof EnumTypeDefinition) {
1418             typeProvider.putReferencedType(leaf.getPath(), returnType);
1419         }
1420
1421         final MethodSignatureBuilder getter = constructGetter(typeBuilder,  returnType, leaf);
1422         processContextRefExtension(leaf, getter, parentModule);
1423         return returnType;
1424     }
1425
1426     private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1427         // Returns DerivedType in case of new parser.
1428         final TypeDefinition<?> baseType = typeDef.getBaseType();
1429         return baseType != null && baseType.getBaseType() != null ? baseType : typeDef;
1430     }
1431
1432     private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1433             final Module module) {
1434         for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1435             final QName nodeType = node.getNodeType();
1436             if ("context-reference".equals(nodeType.getLocalName())) {
1437                 final String nodeParam = node.getNodeParameter();
1438                 IdentitySchemaNode identity = null;
1439                 String basePackageName = null;
1440                 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1441                 final Iterator<String> iterator = splittedElement.iterator();
1442                 final int length = Iterables.size(splittedElement);
1443                 if (length == 1) {
1444                     identity = findIdentityByName(module.getIdentities(), iterator.next());
1445                     basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1446                 } else if (length == 2) {
1447                     final String prefix = iterator.next();
1448                     final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1449                     if (dependentModule == null) {
1450                         throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1451                                 + prefix);
1452                     }
1453                     identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1454                     basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1455                 } else {
1456                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1457                             + nodeParam);
1458                 }
1459                 if (identity == null) {
1460                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1461                             + nodeParam);
1462                 }
1463
1464                 final AnnotationTypeBuilder rc = getter.addAnnotation(ROUTING_CONTEXT);
1465                 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1466                 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1467                 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1468             }
1469         }
1470     }
1471
1472     private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1473         for (final IdentitySchemaNode id : identities) {
1474             if (id.getQName().getLocalName().equals(name)) {
1475                 return id;
1476             }
1477         }
1478         return null;
1479     }
1480
1481     private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1482         for (final ModuleImport imp : imports) {
1483             if (imp.getPrefix().equals(prefix)) {
1484                 return schemaContext.findModule(imp.getModuleName(), imp.getRevision()).orElse(null);
1485             }
1486         }
1487         return null;
1488     }
1489
1490     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1491             final boolean isReadOnly) {
1492         if (leaf != null && toBuilder != null) {
1493             Type returnType;
1494             final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1495             if (typeDef instanceof UnionTypeDefinition) {
1496                 // GeneratedType for this type definition should have be already created
1497                 final ModuleContext mc = moduleContext(typeDef.getQName().getModule());
1498                 returnType = mc.getTypedefs().get(typeDef.getPath());
1499                 if (returnType == null) {
1500                     // This may still be an inner type, try to find it
1501                     returnType = mc.getInnerType(typeDef.getPath());
1502                 }
1503             } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1504                 // Annonymous enumeration (already generated, since it is inherited via uses).
1505                 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1506                 QName qname = originalLeaf.getQName();
1507                 returnType = moduleContext(qname.getModule()).getInnerType(originalLeaf.getType().getPath());
1508             } else {
1509                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1510             }
1511             return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1512         }
1513         return false;
1514     }
1515
1516     /**
1517      * Converts <code>leaf</code> schema node to property of generated TO
1518      * builder.
1519      *
1520      * @param toBuilder
1521      *            generated TO builder to which is <code>leaf</code> added as
1522      *            property
1523      * @param leaf
1524      *            leaf schema node which is added to <code>toBuilder</code> as
1525      *            property
1526      * @param returnType
1527      *            property type
1528      * @param isReadOnly
1529      *            boolean value which says if leaf property is|isn't read only
1530      * @return boolean value
1531      *         <ul>
1532      *         <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1533      *         name equals null or if leaf is added by <i>uses</i>.</li>
1534      *         <li>true - other cases</li>
1535      *         </ul>
1536      */
1537     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1538             final Type returnType, final boolean isReadOnly) {
1539         if (returnType == null) {
1540             return false;
1541         }
1542         final String leafName = leaf.getQName().getLocalName();
1543         final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1544         propBuilder.setReadOnly(isReadOnly);
1545         propBuilder.setReturnType(returnType);
1546         addComment(propBuilder, leaf);
1547
1548         toBuilder.addEqualsIdentity(propBuilder);
1549         toBuilder.addHashIdentity(propBuilder);
1550         toBuilder.addToStringProperty(propBuilder);
1551         return true;
1552     }
1553
1554     /**
1555      * Converts <code>node</code> leaf list schema node to getter method of
1556      * <code>typeBuilder</code>.
1557      *
1558      * @param typeBuilder
1559      *            generated type builder to which is <code>node</code> added as
1560      *            getter method
1561      * @param node
1562      *            leaf list schema node which is added to
1563      *            <code>typeBuilder</code> as getter method
1564      * @param module module
1565      * @return boolean value
1566      *         <ul>
1567      *         <li>true - if <code>node</code>, <code>typeBuilder</code>,
1568      *         nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1569      *         <li>false - other cases</li>
1570      *         </ul>
1571      */
1572     private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node,
1573             final ModuleContext context) {
1574         if (node == null || typeBuilder == null || node.isAddedByUses()) {
1575             return false;
1576         }
1577
1578         final QName nodeName = node.getQName();
1579
1580         final TypeDefinition<?> typeDef = node.getType();
1581         final Module parentModule = findParentModule(schemaContext, node);
1582
1583         Type returnType = null;
1584         if (typeDef.getBaseType() == null) {
1585             if (typeDef instanceof EnumTypeDefinition) {
1586                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1587                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1588                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1589                     typeBuilder, context);
1590                 returnType = new ReferencedTypeImpl(enumBuilder.getIdentifier());
1591                 typeProvider.putReferencedType(node.getPath(), returnType);
1592             } else if (typeDef instanceof UnionTypeDefinition) {
1593                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((UnionTypeDefinition)typeDef, typeBuilder,
1594                     node, parentModule);
1595                 if (genTOBuilder != null) {
1596                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1597                 }
1598             } else if (typeDef instanceof BitsTypeDefinition) {
1599                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder((BitsTypeDefinition)typeDef, typeBuilder,
1600                     node, parentModule);
1601                 returnType = genTOBuilder.build();
1602             } else {
1603                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1604                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1605                 addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1606             }
1607         } else {
1608             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1609             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1610             addPatternConstant(typeBuilder, node.getQName().getLocalName(), restrictions.getPatternConstraints());
1611         }
1612
1613         final ParameterizedType listType = listTypeFor(returnType);
1614         constructGetter(typeBuilder, listType, node);
1615         return true;
1616     }
1617
1618     private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1619             final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1620         final GeneratedTOBuilder returnType = typeProvider.newGeneratedTOBuilder(genTOBuilder.getIdentifier());
1621
1622         addCodegenInformation(returnType, parentModule, typeDef);
1623         returnType.setSchemaPath(typeDef.getPath());
1624         returnType.setModuleName(parentModule.getName());
1625
1626         genTOBuilder.setTypedef(true);
1627         genTOBuilder.setIsUnion(true);
1628         AbstractTypeProvider.addUnitsToGenTO(genTOBuilder, typeDef.getUnits().orElse(null));
1629
1630
1631
1632         final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder, typeBuilder);
1633
1634
1635         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1636         method.setReturnType(returnType);
1637         method.addParameter(Types.STRING, "defaultValue");
1638         method.setAccessModifier(AccessModifier.PUBLIC);
1639         method.setStatic(true);
1640
1641         final Set<Type> types = typeProvider.getAdditionalTypes().get(parentModule);
1642         if (types == null) {
1643             typeProvider.getAdditionalTypes().put(parentModule,
1644                     Sets.newHashSet(unionBuilder.build()));
1645         } else {
1646             types.add(unionBuilder.build());
1647         }
1648         return returnType.build();
1649     }
1650
1651     private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder,
1652             final GeneratedTypeBuilder typeBuilder) {
1653         // Append enclosing path hierarchy without dots
1654         final StringBuilder sb = new StringBuilder();
1655         genTOBuilder.getIdentifier().localNameComponents().forEach(sb::append);
1656         final GeneratedTOBuilder unionBuilder = typeProvider.newGeneratedTOBuilder(
1657             JavaTypeName.create(typeBuilder.getPackageName(), sb.append("Builder").toString()));
1658         unionBuilder.setIsUnionBuilder(true);
1659         return unionBuilder;
1660     }
1661
1662     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1663             final SchemaNode schemaNode) {
1664         return addDefaultInterfaceDefinition(context, schemaNode, DATA_OBJECT);
1665     }
1666
1667     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final ModuleContext context,
1668             final SchemaNode schemaNode, final Type baseInterface) {
1669         final String packageName = packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath());
1670         return addDefaultInterfaceDefinition(packageName, schemaNode, baseInterface, context);
1671     }
1672
1673
1674     /**
1675      * Instantiates generated type builder with <code>packageName</code> and
1676      * <code>schemaNode</code>.
1677      *
1678      * The new builder always implements
1679      * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1680      * If <code>schemaNode</code> is instance of GroupingDefinition it also
1681      * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1682      * Augmentable}.<br>
1683      * If <code>schemaNode</code> is instance of
1684      * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1685      * DataNodeContainer} it can also implement nodes which are specified in
1686      * <i>uses</i>.
1687      *
1688      * @param packageName
1689      *            string with the name of the package to which
1690      *            <code>schemaNode</code> belongs.
1691      * @param schemaNode
1692      *            schema node for which is created generated type builder
1693      * @param parent
1694      *            parent type (can be null)
1695      * @return generated type builder <code>schemaNode</code>
1696      */
1697     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1698             final Type baseInterface, final ModuleContext context) {
1699         JavaTypeName name = renames.get(schemaNode);
1700         if (name == null) {
1701             name = JavaTypeName.create(packageName, BindingMapping.getClassName(schemaNode.getQName()));
1702         }
1703
1704         final GeneratedTypeBuilder it = addRawInterfaceDefinition(name, schemaNode);
1705
1706         it.addImplementsType(baseInterface);
1707         if (!(schemaNode instanceof GroupingDefinition)) {
1708             it.addImplementsType(augmentable(it));
1709         }
1710         if (schemaNode instanceof DataNodeContainer) {
1711             final DataNodeContainer containerSchema = (DataNodeContainer) schemaNode;
1712             groupingsToGenTypes(context, containerSchema.getGroupings());
1713             addImplementedInterfaceFromUses(containerSchema, it);
1714         }
1715
1716         return it;
1717     }
1718
1719     /**
1720      * Wraps the calling of the same overloaded method.
1721      *
1722      * @param packageName
1723      *            string with the package name to which returning generated type
1724      *            builder belongs
1725      * @param schemaNode
1726      *            schema node which provide data about the schema node name
1727      * @return generated type builder for <code>schemaNode</code>
1728      */
1729     private GeneratedTypeBuilder addRawInterfaceDefinition(final ModuleContext context, final SchemaNode schemaNode,
1730             final String prefix) {
1731         return addRawInterfaceDefinition(
1732             JavaTypeName.create(packageNameForGeneratedType(context.modulePackageName(), schemaNode.getPath()),
1733                 prefix + BindingMapping.getClassName(schemaNode.getQName())), schemaNode);
1734     }
1735
1736     /**
1737      * Returns reference to generated type builder for specified
1738      * <code>schemaNode</code> with <code>packageName</code>.
1739      *
1740      * Firstly the generated type builder is searched in
1741      * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1742      * found it is created and added to <code>genTypeBuilders</code>.
1743      *
1744      * @param packageName
1745      *            string with the package name to which returning generated type
1746      *            builder belongs
1747      * @param schemaNode
1748      *            schema node which provide data about the schema node name
1749      * @param prefix
1750      *            return type name prefix
1751      * @return generated type builder for <code>schemaNode</code>
1752      * @throws IllegalArgumentException
1753      *             <ul>
1754      *             <li>if <code>schemaNode</code> is null</li>
1755      *             <li>if <code>packageName</code> is null</li>
1756      *             <li>if QName of schema node is null</li>
1757      *             <li>if schemaNode name is null</li>
1758      *             </ul>
1759      *
1760      */
1761     private GeneratedTypeBuilder addRawInterfaceDefinition(final JavaTypeName identifier, final SchemaNode schemaNode) {
1762         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1763         checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1764         final String schemaNodeName = schemaNode.getQName().getLocalName();
1765         checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1766
1767         // FIXME: Validation of name conflict
1768         final GeneratedTypeBuilder newType = typeProvider.newGeneratedTypeBuilder(identifier);
1769         final Module module = findParentModule(schemaContext, schemaNode);
1770         qnameConstant(newType, JavaTypeName.create(BindingMapping.getRootPackageName(module.getQNameModule()),
1771             BindingMapping.MODULE_INFO_CLASS_NAME), schemaNode.getQName().getLocalName());
1772
1773         addCodegenInformation(newType, module, schemaNode);
1774         newType.setSchemaPath(schemaNode.getPath());
1775         newType.setModuleName(module.getName());
1776
1777         final String packageName = identifier.packageName();
1778         final String simpleName = identifier.simpleName();
1779         if (!genTypeBuilders.containsKey(packageName)) {
1780             final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1781             builders.put(simpleName, newType);
1782             genTypeBuilders.put(packageName, builders);
1783         } else {
1784             final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1785             if (!builders.containsKey(simpleName)) {
1786                 builders.put(simpleName, newType);
1787             }
1788         }
1789         return newType;
1790     }
1791
1792     /**
1793      * Creates the name of the getter method name from <code>localName</code>.
1794      *
1795      * @param localName
1796      *            string with the name of the getter method
1797      * @param returnType
1798      *            return type
1799      * @return string with the name of the getter method for
1800      *         <code>methodName</code> in JAVA method format
1801      */
1802     public static String getterMethodName(final String localName, final Type returnType) {
1803         final StringBuilder method = new StringBuilder();
1804         if (BOOLEAN.equals(returnType)) {
1805             method.append("is");
1806         } else {
1807             method.append("get");
1808         }
1809         final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1810         method.append(name);
1811         return method.toString();
1812     }
1813
1814     /**
1815      * Created a method signature builder as part of <code>interfaceBuilder</code>.
1816      *
1817      * The method signature builder is created for the getter method of <code>schemaNodeName</code>.
1818      * Also <code>comment</code> and <code>returnType</code> information are added to the builder.
1819      *
1820      * @param interfaceBuilder generated type builder for which the getter method should be created
1821      * @param returnType type which represents the return type of the getter method
1822      * @param schemaNodeName string with schema node name. The name will be the part of the getter method name.
1823      * @param comment string with comment for the getter method
1824      * @param status status from yang file, for deprecated annotation
1825      * @return method signature builder which represents the getter method of <code>interfaceBuilder</code>
1826      */
1827     private MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder, final Type returnType,
1828             final SchemaNode node) {
1829         final MethodSignatureBuilder getMethod = interfaceBuilder.addMethod(
1830             getterMethodName(node.getQName().getLocalName(), returnType));
1831         getMethod.setReturnType(returnType);
1832
1833         annotateDeprecatedIfNecessary(node.getStatus(), getMethod);
1834         if (!returnType.getPackageName().isEmpty()) {
1835             // The return type has a package, so it's not a primitive type
1836             getMethod.addAnnotation("javax.annotation", "Nullable");
1837         }
1838         addComment(getMethod, node);
1839
1840         return getMethod;
1841     }
1842
1843     /**
1844      * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1845      * or to <code>genTOBuilder</code> as property.
1846      *
1847      * @param basePackageName
1848      *            string contains the module package name
1849      * @param schemaNode
1850      *            data schema node which should be added as getter method to
1851      *            <code>typeBuilder</code> or as a property to
1852      *            <code>genTOBuilder</code> if is part of the list key
1853      * @param typeBuilder
1854      *            generated type builder for the list schema node
1855      * @param genTOBuilder
1856      *            generated TO builder for the list keys
1857      * @param listKeys
1858      *            list of string which contains names of the list keys
1859      * @param module
1860      *            current module
1861      * @throws IllegalArgumentException
1862      *             <ul>
1863      *             <li>if <code>schemaNode</code> equals null</li>
1864      *             <li>if <code>typeBuilder</code> equals null</li>
1865      *             </ul>
1866      */
1867     private void addSchemaNodeToListBuilders(final ModuleContext context, final DataSchemaNode schemaNode,
1868             final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder,
1869             final List<String> listKeys) {
1870         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1871         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1872
1873         if (schemaNode instanceof LeafSchemaNode) {
1874             final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1875             final String leafName = leaf.getQName().getLocalName();
1876             Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf, context);
1877             if (listKeys.contains(leafName)) {
1878                 if (type == null) {
1879                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true);
1880                 } else {
1881                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1882                 }
1883             }
1884         } else if (!schemaNode.isAddedByUses()) {
1885             if (schemaNode instanceof LeafListSchemaNode) {
1886                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, context);
1887             } else if (schemaNode instanceof ContainerSchemaNode) {
1888                 containerToGenType(context, typeBuilder, childOf(typeBuilder),
1889                     (ContainerSchemaNode) schemaNode);
1890             } else if (schemaNode instanceof ChoiceSchemaNode) {
1891                 choiceToGeneratedType(context, typeBuilder, (ChoiceSchemaNode) schemaNode);
1892             } else if (schemaNode instanceof ListSchemaNode) {
1893                 listToGenType(context, typeBuilder, childOf(typeBuilder), (ListSchemaNode) schemaNode);
1894             }
1895         }
1896     }
1897
1898     private static void typeBuildersToGenTypes(final ModuleContext context, final GeneratedTypeBuilder typeBuilder,
1899             final GeneratedTOBuilder genTOBuilder) {
1900         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1901
1902         if (genTOBuilder != null) {
1903             final GeneratedTransferObject genTO = genTOBuilder.build();
1904             // Add Identifiable.getKey() for items
1905             typeBuilder.addMethod(BindingMapping.IDENTIFIABLE_KEY_NAME).setReturnType(genTO)
1906                 .addAnnotation(OVERRIDE_ANNOTATION);
1907             context.addGeneratedTOBuilder(genTOBuilder);
1908         }
1909     }
1910
1911     /**
1912      * Selects the names of the list keys from <code>list</code> and returns
1913      * them as the list of the strings
1914      *
1915      * @param list
1916      *            of string with names of the list keys
1917      * @return list of string which represents names of the list keys. If the
1918      *         <code>list</code> contains no keys then the empty list is
1919      *         returned.
1920      */
1921     private static List<String> listKeys(final ListSchemaNode list) {
1922         final List<String> listKeys = new ArrayList<>();
1923
1924         final List<QName> keyDefinition = list.getKeyDefinition();
1925         if (keyDefinition != null) {
1926             for (final QName keyDef : keyDefinition) {
1927                 listKeys.add(keyDef.getLocalName());
1928             }
1929         }
1930         return listKeys;
1931     }
1932
1933     /**
1934      * Generates for the <code>list</code> which contains any list keys special
1935      * generated TO builder.
1936      *
1937      * @param packageName
1938      *            string with package name to which the list belongs
1939      * @param list
1940      *            list schema node which is source of data about the list name
1941      * @return generated TO builder which represents the keys of the
1942      *         <code>list</code> or null if <code>list</code> is null or list of
1943      *         key definitions is null or empty.
1944      */
1945     private GeneratedTOBuilder resolveListKeyTOBuilder(final ModuleContext context, final ListSchemaNode list) {
1946         if (list.getKeyDefinition() != null && !list.getKeyDefinition().isEmpty()) {
1947             return typeProvider.newGeneratedTOBuilder(JavaTypeName.create(
1948                 packageNameForGeneratedType(context.modulePackageName(), list.getPath()),
1949                 BindingMapping.getClassName(list.getQName().getLocalName() + "Key")));
1950         }
1951         return null;
1952     }
1953
1954     /**
1955      * Builds a GeneratedTOBuilder for a UnionType {@link UnionTypeDefinition}.
1956      *
1957      * If more then one generated TO builder is created for enclosing then all
1958      * of the generated TO builders are added to <code>typeBuilder</code> as
1959      * enclosing transfer objects.
1960      *
1961      * @param typeDef
1962      *            type definition which can be of type <code>UnionType</code> or
1963      *            <code>BitsTypeDefinition</code>
1964      * @param typeBuilder
1965      *            generated type builder to which is added generated TO created
1966      *            from <code>typeDef</code>
1967      * @param leaf
1968      *            string with name for generated TO builder
1969      * @param parentModule
1970      *            parent module
1971      * @return generated TO builder for <code>typeDef</code>
1972      */
1973     private GeneratedTOBuilder addTOToTypeBuilder(final UnionTypeDefinition typeDef,
1974             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
1975         final List<GeneratedTOBuilder> types = typeProvider.provideGeneratedTOBuildersForUnionTypeDef(
1976             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
1977             typeDef, leaf);
1978
1979         checkState(!types.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typeDef);
1980         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>(types);
1981         final GeneratedTOBuilder resultTOBuilder = types.remove(0);
1982         for (final GeneratedTOBuilder genTOBuilder : types) {
1983             resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
1984         }
1985
1986         processEnclosedTOBuilderes(typeBuilder, genTOBuilders);
1987         return resultTOBuilder;
1988     }
1989
1990     /**
1991      * Builds generated TO builders for <code>typeDef</code> of type {@link BitsTypeDefinition} which are
1992      * also added to <code>typeBuilder</code> as enclosing transfer object.
1993      *
1994      * If more then one generated TO builder is created for enclosing then all
1995      * of the generated TO builders are added to <code>typeBuilder</code> as
1996      * enclosing transfer objects.
1997      *
1998      * @param typeDef
1999      *            type definition which can be of type <code>UnionType</code> or
2000      *            <code>BitsTypeDefinition</code>
2001      * @param typeBuilder
2002      *            generated type builder to which is added generated TO created
2003      *            from <code>typeDef</code>
2004      * @param leaf
2005      *            string with name for generated TO builder
2006      * @param parentModule
2007      *            parent module
2008      * @return generated TO builder for <code>typeDef</code>
2009      */
2010     private GeneratedTOBuilder addTOToTypeBuilder(final BitsTypeDefinition typeDef,
2011             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2012         final GeneratedTOBuilder genTOBuilder = typeProvider.provideGeneratedTOBuilderForBitsTypeDefinition(
2013             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(leaf.getQName())),
2014             typeDef, parentModule.getName());
2015         typeBuilder.addEnclosingTransferObject(genTOBuilder);
2016         return genTOBuilder;
2017
2018     }
2019
2020     private static GeneratedTOBuilder processEnclosedTOBuilderes(final GeneratedTypeBuilder typeBuilder,
2021             final List<GeneratedTOBuilder> genTOBuilders) {
2022         for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2023             typeBuilder.addEnclosingTransferObject(genTOBuilder);
2024         }
2025         return genTOBuilders.get(0);
2026     }
2027
2028     /**
2029      * Adds the implemented types to type builder.
2030      *
2031      * The method passes through the list of <i>uses</i> in
2032      * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2033      * generated type from {@link ModuleContext#groupings
2034      * allGroupings} which is added as <i>implements type</i> to
2035      * <code>builder</code>
2036      *
2037      * @param dataNodeContainer
2038      *            element which contains the list of used YANG groupings
2039      * @param builder
2040      *            builder to which are added implemented types according to
2041      *            <code>dataNodeContainer</code>
2042      * @return generated type builder with all implemented types
2043      */
2044     private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2045             final GeneratedTypeBuilder builder) {
2046         for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2047             final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).build();
2048             if (genType == null) {
2049                 throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2050                         + builder.getName());
2051             }
2052
2053             builder.addImplementsType(genType);
2054         }
2055         return builder;
2056     }
2057
2058     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2059         for (final ModuleContext ctx : genCtx.values()) {
2060             final GeneratedTypeBuilder result = ctx.getChildNode(path);
2061             if (result != null) {
2062                 return result;
2063             }
2064         }
2065         return null;
2066     }
2067
2068     private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2069         for (final ModuleContext ctx : genCtx.values()) {
2070             final GeneratedTypeBuilder result = ctx.getGrouping(path);
2071             if (result != null) {
2072                 return result;
2073             }
2074         }
2075         return null;
2076     }
2077
2078     private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2079         for (final ModuleContext ctx : genCtx.values()) {
2080             final GeneratedTypeBuilder result = ctx.getCase(path);
2081             if (result != null) {
2082                 return result;
2083             }
2084         }
2085         return null;
2086     }
2087
2088     private static void annotateDeprecatedIfNecessary(final Status status, final AnnotableTypeBuilder builder) {
2089         if (status == Status.DEPRECATED) {
2090             builder.addAnnotation(DEPRECATED_ANNOTATION);
2091         }
2092     }
2093 }