Move BaseYangTypesProvider
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / mdsal / binding / yang / types / AbstractTypeProvider.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.mdsal.binding.yang.types;
9
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.TYPE_OBJECT;
12
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableMap;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Optional;
24 import java.util.Set;
25 import java.util.TreeMap;
26 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
27 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
28 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
29 import org.opendaylight.mdsal.binding.model.api.Enumeration;
30 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
33 import org.opendaylight.mdsal.binding.model.api.Restrictions;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
36 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
37 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
38 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
39 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
40 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
41 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
42 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
43 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
44 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
45 import org.opendaylight.mdsal.binding.model.util.Types;
46 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
47 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
48 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
49 import org.opendaylight.yangtools.yang.common.Revision;
50 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
55 import org.opendaylight.yangtools.yang.model.api.Status;
56 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
59 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
63 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
66
67 // FIXME: remove this class
68 @Deprecated(forRemoval = true)
69 abstract class AbstractTypeProvider implements TypeProvider {
70     private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
71
72     /**
73      * Contains the schema data red from YANG files.
74      */
75     private final SchemaContext schemaContext;
76
77     private final Map<String, Map<Optional<Revision>, Map<String, GeneratedType>>> genTypeDefsContextMap =
78         new HashMap<>();
79
80     /**
81      * The map which maps schema paths to JAVA <code>Type</code>.
82      */
83     private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
84     private final Map<Module, Set<GeneratedType>> additionalTypes = new HashMap<>();
85
86     /**
87      * Creates new instance of class <code>TypeProviderImpl</code>.
88      *
89      * @param schemaContext contains the schema data red from YANG files
90      * @param renames renaming table
91      * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
92      */
93     AbstractTypeProvider(final EffectiveModelContext schemaContext) {
94         this.schemaContext = requireNonNull(schemaContext);
95
96         resolveTypeDefsFromContext();
97     }
98
99     /**
100      * Puts <code>refType</code> to map with key <code>refTypePath</code>.
101      *
102      * @param refTypePath schema path used as the map key
103      * @param refType type which represents the map value
104      * @throws IllegalArgumentException
105      *             <ul>
106      *             <li>if <code>refTypePath</code> equal null</li>
107      *             <li>if <code>refType</code> equal null</li>
108      *             </ul>
109      *
110      */
111     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
112         Preconditions.checkArgument(refTypePath != null,
113                 "Path reference of Enumeration Type Definition cannot be NULL!");
114         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
115         referencedTypes.put(refTypePath, refType);
116     }
117
118     public Map<Module, Set<GeneratedType>> getAdditionalTypes() {
119         return additionalTypes;
120     }
121
122     @Override
123     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
124             final boolean lenientRelativeLeafrefs) {
125         return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
126     }
127
128     /**
129      * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
130      *
131      * @param typeDefinition type definition which is converted to JAVA type
132      * @throws IllegalArgumentException
133      *             <ul>
134      *             <li>if <code>typeDefinition</code> equal null</li>
135      *             <li>if Qname of <code>typeDefinition</code> equal null</li>
136      *             <li>if name of <code>typeDefinition</code> equal null</li>
137      *             </ul>
138      */
139     @Override
140     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
141             final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
142         throw new UnsupportedOperationException();
143     }
144
145     /**
146      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
147      *
148      * @param typeDefinition
149      *            type definition which should be converted to JAVA
150      *            <code>Type</code>
151      * @return JAVA <code>Type</code> which represents
152      *         <code>typeDefinition</code>
153      * @throws IllegalArgumentException
154      *             <ul>
155      *             <li>if <code>typeDefinition</code> equal null</li>
156      *             <li>if Q name of <code>typeDefinition</code></li>
157      *             <li>if name of <code>typeDefinition</code></li>
158      *             </ul>
159      */
160     public GeneratedType generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
161             final SchemaNode parentNode) {
162         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
163         if (typeDefinition.getQName() == null) {
164             throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
165         }
166         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
167                 "Type Definitions Local Name cannot be NULL!");
168
169         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
170         if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
171             /*
172              * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
173              * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
174              * this:
175              *
176              *     identity iden;
177              *
178              *     container foo {
179              *         leaf foo {
180              *             type identityref {
181              *                 base iden;
182              *             }
183              *         }
184              *     }
185              *
186              * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
187              * dicey when we throw in:
188              *
189              *     typedef bar-ref {
190              *         type identityref {
191              *             base iden;
192              *         }
193              *     }
194              *
195              *     container bar {
196              *         leaf bar {
197              *             type bar-ref;
198              *         }
199              *     }
200              *
201              * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
202              * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
203              * is formed.
204              *
205              * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
206              * an encapsulation for identityref typedefs.
207              *
208              * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
209              * option, as it would look as though it is the product of a different construct:
210              *
211              *     identity bar-ref {
212              *         base iden;
213              *     }
214              *
215              * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
216              * sub-identities of iden.
217              *
218              * The story behind leafrefs is probably similar, but that needs to be ascertained.
219              */
220             return null;
221         }
222
223         final Module module = findParentModule(schemaContext, parentNode);
224         if (module != null) {
225             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
226                 module.getName());
227             final Map<String, GeneratedType> genTOs = modulesByDate.get(module.getRevision());
228             if (genTOs != null) {
229                 return genTOs.get(typeDefinition.getQName().getLocalName());
230             }
231         }
232         return null;
233     }
234
235     /**
236      * Gets base type definition for <code>extendTypeDef</code>. The method is
237      * recursively called until non <code>ExtendedType</code> type is found.
238      *
239      * @param extendTypeDef
240      *            type definition for which is the base type definition sought
241      * @return type definition which is base type for <code>extendTypeDef</code>
242      * @throws IllegalArgumentException
243      *             if <code>extendTypeDef</code> equal null
244      */
245     private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
246         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
247
248         TypeDefinition<?> ret = extendTypeDef;
249         while (ret.getBaseType() != null) {
250             ret = ret.getBaseType();
251         }
252
253         return ret;
254     }
255
256     /**
257      * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
258      *
259      * @param enumTypeDef enumeration type definition which is converted to enumeration
260      * @param enumName string with name which is used as the enumeration name
261      * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
262      * @throws IllegalArgumentException
263      *             <ul>
264      *             <li>if <code>enumTypeDef</code> equals null</li>
265      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
266      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
267      *             <li>if name of <code>enumTypeDef</code> equal null</li>
268      *             </ul>
269      */
270     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
271             final SchemaNode parentNode) {
272         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
273         Preconditions.checkArgument(enumTypeDef.getValues() != null,
274                 "EnumTypeDefinition MUST contain at least ONE value definition!");
275         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
276         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
277                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
278
279         final Module module = findParentModule(schemaContext, parentNode);
280         final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
281             BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
282         addEnumDescription(enumBuilder, enumTypeDef);
283         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
284         enumBuilder.setModuleName(module.getName());
285         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
286         return enumBuilder.toInstance();
287     }
288
289     /**
290      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
291      *
292      * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
293      * @param enumName string with the name of enumeration
294      * @param typeBuilder generated type builder to which is enumeration added
295      * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
296      * @throws IllegalArgumentException
297      *             <ul>
298      *             <li>if <code>enumTypeDef</code> equals null</li>
299      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
300      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
301      *             <li>if name of <code>enumTypeDef</code> equal null</li>
302      *             <li>if name of <code>typeBuilder</code> equal null</li>
303      *             </ul>
304      *
305      */
306     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
307             final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
308         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
309         Preconditions.checkArgument(enumTypeDef.getValues() != null,
310                 "EnumTypeDefinition MUST contain at least ONE value definition!");
311         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
312         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
313                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
314         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
315
316         final EnumBuilder enumBuilder = newEnumerationBuilder(
317             typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(enumName), "$"));
318         addEnumDescription(enumBuilder, enumTypeDef);
319         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
320         final Enumeration ret = enumBuilder.toInstance();
321         typeBuilder.addEnumeration(ret);
322
323         return ret;
324     }
325
326     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
327
328     public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
329
330     public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
331
332     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
333
334     /**
335      * Converts the pattern constraints to the list of the strings which represents these constraints.
336      *
337      * @param patternConstraints list of pattern constraints
338      * @return list of strings which represents the constraint patterns
339      */
340     public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
341
342     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
343
344     /**
345      * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
346      * constraints.
347      *
348      * @param typedef extended type in which are the pattern constraints sought
349      * @return list of strings which represents the constraint patterns
350      * @throws IllegalArgumentException if <code>typedef</code> equals null
351      *
352      */
353     private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
354         if (!(typedef instanceof StringTypeDefinition)) {
355             return ImmutableMap.of();
356         }
357
358         // TODO: run diff against base ?
359         return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
360     }
361
362     /**
363      * Passes through all modules and through all its type definitions and convert it to generated types.
364      *
365      * <p>
366      * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
367      * of a module are at the beginning sorted so that type definition with less amount of references to other type
368      * definition are processed first.<br>
369      * For each module is created mapping record in the map
370      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
371      * which map current module name to the map which maps type names to returned types (generated types).
372      */
373     private void resolveTypeDefsFromContext() {
374         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
375
376         for (Module module : modulesSortedByDependency) {
377             Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
378                 module.getName(), key -> new HashMap<>());
379             dateTypeMap.put(module.getRevision(), Collections.emptyMap());
380             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
381         }
382
383         for (Module module : modulesSortedByDependency) {
384             if (module != null) {
385                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
386                 if (basePackageName != null) {
387                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
388                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
389                         typedefToGeneratedType(basePackageName, module, typedef);
390                     }
391                 }
392             }
393         }
394     }
395
396     /**
397      * Create Type for specified type definition.
398      *
399      * @param basePackageName string with name of package to which the module belongs
400      * @param module string with the name of the module for to which the <code>typedef</code> belongs
401      * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
402      *                (usually generated TO)
403      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
404      *         <code>null</code> value if <code>basePackageName</code> or
405      *         <code>modulName</code> or <code>typedef</code> or Q name of
406      *         <code>typedef</code> equals <code>null</code>
407      */
408     private Type typedefToGeneratedType(final String basePackageName, final Module module,
409             final TypeDefinition<?> typedef) {
410         final TypeDefinition<?> baseTypedef = typedef.getBaseType();
411
412         // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
413         if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
414             return null;
415         }
416
417         final String typedefName = typedef.getQName().getLocalName();
418
419         final GeneratedType returnType;
420         if (baseTypedef.getBaseType() != null) {
421             returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
422                 module.getName());
423         } else if (baseTypedef instanceof UnionTypeDefinition) {
424             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
425                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
426                 (UnionTypeDefinition) baseTypedef, typedef);
427             genTOBuilder.setTypedef(true);
428             genTOBuilder.setIsUnion(true);
429             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
430             makeSerializable(genTOBuilder);
431             returnType = genTOBuilder.build();
432
433             // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
434             // so we are placing the builder alongside the union.
435             final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
436                 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
437             unionBuilder.setIsUnionBuilder(true);
438             final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
439             method.setReturnType(returnType);
440             method.addParameter(Types.STRING, "defaultValue");
441             method.setAccessModifier(AccessModifier.PUBLIC);
442             method.setStatic(true);
443             additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
444         } else if (baseTypedef instanceof EnumTypeDefinition) {
445             // enums are automatically Serializable
446             final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
447             // TODO units for typedef enum
448             returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
449         } else if (baseTypedef instanceof BitsTypeDefinition) {
450             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
451                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
452                 (BitsTypeDefinition) baseTypedef, module.getName());
453             genTOBuilder.setTypedef(true);
454             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
455             makeSerializable(genTOBuilder);
456             returnType = genTOBuilder.build();
457         } else {
458             final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
459             returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
460         }
461         if (returnType != null) {
462             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
463                     genTypeDefsContextMap.get(module.getName());
464             final Optional<Revision> moduleRevision = module.getRevision();
465             Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
466             if (typeMap != null) {
467                 if (typeMap.isEmpty()) {
468                     typeMap = new HashMap<>(4);
469                     modulesByDate.put(moduleRevision, typeMap);
470                 }
471                 typeMap.put(typedefName, returnType);
472             }
473             return returnType;
474         }
475         return null;
476     }
477
478     /**
479      * Wraps base YANG type to generated TO.
480      *
481      * @param basePackageName string with name of package to which the module belongs
482      * @param typedef type definition which is converted to the TO
483      * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
484      * @return generated transfer object which represent<code>javaType</code>
485      */
486     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
487             final Type javaType, final String moduleName) {
488         requireNonNull(javaType, "javaType cannot be null");
489
490         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
491         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
492         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
493         genPropBuilder.setReturnType(javaType);
494
495         genTOBuilder.addEqualsIdentity(genPropBuilder);
496         genTOBuilder.addHashIdentity(genPropBuilder);
497         genTOBuilder.addToStringProperty(genPropBuilder);
498         genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
499         if (typedef.getStatus() == Status.DEPRECATED) {
500             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
501         }
502         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
503             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
504         }
505         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
506         genTOBuilder.setTypedef(true);
507         makeSerializable(genTOBuilder);
508         return genTOBuilder.build();
509     }
510
511     /**
512      * Converts output list of generated TO builders to one TO builder (first
513      * from list) which contains the remaining builders as its enclosing TO.
514      *
515      * @param typeName new type identifier
516      * @param typedef type definition which should be of type {@link UnionTypeDefinition}
517      * @return generated TO builder with the list of enclosed generated TO builders
518      */
519     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
520             final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
521         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
522             parentNode);
523         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
524
525         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
526         builders.forEach(builder -> resultTOBuilder.addEnclosingTransferObject(builder.build()));
527         return resultTOBuilder;
528     }
529
530     /**
531      * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
532      * <code>typedef</code> is added to generated TO builder as property.
533      *
534      * @param typeName new type identifier
535      * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
536      * @return generated TO builder which represents <code>typedef</code>
537      * @throws NullPointerException
538      *             <ul>
539      *             <li>if <code>basePackageName</code> is null</li>
540      *             <li>if <code>typedef</code> is null</li>
541      *             <li>if Qname of <code>typedef</code> is null</li>
542      *             </ul>
543      */
544     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
545             final UnionTypeDefinition typedef, final SchemaNode parentNode) {
546         requireNonNull(typedef, "Type Definition cannot be NULL!");
547         requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
548
549         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
550         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
551         final Module module = findParentModule(schemaContext, parentNode);
552
553         final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
554         unionGenTOBuilder.setIsUnion(true);
555         unionGenTOBuilder.setSchemaPath(typedef.getPath());
556         unionGenTOBuilder.setModuleName(module.getName());
557         unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
558         addCodegenInformation(unionGenTOBuilder, typedef);
559         generatedTOBuilders.add(unionGenTOBuilder);
560
561         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
562         // also negation information and hence guarantees uniqueness.
563         final Map<String, String> expressions = new HashMap<>();
564         for (TypeDefinition<?> unionType : unionTypes) {
565             final String unionTypeName = unionType.getQName().getLocalName();
566
567             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
568             // do not follow type encapsulation -- we use the general case for that.
569             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
570                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
571             } else if (unionType instanceof UnionTypeDefinition) {
572                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
573                     (UnionTypeDefinition) unionType, parentNode));
574             } else if (unionType instanceof EnumTypeDefinition) {
575                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
576                         unionTypeName, unionGenTOBuilder);
577                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
578             } else {
579                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
580                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
581             }
582         }
583         addStringRegExAsConstant(unionGenTOBuilder, expressions);
584
585         storeGenTO(typedef, unionGenTOBuilder, parentNode);
586
587         return generatedTOBuilders;
588     }
589
590     /**
591      * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
592      *
593      * <p>
594      * In this case the new generated TO is created for union subtype (recursive call of method
595      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
596      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
597      * created property which type is equal to new generated TO.
598      *
599      * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
600      * @param basePackageName string with the name of the module package
601      * @param unionSubtype type definition which represents union subtype
602      * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
603      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
604      */
605     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
606             final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
607         final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
608             provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
609         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
610             newTOBuilderName, unionSubtype, parentNode);
611
612         final GeneratedPropertyBuilder propertyBuilder;
613         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
614             newTOBuilderName.simpleName()));
615         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
616         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
617         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
618
619         return subUnionGenTOBUilders;
620     }
621
622     /**
623      * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
624      * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
625      * the base type is used for the property creation.
626      *
627      * @param parentUnionGenTOBuilder generated TO builder in which new property is created
628      * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
629      * @param expressions list of strings with the regular expressions
630      * @param parentNode parent Schema Node for Extended Subtype
631      */
632     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
633             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
634         final String unionTypeName = unionSubtype.getQName().getLocalName();
635         final Type genTO = findGenTO(unionTypeName, unionSubtype);
636         if (genTO != null) {
637             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
638             return;
639         }
640
641         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
642         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
643             final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
644                 BindingGeneratorUtil.getRestrictions(unionSubtype));
645             if (javaType != null) {
646                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
647             }
648         } else if (baseType instanceof LeafrefTypeDefinition) {
649             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
650             boolean typeExist = false;
651             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
652                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
653                 if (origType != null && javaType != null && javaType == origType) {
654                     typeExist = true;
655                     break;
656                 }
657             }
658             if (!typeExist && javaType != null) {
659                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
660                     BindingMapping.getUnionLeafrefMemberName(parentUnionGenTOBuilder.getName(), javaType.getName()));
661             }
662         }
663         if (baseType instanceof StringTypeDefinition) {
664             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
665         }
666     }
667
668     /**
669      * Searches for generated TO for <code>searchedTypeDef</code> type  definition
670      * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
671      *
672      * @param searchedTypeName string with name of <code>searchedTypeDef</code>
673      * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
674      */
675     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
676         final Module typeModule = findParentModule(schemaContext, parentNode);
677         if (typeModule != null && typeModule.getName() != null) {
678             final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
679                 typeModule.getName());
680             final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
681             if (genTOs != null) {
682                 return genTOs.get(searchedTypeName);
683             }
684         }
685         return null;
686     }
687
688     /**
689      * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
690      * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
691      *
692      * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
693      * @param genTOBuilder generated TO builder which is converted to generated TO and stored
694      */
695     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
696             final SchemaNode parentNode) {
697         if (!(newTypeDef instanceof UnionTypeDefinition)) {
698             final Module parentModule = findParentModule(schemaContext, parentNode);
699             if (parentModule != null && parentModule.getName() != null) {
700                 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
701                     parentModule.getName());
702                 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
703                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
704             }
705         }
706     }
707
708     /**
709      * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
710      * to <code>unonGenTransObject</code>.
711      *
712      * @param unionGenTransObject generated TO to which should be property added
713      * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
714      * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
715      */
716     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
717             final String propertyName) {
718         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
719             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
720                     .addProperty(BindingMapping.getPropertyName(propertyName));
721             propBuilder.setReturnType(type);
722
723             unionGenTransObject.addEqualsIdentity(propBuilder);
724             unionGenTransObject.addHashIdentity(propBuilder);
725             unionGenTransObject.addToStringProperty(propBuilder);
726         }
727     }
728
729     /**
730      * Converts <code>typedef</code> to the generated TO builder.
731      *
732      * @param basePackageName string with name of package to which the module belongs
733      * @param typedef type definition from which is the generated TO builder created
734      * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
735      */
736     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
737             final TypeDefinition<?> typedef, final String moduleName) {
738         final JavaTypeName name = JavaTypeName.create(
739                 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
740                 BindingMapping.getClassName(typedef.getQName().getLocalName()));
741
742         final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
743         newType.setSchemaPath(typedef.getPath());
744         newType.setModuleName(moduleName);
745         addCodegenInformation(newType, typedef);
746         return newType;
747     }
748
749     /**
750      * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
751      * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
752      * properties.
753      *
754      * @param typeName new type identifier
755      * @param typeDef type definition from which is the generated TO builder created
756      * @return generated TO builder which represents <code>typeDef</code>
757      * @throws IllegalArgumentException
758      *             <ul>
759      *             <li>if <code>typeDef</code> equals null</li>
760      *             <li>if <code>basePackageName</code> equals null</li>
761      *             </ul>
762      */
763     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
764             final BitsTypeDefinition typeDef, final String moduleName) {
765         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
766         genTOBuilder.setSchemaPath(typeDef.getPath());
767         genTOBuilder.setModuleName(moduleName);
768         genTOBuilder.setBaseType(typeDef);
769         genTOBuilder.addImplementsType(TYPE_OBJECT);
770         addCodegenInformation(genTOBuilder, typeDef);
771
772         for (Bit bit : typeDef.getBits()) {
773             final String name = bit.getName();
774             GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
775                 BindingMapping.getPropertyName(name));
776             genPropertyBuilder.setReadOnly(true);
777             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
778
779             genTOBuilder.addEqualsIdentity(genPropertyBuilder);
780             genTOBuilder.addHashIdentity(genPropertyBuilder);
781             genTOBuilder.addToStringProperty(genPropertyBuilder);
782         }
783
784         return genTOBuilder;
785     }
786
787     /**
788      * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
789      * the <code>regularExpressions</code>.
790      *
791      * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
792      * @param expressions list of string which represent regular expressions
793      */
794     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
795             final Map<String, String> expressions) {
796         if (!expressions.isEmpty()) {
797             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
798                 ImmutableMap.copyOf(expressions));
799         }
800     }
801
802     /**
803      * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
804      * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
805      *
806      * <p>
807      * It is assumed that <code>innerExtendedType</code> is already present in
808      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
809      * for the returning generated TO.
810      *
811      * @param typedef Type Definition
812      * @param innerExtendedType extended type which is part of some other extended type
813      * @param basePackageName string with the package name of the module
814      * @param moduleName Module Name
815      * @return generated TO which extends generated TO for <code>innerExtendedType</code>
816      * @throws IllegalArgumentException
817      *             <ul>
818      *             <li>if <code>extendedType</code> equals null</li>
819      *             <li>if <code>basePackageName</code> equals null</li>
820      *             <li>if <code>typedefName</code> equals null</li>
821      *             </ul>
822      */
823     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
824             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
825         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
826         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
827
828         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
829             BindingMapping.getClassName(typedef.getQName())));
830         genTOBuilder.setSchemaPath(typedef.getPath());
831         genTOBuilder.setModuleName(moduleName);
832         genTOBuilder.setTypedef(true);
833         addCodegenInformation(genTOBuilder, typedef);
834
835         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
836         genTOBuilder.setRestrictions(r);
837         addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
838
839         if (typedef.getStatus() == Status.DEPRECATED) {
840             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
841         }
842
843         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
844             genTOBuilder.setIsUnion(true);
845         }
846
847         Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
848         Map<String, GeneratedType> typeMap = null;
849         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
850         if (parentModule != null) {
851             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
852             typeMap = modulesByDate.get(parentModule.getRevision());
853         }
854
855         if (typeMap != null) {
856             final String innerTypeDef = innerExtendedType.getQName().getLocalName();
857             final GeneratedType type = typeMap.get(innerTypeDef);
858             if (type instanceof GeneratedTransferObject) {
859                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
860             }
861         }
862         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
863         makeSerializable(genTOBuilder);
864
865         return genTOBuilder.build();
866     }
867
868     /**
869      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
870      * property.
871      *
872      * @param gto transfer object which needs to be made serializable
873      */
874     private static void makeSerializable(final GeneratedTOBuilder gto) {
875         gto.addImplementsType(Types.serializableType());
876         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
877         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
878         gto.setSUID(prop);
879     }
880
881     /**
882      * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
883      * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
884      * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
885      * type definitions are in the list behind all type definitions on which depends.
886      *
887      * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
888      * @return list of type definitions sorted according their each other dependencies (type definitions which are
889      *              dependent on other type definitions are in list behind them).
890      */
891     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
892             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
893         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
894
895         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
896         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
897             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
898             List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
899                 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
900             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
901         }
902
903         // SortedMap guarantees order corresponding to keys in ascending order
904         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
905             sortedTypeDefinition.addAll(v);
906         }
907
908         return sortedTypeDefinition;
909     }
910
911     /**
912      * Returns how many immersion is necessary to get from the type definition to the base type.
913      *
914      * @param typeDefinition type definition for which is depth sought.
915      * @return number of immersions which are necessary to get from the type definition to the base type
916      */
917     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
918         // FIXME: rewrite this in a non-recursive manner
919         if (typeDefinition == null) {
920             return 1;
921         }
922         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
923         if (baseType == null) {
924             return 1;
925         }
926
927         int depth = 1;
928         if (baseType.getBaseType() != null) {
929             depth = depth + getTypeDefinitionDepth(baseType);
930         } else if (baseType instanceof UnionTypeDefinition) {
931             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
932             int maxChildDepth = 0;
933             int childDepth = 1;
934             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
935                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
936                 if (childDepth > maxChildDepth) {
937                     maxChildDepth = childDepth;
938                 }
939             }
940             return maxChildDepth;
941         }
942         return depth;
943     }
944
945     /**
946      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
947      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
948      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
949      *
950      * @param name string with name of augmented node
951      * @return string with the number suffix incremented by one (or 1 is added)
952      */
953     private static String provideAvailableNameForGenTOBuilder(final String name) {
954         final int dollar = name.indexOf('$');
955         if (dollar == -1) {
956             return name + "$1";
957         }
958
959         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
960         Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
961         return name.substring(0, dollar + 1) + newSuffix;
962     }
963
964     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
965         if (!Strings.isNullOrEmpty(units)) {
966             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
967             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
968             prop.setReturnType(Types.STRING);
969             to.addToStringProperty(prop);
970         }
971     }
972
973     /**
974      * Returns parent Yang Module for specified Schema Context in which Schema
975      * Node is declared. If the Schema Node is not present in Schema Context the
976      * operation will return <code>null</code>.
977      *
978      * @param context Schema Context
979      * @param schemaNode Schema Node
980      * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
981      *         return <code>null</code>
982      * @throws NullPointerException if any of the arguments is null
983      */
984     private static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
985         return context.findModule(schemaNode.getQName().getModule()).orElse(null);
986     }
987 }