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