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