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