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