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