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