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