Correct docs declaration
[mdsal.git] / binding2 / mdsal-binding2-generator-impl / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / yang / types / TypeProviderImpl.java
old mode 100644 (file)
new mode 100755 (executable)
index 31e1f0f..13b960b
@@ -8,6 +8,7 @@
 
 package org.opendaylight.mdsal.binding.javav2.generator.yang.types;
 
+import static java.util.Objects.requireNonNull;
 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.packageNameWithNamespacePrefix;
 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.getOuterClassPackageName;
@@ -26,21 +27,22 @@ import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findD
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
 
-import com.google.common.base.Optional;
 import com.google.common.annotations.Beta;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
-import com.google.common.collect.Sets;
 import java.util.ArrayList;
 import java.util.Collections;
-import java.util.Date;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+
 import org.opendaylight.mdsal.binding.javav2.generator.context.ModuleContext;
 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
@@ -63,6 +65,7 @@ import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignat
 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
@@ -101,9 +104,9 @@ public final class TypeProviderImpl implements TypeProvider {
     private final SchemaContext schemaContext;
 
     /**
-     * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
+     * Map&lt;moduleName, Map&lt;moduleDate, Map&lt;typeName, type&gt;&gt;&gt;.
      */
-    private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
+    private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap;
 
     /**
      * Map which maps schema paths to JAVA <code>Type</code>.
@@ -111,50 +114,45 @@ public final class TypeProviderImpl implements TypeProvider {
     private final Map<SchemaPath, Type> referencedTypes;
 
     /**
-     * Map for additional types e.g unions
+     * Map for additional types e.g unions.
      */
     private final Map<Module, Set<Type>> additionalTypes;
 
     /**
      * Creates new instance of class <code>TypeProviderImpl</code>.
      *
-     * @param schemaContext
-     *            contains the schema data red from YANG files
-     * @throws IllegalArgumentException
-     *             if <code>schemaContext</code> equal null.
+     * @param schemaContext contains the schema data red from YANG files
+     * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
      */
     public TypeProviderImpl(final SchemaContext schemaContext) {
         this.schemaContext = schemaContext;
         this.genTypeDefsContextMap = new HashMap<>();
         this.referencedTypes = new HashMap<>();
         this.additionalTypes = new HashMap<>();
-        resolveTypeDefsFromContext(schemaContext, this.genTypeDefsContextMap, this.additionalTypes);
+        resolveTypeDefsFromContext();
     }
 
     @Override
     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode,
-            ModuleContext context) {
+            final ModuleContext context) {
         return javaTypeForSchemaDefinitionType(type, parentNode, null, context);
     }
 
     /**
      * Converts schema definition type <code>typeDefinition</code> to JAVA
-     * <code>Type</code>
+     * <code>Type</code>.
      *
-     * @param type
-     *            type definition which is converted to JAVA type
-     * @throws IllegalArgumentException
-     *             <ul>
-     *             <li>if <code>typeDefinition</code> equal null</li>
-     *             <li>if QName of <code>typeDefinition</code> equal null</li>
-     *             <li>if name of <code>typeDefinition</code> equal null</li>
-     *             </ul>
+     * @param type type definition which is converted to JAVA type
+     * @throws IllegalArgumentException <ul>
+     *                                  <li>if <code>typeDefinition</code> equal null</li>
+     *                                  <li>if QName of <code>typeDefinition</code> equal null</li>
+     *                                  <li>if name of <code>typeDefinition</code> equal null</li>
+     *                                  </ul>
      */
     @Override
-    public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode, final
-            Restrictions restrictions, ModuleContext context) {
-        return javaTypeForSchemaDefType(type, parentNode, restrictions, this.schemaContext, this
-                .genTypeDefsContextMap, context);
+    public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode,
+            final Restrictions restrictions, final ModuleContext context) {
+        return javaTypeForSchemaDefType(type, parentNode, restrictions, context);
     }
 
     @Override
@@ -172,7 +170,7 @@ public final class TypeProviderImpl implements TypeProvider {
         return null;
     }
 
