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