8ae66d0d0b6ccb1090f5b222ee5592c2650190f7
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / generator / impl / BindingGeneratorImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkNotNull;
12 import static com.google.common.base.Preconditions.checkState;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.computeDefaultSUID;
14 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
15 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForAugmentedGeneratedType;
16 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
17 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_OBJECT;
18 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.DATA_ROOT;
19 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIABLE;
20 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.IDENTIFIER;
21 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.NOTIFICATION;
22 import static org.opendaylight.yangtools.binding.generator.util.BindingTypes.augmentable;
23 import static org.opendaylight.yangtools.binding.generator.util.Types.BOOLEAN;
24 import static org.opendaylight.yangtools.binding.generator.util.Types.FUTURE;
25 import static org.opendaylight.yangtools.binding.generator.util.Types.VOID;
26 import static org.opendaylight.yangtools.binding.generator.util.Types.typeForClass;
27 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
28 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
29 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
30
31 import com.google.common.annotations.VisibleForTesting;
32 import com.google.common.base.Optional;
33 import com.google.common.base.Preconditions;
34 import com.google.common.base.Splitter;
35 import com.google.common.base.Strings;
36 import com.google.common.collect.Iterables;
37 import com.google.common.collect.Sets;
38 import java.util.ArrayList;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.Comparator;
42 import java.util.HashMap;
43 import java.util.Iterator;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47 import java.util.regex.Pattern;
48 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
49 import org.opendaylight.yangtools.binding.generator.util.BindingTypes;
50 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
51 import org.opendaylight.yangtools.binding.generator.util.Types;
52 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
53 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
54 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTypeBuilderImpl;
55 import org.opendaylight.yangtools.sal.binding.generator.api.BindingGenerator;
56 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
57 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
58 import org.opendaylight.yangtools.sal.binding.model.api.Constant;
59 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
60 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
61 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
62 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
63 import org.opendaylight.yangtools.sal.binding.model.api.Type;
64 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
65 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
66 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
67 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
68 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
69 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
70 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
71 import org.opendaylight.yangtools.sal.binding.yang.types.GroupingDefinitionDependencySort;
72 import org.opendaylight.yangtools.sal.binding.yang.types.TypeProviderImpl;
73 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
74 import org.opendaylight.yangtools.yang.binding.BindingMapping;
75 import org.opendaylight.yangtools.yang.binding.DataContainer;
76 import org.opendaylight.yangtools.yang.binding.RpcService;
77 import org.opendaylight.yangtools.yang.binding.annotations.RoutingContext;
78 import org.opendaylight.yangtools.yang.common.QName;
79 import org.opendaylight.yangtools.yang.common.RpcResult;
80 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
81 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
82 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
83 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
84 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
85 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
86 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
87 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
88 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
89 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
90 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
91 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
92 import org.opendaylight.yangtools.yang.model.api.Module;
93 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
94 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
95 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
96 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
97 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
98 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
99 import org.opendaylight.yangtools.yang.model.api.Status;
100 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
101 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
102 import org.opendaylight.yangtools.yang.model.api.UsesNode;
103 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
104 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
105 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
106 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
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             if (result instanceof DataNodeContainer) {
917                 final QName resultNode = QName.create(result.getQName().getModule(), node.getLocalName());
918                 result = ((DataNodeContainer) result).getDataChildByName(resultNode);
919             } else if (result instanceof ChoiceSchemaNode) {
920                 result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
921             }
922         }
923         if (result == null) {
924             return null;
925         }
926
927         if (result instanceof DerivableSchemaNode) {
928             DerivableSchemaNode castedResult = (DerivableSchemaNode) result;
929             Optional<? extends SchemaNode> originalNode = castedResult
930                     .getOriginal();
931             if (castedResult.isAddedByUses() && originalNode.isPresent()) {
932                 result = originalNode.get();
933             }
934         }
935
936         if (result instanceof DataSchemaNode) {
937             DataSchemaNode resultDataSchemaNode = (DataSchemaNode) result;
938             if (resultDataSchemaNode.isAddedByUses()) {
939                 // The original node is required, but we have only the copy of
940                 // the original node.
941                 // Maybe this indicates a bug in Yang parser.
942                 throw new IllegalStateException(
943                         "Failed to generate code for augment in "
944                                 + parentUsesNode);
945             } else {
946                 return resultDataSchemaNode;
947             }
948         } else {
949             throw new IllegalStateException(
950                     "Target node of uses-augment statement must be DataSchemaNode. Failed to generate code for augment in "
951                             + parentUsesNode);
952         }
953     }
954
955     /**
956      * Returns a generated type builder for an augmentation.
957      *
958      * The name of the type builder is equal to the name of augmented node with
959      * serial number as suffix.
960      *
961      * @param module
962      *            current module
963      * @param augmentPackageName
964      *            string with contains the package name to which the augment
965      *            belongs
966      * @param basePackageName
967      *            string with the package name to which the augmented node
968      *            belongs
969      * @param targetTypeRef
970      *            target type
971      * @param augSchema
972      *            augmentation schema which contains data about the child nodes
973      *            and uses of augment
974      * @return generated type builder for augment
975      */
976     private GeneratedTypeBuilder addRawAugmentGenTypeDefinition(final Module module, final String augmentPackageName,
977             final String basePackageName, final Type targetTypeRef, final AugmentationSchema augSchema) {
978         Map<String, GeneratedTypeBuilder> augmentBuilders = genTypeBuilders.get(augmentPackageName);
979         if (augmentBuilders == null) {
980             augmentBuilders = new HashMap<>();
981             genTypeBuilders.put(augmentPackageName, augmentBuilders);
982         }
983         final String augIdentifier = getAugmentIdentifier(augSchema.getUnknownSchemaNodes());
984
985         String augTypeName;
986         if (augIdentifier != null) {
987             augTypeName = BindingMapping.getClassName(augIdentifier);
988         } else {
989             augTypeName = augGenTypeName(augmentBuilders, targetTypeRef.getName());
990         }
991
992         final GeneratedTypeBuilder augTypeBuilder = new GeneratedTypeBuilderImpl(augmentPackageName, augTypeName);
993
994         augTypeBuilder.addImplementsType(DATA_OBJECT);
995         augTypeBuilder.addImplementsType(Types.augmentationTypeFor(targetTypeRef));
996         annotateDeprecatedIfNecessary(augSchema.getStatus(), augTypeBuilder);
997         addImplementedInterfaceFromUses(augSchema, augTypeBuilder);
998
999         augSchemaNodeToMethods(module, basePackageName, augTypeBuilder, augTypeBuilder, augSchema.getChildNodes());
1000         augmentBuilders.put(augTypeName, augTypeBuilder);
1001
1002         if (!augSchema.getChildNodes().isEmpty()) {
1003             genCtx.get(module).addTypeToAugmentation(augTypeBuilder, augSchema);
1004
1005         }
1006         genCtx.get(module).addAugmentType(augTypeBuilder);
1007         return augTypeBuilder;
1008     }
1009
1010     /**
1011      *
1012      * @param unknownSchemaNodes
1013      * @return nodeParameter of UnknownSchemaNode
1014      */
1015     private static String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
1016         for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
1017             final QName nodeType = unknownSchemaNode.getNodeType();
1018             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
1019                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
1020                 return unknownSchemaNode.getNodeParameter();
1021             }
1022         }
1023         return null;
1024     }
1025
1026     /**
1027      * Returns first unique name for the augment generated type builder. The
1028      * generated type builder name for augment consists from name of augmented
1029      * node and serial number of its augmentation.
1030      *
1031      * @param builders
1032      *            map of builders which were created in the package to which the
1033      *            augmentation belongs
1034      * @param genTypeName
1035      *            string with name of augmented node
1036      * @return string with unique name for augmentation builder
1037      */
1038     private static String augGenTypeName(final Map<String, GeneratedTypeBuilder> builders, final String genTypeName) {
1039         int index = 1;
1040         if (builders != null) {
1041             while (builders.containsKey(genTypeName + index)) {
1042                 index = index + 1;
1043             }
1044         }
1045         return genTypeName + index;
1046     }
1047
1048     /**
1049      * Adds the methods to <code>typeBuilder</code> which represent subnodes of
1050      * node for which <code>typeBuilder</code> was created.
1051      *
1052      * The subnodes aren't mapped to the methods if they are part of grouping or
1053      * augment (in this case are already part of them).
1054      *
1055      * @param module
1056      *            current module
1057      * @param basePackageName
1058      *            string contains the module package name
1059      * @param parent
1060      *            generated type builder which represents any node. The subnodes
1061      *            of this node are added to the <code>typeBuilder</code> as
1062      *            methods. The subnode can be of type leaf, leaf-list, list,
1063      *            container, choice.
1064      * @param childOf
1065      *            parent type
1066      * @param schemaNodes
1067      *            set of data schema nodes which are the children of the node
1068      *            for which <code>typeBuilder</code> was created
1069      * @return generated type builder which is the same builder as input
1070      *         parameter. The getter methods (representing child nodes) could be
1071      *         added to it.
1072      */
1073     private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
1074             final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
1075         if (schemaNodes != null && parent != null) {
1076             for (final DataSchemaNode schemaNode : schemaNodes) {
1077                 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
1078                     addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
1079                 }
1080             }
1081         }
1082         return parent;
1083     }
1084
1085     /**
1086      * Adds the methods to <code>typeBuilder</code> what represents subnodes of
1087      * node for which <code>typeBuilder</code> was created.
1088      *
1089      * @param module
1090      *            current module
1091      * @param basePackageName
1092      *            string contains the module package name
1093      * @param typeBuilder
1094      *            generated type builder which represents any node. The subnodes
1095      *            of this node are added to the <code>typeBuilder</code> as
1096      *            methods. The subnode can be of type leaf, leaf-list, list,
1097      *            container, choice.
1098      * @param childOf
1099      *            parent type
1100      * @param schemaNodes
1101      *            set of data schema nodes which are the children of the node
1102      *            for which <code>typeBuilder</code> was created
1103      * @return generated type builder which is the same object as the input
1104      *         parameter <code>typeBuilder</code>. The getter method could be
1105      *         added to it.
1106      */
1107     private GeneratedTypeBuilder augSchemaNodeToMethods(final Module module, final String basePackageName,
1108             final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
1109             final Iterable<DataSchemaNode> schemaNodes) {
1110         if ((schemaNodes != null) && (typeBuilder != null)) {
1111             for (final DataSchemaNode schemaNode : schemaNodes) {
1112                 if (!schemaNode.isAugmenting()) {
1113                     addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
1114                 }
1115             }
1116         }
1117         return typeBuilder;
1118     }
1119
1120     /**
1121      * Adds to <code>typeBuilder</code> a method which is derived from
1122      * <code>schemaNode</code>.
1123      *
1124      * @param basePackageName
1125      *            string with the module package name
1126      * @param node
1127      *            data schema node which is added to <code>typeBuilder</code> as
1128      *            a method
1129      * @param typeBuilder
1130      *            generated type builder to which is <code>schemaNode</code>
1131      *            added as a method.
1132      * @param childOf
1133      *            parent type
1134      * @param module
1135      *            current module
1136      */
1137     private void addSchemaNodeToBuilderAsMethod(final String basePackageName, final DataSchemaNode node,
1138             final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
1139         if (node != null && typeBuilder != null) {
1140             if (node instanceof LeafSchemaNode) {
1141                 resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
1142             } else if (node instanceof LeafListSchemaNode) {
1143                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
1144             } else if (node instanceof ContainerSchemaNode) {
1145                 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
1146             } else if (node instanceof ListSchemaNode) {
1147                 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
1148             } else if (node instanceof ChoiceSchemaNode) {
1149                 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
1150             } else {
1151                 // TODO: anyxml not yet supported
1152                 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
1153                         typeBuilder.getFullyQualifiedName());
1154             }
1155         }
1156     }
1157
1158     /**
1159      * Converts <code>choiceNode</code> to the list of generated types for
1160      * choice and its cases.
1161      *
1162      * The package names for choice and for its cases are created as
1163      * concatenation of the module package (<code>basePackageName</code>) and
1164      * names of all parents node.
1165      *
1166      * @param module
1167      *            current module
1168      * @param basePackageName
1169      *            string with the module package name
1170      * @param parent
1171      *            parent type
1172      * @param choiceNode
1173      *            choice node which is mapped to generated type. Also child
1174      *            nodes - cases are mapped to generated types.
1175      * @throws IllegalArgumentException
1176      *             <ul>
1177      *             <li>if <code>basePackageName</code> is null</li>
1178      *             <li>if <code>choiceNode</code> is null</li>
1179      *             </ul>
1180      */
1181     private void choiceToGeneratedType(final Module module, final String basePackageName,
1182             final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
1183         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1184         checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
1185
1186         if (!choiceNode.isAddedByUses()) {
1187             final String packageName = packageNameForGeneratedType(basePackageName, choiceNode.getPath());
1188             final GeneratedTypeBuilder choiceTypeBuilder = addRawInterfaceDefinition(packageName, choiceNode);
1189             constructGetter(parent, choiceNode.getQName().getLocalName(),
1190                     choiceNode.getDescription(), choiceTypeBuilder, choiceNode.getStatus());
1191             choiceTypeBuilder.addImplementsType(typeForClass(DataContainer.class));
1192             annotateDeprecatedIfNecessary(choiceNode.getStatus(), choiceTypeBuilder);
1193             genCtx.get(module).addChildNodeType(choiceNode, choiceTypeBuilder);
1194             generateTypesFromChoiceCases(module, basePackageName, choiceTypeBuilder.toInstance(), choiceNode);
1195         }
1196     }
1197
1198     /**
1199      * Converts <code>caseNodes</code> set to list of corresponding generated
1200      * types.
1201      *
1202      * For every <i>case</i> which isn't added through augment or <i>uses</i> is
1203      * created generated type builder. The package names for the builder is
1204      * created as concatenation of the module package (
1205      * <code>basePackageName</code>) and names of all parents nodes of the
1206      * concrete <i>case</i>. There is also relation "<i>implements type</i>"
1207      * between every case builder and <i>choice</i> type
1208      *
1209      * @param module
1210      *            current module
1211      * @param basePackageName
1212      *            string with the module package name
1213      * @param refChoiceType
1214      *            type which represents superior <i>case</i>
1215      * @param choiceNode
1216      *            choice case node which is mapped to generated type
1217      * @return list of generated types for <code>caseNodes</code>.
1218      * @throws IllegalArgumentException
1219      *             <ul>
1220      *             <li>if <code>basePackageName</code> equals null</li>
1221      *             <li>if <code>refChoiceType</code> equals null</li>
1222      *             <li>if <code>caseNodes</code> equals null</li>
1223      *             </ul>
1224      */
1225     private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
1226             final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
1227         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1228         checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
1229         checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
1230
1231         final Set<ChoiceCaseNode> caseNodes = choiceNode.getCases();
1232         if (caseNodes == null) {
1233             return;
1234         }
1235
1236         for (final ChoiceCaseNode caseNode : caseNodes) {
1237             if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
1238                 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1239                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1240                 caseTypeBuilder.addImplementsType(refChoiceType);
1241                 annotateDeprecatedIfNecessary(caseNode.getStatus(), caseTypeBuilder);
1242                 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1243                 genCtx.get(module).addChoiceToCaseMapping(refChoiceType, caseTypeBuilder, caseNode);
1244                 final Iterable<DataSchemaNode> caseChildNodes = caseNode.getChildNodes();
1245                 if (caseChildNodes != null) {
1246                     final SchemaPath choiceNodeParentPath = choiceNode.getPath().getParent();
1247
1248                     if (!Iterables.isEmpty(choiceNodeParentPath.getPathFromRoot())) {
1249                         SchemaNode parent = findDataSchemaNode(schemaContext, choiceNodeParentPath);
1250
1251                         if (parent instanceof AugmentationSchema) {
1252                             final AugmentationSchema augSchema = (AugmentationSchema) parent;
1253                             final SchemaPath targetPath = augSchema.getTargetPath();
1254                             SchemaNode targetSchemaNode = findDataSchemaNode(schemaContext, targetPath);
1255                             if (targetSchemaNode instanceof DataSchemaNode
1256                                     && ((DataSchemaNode) targetSchemaNode).isAddedByUses()) {
1257                                 if (targetSchemaNode instanceof DerivableSchemaNode) {
1258                                     targetSchemaNode = ((DerivableSchemaNode) targetSchemaNode).getOriginal().orNull();
1259                                 }
1260                                 if (targetSchemaNode == null) {
1261                                     throw new IllegalStateException(
1262                                             "Failed to find target node from grouping for augmentation " + augSchema
1263                                                     + " in module " + module.getName());
1264                                 }
1265                             }
1266                             parent = targetSchemaNode;
1267                         }
1268
1269                         Preconditions.checkState(parent != null, "Could not find Choice node parent %s",
1270                                 choiceNodeParentPath);
1271                         GeneratedTypeBuilder childOfType = findChildNodeByPath(parent.getPath());
1272                         if (childOfType == null) {
1273                             childOfType = findGroupingByPath(parent.getPath());
1274                         }
1275                         resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, caseChildNodes);
1276                     } else {
1277                         resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, moduleToDataType(module),
1278                                 caseChildNodes);
1279                     }
1280                }
1281             }
1282             processUsesAugments(caseNode, module);
1283         }
1284     }
1285
1286     /**
1287      * Generates list of generated types for all the cases of a choice which are
1288      * added to the choice through the augment.
1289      *
1290      * @param module
1291      *            current module
1292      * @param basePackageName
1293      *            string contains name of package to which augment belongs. If
1294      *            an augmented choice is from an other package (pcg1) than an
1295      *            augmenting choice (pcg2) then case's of the augmenting choice
1296      *            will belong to pcg2.
1297      * @param targetType
1298      *            Type which represents target choice
1299      * @param targetNode
1300      *            node which represents target choice
1301      * @param augmentedNodes
1302      *            set of choice case nodes for which is checked if are/aren't
1303      *            added to choice through augmentation
1304      * @return list of generated types which represents augmented cases of
1305      *         choice <code>refChoiceType</code>
1306      * @throws IllegalArgumentException
1307      *             <ul>
1308      *             <li>if <code>basePackageName</code> is null</li>
1309      *             <li>if <code>targetType</code> is null</li>
1310      *             <li>if <code>augmentedNodes</code> is null</li>
1311      *             </ul>
1312      */
1313     private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
1314             final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes,
1315             final DataNodeContainer usesNodeParent) {
1316         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
1317         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
1318         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
1319
1320         for (final DataSchemaNode caseNode : augmentedNodes) {
1321             if (caseNode != null) {
1322                 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
1323                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
1324                 caseTypeBuilder.addImplementsType(targetType);
1325
1326                 SchemaNode parent = null;
1327                 final SchemaPath nodeSp = targetNode.getPath();
1328                 parent = findDataSchemaNode(schemaContext, nodeSp.getParent());
1329
1330                 GeneratedTypeBuilder childOfType = null;
1331                 if (parent instanceof Module) {
1332                     childOfType = genCtx.get(parent).getModuleNode();
1333                 } else if (parent instanceof ChoiceCaseNode) {
1334                     childOfType = findCaseByPath(parent.getPath());
1335                 } else if (parent instanceof DataSchemaNode || parent instanceof NotificationDefinition) {
1336                     childOfType = findChildNodeByPath(parent.getPath());
1337                 } else if (parent instanceof GroupingDefinition) {
1338                     childOfType = findGroupingByPath(parent.getPath());
1339                 }
1340
1341                 if (childOfType == null) {
1342                     throw new IllegalArgumentException("Failed to find parent type of choice " + targetNode);
1343                 }
1344
1345                 ChoiceCaseNode node = null;
1346                 final String caseLocalName = caseNode.getQName().getLocalName();
1347                 if (caseNode instanceof ChoiceCaseNode) {
1348                     node = (ChoiceCaseNode) caseNode;
1349                 } else if (targetNode.getCaseNodeByName(caseLocalName) == null) {
1350                     final String targetNodeLocalName = targetNode.getQName().getLocalName();
1351                     for (DataSchemaNode dataSchemaNode : usesNodeParent.getChildNodes()) {
1352                         if (dataSchemaNode instanceof ChoiceSchemaNode && targetNodeLocalName.equals(dataSchemaNode.getQName
1353                                 ().getLocalName())) {
1354                             node = ((ChoiceSchemaNode) dataSchemaNode).getCaseNodeByName(caseLocalName);
1355                             break;
1356                         }
1357                     }
1358                 } else {
1359                     node = targetNode.getCaseNodeByName(caseLocalName);
1360                 }
1361                 final Iterable<DataSchemaNode> childNodes = node.getChildNodes();
1362                 if (childNodes != null) {
1363                     resolveDataSchemaNodes(module, basePackageName, caseTypeBuilder, childOfType, childNodes);
1364                 }
1365                 genCtx.get(module).addCaseType(caseNode.getPath(), caseTypeBuilder);
1366                 genCtx.get(module).addChoiceToCaseMapping(targetType, caseTypeBuilder, node);
1367             }
1368         }
1369     }
1370
1371     private static boolean isInnerType(final LeafSchemaNode leaf, final TypeDefinition<?> type) {
1372         // New parser with encapsulated type
1373         if (leaf.getPath().equals(type.getPath())) {
1374             return true;
1375         }
1376
1377         // Embedded type definition with new parser. Also takes care of the old parser with bits
1378         if (leaf.getPath().equals(type.getPath().getParent())) {
1379             return true;
1380         }
1381
1382         return false;
1383     }
1384
1385     /**
1386      * Converts <code>leaf</code> to the getter method which is added to
1387      * <code>typeBuilder</code>.
1388      *
1389      * @param typeBuilder
1390      *            generated type builder to which is added getter method as
1391      *            <code>leaf</code> mapping
1392      * @param leaf
1393      *            leaf schema node which is mapped as getter method which is
1394      *            added to <code>typeBuilder</code>
1395      * @param module
1396      *            Module in which type was defined
1397      * @return boolean value
1398      *         <ul>
1399      *         <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
1400      *         null</li>
1401      *         <li>true - in other cases</li>
1402      *         </ul>
1403      */
1404     private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, final Module module) {
1405         if (leaf == null || typeBuilder == null || leaf.isAddedByUses()) {
1406             return null;
1407         }
1408
1409         final String leafName = leaf.getQName().getLocalName();
1410         if (leafName == null) {
1411             return null;
1412         }
1413
1414         final Module parentModule = findParentModule(schemaContext, leaf);
1415         Type returnType = null;
1416
1417         final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1418         if (isInnerType(leaf, typeDef)) {
1419             if (typeDef instanceof EnumTypeDefinition) {
1420                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1421                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1422                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
1423                     typeBuilder, module);
1424                 if (enumBuilder != null) {
1425                     returnType = enumBuilder.toInstance(typeBuilder);
1426                 }
1427                 ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1428             } else if (typeDef instanceof UnionTypeDefinition) {
1429                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1430                 if (genTOBuilder != null) {
1431                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1432                 }
1433             } else if (typeDef instanceof BitsTypeDefinition) {
1434                 GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, leaf, parentModule);
1435                 if (genTOBuilder != null) {
1436                     returnType = genTOBuilder.toInstance();
1437                 }
1438             } else {
1439                 // It is constrained version of already declared type (inner declared type exists,
1440                 // onlyfor special cases (Enum, Union, Bits), which were already checked.
1441                 // In order to get proper class we need to look up closest derived type
1442                 // and apply restrictions from leaf type
1443                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1444                 returnType = typeProvider.javaTypeForSchemaDefinitionType(getBaseOrDeclaredType(typeDef), leaf,
1445                         restrictions);
1446             }
1447         } else {
1448             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1449             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf, restrictions);
1450         }
1451
1452         if (returnType == null) {
1453             return null;
1454         }
1455
1456         if (typeDef instanceof EnumTypeDefinition) {
1457             ((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
1458         }
1459
1460         String leafDesc = leaf.getDescription();
1461         if (leafDesc == null) {
1462             leafDesc = "";
1463         }
1464
1465         final MethodSignatureBuilder getter = constructGetter(typeBuilder, leafName, leafDesc, returnType, leaf.getStatus());
1466         processContextRefExtension(leaf, getter, parentModule);
1467         return returnType;
1468     }
1469
1470     private static TypeDefinition<?> getBaseOrDeclaredType(final TypeDefinition<?> typeDef) {
1471         // Returns DerivedType in case of new parser.
1472         final TypeDefinition<?> baseType = typeDef.getBaseType();
1473         return (baseType != null && baseType.getBaseType() != null) ? baseType : typeDef;
1474     }
1475
1476     private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
1477             final Module module) {
1478         for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
1479             final QName nodeType = node.getNodeType();
1480             if ("context-reference".equals(nodeType.getLocalName())) {
1481                 final String nodeParam = node.getNodeParameter();
1482                 IdentitySchemaNode identity = null;
1483                 String basePackageName = null;
1484                 final Iterable<String> splittedElement = COLON_SPLITTER.split(nodeParam);
1485                 final Iterator<String> iterator = splittedElement.iterator();
1486                 final int length = Iterables.size(splittedElement);
1487                 if (length == 1) {
1488                     identity = findIdentityByName(module.getIdentities(), iterator.next());
1489                     basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1490                 } else if (length == 2) {
1491                     final String prefix = iterator.next();
1492                     final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
1493                     if (dependentModule == null) {
1494                         throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
1495                                 + prefix);
1496                     }
1497                     identity = findIdentityByName(dependentModule.getIdentities(), iterator.next());
1498                     basePackageName = BindingMapping.getRootPackageName(dependentModule.getQNameModule());
1499                 } else {
1500                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1501                             + nodeParam);
1502                 }
1503                 if (identity == null) {
1504                     throw new IllegalArgumentException("Failed to process context-reference: unknown identity "
1505                             + nodeParam);
1506                 }
1507
1508                 final Class<RoutingContext> clazz = RoutingContext.class;
1509                 final AnnotationTypeBuilder rc = getter.addAnnotation(clazz.getPackage().getName(),
1510                         clazz.getSimpleName());
1511                 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
1512                 final String genTypeName = BindingMapping.getClassName(identity.getQName().getLocalName());
1513                 rc.addParameter("value", packageName + "." + genTypeName + ".class");
1514             }
1515         }
1516     }
1517
1518     private static IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
1519         for (final IdentitySchemaNode id : identities) {
1520             if (id.getQName().getLocalName().equals(name)) {
1521                 return id;
1522             }
1523         }
1524         return null;
1525     }
1526
1527     private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
1528         for (final ModuleImport imp : imports) {
1529             if (imp.getPrefix().equals(prefix)) {
1530                 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
1531             }
1532         }
1533         return null;
1534     }
1535
1536     private boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1537             final boolean isReadOnly, final Module module) {
1538         if ((leaf != null) && (toBuilder != null)) {
1539             String leafDesc = leaf.getDescription();
1540             if (leafDesc == null) {
1541                 leafDesc = "";
1542             }
1543             Type returnType = null;
1544             final TypeDefinition<?> typeDef = CompatUtils.compatLeafType(leaf);
1545             if (typeDef instanceof UnionTypeDefinition) {
1546                 // GeneratedType for this type definition should be already
1547                 // created
1548                 final QName qname = typeDef.getQName();
1549                 final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1550                         qname.getRevision());
1551                 final ModuleContext mc = genCtx.get(unionModule);
1552                 returnType = mc.getTypedefs().get(typeDef.getPath());
1553             } else if (typeDef instanceof EnumTypeDefinition && typeDef.getBaseType() == null) {
1554                 // Annonymous enumeration (already generated, since it is inherited via uses).
1555                 LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
1556                 QName qname = originalLeaf.getQName();
1557                 final Module enumModule =  schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
1558                         qname.getRevision());
1559                 returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
1560             } else {
1561                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
1562             }
1563             return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
1564         }
1565         return false;
1566     }
1567
1568     /**
1569      * Converts <code>leaf</code> schema node to property of generated TO
1570      * builder.
1571      *
1572      * @param toBuilder
1573      *            generated TO builder to which is <code>leaf</code> added as
1574      *            property
1575      * @param leaf
1576      *            leaf schema node which is added to <code>toBuilder</code> as
1577      *            property
1578      * @param returnType
1579      *            property type
1580      * @param isReadOnly
1581      *            boolean value which says if leaf property is|isn't read only
1582      * @return boolean value
1583      *         <ul>
1584      *         <li>false - if <code>leaf</code>, <code>toBuilder</code> or leaf
1585      *         name equals null or if leaf is added by <i>uses</i>.</li>
1586      *         <li>true - other cases</li>
1587      *         </ul>
1588      */
1589     private static boolean resolveLeafSchemaNodeAsProperty(final GeneratedTOBuilder toBuilder, final LeafSchemaNode leaf,
1590             final Type returnType, final boolean isReadOnly) {
1591         if (returnType == null) {
1592             return false;
1593         }
1594         final String leafName = leaf.getQName().getLocalName();
1595         final String leafDesc = encodeAngleBrackets(leaf.getDescription());
1596         final GeneratedPropertyBuilder propBuilder = toBuilder.addProperty(BindingMapping.getPropertyName(leafName));
1597         propBuilder.setReadOnly(isReadOnly);
1598         propBuilder.setReturnType(returnType);
1599         propBuilder.setComment(leafDesc);
1600         toBuilder.addEqualsIdentity(propBuilder);
1601         toBuilder.addHashIdentity(propBuilder);
1602         toBuilder.addToStringProperty(propBuilder);
1603         return true;
1604     }
1605
1606     /**
1607      * Converts <code>node</code> leaf list schema node to getter method of
1608      * <code>typeBuilder</code>.
1609      *
1610      * @param typeBuilder
1611      *            generated type builder to which is <code>node</code> added as
1612      *            getter method
1613      * @param node
1614      *            leaf list schema node which is added to
1615      *            <code>typeBuilder</code> as getter method
1616      * @param module
1617      * @return boolean value
1618      *         <ul>
1619      *         <li>true - if <code>node</code>, <code>typeBuilder</code>,
1620      *         nodeName equal null or <code>node</code> is added by <i>uses</i></li>
1621      *         <li>false - other cases</li>
1622      *         </ul>
1623      */
1624     private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, final Module module) {
1625         if (node == null || typeBuilder == null || node.isAddedByUses()) {
1626             return false;
1627         }
1628
1629         final QName nodeName = node.getQName();
1630         if (nodeName == null) {
1631             return false;
1632         }
1633
1634         final TypeDefinition<?> typeDef = node.getType();
1635         final Module parentModule = findParentModule(schemaContext, node);
1636
1637         Type returnType = null;
1638         if (typeDef.getBaseType() == null) {
1639             if (typeDef instanceof EnumTypeDefinition) {
1640                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
1641                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
1642                 final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
1643                     typeBuilder,module);
1644                 returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
1645                 ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
1646             } else if (typeDef instanceof UnionTypeDefinition) {
1647                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1648                 if (genTOBuilder != null) {
1649                     returnType = createReturnTypeForUnion(genTOBuilder, typeDef, typeBuilder, parentModule);
1650                 }
1651             } else if (typeDef instanceof BitsTypeDefinition) {
1652                 final GeneratedTOBuilder genTOBuilder = addTOToTypeBuilder(typeDef, typeBuilder, node, parentModule);
1653                 returnType = genTOBuilder.toInstance();
1654             } else {
1655                 final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1656                 returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1657             }
1658         } else {
1659             final Restrictions restrictions = BindingGeneratorUtil.getRestrictions(typeDef);
1660             returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node, restrictions);
1661         }
1662
1663         final ParameterizedType listType = Types.listTypeFor(returnType);
1664         constructGetter(typeBuilder, nodeName.getLocalName(), node.getDescription(), listType, node.getStatus());
1665         return true;
1666     }
1667
1668     private Type createReturnTypeForUnion(final GeneratedTOBuilder genTOBuilder, final TypeDefinition<?> typeDef,
1669             final GeneratedTypeBuilder typeBuilder, final Module parentModule) {
1670         final GeneratedTOBuilderImpl returnType = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
1671                 genTOBuilder.getName());
1672         final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1673
1674         returnType.setDescription(typedefDescription);
1675         returnType.setReference(typeDef.getReference());
1676         returnType.setSchemaPath(typeDef.getPath().getPathFromRoot());
1677         returnType.setModuleName(parentModule.getName());
1678
1679         genTOBuilder.setTypedef(true);
1680         genTOBuilder.setIsUnion(true);
1681         TypeProviderImpl.addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
1682
1683
1684
1685         final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
1686
1687
1688         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
1689         method.setReturnType(returnType);
1690         method.addParameter(Types.STRING, "defaultValue");
1691         method.setAccessModifier(AccessModifier.PUBLIC);
1692         method.setStatic(true);
1693
1694         final Set<Type> types = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(parentModule);
1695         if (types == null) {
1696             ((TypeProviderImpl) typeProvider).getAdditionalTypes().put(parentModule,
1697                     Sets.<Type> newHashSet(unionBuilder.toInstance()));
1698         } else {
1699             types.add(unionBuilder.toInstance());
1700         }
1701         return returnType.toInstance();
1702     }
1703
1704     private static GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
1705         final String outerCls = Types.getOuterClassName(genTOBuilder);
1706         final StringBuilder name;
1707         if (outerCls != null) {
1708             name = new StringBuilder(outerCls);
1709         } else {
1710             name = new StringBuilder();
1711         }
1712         name.append(genTOBuilder.getName());
1713         name.append("Builder");
1714         final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
1715         unionBuilder.setIsUnionBuilder(true);
1716         return unionBuilder;
1717     }
1718
1719     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1720             final Module module) {
1721         return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
1722     }
1723
1724     /**
1725      * Instantiates generated type builder with <code>packageName</code> and
1726      * <code>schemaNode</code>.
1727      *
1728      * The new builder always implements
1729      * {@link org.opendaylight.yangtools.yang.binding.DataObject DataObject}.<br>
1730      * If <code>schemaNode</code> is instance of GroupingDefinition it also
1731      * implements {@link org.opendaylight.yangtools.yang.binding.Augmentable
1732      * Augmentable}.<br>
1733      * If <code>schemaNode</code> is instance of
1734      * {@link org.opendaylight.yangtools.yang.model.api.DataNodeContainer
1735      * DataNodeContainer} it can also implement nodes which are specified in
1736      * <i>uses</i>.
1737      *
1738      * @param packageName
1739      *            string with the name of the package to which
1740      *            <code>schemaNode</code> belongs.
1741      * @param schemaNode
1742      *            schema node for which is created generated type builder
1743      * @param parent
1744      *            parent type (can be null)
1745      * @return generated type builder <code>schemaNode</code>
1746      */
1747     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1748             final Type parent, final Module module) {
1749         final GeneratedTypeBuilder it = addRawInterfaceDefinition(packageName, schemaNode, "");
1750         if (parent == null) {
1751             it.addImplementsType(DATA_OBJECT);
1752         } else {
1753             it.addImplementsType(BindingTypes.childOf(parent));
1754         }
1755         if (!(schemaNode instanceof GroupingDefinition)) {
1756             it.addImplementsType(augmentable(it));
1757         }
1758
1759         if (schemaNode instanceof DataNodeContainer) {
1760             groupingsToGenTypes(module, ((DataNodeContainer) schemaNode).getGroupings());
1761             addImplementedInterfaceFromUses((DataNodeContainer) schemaNode, it);
1762         }
1763
1764         return it;
1765     }
1766
1767     /**
1768      * Wraps the calling of the same overloaded method.
1769      *
1770      * @param packageName
1771      *            string with the package name to which returning generated type
1772      *            builder belongs
1773      * @param schemaNode
1774      *            schema node which provide data about the schema node name
1775      * @return generated type builder for <code>schemaNode</code>
1776      */
1777     private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode) {
1778         return addRawInterfaceDefinition(packageName, schemaNode, "");
1779     }
1780
1781     /**
1782      * Returns reference to generated type builder for specified
1783      * <code>schemaNode</code> with <code>packageName</code>.
1784      *
1785      * Firstly the generated type builder is searched in
1786      * {@link BindingGeneratorImpl#genTypeBuilders genTypeBuilders}. If it isn't
1787      * found it is created and added to <code>genTypeBuilders</code>.
1788      *
1789      * @param packageName
1790      *            string with the package name to which returning generated type
1791      *            builder belongs
1792      * @param schemaNode
1793      *            schema node which provide data about the schema node name
1794      * @param prefix
1795      *            return type name prefix
1796      * @return generated type builder for <code>schemaNode</code>
1797      * @throws IllegalArgumentException
1798      *             <ul>
1799      *             <li>if <code>schemaNode</code> is null</li>
1800      *             <li>if <code>packageName</code> is null</li>
1801      *             <li>if QName of schema node is null</li>
1802      *             <li>if schemaNode name is null</li>
1803      *             </ul>
1804      *
1805      */
1806     private GeneratedTypeBuilder addRawInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
1807             final String prefix) {
1808         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1809         checkArgument(packageName != null, "Package Name for Generated Type cannot be NULL.");
1810         checkArgument(schemaNode.getQName() != null, "QName for Data Schema Node cannot be NULL.");
1811         final String schemaNodeName = schemaNode.getQName().getLocalName();
1812         checkArgument(schemaNodeName != null, "Local Name of QName for Data Schema Node cannot be NULL.");
1813
1814         String genTypeName;
1815         if (prefix == null) {
1816             genTypeName = BindingMapping.getClassName(schemaNodeName);
1817         } else {
1818             genTypeName = prefix + BindingMapping.getClassName(schemaNodeName);
1819         }
1820
1821         // FIXME: Validation of name conflict
1822         final GeneratedTypeBuilderImpl newType = new GeneratedTypeBuilderImpl(packageName, genTypeName);
1823         final Module module = findParentModule(schemaContext, schemaNode);
1824         qnameConstant(newType, BindingMapping.QNAME_STATIC_FIELD_NAME, schemaNode.getQName());
1825         newType.addComment(schemaNode.getDescription());
1826         newType.setDescription(createDescription(schemaNode, newType.getFullyQualifiedName()));
1827         newType.setReference(schemaNode.getReference());
1828         newType.setSchemaPath(schemaNode.getPath().getPathFromRoot());
1829         newType.setModuleName(module.getName());
1830
1831         if (!genTypeBuilders.containsKey(packageName)) {
1832             final Map<String, GeneratedTypeBuilder> builders = new HashMap<>();
1833             builders.put(genTypeName, newType);
1834             genTypeBuilders.put(packageName, builders);
1835         } else {
1836             final Map<String, GeneratedTypeBuilder> builders = genTypeBuilders.get(packageName);
1837             if (!builders.containsKey(genTypeName)) {
1838                 builders.put(genTypeName, newType);
1839             }
1840         }
1841         return newType;
1842     }
1843
1844     /**
1845      * Creates the name of the getter method name from <code>localName</code>.
1846      *
1847      * @param localName
1848      *            string with the name of the getter method
1849      * @param returnType
1850      *            return type
1851      * @return string with the name of the getter method for
1852      *         <code>methodName</code> in JAVA method format
1853      */
1854     public static String getterMethodName(final String localName, final Type returnType) {
1855         final StringBuilder method = new StringBuilder();
1856         if (BOOLEAN.equals(returnType)) {
1857             method.append("is");
1858         } else {
1859             method.append("get");
1860         }
1861         final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
1862         method.append(name);
1863         return method.toString();
1864     }
1865
1866     /**
1867      * Created a method signature builder as part of
1868      * <code>interfaceBuilder</code>.
1869      *
1870      * The method signature builder is created for the getter method of
1871      * <code>schemaNodeName</code>. Also <code>comment</code> and
1872      * <code>returnType</code> information are added to the builder.
1873      *
1874      * @param interfaceBuilder
1875      *            generated type builder for which the getter method should be
1876      *            created
1877      * @param schemaNodeName
1878      *            string with schema node name. The name will be the part of the
1879      *            getter method name.
1880      * @param comment
1881      *            string with comment for the getter method
1882      * @param returnType
1883      *            type which represents the return type of the getter method
1884      * @param status
1885      *            status from yang file, for deprecated annotation
1886      * @return method signature builder which represents the getter method of
1887      *         <code>interfaceBuilder</code>
1888      */
1889     private static MethodSignatureBuilder constructGetter(final GeneratedTypeBuilder interfaceBuilder,
1890             final String schemaNodeName, final String comment, final Type returnType, final Status status) {
1891         final MethodSignatureBuilder getMethod = interfaceBuilder
1892                 .addMethod(getterMethodName(schemaNodeName, returnType));
1893         if (status == Status.DEPRECATED) {
1894             getMethod.addAnnotation("", "Deprecated");
1895         }
1896         getMethod.setComment(encodeAngleBrackets(comment));
1897         getMethod.setReturnType(returnType);
1898         return getMethod;
1899     }
1900
1901     /**
1902      * Adds <code>schemaNode</code> to <code>typeBuilder</code> as getter method
1903      * or to <code>genTOBuilder</code> as property.
1904      *
1905      * @param basePackageName
1906      *            string contains the module package name
1907      * @param schemaNode
1908      *            data schema node which should be added as getter method to
1909      *            <code>typeBuilder</code> or as a property to
1910      *            <code>genTOBuilder</code> if is part of the list key
1911      * @param typeBuilder
1912      *            generated type builder for the list schema node
1913      * @param genTOBuilder
1914      *            generated TO builder for the list keys
1915      * @param listKeys
1916      *            list of string which contains names of the list keys
1917      * @param module
1918      *            current module
1919      * @throws IllegalArgumentException
1920      *             <ul>
1921      *             <li>if <code>schemaNode</code> equals null</li>
1922      *             <li>if <code>typeBuilder</code> equals null</li>
1923      *             </ul>
1924      */
1925     private void addSchemaNodeToListBuilders(final String basePackageName, final DataSchemaNode schemaNode,
1926             final GeneratedTypeBuilder typeBuilder, final GeneratedTOBuilder genTOBuilder, final List<String> listKeys,
1927             final Module module) {
1928         checkArgument(schemaNode != null, "Data Schema Node cannot be NULL.");
1929         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1930
1931         if (schemaNode instanceof LeafSchemaNode) {
1932             final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
1933             final String leafName = leaf.getQName().getLocalName();
1934             final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
1935             if (listKeys.contains(leafName)) {
1936                 if (type == null) {
1937                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
1938                 } else {
1939                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, type, true);
1940                 }
1941             }
1942         } else if (!schemaNode.isAddedByUses()) {
1943             if (schemaNode instanceof LeafListSchemaNode) {
1944                 resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
1945             } else if (schemaNode instanceof ContainerSchemaNode) {
1946                 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
1947             } else if (schemaNode instanceof ChoiceSchemaNode) {
1948                 choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
1949             } else if (schemaNode instanceof ListSchemaNode) {
1950                 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
1951             }
1952         }
1953     }
1954
1955     private void typeBuildersToGenTypes(final Module module, final GeneratedTypeBuilder typeBuilder,
1956             final GeneratedTOBuilder genTOBuilder) {
1957         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
1958
1959         if (genTOBuilder != null) {
1960             final GeneratedTransferObject genTO = genTOBuilder.toInstance();
1961             constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO, Status.CURRENT);
1962             genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
1963         }
1964     }
1965
1966     /**
1967      * Selects the names of the list keys from <code>list</code> and returns
1968      * them as the list of the strings
1969      *
1970      * @param list
1971      *            of string with names of the list keys
1972      * @return list of string which represents names of the list keys. If the
1973      *         <code>list</code> contains no keys then the empty list is
1974      *         returned.
1975      */
1976     private static List<String> listKeys(final ListSchemaNode list) {
1977         final List<String> listKeys = new ArrayList<>();
1978
1979         final List<QName> keyDefinition = list.getKeyDefinition();
1980         if (keyDefinition != null) {
1981             for (final QName keyDef : keyDefinition) {
1982                 listKeys.add(keyDef.getLocalName());
1983             }
1984         }
1985         return listKeys;
1986     }
1987
1988     /**
1989      * Generates for the <code>list</code> which contains any list keys special
1990      * generated TO builder.
1991      *
1992      * @param packageName
1993      *            string with package name to which the list belongs
1994      * @param list
1995      *            list schema node which is source of data about the list name
1996      * @return generated TO builder which represents the keys of the
1997      *         <code>list</code> or null if <code>list</code> is null or list of
1998      *         key definitions is null or empty.
1999      */
2000     private static GeneratedTOBuilder resolveListKeyTOBuilder(final String packageName, final ListSchemaNode list) {
2001         GeneratedTOBuilder genTOBuilder = null;
2002         if ((list.getKeyDefinition() != null) && (!list.getKeyDefinition().isEmpty())) {
2003             final String listName = list.getQName().getLocalName() + "Key";
2004             final String genTOName = BindingMapping.getClassName(listName);
2005             genTOBuilder = new GeneratedTOBuilderImpl(packageName, genTOName);
2006         }
2007         return genTOBuilder;
2008     }
2009
2010     /**
2011      * Builds generated TO builders for <code>typeDef</code> of type
2012      * {@link UnionTypeDefinition} or {@link BitsTypeDefinition} which are
2013      * also added to <code>typeBuilder</code> as enclosing transfer object.
2014      *
2015      * If more then one generated TO builder is created for enclosing then all
2016      * of the generated TO builders are added to <code>typeBuilder</code> as
2017      * enclosing transfer objects.
2018      *
2019      * @param typeDef
2020      *            type definition which can be of type <code>UnionType</code> or
2021      *            <code>BitsTypeDefinition</code>
2022      * @param typeBuilder
2023      *            generated type builder to which is added generated TO created
2024      *            from <code>typeDef</code>
2025      * @param leafName
2026      *            string with name for generated TO builder
2027      * @param leaf
2028      * @return generated TO builder for <code>typeDef</code>
2029      */
2030     private GeneratedTOBuilder addTOToTypeBuilder(final TypeDefinition<?> typeDef,
2031             final GeneratedTypeBuilder typeBuilder, final DataSchemaNode leaf, final Module parentModule) {
2032         final String classNameFromLeaf = BindingMapping.getClassName(leaf.getQName());
2033         final List<GeneratedTOBuilder> genTOBuilders = new ArrayList<>();
2034         final String packageName = typeBuilder.getFullyQualifiedName();
2035         if (typeDef instanceof UnionTypeDefinition) {
2036             final List<GeneratedTOBuilder> types = ((TypeProviderImpl) typeProvider)
2037                     .provideGeneratedTOBuildersForUnionTypeDef(packageName, ((UnionTypeDefinition) typeDef),
2038                             classNameFromLeaf, leaf);
2039             genTOBuilders.addAll(types);
2040
2041             GeneratedTOBuilder resultTOBuilder = null;
2042             if (types.isEmpty()) {
2043                 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
2044             }
2045             resultTOBuilder = types.remove(0);
2046             for (final GeneratedTOBuilder genTOBuilder : types) {
2047                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
2048             }
2049
2050             final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
2051             genPropBuilder.setReturnType(Types.CHAR_ARRAY);
2052             resultTOBuilder.addEqualsIdentity(genPropBuilder);
2053             resultTOBuilder.addHashIdentity(genPropBuilder);
2054             resultTOBuilder.addToStringProperty(genPropBuilder);
2055
2056         } else if (typeDef instanceof BitsTypeDefinition) {
2057             genTOBuilders.add((((TypeProviderImpl) typeProvider)).provideGeneratedTOBuilderForBitsTypeDefinition(
2058                     packageName, typeDef, classNameFromLeaf, parentModule.getName()));
2059         }
2060         if (!genTOBuilders.isEmpty()) {
2061             for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
2062                 typeBuilder.addEnclosingTransferObject(genTOBuilder);
2063             }
2064             return genTOBuilders.get(0);
2065         }
2066         return null;
2067
2068     }
2069
2070     /**
2071      * Adds the implemented types to type builder.
2072      *
2073      * The method passes through the list of <i>uses</i> in
2074      * {@code dataNodeContainer}. For every <i>use</i> is obtained corresponding
2075      * generated type from {@link BindingGeneratorImpl#allGroupings
2076      * allGroupings} which is added as <i>implements type</i> to
2077      * <code>builder</code>
2078      *
2079      * @param dataNodeContainer
2080      *            element which contains the list of used YANG groupings
2081      * @param builder
2082      *            builder to which are added implemented types according to
2083      *            <code>dataNodeContainer</code>
2084      * @return generated type builder with all implemented types
2085      */
2086     private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
2087             final GeneratedTypeBuilder builder) {
2088         for (final UsesNode usesNode : dataNodeContainer.getUses()) {
2089             if (usesNode.getGroupingPath() != null) {
2090                 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
2091                 if (genType == null) {
2092                     throw new IllegalStateException("Grouping " + usesNode.getGroupingPath() + "is not resolved for "
2093                             + builder.getName());
2094                 }
2095
2096                 builder.addImplementsType(genType);
2097                 /*
2098                 builder.addComment(genType.getDescription());
2099                 builder.setDescription(genType.getDescription());
2100                 builder.setModuleName(genType.getModuleName());
2101                 builder.setReference(genType.getReference());
2102                 builder.setSchemaPath(genType.getSchemaPath());
2103                 */
2104             }
2105         }
2106         return builder;
2107     }
2108
2109     private static boolean isNullOrEmpty(final Collection<?> list) {
2110         return list == null || list.isEmpty();
2111     }
2112
2113     private String createDescription(final Set<? extends SchemaNode> schemaNodes, final String moduleName) {
2114         final StringBuilder sb = new StringBuilder();
2115
2116         if (!isNullOrEmpty(schemaNodes)) {
2117             final SchemaNode node = schemaNodes.iterator().next();
2118
2119             if (node instanceof RpcDefinition) {
2120                 sb.append("Interface for implementing the following YANG RPCs defined in module <b>" + moduleName + "</b>");
2121             } else if (node instanceof NotificationDefinition) {
2122                 sb.append("Interface for receiving the following YANG notifications defined in module <b>" + moduleName + "</b>");
2123             }
2124         }
2125         sb.append(NEW_LINE);
2126
2127         if (verboseClassComments) {
2128             sb.append("<pre>");
2129             sb.append(NEW_LINE);
2130             sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNodes)));
2131             sb.append("</pre>");
2132             sb.append(NEW_LINE);
2133         }
2134
2135         return replaceAllIllegalChars(sb);
2136     }
2137
2138     private String createDescription(final SchemaNode schemaNode, final String fullyQualifiedName) {
2139         final StringBuilder sb = new StringBuilder();
2140         final String nodeDescription = encodeAngleBrackets(schemaNode.getDescription());
2141         final String formattedDescription = YangTextTemplate.formatToParagraph(nodeDescription, 0);
2142
2143         if (!Strings.isNullOrEmpty(formattedDescription)) {
2144             sb.append(formattedDescription);
2145             sb.append(NEW_LINE);
2146         }
2147
2148         if (verboseClassComments) {
2149             final Module module = findParentModule(schemaContext, schemaNode);
2150             final StringBuilder linkToBuilderClass = new StringBuilder();
2151             final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
2152             final String className = namespace[namespace.length - 1];
2153
2154             if (hasBuilderClass(schemaNode)) {
2155                 linkToBuilderClass.append(className);
2156                 linkToBuilderClass.append("Builder");
2157             }
2158
2159             sb.append("<p>");
2160             sb.append("This class represents the following YANG schema fragment defined in module <b>");
2161             sb.append(module.getName());
2162             sb.append("</b>");
2163             sb.append(NEW_LINE);
2164             sb.append("<pre>");
2165             sb.append(NEW_LINE);
2166             sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(schemaNode)));
2167             sb.append("</pre>");
2168             sb.append(NEW_LINE);
2169             sb.append("The schema path to identify an instance is");
2170             sb.append(NEW_LINE);
2171             sb.append("<i>");
2172             sb.append(YangTextTemplate.formatSchemaPath(module.getName(), schemaNode.getPath().getPathFromRoot()));
2173             sb.append("</i>");
2174             sb.append(NEW_LINE);
2175
2176             if (hasBuilderClass(schemaNode)) {
2177                 sb.append(NEW_LINE);
2178                 sb.append("<p>To create instances of this class use " + "{@link " + linkToBuilderClass + "}.");
2179                 sb.append(NEW_LINE);
2180                 sb.append("@see ");
2181                 sb.append(linkToBuilderClass);
2182                 sb.append(NEW_LINE);
2183                 if (schemaNode instanceof ListSchemaNode) {
2184                     final List<QName> keyDef = ((ListSchemaNode)schemaNode).getKeyDefinition();
2185                     if (keyDef != null && !keyDef.isEmpty()) {
2186                         sb.append("@see ");
2187                         sb.append(className);
2188                         sb.append("Key");
2189                     }
2190                     sb.append(NEW_LINE);
2191                 }
2192             }
2193         }
2194
2195         return replaceAllIllegalChars(sb);
2196     }
2197
2198     private static boolean hasBuilderClass(final SchemaNode schemaNode) {
2199         if (schemaNode instanceof ContainerSchemaNode || schemaNode instanceof ListSchemaNode ||
2200                 schemaNode instanceof RpcDefinition || schemaNode instanceof NotificationDefinition) {
2201             return true;
2202         }
2203         return false;
2204     }
2205
2206     private String createDescription(final Module module) {
2207         final StringBuilder sb = new StringBuilder();
2208         final String moduleDescription = encodeAngleBrackets(module.getDescription());
2209         final String formattedDescription = YangTextTemplate.formatToParagraph(moduleDescription, 0);
2210
2211         if (!Strings.isNullOrEmpty(formattedDescription)) {
2212             sb.append(formattedDescription);
2213             sb.append(NEW_LINE);
2214         }
2215
2216         if (verboseClassComments) {
2217             sb.append("<p>");
2218             sb.append("This class represents the following YANG schema fragment defined in module <b>");
2219             sb.append(module.getName());
2220             sb.append("</b>");
2221             sb.append(NEW_LINE);
2222             sb.append("<pre>");
2223             sb.append(NEW_LINE);
2224             sb.append(encodeAngleBrackets(YangTemplate.generateYangSnipet(module)));
2225             sb.append("</pre>");
2226         }
2227
2228         return replaceAllIllegalChars(sb);
2229     }
2230
2231     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
2232         for (final ModuleContext ctx : genCtx.values()) {
2233             final GeneratedTypeBuilder result = ctx.getChildNode(path);
2234             if (result != null) {
2235                 return result;
2236             }
2237         }
2238         return null;
2239     }
2240
2241     private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
2242         for (final ModuleContext ctx : genCtx.values()) {
2243             final GeneratedTypeBuilder result = ctx.getGrouping(path);
2244             if (result != null) {
2245                 return result;
2246             }
2247         }
2248         return null;
2249     }
2250
2251     private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
2252         for (final ModuleContext ctx : genCtx.values()) {
2253             final GeneratedTypeBuilder result = ctx.getCase(path);
2254             if (result != null) {
2255                 return result;
2256             }
2257         }
2258         return null;
2259     }
2260
2261     public Map<Module, ModuleContext> getModuleContexts() {
2262         return genCtx;
2263     }
2264
2265     @VisibleForTesting
2266     static String replaceAllIllegalChars(final StringBuilder stringBuilder){
2267         final String ret = UNICODE_CHAR_PATTERN.matcher(stringBuilder).replaceAll("\\\\\\\\u");
2268         return ret.isEmpty() ? "" : ret;
2269     }
2270
2271     private static void annotateDeprecatedIfNecessary(final Status status, final GeneratedTypeBuilder builder) {
2272         if (status == Status.DEPRECATED) {
2273             builder.addAnnotation("", "Deprecated");
2274         }
2275     }
2276 }