5e719b49feb923995bf6cbc161de0ccf9eaea518
[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(), null);
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(), usesNodeParent);
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             final DataNodeContainer usesNodeParent) {
1300         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1301         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1302         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1303
1304         for (final DataSchemaNode caseNode : augmentedNodes) {
1305             if (caseNode != null) {
1306                 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1307                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1308                 caseTypeBuilder.addImplementsType(targetType);
1309
1310                 SchemaNode parent = null;
1311                 final SchemaPath nodeSp = targetNode.getPath();
1312                 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1313
1314                 GeneratedTypeBuilder childOfType = null;
1315                 if (parent instanceof Module) {
1316                     childOfType = genCtx.get(parent).getModuleNode();
1317                 } else if (parent instanceof ChoiceCaseNode) {
1318                     childOfType = findCaseByPath(parent.getPath());
1319                 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1320                     childOfType = findChildNodeByPath(parent.getPath());
1321                 } else if (parent instanceof GroupingDefinition) {
1322                     childOfType = findGroupingByPath(parent.getPath());
1323                 }
1324
1325                 if (childOfType == null) {
1326                     throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1327                 }
1328
1329                 ChoiceCaseNode node = null;
1330                 final String caseLocalName = caseNode.getQName().getLocalName();
1331                 if (caseNode instanceof ChoiceCaseNode) {
1332                     node = (ChoiceCaseNode) caseNode;
1333                 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1334                     final String targetNodeLocalName = targetNode.getQName().getLocalName();
1335                     for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1336                         if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1337                                 ().getLocalName())) {
1338                             node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1339                             break;
1340                         }
1341                     }
1342                 } else {
1343                     node = targetNode.getCaseNodeByName(caseLocalName);
1344                 }
1345                 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1346                 if (childNodes != null) {
1347                     resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1348                 }
1349                 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1350                 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1351             }
1352         }
1353     }
1354
1355     private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1356         // Deal with old parser, clearing out references to typedefs
1357         if (type instanceof ExtendedType) {
1358             return false;
1359         }
1360
1361         // New parser with encapsulated type
1362         if (leaf.getPath().equals(type.getPath())) {
1363             return true;
1364         }
1365
1366         // Embedded type definition with new parser. Also takes care of the old parser with bits
1367         if (leaf.getPath().equals(type.getPath().getParent())) {
1368             return true;
1369         }
1370
1371         // Old parser uses broken Union type, which does not change its schema path
1372         if (type instanceof UnionType) {
1373             return true;
1374         }
1375
1376         return false;
1377     }
1378
1379     /**
1380      * Converts <code>leaf</code> to the getter method which is added to
1381      * <code>typeBuilder</code>.
1382      *
1383      * @param typeBuilder
1384      *            generated type builder to which is added getter method as
1385      *            <code>leaf</code> mapping
1386      * @param leaf
1387      *            leaf schema node which is mapped as getter method which is
1388      *            added to <code>typeBuilder</code>
1389      * @param module
1390      *            Module in which type was defined
1391      * @return boolean value
1392      *         <ul>
1393      *         <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1394      *         null</li>
1395      *         <li>true - in other cases</li>
1396      *         </ul>
1397      */
1398     private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1399         if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1400             return null;
1401         }
1402
1403         final String leafName = leaf.getQName().getLocalName();
1404         if (leafName == null) {
1405             return null;
1406         }
1407
1408         final Module parentModule = findParentModule(schemaContext, leaf);
1409         Type returnType = null;
1410
1411         final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1412         if (isInnerType(leaf, typeDef)) {
1413             if (typeDef instanceof EnumTypeDefinition) {
1414                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1415                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1416                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1417                     typeBuilder, module);
1418
1419                 if (enumBuilder != null) {
1420                     returnType = enumBuilder.toInstance(typeBuilder);
1421                 }
1422                 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1423             } else if (typeDef instanceof UnionTypeDefinition) {
1424                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1425                 if (genTOBuilder != null) {
1426                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1427                 }
1428             } else if (typeDef instanceof BitsTypeDefinition) {
1429                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1430                 if (genTOBuilder != null) {
1431                     returnType = genTOBuilder.toInstance();
1432                 }
1433             } else {
1434                 // It is constrained version of already declared type (inner declared type exists,
1435                 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1436                 // In order to get proper class we need to look up closest derived type
1437                 // and apply restrictions from leaf type
1438                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1439                 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1440                         restrictions);
1441             }
1442         } else {
1443             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1444             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1445         }
1446
1447         if (returnType == null) {
1448             return null;
1449         }
1450
1451         String leafDesc = leaf.getDescription();
1452         if (leafDesc == null) {
1453             leafDesc = "";
1454         }
1455
1456         final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType);
1457         processContextRefExtension(leaf, getter, parentModule);
1458         return returnType;
1459     }
1460
1461     private static TypeDefinition<?> getBaseOrDeclaredType(TypeDefinition<?> typeDef) {
1462         if (typeDef instanceof ExtendedType) {
1463             // Legacy behaviour returning ExtendedType is enough
1464             return typeDef;
1465         }
1466         // Returns DerivedType in case of new parser.
1467         final TypeDefinition<?> baseType = typeDef.getBaseType();
1468         return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1469     }
1470
1471     private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1472             final Module module) {
1473         for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1474             final QName nodeType = node.getNodeType();
1475             if ("context-reference".equals(nodeType.getLocalName())) {
1476                 final String nodeParam = node.getNodeParameter();
1477                 IdentitySchemaNode identity = null;
1478                 String basePackageName = null;
1479                 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1480                 final Iterator<String> iterator = splittedElement.iterator();
1481                 final int length = Iterables.size(splittedElement);
1482                 if (length == 1) {
1483                     identity = findIdentityByName(module.getIdentities(), iterator.next());
1484                     basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1485                 } else if (length == 2) {
1486                     final String prefix = iterator.next();
1487                     final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1488                     if (dependentModule == null) {
1489                         throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1490                                 + prefix);
1491                     }
1492                     identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1493                     basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1494                 } else {
1495                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1496                             + nodeParam);
1497                 }
1498                 if (identity == null) {
1499                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1500                             + nodeParam);
1501                 }
1502
1503                 final Class<RoutingContext> clazz = RoutingContext.class;
1504                 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1505                         clazz.getSimpleName());
1506                 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1507                 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1508                 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1509             }
1510         }
1511     }
1512
1513     private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1514         for (final IdentitySchemaNode id : identities) {
1515             if (id.getQName().getLocalName().equals(name)) {
1516                 return id;
1517             }
1518         }
1519         return null;
1520     }
1521
1522     private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1523         for (final ModuleImport imp : imports) {
1524             if (imp.getPrefix().equals(prefix)) {
1525                 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1526             }
1527         }
1528         return null;
1529     }
1530
1531     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1532             final boolean isReadOnly, final Module module) {
1533         if ((leaf != null) && (toBuilder != null)) {
1534             String leafDesc = leaf.getDescription();
1535             if (leafDesc == null) {
1536                 leafDesc = "";
1537             }
1538             Type returnType = null;
1539             final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1540             if (typeDef instanceof UnionTypeDefinition) {
1541                 // GeneratedType for this type definition should be already
1542                 // created
1543                 final QName qname = typeDef.getQName();
1544                 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1545                         qname.getRevision());
1546                 final ModuleContext mc = genCtx.get(unionModule);
1547                 returnType = mc.getTypedefs().get(typeDef.getPath());
1548             } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1549                 // Annonymous enumeration (already generated, since it is inherited via uses).
1550                 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1551                 QName qname = originalLeaf.getQName();
1552                 final Module enumModule =  schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1553                         qname.getRevision());
1554                 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1555             } else {
1556                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1557             }
1558             return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1559         }
1560         return false;
1561     }
1562
1563     /**
1564      * Converts <code>leaf</code> schema node to property of generated TO
1565      * builder.
1566      *
1567      * @param toBuilder
1568      *            generated TO builder to which is <code>leaf</code> added as
1569      *            property
1570      * @param leaf
1571      *            leaf schema node which is added to <code>toBuilder</code> as
1572      *            property
1573      * @param returnType
1574      *            property type
1575      * @param isReadOnly
1576      *            boolean value which says if leaf property is|isn't read only
1577      * @return boolean value
1578      *         <ul>
1579      *         <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1580      *         name equals null or if leaf is added by <i>uses</i>.</li>
1581      *         <li>true - other cases</li>
1582      *         </ul>
1583      */
1584     private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1585             final Type returnType, final boolean isReadOnly) {
1586         if (returnType == null) {
1587             return false;
1588         }
1589         final String leafName = leaf.getQName().getLocalName();
1590         final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1591         final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1592         propBuilder.setReadOnly(isReadOnly);
1593         propBuilder.setReturnType(returnType);
1594         propBuilder.setComment(leafDesc);
1595         toBuilder.addEqualsIdentity(propBuilder);
1596         toBuilder.addHashIdentity(propBuilder);
1597         toBuilder.addToStringProperty(propBuilder);
1598         return true;
1599     }
1600
1601     /**
1602      * Converts <code>node</code> leaf list schema node to getter method of
1603      * <code>typeBuilder</code>.
1604      *
1605      * @param typeBuilder
1606      *            generated type builder to which is <code>node</code> added as
1607      *            getter method
1608      * @param node
1609      *            leaf list schema node which is added to
1610      *            <code>typeBuilder</code> as getter method
1611      * @param module
1612      * @return boolean value
1613      *         <ul>
1614      *         <li>true - if <code>node</code>, <code>typeBuilder</code>,
1615      *         nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1616      *         <li>false - other cases</li>
1617      *         </ul>
1618      */
1619     private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1620         if (node == null || typeBuilder == null || node.isAddedByUses()) {
1621             return false;
1622         }
1623
1624         final QName nodeName = node.getQName();
1625         if (nodeName == null) {
1626             return false;
1627         }
1628
1629         final TypeDefinition<?> typeDef = node.getType();
1630         final Module parentModule = findParentModule(schemaContext, node);
1631
1632         Type returnType = null;
1633         if (typeDef.getBaseType() == null) {
1634             if (typeDef instanceof EnumTypeDefinition) {
1635                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1636                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1637                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1638                     typeBuilder,module);
1639                 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1640                 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1641             } else if (typeDef instanceof UnionTypeDefinition) {
1642                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1643                 if (genTOBuilder != null) {
1644                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1645                 }
1646             } else if (typeDef instanceof BitsTypeDefinition) {
1647                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1648                 returnType = genTOBuilder.toInstance();
1649             } else {
1650                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1651                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1652             }
1653         } else {
1654             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1655             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1656         }
1657
1658         final ParameterizedType listType = Types.listTypeFor(returnType);
1659         constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType);
1660         return true;
1661     }
1662
1663     private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1664             final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1665         final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1666                 genTOBuilder.getName());
1667         final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1668
1669         returnType.setDescription(typedefDescription);
1670         returnType.setReference(typeDef.getReference());
1671         returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1672         returnType.setModuleName(parentModule.getName());
1673
1674         genTOBuilder.setTypedef(true);
1675         genTOBuilder.setIsUnion(true);
1676         TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1677
1678
1679
1680         final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1681
1682
1683         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1684         method.setReturnType(returnType);
1685         method.addParameter(Types.STRING, "defaultValue");
1686         method.setAccessModifier(AccessModifier.PUBLIC);
1687         method.setStatic(true);
1688
1689         final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1690         if (types == null) {
1691             ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1692                     Sets.<Type> newHashSet(unionBuilder.toInstance()));
1693         } else {
1694             types.add(unionBuilder.toInstance());
1695         }
1696         return returnType.toInstance();
1697     }
1698
1699     private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1700         final String outerCls = Types.getOuterClassName(genTOBuilder);
1701         final StringBuilder name;
1702         if (outerCls != null) {
1703             name = new StringBuilder(outerCls);
1704         } else {
1705             name = new StringBuilder();
1706         }
1707         name.append(genTOBuilder.getName());
1708         name.append("Builder");
1709         final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1710         unionBuilder.setIsUnionBuilder(true);
1711         return unionBuilder;
1712     }
1713
1714     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1715             final Module module) {
1716         return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1717     }
1718
1719     /**
1720      * Instantiates generated type builder with <code>packageName</code> and
1721      * <code>schemaNode</code>.
1722      *
1723      * The new builder always implements
1724      * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1725      * If <code>schemaNode</code> is instance of GroupingDefinition it also
1726      * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1727      * Augmentable}.<br>
1728      * If <code>schemaNode</code> is instance of
1729      * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1730      * DataNodeContainer} it can also implement nodes which are specified in
1731      * <i>uses</i>.
1732      *
1733      * @param packageName
1734      *            string with the name of the package to which
1735      *            <code>schemaNode</code> belongs.
1736      * @param schemaNode
1737      *            schema node for which is created generated type builder
1738      * @param parent
1739      *            parent type (can be null)
1740      * @return generated type builder <code>schemaNode</code>
1741      */
1742     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1743             final Type parent, final Module module) {
1744         final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1745         if (parent == null) {
1746             it.addImplementsType(DATA_OBJECT);
1747         } else {
1748             it.addImplementsType(BindingTypes.childOf(parent));
1749         }
1750         if (!(schemaNode instanceof GroupingDefinition)) {
1751             it.addImplementsType(augmentable(it));
1752         }
1753
1754         if (schemaNode instanceof DataNodeContainer) {
1755             groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1756             addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1757         }
1758
1759         return it;
1760     }
1761
1762     /**
1763      * Wraps the calling of the same overloaded method.
1764      *
1765      * @param packageName
1766      *            string with the package name to which returning generated type
1767      *            builder belongs
1768      * @param schemaNode
1769      *            schema node which provide data about the schema node name
1770      * @return generated type builder for <code>schemaNode</code>
1771      */
1772     private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1773         return addRawInterfaceDefinition(packageName, schemaNode, "");
1774     }
1775
1776     /**
1777      * Returns reference to generated type builder for specified
1778      * <code>schemaNode</code> with <code>packageName</code>.
1779      *
1780      * Firstly the generated type builder is searched in
1781      * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1782      * found it is created and added to <code>genTypeBuilders</code>.
1783      *
1784      * @param packageName
1785      *            string with the package name to which returning generated type
1786      *            builder belongs
1787      * @param schemaNode
1788      *            schema node which provide data about the schema node name
1789      * @param prefix
1790      *            return type name prefix
1791      * @return generated type builder for <code>schemaNode</code>
1792      * @throws IllegalArgumentException
1793      *             <ul>
1794      *             <li>if <code>schemaNode</code> is null</li>
1795      *             <li>if <code>packageName</code> is null</li>
1796      *             <li>if QName of schema node is null</li>
1797      *             <li>if schemaNode name is null</li>
1798      *             </ul>
1799      *
1800      */
1801     private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1802             final String prefix) {
1803         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1804         checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1805         checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1806         final String schemaNodeName = schemaNode.getQName().getLocalName();
1807         checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1808
1809         String genTypeName;
1810         if (prefix == null) {
1811             genTypeName = BindingMapping.getClassName(schemaNodeName);
1812         } else {
1813             genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1814         }
1815
1816         // FIXME: Validation of name conflict
1817         final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1818         final Module module = findParentModule(schemaContext, schemaNode);
1819         qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1820         newType.addComment(schemaNode.getDescription());
1821         newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1822         newType.setReference(schemaNode.getReference());
1823         newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1824         newType.setModuleName(module.getName());
1825
1826         if (!genTypeBuilders.containsKey(packageName)) {
1827             final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1828             builders.put(genTypeName, newType);
1829             genTypeBuilders.put(packageName, builders);
1830         } else {
1831             final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1832             if (!builders.containsKey(genTypeName)) {
1833                 builders.put(genTypeName, newType);
1834             }
1835         }
1836         return newType;
1837     }
1838
1839     /**
1840      * Creates the name of the getter method name from <code>localName</code>.
1841      *
1842      * @param localName
1843      *            string with the name of the getter method
1844      * @param returnType
1845      *            return type
1846      * @return string with the name of the getter method for
1847      *         <code>methodName</code> in JAVA method format
1848      */
1849     public static String getterMethodName(final String localName, final Type returnType) {
1850         final StringBuilder method = new StringBuilder();
1851         if (BOOLEAN.equals(returnType)) {
1852             method.append("is");
1853         } else {
1854             method.append("get");
1855         }
1856         final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1857         method.append(name);
1858         return method.toString();
1859     }
1860
1861     /**
1862      * Created a method signature builder as part of
1863      * <code>interfaceBuilder</code>.
1864      *
1865      * The method signature builder is created for the getter method of
1866      * <code>schemaNodeName</code>. Also <code>comment</code> and
1867      * <code>returnType</code> information are added to the builder.
1868      *
1869      * @param interfaceBuilder
1870      *            generated type builder for which the getter method should be
1871      *            created
1872      * @param schemaNodeName
1873      *            string with schema node name. The name will be the part of the
1874      *            getter method name.
1875      * @param comment
1876      *            string with comment for the getter method
1877      * @param returnType
1878      *            type which represents the return type of the getter method
1879      * @return method signature builder which represents the getter method of
1880      *         <code>interfaceBuilder</code>
1881      */
1882     private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1883             final String schemaNodeName, final String comment, final Type returnType) {
1884         final MethodSignatureBuilder getMethod = interfaceBuilder
1885                 .addMethod(getterMethodName(schemaNodeName, returnType));
1886         getMethod.setComment(encodeAngleBrackets(comment));
1887         getMethod.setReturnType(returnType);
1888         return getMethod;
1889     }
1890
1891     /**
1892      * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1893      * or to <code>genTOBuilder</code> as property.
1894      *
1895      * @param basePackageName
1896      *            string contains the module package name
1897      * @param schemaNode
1898      *            data schema node which should be added as getter method to
1899      *            <code>typeBuilder</code> or as a property to
1900      *            <code>genTOBuilder</code> if is part of the list key
1901      * @param typeBuilder
1902      *            generated type builder for the list schema node
1903      * @param genTOBuilder
1904      *            generated TO builder for the list keys
1905      * @param listKeys
1906      *            list of string which contains names of the list keys
1907      * @param module
1908      *            current module
1909      * @throws IllegalArgumentException
1910      *             <ul>
1911      *             <li>if <code>schemaNode</code> equals null</li>
1912      *             <li>if <code>typeBuilder</code> equals null</li>
1913      *             </ul>
1914      */
1915     private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1916             final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1917             final Module module) {
1918         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1919         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1920
1921         if (schemaNode instanceof LeafSchemaNode) {
1922             final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1923             final String leafName = leaf.getQName().getLocalName();
1924             final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1925             if (listKeys.contains(leafName)) {
1926                 if (type == null) {
1927                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1928                 } else {
1929                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1930                 }
1931             }
1932         } else if (!schemaNode.isAddedByUses()) {
1933             if (schemaNode instanceof LeafListSchemaNode) {
1934                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1935             } else if (schemaNode instanceof ContainerSchemaNode) {
1936                 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1937             } else if (schemaNode instanceof ChoiceSchemaNode) {
1938                 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1939             } else if (schemaNode instanceof ListSchemaNode) {
1940                 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1941             }
1942         }
1943     }
1944
1945     private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1946             final GeneratedTOBuilder genTOBuilder) {
1947         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1948
1949         if (genTOBuilder != null) {
1950             final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1951             constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
1952             genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1953         }
1954     }
1955
1956     /**
1957      * Selects the names of the list keys from <code>list</code> and returns
1958      * them as the list of the strings
1959      *
1960      * @param list
1961      *            of string with names of the list keys
1962      * @return list of string which represents names of the list keys. If the
1963      *         <code>list</code> contains no keys then the empty list is
1964      *         returned.
1965      */
1966     private static List<String> listKeys(final ListSchemaNode list) {
1967         final List<String> listKeys = new ArrayList<>();
1968
1969         final List<QName> keyDefinition = list.getKeyDefinition();
1970         if (keyDefinition != null) {
1971             for (final QName keyDef : keyDefinition) {
1972                 listKeys.add(keyDef.getLocalName());
1973             }
1974         }
1975         return listKeys;
1976     }
1977
1978     /**
1979      * Generates for the <code>list</code> which contains any list keys special
1980      * generated TO builder.
1981      *
1982      * @param packageName
1983      *            string with package name to which the list belongs
1984      * @param list
1985      *            list schema node which is source of data about the list name
1986      * @return generated TO builder which represents the keys of the
1987      *         <code>list</code> or null if <code>list</code> is null or list of
1988      *         key definitions is null or empty.
1989      */
1990     private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
1991         GeneratedTOBuilder genTOBuilder = null;
1992         if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
1993             final String listName = list.getQName().getLocalName() + "Key";
1994             final String genTOName = BindingMapping.getClassName(listName);
1995             genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
1996         }
1997         return genTOBuilder;
1998     }
1999
2000     /**
2001      * Builds generated TO builders for <code>typeDef</code> of type
2002      * {@link org.opendaylight.yangtools.yang.model.util.UnionType UnionType} or
2003      * {@link org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
2004      * BitsTypeDefinition} which are also added to <code>typeBuilder</code> as
2005      * enclosing transfer object.
2006      *
2007      * If more then one generated TO builder is created for enclosing then all
2008      * of the generated TO builders are added to <code>typeBuilder</code> as
2009      * enclosing transfer objects.
2010      *
2011      * @param typeDef
2012      *            type definition which can be of type <code>UnionType</code> or
2013      *            <code>BitsTypeDefinition</code>
2014      * @param typeBuilder
2015      *            generated type builder to which is added generated TO created
2016      *            from <code>typeDef</code>
2017      * @param leafName
2018      *            string with name for generated TO builder
2019      * @param leaf
2020      * @return generated TO builder for <code>typeDef</code>
2021      */
2022     private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2023             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2024         final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2025         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2026         final String packageName = typeBuilder.getFullyQualifiedName();
2027         if (typeDef instanceof UnionTypeDefinition) {
2028             final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2029                     .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2030                             classNameFromLeaf, leaf);
2031             genTOBuilders.addAll(types);
2032
2033             GeneratedTOBuilder resultTOBuilder = null;
2034             if (types.isEmpty()) {
2035                 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2036             }
2037             resultTOBuilder = types.remove(0);
2038             for (final GeneratedTOBuilder genTOBuilder : types) {
2039                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2040             }
2041
2042             final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2043             genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2044             resultTOBuilder.addEqualsIdentity(genPropBuilder);
2045             resultTOBuilder.addHashIdentity(genPropBuilder);
2046             resultTOBuilder.addToStringProperty(genPropBuilder);
2047
2048         } else if (typeDef instanceof BitsTypeDefinition) {
2049             genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2050                     packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2051         }
2052         if (!genTOBuilders.isEmpty()) {
2053             for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2054                 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2055             }
2056             return genTOBuilders.get(0);
2057         }
2058         return null;
2059
2060     }
2061
2062     /**
2063      * Adds the implemented types to type builder.
2064      *
2065      * The method passes through the list of <i>uses</i> in
2066      * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2067      * generated type from {@link BindingGeneratorImpl#allGroupings
2068      * allGroupings} which is added as <i>implements type</i> to
2069      * <code>builder</code>
2070      *
2071      * @param dataNodeContainer
2072      *            element which contains the list of used YANG groupings
2073      * @param builder
2074      *            builder to which are added implemented types according to
2075      *            <code>dataNodeContainer</code>
2076      * @return generated type builder with all implemented types
2077      */
2078     private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2079             final GeneratedTypeBuilder builder) {
2080         for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2081             if (usesNode.getGroupingPath() != null) {
2082                 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2083                 if (genType == null) {
2084                     throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2085                             + builder.getName());
2086                 }
2087
2088                 builder.addImplementsType(genType);
2089                 /*
2090                 builder.addComment(genType.getDescription());
2091                 builder.setDescription(genType.getDescription());
2092                 builder.setModuleName(genType.getModuleName());
2093                 builder.setReference(genType.getReference());
2094                 builder.setSchemaPath(genType.getSchemaPath());
2095                 */
2096             }
2097         }
2098         return builder;
2099     }
2100
2101     private static boolean isNullOrEmpty(final Collection<?> list) {
2102         return list == null || list.isEmpty();
2103     }
2104
2105     private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName, final String moduleSourcePath) {
2106         final StringBuilder sb = new StringBuilder();
2107
2108         if (!isNullOrEmpty(schemaNodes)) {
2109             final SchemaNode node = schemaNodes.iterator().next();
2110
2111             if (node instanceof RpcDefinition) {
2112                 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2113             } else if (node instanceof NotificationDefinition) {
2114                 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2115             }
2116         }
2117         sb.append(NEW_LINE);
2118         sb.append("<br>(Source path: <i>");
2119         sb.append(moduleSourcePath);
2120         sb.append("</i>):");
2121         sb.append(NEW_LINE);
2122
2123         if (verboseClassComments) {
2124             sb.append("<pre>");
2125             sb.append(NEW_LINE);
2126             sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2127             sb.append("</pre>");
2128             sb.append(NEW_LINE);
2129         }
2130
2131         return replaceAllIllegalChars(sb);
2132     }
2133
2134     private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2135         final StringBuilder sb = new StringBuilder();
2136         final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2137         final String formattedDescription = YangTemplate.formatToParagraph(nodeDescription, 0);
2138
2139         if (!Strings.isNullOrEmpty(formattedDescription)) {
2140             sb.append(formattedDescription);
2141             sb.append(NEW_LINE);
2142         }
2143
2144         if (verboseClassComments) {
2145             final Module module = findParentModule(schemaContext, schemaNode);
2146             final StringBuilder linkToBuilderClass = new StringBuilder();
2147             final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2148             final String className = namespace[namespace.length - 1];
2149
2150             if (hasBuilderClass(schemaNode)) {
2151                 linkToBuilderClass.append(className);
2152                 linkToBuilderClass.append("Builder");
2153             }
2154
2155             sb.append("<p>");
2156             sb.append("This class represents the following YANG schema fragment defined in module <b>");
2157             sb.append(module.getName());
2158             sb.append("</b>");
2159             sb.append(NEW_LINE);
2160             sb.append("<br>(Source path: <i>");
2161             sb.append(module.getModuleSourcePath());
2162             sb.append("</i>):");
2163             sb.append(NEW_LINE);
2164             sb.append("<pre>");
2165             sb.append(NEW_LINE);
2166             sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2167             sb.append("</pre>");
2168             sb.append(NEW_LINE);
2169             sb.append("The schema path to identify an instance is");
2170             sb.append(NEW_LINE);
2171             sb.append("<i>");
2172             sb.append(YangTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2173             sb.append("</i>");
2174             sb.append(NEW_LINE);
2175
2176             if (hasBuilderClass(schemaNode)) {
2177                 sb.append(NEW_LINE);
2178                 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2179                 sb.append(NEW_LINE);
2180                 sb.append("@see ");
2181                 sb.append(linkToBuilderClass);
2182                 sb.append(NEW_LINE);
2183                 if (schemaNode instanceof ListSchemaNode) {
2184                     final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2185                     if (keyDef != null && !keyDef.isEmpty()) {
2186                         sb.append("@see ");
2187                         sb.append(className);
2188                         sb.append("Key");
2189                     }
2190                     sb.append(NEW_LINE);
2191                 }
2192             }
2193         }
2194
2195         return replaceAllIllegalChars(sb);
2196     }
2197
2198     private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2199         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2200                 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2201             return true;
2202         }
2203         return false;
2204     }
2205
2206     private String createDescription(final Module module) {
2207         final StringBuilder sb = new StringBuilder();
2208         final String moduleDescription = encodeAngleBrackets(module.getDescription());
2209         final String formattedDescription = YangTemplate.formatToParagraph(moduleDescription, 0);
2210
2211         if (!Strings.isNullOrEmpty(formattedDescription)) {
2212             sb.append(formattedDescription);
2213             sb.append(NEW_LINE);
2214         }
2215
2216         if (verboseClassComments) {
2217             sb.append("<p>");
2218             sb.append("This class represents the following YANG schema fragment defined in module <b>");
2219             sb.append(module.getName());
2220             sb.append("</b>");
2221             sb.append(NEW_LINE);
2222             sb.append("<br>Source path: <i>");
2223             sb.append(module.getModuleSourcePath());
2224             sb.append("</i>):");
2225             sb.append(NEW_LINE);
2226             sb.append("<pre>");
2227             sb.append(NEW_LINE);
2228             sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2229             sb.append("</pre>");
2230         }
2231
2232         return replaceAllIllegalChars(sb);
2233     }
2234
2235     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2236         for (final ModuleContext ctx : genCtx.values()) {
2237             final GeneratedTypeBuilder result = ctx.getChildNode(path);
2238             if (result != null) {
2239                 return result;
2240             }
2241         }
2242         return null;
2243     }
2244
2245     private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2246         for (final ModuleContext ctx : genCtx.values()) {
2247             final GeneratedTypeBuilder result = ctx.getGrouping(path);
2248             if (result != null) {
2249                 return result;
2250             }
2251         }
2252         return null;
2253     }
2254
2255     private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2256         for (final ModuleContext ctx : genCtx.values()) {
2257             final GeneratedTypeBuilder result = ctx.getCase(path);
2258             if (result != null) {
2259                 return result;
2260             }
2261         }
2262         return null;
2263     }
2264
2265     public Map<Module, ModuleContext> getModuleContexts() {
2266         return genCtx;
2267     }
2268
2269     @VisibleForTesting
2270     static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2271         final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2272         return ret.isEmpty() ? "" : ret;
2273     }
2274
2275     private void annotateDeprecatedIfNecessary(Status status, GeneratedTypeBuilder builder) {
2276         if (status == Status.DEPRECATED) {
2277             builder.addAnnotation("", "Deprecated");
2278         }
2279     }
2280 }