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