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