-    public Map<String, Map<Date, Map<String, Type>>> getGenTypeDefsContextMap() {
+    public Map<String, Map<Optional<Revision>, Map<String, Type>>> getGenTypeDefsContextMap() {
         return this.genTypeDefsContextMap;
     }
 
@@ -180,6 +178,7 @@ public final class TypeProviderImpl implements TypeProvider {
      * Passes through all modules and through all its type definitions and
      * convert it to generated types.
      *
+     * <p>
      * The modules are firstly sorted by mutual dependencies. The modules are
      * sequentially passed. All type definitions of a module are at the
      * beginning sorted so that type definition with less amount of references
@@ -188,17 +187,15 @@ public final class TypeProviderImpl implements TypeProvider {
      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
      * which map current module name to the map which maps type names to
      * returned types (generated types).
-     *
      */
-    private void resolveTypeDefsFromContext(final SchemaContext schemaContext, final Map<String, Map<Date, Map<String,
-            Type>>> genTypeDefsContextMap, final Map<Module, Set<Type>> additionalTypes) {
+    private void resolveTypeDefsFromContext() {
 
         final Set<Module> modules = schemaContext.getModules();
         Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
 
         for (final Module module : modulesSortedByDependency) {
-            Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
+            Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
             if (dateTypeMap == null) {
                 dateTypeMap = new HashMap<>();
             }
@@ -206,17 +203,13 @@ public final class TypeProviderImpl implements TypeProvider {
             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
         }
 
-        modulesSortedByDependency.stream().filter(module -> module != null).forEach(module -> {
+        modulesSortedByDependency.stream().filter(Objects::nonNull).forEach(module -> {
             ModuleContext context = new ModuleContext();
             final String basePackageName = packageNameWithNamespacePrefix(getRootPackageName(module),
                     BindingNamespaceType.Typedef);
             final List<TypeDefinition<?>> typeDefinitions = getAllTypedefs(module);
-            final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
-            if (listTypeDefinitions != null) {
-                for (final TypeDefinition<?> typedef : listTypeDefinitions) {
-                    typedefToGeneratedType(basePackageName, module, typedef, genTypeDefsContextMap,
-                            additionalTypes, schemaContext, context);
-                }
+            for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
+                typedefToGeneratedType(basePackageName, module, typedef, context);
             }
         });
     }
@@ -224,19 +217,18 @@ public final class TypeProviderImpl implements TypeProvider {
     /**
      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
      *
-     * @param typeDefinition
-     *            type definition which should be converted to JAVA
-     *            <code>Type</code>
+     * @param typeDefinition type definition which should be converted to JAVA
+     *                       <code>Type</code>
      * @return JAVA <code>Type</code> which represents
-     *         <code>typeDefinition</code>
-     * @throws IllegalArgumentException
-     *             <ul>
-     *             <li>if <code>typeDefinition</code> equal null</li>
-     *             <li>if Q name of <code>typeDefinition</code></li>
-     *             <li>if name of <code>typeDefinition</code></li>
-     *             </ul>
+     * <code>typeDefinition</code>
+     * @throws IllegalArgumentException <ul>
+     *                                  <li>if <code>typeDefinition</code> equal null</li>
+     *                                  <li>if Q name of <code>typeDefinition</code></li>
+     *                                  <li>if name of <code>typeDefinition</code></li>
+     *                                  </ul>
      */
-    public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
+    public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
+                                                       final SchemaNode parentNode) {
         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
                 "Type Definitions Local Name cannot be NULL!");
@@ -246,7 +238,8 @@ public final class TypeProviderImpl implements TypeProvider {
             final Module module = findParentModule(this.schemaContext, parentNode);
 
             if (module != null) {
-                final Map<Date, Map<String, Type>> modulesByDate = this.genTypeDefsContextMap.get(module.getName());
+                final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
+                        this.genTypeDefsContextMap.get(module.getName());
                 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
                 if (genTOs != null) {
                     return genTOs.get(typeDefinition.getQName().getLocalName());
@@ -257,18 +250,14 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     /**
-     * Puts <code>refType</code> to map with key <code>refTypePath</code>
-     *
-     * @param refTypePath
-     *            schema path used as the map key
-     * @param refType
-     *            type which represents the map value
-     * @throws IllegalArgumentException
-     *             <ul>
-     *             <li>if <code>refTypePath</code> equal null</li>
-     *             <li>if <code>refType</code> equal null</li>
-     *             </ul>
+     * Puts <code>refType</code> to map with key <code>refTypePath</code>.
      *
+     * @param refTypePath schema path used as the map key
+     * @param refType     type which represents the map value
+     * @throws IllegalArgumentException <ul>
+     *                                  <li>if <code>refTypePath</code> equal null</li>
+     *                                  <li>if <code>refType</code> equal null</li>
+     *                                  </ul>
      */
     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
         Preconditions.checkArgument(refTypePath != null,
@@ -281,25 +270,25 @@ public final class TypeProviderImpl implements TypeProvider {
      * Converts <code>typeDef</code> which should be of the type
      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
      *
+     * <p>
      * All the bits of the typeDef are added to returning generated TO as
      * properties.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typeDef
-     *            type definition from which is the generated TO builder created
-     * @param typeDefName
-     *            string with the name for generated TO builder
+     * @param basePackageName string with name of package to which the module belongs
+     * @param typeDef         type definition from which is the generated TO builder created
+     * @param typeDefName     string with the name for generated TO builder
      * @return generated TO builder which represents <code>typeDef</code>
-     * @throws IllegalArgumentException
-     *             <ul>
-     *             <li>if <code>typeDef</code> equals null</li>
-     *             <li>if <code>basePackageName</code> equals null</li>
-     *             </ul>
+     * @throws IllegalArgumentException <ul>
+     *                                  <li>if <code>typeDef</code> equals null</li>
+     *                                  <li>if <code>basePackageName</code> equals null</li>
+     *                                  </ul>
      */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
-            final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName, ModuleContext context) {
+                                                                             final TypeDefinition<?> typeDef, final
+                                                                             String typeDefName, final String
+                                                                                     moduleName,
+                                                                             final ModuleContext context) {
 
         Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
@@ -309,10 +298,10 @@ public final class TypeProviderImpl implements TypeProvider {
 
             final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName,
                     true, false, context);
-            final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
+            final String typedefDescription = encodeAngleBrackets(typeDef.getDescription().orElse(null));
 
             genTOBuilder.setDescription(typedefDescription);
-            genTOBuilder.setReference(typeDef.getReference());
+            typeDef.getReference().ifPresent(genTOBuilder::setReference);
             genTOBuilder.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
             genTOBuilder.setModuleName(moduleName);
             genTOBuilder.setBaseType(typeDef);
@@ -321,8 +310,8 @@ public final class TypeProviderImpl implements TypeProvider {
             GeneratedPropertyBuilder genPropertyBuilder;
             for (final Bit bit : bitList) {
                 final String name = bit.getName();
-                genPropertyBuilder =
-                        genTOBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(name, JavaIdentifier.METHOD));
+                genPropertyBuilder = genTOBuilder.addProperty(
+                        JavaIdentifierNormalizer.normalizeSpecificIdentifier(name, JavaIdentifier.METHOD));
                 genPropertyBuilder.setReadOnly(true);
                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
 
@@ -341,28 +330,24 @@ public final class TypeProviderImpl implements TypeProvider {
      * <code>typeDefName</code>. Every union type from <code>typedef</code> is
      * added to generated TO builder as property.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typedef
-     *            type definition which should be of type
-     *            <code>UnionTypeDefinition</code>
-     * @param typeDefName
-     *            string with name for generated TO
+     * @param basePackageName string with name of package to which the module belongs
+     * @param typedef         type definition which should be of type
+     *                        <code>UnionTypeDefinition</code>
+     * @param typeDefName     string with name for generated TO
      * @return generated TO builder which represents <code>typedef</code>
-     * @throws NullPointerException
-     *             <ul>
-     *             <li>if <code>basePackageName</code> is null</li>
-     *             <li>if <code>typedef</code> is null</li>
-     *             <li>if QName of <code>typedef</code> is null</li>
-     *             </ul>
+     * @throws NullPointerException <ul>
+     *                              <li>if <code>basePackageName</code> is null</li>
+     *                              <li>if <code>typedef</code> is null</li>
+     *                              <li>if QName of <code>typedef</code> is null</li>
+     *                              </ul>
      */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @SuppressWarnings({"rawtypes", "unchecked"})
     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
-        Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
-        Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
-        Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
+            final ModuleContext context) {
+        requireNonNull(basePackageName, "Base Package Name cannot be NULL!");
+        requireNonNull(typedef, "Type Definition cannot be NULL!");
+        requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
 
         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
@@ -371,36 +356,33 @@ public final class TypeProviderImpl implements TypeProvider {
         final GeneratedTOBuilderImpl unionGenTOBuilder;
         unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName, true, false,
                 context);
-        final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
+        final String typedefDescription = encodeAngleBrackets(typedef.getDescription().orElse(null));
         unionGenTOBuilder.setDescription(typedefDescription);
-        unionGenTOBuilder.setReference(typedef.getReference());
+        typedef.getReference().ifPresent(unionGenTOBuilder::setReference);
         unionGenTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot());
         unionGenTOBuilder.setModuleName(module.getName());
 
         generatedTOBuilders.add(unionGenTOBuilder);
         unionGenTOBuilder.setIsUnion(true);
-        final List<String> regularExpressions = new ArrayList<>();
+        final Map<String, String> expressions = new HashMap<>();
         for (final TypeDefinition<?> unionType : unionTypes) {
             final String unionTypeName = unionType.getQName().getLocalName();
             if (unionType.getBaseType() != null) {
-                resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
-                        parentNode, schemaContext, genTypeDefsContextMap);
+                resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
             } else if (unionType instanceof UnionTypeDefinition) {
                 generatedTOBuilders.add(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
-                        unionGenTOBuilder.getFullyQualifiedName(), parentNode, schemaContext, genTypeDefsContextMap,
-                        context));
+                        unionGenTOBuilder.getFullyQualifiedName(), parentNode, context));
             } else if (unionType instanceof EnumTypeDefinition) {
                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
                         unionTypeName, unionGenTOBuilder, context);
                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
             } else {
-                final Type javaType = javaTypeForSchemaDefType(unionType, parentNode, null, schemaContext,
-                        genTypeDefsContextMap, context);
+                final Type javaType = javaTypeForSchemaDefType(unionType, parentNode, null, context);
                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
             }
         }
-        if (!regularExpressions.isEmpty()) {
-            addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
+        if (!expressions.isEmpty()) {
+            addStringRegExAsConstant(unionGenTOBuilder, expressions);
         }
 
         //storeGenTO(typedef, unionGenTOBuilder, parentNode);
@@ -422,8 +404,7 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private Type javaTypeForSchemaDefType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
-            final Restrictions r, final SchemaContext schemaContext,
-            final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+            final Restrictions restrictions, final ModuleContext context) {
         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
         final String typedefName = typeDefinition.getQName().getLocalName();
         Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
@@ -434,16 +415,15 @@ public final class TypeProviderImpl implements TypeProvider {
             // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
             // a base type which holds these constraints.
             if (typeDefinition instanceof DecimalTypeDefinition) {
-                final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType
-                        (typeDefinition, parentNode, r, context);
+                final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
+                        parentNode, restrictions, context);
                 if (ret != null) {
                     return ret;
                 }
             }
 
             // Deal with leafrefs/identityrefs
-            Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, schemaContext,
-                    genTypeDefsContextMap, context);
+            Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, context);
             if (ret != null) {
                 return ret;
             }
@@ -457,8 +437,8 @@ public final class TypeProviderImpl implements TypeProvider {
             return ret;
         }
 
-        Type returnType = javaTypeForExtendedType(typeDefinition, schemaContext, genTypeDefsContextMap, context);
-        if (r != null && !r.isEmpty() && returnType instanceof GeneratedTransferObject) {
+        Type returnType = javaTypeForExtendedType(typeDefinition, context);
+        if (restrictions != null && !restrictions.isEmpty() && returnType instanceof GeneratedTransferObject) {
             final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
             final Module module = findParentModule(schemaContext, parentNode);
             final Module module1 = findParentModule(schemaContext, typeDefinition);
@@ -468,34 +448,30 @@ public final class TypeProviderImpl implements TypeProvider {
             final String genTOName =
                     JavaIdentifierNormalizer.normalizeSpecificIdentifier(typedefName, JavaIdentifier.CLASS);
             final String name = packageName + "." + genTOName;
-            if (module.equals(module1) && !(returnType.getFullyQualifiedName().equals(name))) {
-                returnType = shadedTOWithRestrictions(gto, r, context);
+            if (module.equals(module1) && !returnType.getFullyQualifiedName().equals(name)) {
+                returnType = shadedTOWithRestrictions(gto, restrictions, context);
             }
         }
         return returnType;
     }
 
     /**
-     *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param module
-     *            string with the name of the module for to which the
-     *            <code>typedef</code> belongs
-     * @param typedef
-     *            type definition of the node for which should be creted JAVA
-     *            <code>Type</code> (usually generated TO)
+     * Return JAVA <code>Type</code> representation of <code>typedef</code>.
+     * @param basePackageName string with name of package to which the module belongs
+     * @param module          string with the name of the module for to which the
+     *                        <code>typedef</code> belongs
+     * @param typedef         type definition of the node for which should be creted JAVA
+     *                        <code>Type</code> (usually generated TO)
      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
-     *         <code>null</code> value if <code>basePackageName</code> or
-     *         <code>modulName</code> or <code>typedef</code> or Q name of
-     *         <code>typedef</code> equals <code>null</code>
+     * <code>null</code> value if <code>basePackageName</code> or
+     * <code>modulName</code> or <code>typedef</code> or Q name of
+     * <code>typedef</code> equals <code>null</code>
      */
     private Type typedefToGeneratedType(final String basePackageName, final Module module,
-            final TypeDefinition<?> typedef, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
-            final Map<Module, Set<Type>> additionalTypes, final SchemaContext schemaContext, ModuleContext context) {
+            final TypeDefinition<?> typedef, final ModuleContext context) {
         final String moduleName = module.getName();
-        final Date moduleRevision = module.getRevision();
-        if ((basePackageName != null) && (moduleName != null) && (typedef != null)) {
+        final Optional<Revision> moduleRevision = module.getRevision();
+        if (basePackageName != null && moduleName != null && typedef != null) {
             final String typedefName = typedef.getQName().getLocalName();
             final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
             if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
@@ -506,11 +482,10 @@ public final class TypeProviderImpl implements TypeProvider {
                             module.getName(), schemaContext, genTypeDefsContextMap, context);
                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
-                            (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef, schemaContext,
-                            genTypeDefsContextMap, context);
+                            (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef, context);
                     genTOBuilder.setTypedef(true);
                     genTOBuilder.setIsUnion(true);
-                    addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+                    addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
                     returnType = genTOBuilder.toInstance();
                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
@@ -524,16 +499,17 @@ public final class TypeProviderImpl implements TypeProvider {
                             provideGeneratedTOBuilderForBitsTypeDefinition(
                                     basePackageName, bitsTypeDefinition, typedefName, module.getName(), context);
                     genTOBuilder.setTypedef(true);
-                    addUnitsToGenTO(genTOBuilder, typedef.getUnits());
+                    addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
                     returnType = genTOBuilder.toInstance();
                 } else {
                     final Type javaType = javaTypeForSchemaDefType(innerTypeDefinition, typedef, null,
-                            schemaContext, genTypeDefsContextMap, context);
+                            context);
                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName(), context);
                 }
                 if (returnType != null) {
-                    final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
+                    final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
+                        genTypeDefsContextMap.get(moduleName);
                     Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
                     if (typeMap != null) {
                         if (typeMap.isEmpty()) {
@@ -553,22 +529,20 @@ public final class TypeProviderImpl implements TypeProvider {
      * Returns JAVA <code>Type</code> for instances of the type
      * <code>ExtendedType</code>.
      *
-     * @param typeDefinition
-     *            type definition which is converted to JAVA <code>Type</code>
+     * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
      */
-    private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final SchemaContext schemaContext,
-            final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+    private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final ModuleContext context) {
 
         final String typedefName = typeDefinition.getQName().getLocalName();
         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
-        Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, schemaContext,
-                genTypeDefsContextMap, context);
+        Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, context);
         if (returnType == null) {
             final Module module = findParentModule(schemaContext, typeDefinition);
             final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
             if (module != null) {
-                final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
+                final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module
+                        .getName());
                 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
                 if (genTOs != null) {
                     returnType = genTOs.get(typedefName);
@@ -587,18 +561,16 @@ public final class TypeProviderImpl implements TypeProvider {
      * <code>LeafrefTypeDefinition</code> or
      * <code>IdentityrefTypeDefinition</code>.
      *
-     * @param typeDefinition
-     *            type definition which is converted to JAVA <code>Type</code>
+     * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
      */
     private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
-            ModuleContext context) {
+            final ModuleContext context) {
         if (typeDefinition instanceof LeafrefTypeDefinition) {
             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
             Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode, schemaContext),
-                "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
-            return provideTypeForLeafref(leafref, parentNode, schemaContext, genTypeDefsContextMap, context);
+                    "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
+            return provideTypeForLeafref(leafref, parentNode, context);
         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
             final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
             return provideTypeForIdentityref(idref, schemaContext);
@@ -610,24 +582,20 @@ public final class TypeProviderImpl implements TypeProvider {
     /**
      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
      *
+     * <p>
      * The path of <code>leafrefType</code> is followed to find referenced node
      * and its <code>Type</code> is returned.
      *
-     * @param leafrefType
-     *            leafref type definition for which is the type sought
+     * @param leafrefType leafref type definition for which is the type sought
      * @return JAVA <code>Type</code> of data schema node which is referenced in
-     *         <code>leafrefType</code>
-     * @throws IllegalArgumentException
-     *             <ul>
-     *             <li>if <code>leafrefType</code> equal null</li>
-     *             <li>if path statement of <code>leafrefType</code> equal null</li>
-     *             </ul>
-     *
+     * <code>leafrefType</code>
+     * @throws IllegalArgumentException <ul>
+     *                                  <li>if <code>leafrefType</code> equal null</li>
+     *                                  <li>if path statement of <code>leafrefType</code> equal null</li>
+     *                                  </ul>
      */
     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
-            ModuleContext context) {
-
+            final ModuleContext context) {
         Type returnType = null;
         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
 
@@ -640,8 +608,9 @@ public final class TypeProviderImpl implements TypeProvider {
             if (strXPath.indexOf('[') == -1) {
                 final Module module;
                 final SchemaNode actualParentSchemaNode;
-                if ((parentNode instanceof DerivableSchemaNode) && ((DerivableSchemaNode) parentNode).isAddedByUses()) {
-                    final Optional<? extends SchemaNode> originalNode = ((DerivableSchemaNode) parentNode).getOriginal();
+                if (parentNode instanceof DerivableSchemaNode && ((DerivableSchemaNode) parentNode).isAddedByUses()) {
+                    final Optional<? extends SchemaNode> originalNode = ((DerivableSchemaNode) parentNode)
+                            .getOriginal();
                     Preconditions.checkArgument(originalNode.isPresent(), "originalNode can not be null.");
                     actualParentSchemaNode = originalNode.get();
                     module = findParentModule(schemaContext, originalNode.get());
@@ -658,14 +627,15 @@ public final class TypeProviderImpl implements TypeProvider {
                     dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, actualParentSchemaNode, xpath);
                 }
                 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
-                        strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName().getModule());
+                        strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName()
+                                .getModule());
 
                 if (leafContainsEnumDefinition(dataNode)) {
                     returnType = this.referencedTypes.get(dataNode.getPath());
                 } else if (leafListContainsEnumDefinition(dataNode)) {
                     returnType = Types.listTypeFor(this.referencedTypes.get(dataNode.getPath()));
                 } else {
-                    returnType = resolveTypeFromDataSchemaNode(dataNode, schemaContext, genTypeDefsContextMap, context);
+                    returnType = resolveTypeFromDataSchemaNode(dataNode, context);
                 }
             } else {
                 returnType = Types.typeForClass(Object.class);
@@ -680,14 +650,13 @@ public final class TypeProviderImpl implements TypeProvider {
      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
      * so then checks if it is of type <code>EnumTypeDefinition</code>.
      *
-     * @param dataNode
-     *            data schema node for which is checked if it is leaf and if it
-     *            is of enum type
+     * @param dataNode data schema node for which is checked if it is leaf and if it
+     *                 is of enum type
      * @return boolean value
-     *         <ul>
-     *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
-     *         <li>false - other cases</li>
-     *         </ul>
+     * <ul>
+     * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
+     * <li>false - other cases</li>
+     * </ul>
      */
     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
         if (dataNode instanceof LeafSchemaNode) {
@@ -704,15 +673,14 @@ public final class TypeProviderImpl implements TypeProvider {
      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
      *
-     * @param dataNode
-     *            data schema node for which is checked if it is leaflist and if
-     *            it is of enum type
+     * @param dataNode data schema node for which is checked if it is leaflist and if
+     *                 it is of enum type
      * @return boolean value
-     *         <ul>
-     *         <li>true - if <code>dataNode</code> is leaflist of type
-     *         enumeration</li>
-     *         <li>false - other cases</li>
-     *         </ul>
+     * <ul>
+     * <li>true - if <code>dataNode</code> is leaflist of type
+     * enumeration</li>
+     * <li>false - other cases</li>
+     * </ul>
      */
     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
         if (dataNode instanceof LeafListSchemaNode) {
@@ -727,23 +695,20 @@ public final class TypeProviderImpl implements TypeProvider {
     /**
      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
      *
-     * @param dataNode
-     *            contains information about YANG type
+     * @param dataNode contains information about YANG type
      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
      */
-    private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final SchemaContext schemaContext,
-            final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, ModuleContext context) {
+    private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final ModuleContext context) {
         Type returnType = null;
         if (dataNode != null) {
             if (dataNode instanceof LeafSchemaNode) {
                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
                 //not using CompatUtils here anymore
                 final TypeDefinition<?> type = leaf.getType();
-                returnType = javaTypeForSchemaDefType(type, leaf, null, schemaContext, genTypeDefsContextMap, context);
+                returnType = javaTypeForSchemaDefType(type, leaf, null, context);
             } else if (dataNode instanceof LeafListSchemaNode) {
                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
-                returnType = javaTypeForSchemaDefType(leafList.getType(), leafList, null, schemaContext,
-                        genTypeDefsContextMap, context);
+                returnType = javaTypeForSchemaDefType(leafList.getType(), leafList, null, context);
             }
         }
         return returnType;
@@ -754,21 +719,21 @@ public final class TypeProviderImpl implements TypeProvider {
      * <code>type</code>.<br />
      * <br />
      *
+     * <p>
      * <i>Example:<br />
      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
      *
-     * @param idref
-     *            identityref type definition for which JAVA <code>Type</code>
-     *            is sought
+     * @param idref identityref type definition for which JAVA <code>Type</code>
+     *              is sought
      * @return JAVA <code>Type</code> of the identity which is refrenced through
-     *         <code>idref</code>
+     * <code>idref</code>
      */
-    private static Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref, final SchemaContext schemaContext) {
+    private static Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref,
+                                                  final SchemaContext schemaContext) {
         //TODO: incompatibility with Binding spec v2, get first or only one
         final QName baseIdQName = idref.getIdentities().iterator().next().getQName();
-        final Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
-                baseIdQName.getRevision());
+        final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
         IdentitySchemaNode identity = null;
         for (final IdentitySchemaNode id : module.getIdentities()) {
             if (id.getQName().equals(baseIdQName)) {
@@ -778,10 +743,11 @@ public final class TypeProviderImpl implements TypeProvider {
         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
 
         final String basePackageName = BindingMapping.getRootPackageName(module);
-        final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath
-                (), BindingNamespaceType.Identity);
+        final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath(),
+                BindingNamespaceType.Identity);
 
-        final String genTypeName = JavaIdentifierNormalizer.normalizeSpecificIdentifier(identity.getQName().getLocalName(),
+        final String genTypeName = JavaIdentifierNormalizer.normalizeSpecificIdentifier(identity.getQName()
+                        .getLocalName(),
                 JavaIdentifier.CLASS);
 
         final Type baseType = Types.typeForClass(Class.class);
@@ -790,13 +756,13 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
-            final Restrictions r, ModuleContext context) {
+            final Restrictions restrictions, final ModuleContext context) {
         final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName(), context);
         final GeneratedTransferObject parent = gto.getSuperType();
         if (parent != null) {
             gtob.setExtendsType(parent);
         }
-        gtob.setRestrictions(r);
+        gtob.setRestrictions(restrictions);
         for (final GeneratedProperty gp : gto.getProperties()) {
             final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
             gpb.setValue(gp.getValue());
@@ -813,19 +779,18 @@ public final class TypeProviderImpl implements TypeProvider {
      * Adds a new property with the name <code>propertyName</code> and with type
      * <code>type</code> to <code>unonGenTransObject</code>.
      *
-     * @param unionGenTransObject
-     *            generated TO to which should be property added
-     * @param type
-     *            JAVA <code>type</code> of the property which should be added
-     *            to <code>unionGentransObject</code>
-     * @param propertyName
-     *            string with name of property which should be added to
-     *            <code>unionGentransObject</code>
+     * @param unionGenTransObject generated TO to which should be property added
+     * @param type                JAVA <code>type</code> of the property which should be added
+     *                            to <code>unionGentransObject</code>
+     * @param propertyName        string with name of property which should be added to
+     *                            <code>unionGentransObject</code>
      */
-    private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
+    private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
+                                                  final String propertyName) {
         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
-                    .addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(propertyName, JavaIdentifier.METHOD));
+                    .addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(propertyName, JavaIdentifier
+                            .METHOD));
             propBuilder.setReturnType(type);
 
             unionGenTransObject.addEqualsIdentity(propBuilder);
@@ -838,37 +803,31 @@ public final class TypeProviderImpl implements TypeProvider {
      * Wraps code which handle case when union subtype is also of the type
      * <code>UnionType</code>.
      *
+     * <p>
      * In this case the new generated TO is created for union subtype (recursive
-     * call of method
-     * {@link #provideGeneratedTOBuilderForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode, SchemaContext, Map, ModuleContext)}
+     * call of method {@link #provideGeneratedTOBuilderForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode,
+     * SchemaContext, Map, ModuleContext)}
      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
      * <code>parentUnionGenTOBuilder</code> is created property which type is
      * equal to new generated TO.
      *
-     * @param parentUnionGenTOBuilder
-     *            generated TO builder to which is the property with the child
-     *            union subtype added
-     * @param basePackageName
-     *            string with the name of the module package
-     * @param unionSubtype
-     *            type definition which represents union subtype
-     * @return list of generated TO builders. The number of the builders can be
-     *         bigger one due to recursive call of
-     *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
+     * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child
+     *                                union subtype added
+     * @param basePackageName         string with the name of the module package
+     * @param unionSubtype            type definition which represents union subtype
+     * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
+     *      <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
      */
     private GeneratedTOBuilder resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
             final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
-            ModuleContext context) {
-
+            final ModuleContext context) {
         final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
         final GeneratedTOBuilder subUnionGenTOBUilder = provideGeneratedTOBuilderForUnionTypeDef(
-                basePackageName, unionSubtype, newTOBuilderName, parentNode, schemaContext, genTypeDefsContextMap,
-                context);
+                basePackageName, unionSubtype, newTOBuilderName, parentNode, context);
 
         final GeneratedPropertyBuilder propertyBuilder;
-        propertyBuilder = parentUnionGenTOBuilder
-                .addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(newTOBuilderName, JavaIdentifier.METHOD));
+        propertyBuilder = parentUnionGenTOBuilder.addProperty(
+                JavaIdentifierNormalizer.normalizeSpecificIdentifier(newTOBuilderName, JavaIdentifier.METHOD));
         propertyBuilder.setReturnType(subUnionGenTOBUilder);
         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
@@ -880,23 +839,18 @@ public final class TypeProviderImpl implements TypeProvider {
      * Converts output list of generated TO builders to one TO builder (first
      * from list) which contains the remaining builders as its enclosing TO.
      *
-     * @param basePackageName
-     *            string with name of package to which the module belongs
-     * @param typedef
-     *            type definition which should be of type
-     *            <code>UnionTypeDefinition</code>
-     * @param typeDefName
-     *            string with name for generated TO
-     * @return generated TO builder with the list of enclosed generated TO
-     *         builders
+     * @param basePackageName string with name of package to which the module belongs
+     * @param typedef         type definition which should be of type
+     *                        <code>UnionTypeDefinition</code>
+     * @param typeDefName     string with name for generated TO
+     * @return generated TO builder with the list of enclosed generated TO builders
      */
     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap,
-            ModuleContext context) {
+            final ModuleContext context) {
 
         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
-                typedef, typeDefName, parentNode, schemaContext, genTypeDefsContextMap, context);
+                typedef, typeDefName, parentNode, context);
         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
 
         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
@@ -918,7 +872,7 @@ public final class TypeProviderImpl implements TypeProvider {
 
 
     private GeneratedTOBuilder provideGeneratedTOBuilderForUnionBuilder(final Module parentModule,
-            final GeneratedTOBuilder genTOBuilder) {
+                                                                        final GeneratedTOBuilder genTOBuilder) {
         final String outerCls = Types.getOuterClassName(genTOBuilder);
         final StringBuilder name;
         if (outerCls != null) {
@@ -938,13 +892,7 @@ public final class TypeProviderImpl implements TypeProvider {
         method.setAccessModifier(AccessModifier.PUBLIC);
         method.setStatic(true);
 
-        final Set<Type> types = this.getAdditionalTypes().get(parentModule);
-        if (types == null) {
-            this.getAdditionalTypes().put(parentModule,
-                    Sets.newHashSet(unionBuilder.toInstance()));
-        } else {
-            types.add(unionBuilder.toInstance());
-        }
+        getAdditionalTypes().computeIfAbsent(parentModule, key -> new HashSet<>()).add(unionBuilder.toInstance());
 
         return unionBuilder;
     }
@@ -953,42 +901,53 @@ public final class TypeProviderImpl implements TypeProvider {
      * Wraps code which handle case when union subtype is of the type
      * <code>ExtendedType</code>.
      *
+     * <p>
      * If TO for this type already exists it is used for the creation of the
      * property in <code>parentUnionGenTOBuilder</code>. In other case the base
      * type is used for the property creation.
      *
-     * @param parentUnionGenTOBuilder
-     *            generated TO builder in which new property is created
-     * @param unionSubtype
-     *            type definition of the <code>ExtendedType</code> type which
-     *            represents union subtype
-     * @param regularExpressions
-     *            list of strings with the regular expressions
-     * @param parentNode
-     *            parent Schema Node for Extended Subtype
-     *
+     * @param parentUnionGenTOBuilder generated TO builder in which new property is created
+     * @param unionSubtype            type definition of the <code>ExtendedType</code> type which
+     *                                represents union subtype
+     * @param expressions             map of strings with the regular expressions
+     * @param parentNode              parent Schema Node for Extended Subtype
      */
-    private static void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
-            final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
-
+    private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
+            final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
         final String unionTypeName = unionSubtype.getQName().getLocalName();
         final Type genTO = findGenTO(unionTypeName, unionSubtype, schemaContext, genTypeDefsContextMap);
         if (genTO != null) {
             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, unionTypeName);
-        } else {
-            final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
-            if (unionTypeName.equals(baseType.getQName().getLocalName())) {
-                final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
-                        parentNode, null);
-                if (javaType != null) {
-                    updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
+            return;
+        }
+
+        final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
+        if (unionTypeName.equals(baseType.getQName().getLocalName())) {
+            final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
+                    parentNode, null);
+            if (javaType != null) {
+                updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
+            }
+        } else if (baseType instanceof LeafrefTypeDefinition) {
+            final Type javaType = javaTypeForSchemaDefinitionType(baseType,
+                    parentNode, null);
+            boolean typeExist = false;
+            for (final GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder
+                    .getProperties()) {
+                final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
+                if (origType != null && javaType != null && javaType == origType) {
+                    typeExist = true;
+                    break;
                 }
             }
-            if (baseType instanceof StringTypeDefinition) {
-                regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
+            if (!typeExist && javaType != null) {
+                updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
+                        javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
             }
         }
+        if (baseType instanceof StringTypeDefinition) {
+            expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
+        }
     }
 
     /**
@@ -996,8 +955,7 @@ public final class TypeProviderImpl implements TypeProvider {
      * integer suffix is incremented by one. If <code>name</code> contains no
      * number suffix then number 1 is added.
      *
-     * @param name
-     *            string with name of augmented node
+     * @param name string with name of augmented node
      * @return string with the number suffix incremented by one (or 1 is added)
      */
     private static String provideAvailableNameForGenTOBuilder(final String name) {
@@ -1012,19 +970,20 @@ public final class TypeProviderImpl implements TypeProvider {
 
     /**
      * Searches for generated TO for <code>searchedTypeDef</code> type
-     * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
+     * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
      *
-     * @param searchedTypeName
-     *            string with name of <code>searchedTypeDef</code>
+     * @param searchedTypeName string with name of <code>searchedTypeDef</code>
      * @return generated TO for <code>searchedTypeDef</code> or
-     *         <code>null</code> it it doesn't exist
+     * <code>null</code> it it doesn't exist
      */
     private static Type findGenTO(final String searchedTypeName, final SchemaNode parentNode,
-            final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
+                                  final SchemaContext schemaContext, final Map<String, Map<Optional<Revision>,
+            Map<String, Type>>> genTypeDefsContextMap) {
 
         final Module typeModule = findParentModule(schemaContext, parentNode);
         if (typeModule != null && typeModule.getName() != null) {
-            final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
+            final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule
+                    .getName());
             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
             if (genTOs != null) {
                 return genTOs.get(searchedTypeName);
@@ -1037,41 +996,38 @@ public final class TypeProviderImpl implements TypeProvider {
      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
      * taken from <code>enumTypeDef</code>.
      *
-     * @param enumTypeDef
-     *            enumeration type definition is source of enumeration data for
-     *            <code>typeBuilder</code>
-     * @param enumName
-     *            string with the name of enumeration
-     * @param typeBuilder
-     *            generated type builder to which is enumeration added
+     * @param enumTypeDef enumeration type definition is source of enumeration data for
+     *                    <code>typeBuilder</code>
+     * @param enumName    string with the name of enumeration
+     * @param typeBuilder generated type builder to which is enumeration added
      * @return enumeration type which contains enumeration data form
-     *         <code>enumTypeDef</code>
-     * @throws IllegalArgumentException
-     *             <ul>
-     *             <li>if <code>enumTypeDef</code> equals null</li>
-     *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
-     *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
-     *             <li>if name of <code>enumTypeDef</code> equal null</li>
-     *             <li>if name of <code>typeBuilder</code> equal null</li>
-     *             </ul>
-     *
+     * <code>enumTypeDef</code>
+     * @throws IllegalArgumentException <ul>
+     *                                  <li>if <code>enumTypeDef</code> equals null</li>
+     *                                  <li>if enum values of <code>enumTypeDef</code> equal null</li>
+     *                                  <li>if Q name of <code>enumTypeDef</code> equal null</li>
+     *                                  <li>if name of <code>enumTypeDef</code> equal null</li>
+     *                                  <li>if name of <code>typeBuilder</code> equal null</li>
+     *                                  </ul>
      */
     private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
-            final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder, ModuleContext context) {
+                                                                final String enumName, final
+                                                                GeneratedTypeBuilderBase<?> typeBuilder, final
+                                                                ModuleContext context) {
         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
 
         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName, context);
-        final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
+        final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription().orElse(null));
         enumBuilder.setDescription(enumTypedefDescription);
         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
         return enumBuilder.toInstance(enumBuilder);
     }
 
     private static boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode,
-            final SchemaContext schemaContext) {
+                                                  final SchemaContext schemaContext) {
         final SchemaNode leafRefValueNode;
         final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
         final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
@@ -1111,7 +1067,7 @@ public final class TypeProviderImpl implements TypeProvider {
         } else {
             leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
         }
-        return (leafRefValueNode != null) && leafRefValueNode.equals(parentNode);
+        return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
     }