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