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