Migrate getDataChildByName() users
[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 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataTreeSchemaNode;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
15
16 import com.google.common.annotations.Beta;
17 import com.google.common.annotations.VisibleForTesting;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Strings;
20 import com.google.common.collect.ImmutableMap;
21 import java.math.BigDecimal;
22 import java.util.ArrayList;
23 import java.util.Base64;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Optional;
33 import java.util.Set;
34 import java.util.TreeMap;
35 import java.util.regex.Pattern;
36 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
37 import org.opendaylight.mdsal.binding.generator.util.BaseYangTypesProvider;
38 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
39 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
40 import org.opendaylight.mdsal.binding.model.api.Enumeration;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
43 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
44 import org.opendaylight.mdsal.binding.model.api.Restrictions;
45 import org.opendaylight.mdsal.binding.model.api.Type;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
52 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
53 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
54 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
55 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
56 import org.opendaylight.mdsal.binding.model.util.Types;
57 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
58 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
59 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.common.Revision;
62 import org.opendaylight.yangtools.yang.common.Uint16;
63 import org.opendaylight.yangtools.yang.common.Uint32;
64 import org.opendaylight.yangtools.yang.common.Uint64;
65 import org.opendaylight.yangtools.yang.common.Uint8;
66 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
67 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.Module;
72 import org.opendaylight.yangtools.yang.model.api.PathExpression;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
76 import org.opendaylight.yangtools.yang.model.api.Status;
77 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
81 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
87 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
88 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
89 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
90 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
91 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
92 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
93 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
94 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
95 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
98
99 @Beta
100 public abstract class AbstractTypeProvider implements TypeProvider {
101     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
102     private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
103     private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
104
105     // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
106     // the case, as unions are emitted to their correct schema path.
107     private static final SchemaPath UNION_PATH = SchemaPath.create(true,
108         org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
109
110     /**
111      * Contains the schema data red from YANG files.
112      */
113     private final SchemaContext schemaContext;
114
115     private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
116
117     /**
118      * The map which maps schema paths to JAVA <code>Type</code>.
119      */
120     private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
121     private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
122     private final Map<SchemaNode, JavaTypeName> renames;
123
124     /**
125      * Creates new instance of class <code>TypeProviderImpl</code>.
126      *
127      * @param schemaContext contains the schema data red from YANG files
128      * @param renames renaming table
129      * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
130      */
131     AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
132         Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
133         this.schemaContext = schemaContext;
134         this.renames = requireNonNull(renames);
135         resolveTypeDefsFromContext();
136     }
137
138     /**
139      * Puts <code>refType</code> to map with key <code>refTypePath</code>.
140      *
141      * @param refTypePath schema path used as the map key
142      * @param refType type which represents the map value
143      * @throws IllegalArgumentException
144      *             <ul>
145      *             <li>if <code>refTypePath</code> equal null</li>
146      *             <li>if <code>refType</code> equal null</li>
147      *             </ul>
148      *
149      */
150     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
151         Preconditions.checkArgument(refTypePath != null,
152                 "Path reference of Enumeration Type Definition cannot be NULL!");
153         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
154         referencedTypes.put(refTypePath, refType);
155     }
156
157     public Map<Module, Set<Type>> getAdditionalTypes() {
158         return additionalTypes;
159     }
160
161     @Override
162     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
163             final boolean lenientRelativeLeafrefs) {
164         return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
165     }
166
167     /**
168      * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
169      *
170      * @param typeDefinition type definition which is converted to JAVA type
171      * @throws IllegalArgumentException
172      *             <ul>
173      *             <li>if <code>typeDefinition</code> equal null</li>
174      *             <li>if Qname of <code>typeDefinition</code> equal null</li>
175      *             <li>if name of <code>typeDefinition</code> equal null</li>
176      *             </ul>
177      */
178     @Override
179     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
180             final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
181         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
182         Preconditions.checkArgument(typeDefinition.getQName() != null,
183                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
184         final String typedefName = typeDefinition.getQName().getLocalName();
185         Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
186
187         // Deal with base types
188         if (typeDefinition.getBaseType() == null) {
189             // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
190             // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
191             // a base type which holds these constraints.
192             if (typeDefinition instanceof DecimalTypeDefinition) {
193                 final Type ret = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(typeDefinition,
194                     parentNode, restrictions, lenientRelativeLeafrefs);
195                 if (ret != null) {
196                     return ret;
197                 }
198             }
199
200             // Deal with leafrefs/identityrefs
201             Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
202             if (ret != null) {
203                 return ret;
204             }
205
206             // FIXME: it looks as though we could be using the same codepath as above...
207             ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
208             if (ret == null) {
209                 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
210             }
211
212             return ret;
213         }
214
215         Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
216         if (restrictions != null && returnType instanceof GeneratedTransferObject) {
217             final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
218             final Module module = findParentModule(schemaContext, parentNode);
219             final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
220             final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
221                 typeDefinition.getPath());
222             final String genTOName = BindingMapping.getClassName(typedefName);
223             final String name = packageName + "." + genTOName;
224             if (!returnType.getFullyQualifiedName().equals(name)) {
225                 returnType = shadedTOWithRestrictions(gto, restrictions);
226             }
227         }
228         return returnType;
229     }
230
231     public SchemaNode getTargetForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
232         final PathExpression xpath = leafrefType.getPathStatement();
233         Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
234
235         final Module module = findParentModule(schemaContext, parentNode);
236         Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
237
238         return xpath.isAbsolute() ? findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath)
239                 : findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
240     }
241
242     private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
243             final Restrictions restrictions) {
244         final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
245         final GeneratedTransferObject parent = gto.getSuperType();
246         if (parent != null) {
247             gtob.setExtendsType(parent);
248         }
249         gtob.setRestrictions(restrictions);
250         for (GeneratedProperty gp : gto.getProperties()) {
251             final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
252             gpb.setValue(gp.getValue());
253             gpb.setReadOnly(gp.isReadOnly());
254             gpb.setAccessModifier(gp.getAccessModifier());
255             gpb.setReturnType(gp.getReturnType());
256             gpb.setFinal(gp.isFinal());
257             gpb.setStatic(gp.isStatic());
258         }
259         return gtob.build();
260     }
261
262     private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
263         /*
264          * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
265          * are resolved.
266          */
267         DataNodeContainer current = null;
268         DataSchemaNode dataChildByName;
269         for (QName next : parentNode.getPath().getPathFromRoot()) {
270             if (current == null) {
271                 dataChildByName = schemaContext.dataChildByName(next);
272             } else {
273                 dataChildByName = current.dataChildByName(next);
274             }
275             if (dataChildByName == null) {
276                 return false;
277             }
278             if (dataChildByName.isAugmenting()) {
279                 return false;
280             }
281             if (dataChildByName instanceof DataNodeContainer) {
282                 current = (DataNodeContainer) dataChildByName;
283             }
284         }
285
286         // Then try to look up the expression.
287         final PathExpression leafRefXPath = leafref.getPathStatement();
288         final Module parentModule = getParentModule(parentNode);
289         final SchemaNode leafRefValueNode;
290         if (leafRefXPath.isAbsolute()) {
291             leafRefValueNode = SchemaContextUtil.findDataTreeSchemaNode(schemaContext, parentModule.getQNameModule(),
292                 leafRefXPath);
293         } else {
294             leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
295                 parentNode, new PathExpressionImpl(
296                     GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), false));
297         }
298
299         return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
300     }
301
302     /**
303      * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
304      * <code>IdentityrefTypeDefinition</code>.
305      *
306      * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
307      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
308      */
309     private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
310             final boolean inGrouping) {
311         if (typeDefinition instanceof LeafrefTypeDefinition) {
312             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
313             Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
314                 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
315             return provideTypeForLeafref(leafref, parentNode, inGrouping);
316         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
317             return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
318         }
319
320         return null;
321     }
322
323     /**
324      * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
325      *
326      * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
327      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
328      */
329     private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
330         final String typedefName = typeDefinition.getQName().getLocalName();
331         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
332         Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
333         if (returnType == null) {
334             if (baseTypeDef instanceof EnumTypeDefinition) {
335                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
336                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
337             } else {
338                 final Module module = findParentModule(schemaContext, typeDefinition);
339                 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
340                 if (module != null) {
341                     final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
342                         module.getName());
343                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
344                     if (genTOs != null) {
345                         returnType = genTOs.get(typedefName);
346                     }
347                     if (returnType == null) {
348                         returnType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseTypeDef,
349                             typeDefinition, r, lenient);
350                     }
351                 }
352             }
353         }
354         return returnType;
355     }
356
357     /**
358      * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
359      *
360      * <p>
361      * <i>Example:<br />
362      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
363      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
364      *
365      * @param idref identityref type definition for which JAVA <code>Type</code> is sought
366      * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
367      */
368     private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
369         final Collection<? extends IdentitySchemaNode> identities = idref.getIdentities();
370         if (identities.size() > 1) {
371             LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
372         }
373
374         final QName baseIdQName = identities.iterator().next().getQName();
375         final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
376         IdentitySchemaNode identity = null;
377         for (IdentitySchemaNode id : module.getIdentities()) {
378             if (id.getQName().equals(baseIdQName)) {
379                 identity = id;
380             }
381         }
382         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exist");
383
384         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
385         final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
386             basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
387         return Types.classType(Types.wildcardTypeFor(identifier));
388     }
389
390     /**
391      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
392      *
393      * @param typeDefinition
394      *            type definition which should be converted to JAVA
395      *            <code>Type</code>
396      * @return JAVA <code>Type</code> which represents
397      *         <code>typeDefinition</code>
398      * @throws IllegalArgumentException
399      *             <ul>
400      *             <li>if <code>typeDefinition</code> equal null</li>
401      *             <li>if Q name of <code>typeDefinition</code></li>
402      *             <li>if name of <code>typeDefinition</code></li>
403      *             </ul>
404      */
405     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
406             final SchemaNode parentNode) {
407         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
408         if (typeDefinition.getQName() == null) {
409             throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
410         }
411         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
412                 "Type Definitions Local Name cannot be NULL!");
413
414         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
415         if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
416             /*
417              * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
418              * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
419              * this:
420              *
421              *     identity iden;
422              *
423              *     container foo {
424              *         leaf foo {
425              *             type identityref {
426              *                 base iden;
427              *             }
428              *         }
429              *     }
430              *
431              * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
432              * dicey when we throw in:
433              *
434              *     typedef bar-ref {
435              *         type identityref {
436              *             base iden;
437              *         }
438              *     }
439              *
440              *     container bar {
441              *         leaf bar {
442              *             type bar-ref;
443              *         }
444              *     }
445              *
446              * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
447              * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
448              * is formed.
449              *
450              * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
451              * an encapsulation for identityref typedefs.
452              *
453              * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
454              * option, as it would look as though it is the product of a different construct:
455              *
456              *     identity bar-ref {
457              *         base iden;
458              *     }
459              *
460              * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
461              * sub-identities of iden.
462              *
463              * The story behind leafrefs is probably similar, but that needs to be ascertained.
464              */
465             return null;
466         }
467
468         final Module module = findParentModule(schemaContext, parentNode);
469         if (module != null) {
470             final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
471                 module.getName());
472             final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
473             if (genTOs != null) {
474                 return genTOs.get(typeDefinition.getQName().getLocalName());
475             }
476         }
477         return null;
478     }
479
480     /**
481      * Gets base type definition for <code>extendTypeDef</code>. The method is
482      * recursively called until non <code>ExtendedType</code> type is found.
483      *
484      * @param extendTypeDef
485      *            type definition for which is the base type definition sought
486      * @return type definition which is base type for <code>extendTypeDef</code>
487      * @throws IllegalArgumentException
488      *             if <code>extendTypeDef</code> equal null
489      */
490     private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
491         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
492
493         TypeDefinition<?> ret = extendTypeDef;
494         while (ret.getBaseType() != null) {
495             ret = ret.getBaseType();
496         }
497
498         return ret;
499     }
500
501     /**
502      * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
503      * to find referenced node and its <code>Type</code> is returned.
504      *
505      * @param leafrefType leafref type definition for which is the type sought
506      * @param parentNode parent node of the leaf being resolved
507      * @param inGrouping true if we are resolving the type within a grouping.
508      * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
509      * @throws IllegalArgumentException
510      *             <ul>
511      *             <li>if <code>leafrefType</code> equal null</li>
512      *             <li>if path statement of <code>leafrefType</code> equal null</li>
513      *             </ul>
514      */
515     @VisibleForTesting
516     Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
517             final boolean inGrouping) {
518         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
519
520         final PathExpression xpath = leafrefType.getPathStatement();
521         Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
522
523         final String strXPath = xpath.getOriginalString();
524         if (strXPath.indexOf('[') != -1) {
525             // XXX: why are we special-casing this?
526             return Types.objectType();
527         }
528
529         final Module module = findParentModule(schemaContext, parentNode);
530         Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
531
532         final SchemaNode dataNode;
533         if (xpath.isAbsolute()) {
534             dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
535         } else {
536             dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
537             if (dataNode == null && inGrouping) {
538                 // Relative path within a grouping may end up being unresolvable because it may refer outside
539                 // the grouping, in which case it is polymorphic based on instantiation, for example:
540                 //
541                 // grouping foo {
542                 //     leaf foo {
543                 //         type leafref {
544                 //             path "../../bar";
545                 //         }
546                 //     }
547                 // }
548                 //
549                 // container one {
550                 //     leaf bar {
551                 //         type string;
552                 //     }
553                 //     uses foo;
554                 // }
555                 //
556                 // container two {
557                 //     leaf bar {
558                 //         type uint16;
559                 //     }
560                 //     uses foo;
561                 // }
562                 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
563                     parentNode);
564                 return Types.objectType();
565             }
566         }
567         Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
568                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
569
570         // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
571         Type returnType = null;
572         if (leafContainsEnumDefinition(dataNode)) {
573             returnType = referencedTypes.get(dataNode.getPath());
574         } else if (leafListContainsEnumDefinition(dataNode)) {
575             returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
576         }
577         if (returnType == null) {
578             returnType = resolveTypeFromDataSchemaNode(dataNode, inGrouping);
579         }
580         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
581                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
582         return returnType;
583     }
584
585     /**
586      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
587      * <code>EnumTypeDefinition</code>.
588      *
589      * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
590      * @return boolean value
591      *         <ul>
592      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
593      *         <li>false - other cases</li>
594      *         </ul>
595      */
596     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
597         if (dataNode instanceof LeafSchemaNode) {
598             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
599             return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
600         }
601         return false;
602     }
603
604     /**
605      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
606      * <code>EnumTypeDefinition</code>.
607      *
608      * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
609      * @return boolean value
610      *         <ul>
611      *         <li>true - if <code>dataNode</code> is leaflist of type
612      *         enumeration</li>
613      *         <li>false - other cases</li>
614      *         </ul>
615      */
616     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
617         if (dataNode instanceof LeafListSchemaNode) {
618             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
619             return leafList.getType() instanceof EnumTypeDefinition;
620         }
621         return false;
622     }
623
624     /**
625      * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
626      *
627      * @param enumTypeDef enumeration type definition which is converted to enumeration
628      * @param enumName string with name which is used as the enumeration name
629      * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
630      * @throws IllegalArgumentException
631      *             <ul>
632      *             <li>if <code>enumTypeDef</code> equals null</li>
633      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
634      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
635      *             <li>if name of <code>enumTypeDef</code> equal null</li>
636      *             </ul>
637      */
638     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
639             final SchemaNode parentNode) {
640         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
641         Preconditions.checkArgument(enumTypeDef.getValues() != null,
642                 "EnumTypeDefinition MUST contain at least ONE value definition!");
643         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
644         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
645                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
646
647         final Module module = findParentModule(schemaContext, parentNode);
648         final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
649             BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
650         addEnumDescription(enumBuilder, enumTypeDef);
651         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
652         enumBuilder.setModuleName(module.getName());
653         enumBuilder.setSchemaPath(enumTypeDef.getPath());
654         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
655         return enumBuilder.toInstance(null);
656     }
657
658     /**
659      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
660      *
661      * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
662      * @param enumName string with the name of enumeration
663      * @param typeBuilder generated type builder to which is enumeration added
664      * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
665      * @throws IllegalArgumentException
666      *             <ul>
667      *             <li>if <code>enumTypeDef</code> equals null</li>
668      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
669      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
670      *             <li>if name of <code>enumTypeDef</code> equal null</li>
671      *             <li>if name of <code>typeBuilder</code> equal null</li>
672      *             </ul>
673      *
674      */
675     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
676             final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
677         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
678         Preconditions.checkArgument(enumTypeDef.getValues() != null,
679                 "EnumTypeDefinition MUST contain at least ONE value definition!");
680         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
681         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
682                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
683         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
684
685         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
686
687         addEnumDescription(enumBuilder, enumTypeDef);
688         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
689         return enumBuilder.toInstance(enumBuilder);
690     }
691
692     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
693
694     public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
695
696     public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
697
698     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
699
700     /**
701      * Converts the pattern constraints to the list of the strings which represents these constraints.
702      *
703      * @param patternConstraints list of pattern constraints
704      * @return list of strings which represents the constraint patterns
705      */
706     public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
707
708     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
709
710     /**
711      * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
712      * constraints.
713      *
714      * @param typedef extended type in which are the pattern constraints sought
715      * @return list of strings which represents the constraint patterns
716      * @throws IllegalArgumentException if <code>typedef</code> equals null
717      *
718      */
719     private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
720         if (!(typedef instanceof StringTypeDefinition)) {
721             return ImmutableMap.of();
722         }
723
724         // TODO: run diff against base ?
725         return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
726     }
727
728     /**
729      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
730      *
731      * @param dataNode contains information about YANG type
732      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
733      */
734     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final boolean inGrouping) {
735         Type returnType = null;
736         if (dataNode != null) {
737             if (dataNode instanceof LeafSchemaNode) {
738                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
739                 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
740                 returnType = javaTypeForSchemaDefinitionType(type, leaf, inGrouping);
741             } else if (dataNode instanceof LeafListSchemaNode) {
742                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
743                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList, inGrouping);
744             }
745         }
746         return returnType;
747     }
748
749     /**
750      * Passes through all modules and through all its type definitions and convert it to generated types.
751      *
752      * <p>
753      * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
754      * of a module are at the beginning sorted so that type definition with less amount of references to other type
755      * definition are processed first.<br>
756      * For each module is created mapping record in the map
757      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
758      * which map current module name to the map which maps type names to returned types (generated types).
759      */
760     private void resolveTypeDefsFromContext() {
761         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
762
763         for (Module module : modulesSortedByDependency) {
764             Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
765                 module.getName(), key -> new HashMap<>());
766             dateTypeMap.put(module.getRevision(), Collections.emptyMap());
767             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
768         }
769
770         for (Module module : modulesSortedByDependency) {
771             if (module != null) {
772                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
773                 if (basePackageName != null) {
774                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
775                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
776                         typedefToGeneratedType(basePackageName, module, typedef);
777                     }
778                 }
779             }
780         }
781     }
782
783     /**
784      * Create Type for specified type definition.
785      *
786      * @param basePackageName string with name of package to which the module belongs
787      * @param module string with the name of the module for to which the <code>typedef</code> belongs
788      * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
789      *                (usually generated TO)
790      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
791      *         <code>null</code> value if <code>basePackageName</code> or
792      *         <code>modulName</code> or <code>typedef</code> or Q name of
793      *         <code>typedef</code> equals <code>null</code>
794      */
795     private Type typedefToGeneratedType(final String basePackageName, final Module module,
796             final TypeDefinition<?> typedef) {
797         final TypeDefinition<?> baseTypedef = typedef.getBaseType();
798
799         // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
800         if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
801             return null;
802         }
803
804         final String typedefName = typedef.getQName().getLocalName();
805
806         final Type returnType;
807         if (baseTypedef.getBaseType() != null) {
808             returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
809                 module.getName());
810         } else if (baseTypedef instanceof UnionTypeDefinition) {
811             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
812                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
813                 (UnionTypeDefinition) baseTypedef, typedef);
814             genTOBuilder.setTypedef(true);
815             genTOBuilder.setIsUnion(true);
816             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
817             makeSerializable(genTOBuilder);
818             returnType = genTOBuilder.build();
819
820             // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
821             // so we are placing the builder alongside the union.
822             final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
823                 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
824             unionBuilder.setIsUnionBuilder(true);
825             final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
826             method.setReturnType(returnType);
827             method.addParameter(Types.STRING, "defaultValue");
828             method.setAccessModifier(AccessModifier.PUBLIC);
829             method.setStatic(true);
830             additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
831         } else if (baseTypedef instanceof EnumTypeDefinition) {
832             // enums are automatically Serializable
833             final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
834             // TODO units for typedef enum
835             returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
836         } else if (baseTypedef instanceof BitsTypeDefinition) {
837             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
838                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
839                 (BitsTypeDefinition) baseTypedef, module.getName());
840             genTOBuilder.setTypedef(true);
841             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
842             makeSerializable(genTOBuilder);
843             returnType = genTOBuilder.build();
844         } else {
845             final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
846             returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
847         }
848         if (returnType != null) {
849             final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
850                     genTypeDefsContextMap.get(module.getName());
851             final Optional<Revision> moduleRevision = module.getRevision();
852             Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
853             if (typeMap != null) {
854                 if (typeMap.isEmpty()) {
855                     typeMap = new HashMap<>(4);
856                     modulesByDate.put(moduleRevision, typeMap);
857                 }
858                 typeMap.put(typedefName, returnType);
859             }
860             return returnType;
861         }
862         return null;
863     }
864
865     /**
866      * Wraps base YANG type to generated TO.
867      *
868      * @param basePackageName string with name of package to which the module belongs
869      * @param typedef type definition which is converted to the TO
870      * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
871      * @return generated transfer object which represent<code>javaType</code>
872      */
873     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
874             final Type javaType, final String moduleName) {
875         requireNonNull(javaType, "javaType cannot be null");
876
877         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
878         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
879         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
880         genPropBuilder.setReturnType(javaType);
881
882         genTOBuilder.addEqualsIdentity(genPropBuilder);
883         genTOBuilder.addHashIdentity(genPropBuilder);
884         genTOBuilder.addToStringProperty(genPropBuilder);
885         genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
886         if (typedef.getStatus() == Status.DEPRECATED) {
887             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
888         }
889         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
890             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
891         }
892         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
893         genTOBuilder.setTypedef(true);
894         makeSerializable(genTOBuilder);
895         return genTOBuilder.build();
896     }
897
898     /**
899      * Converts output list of generated TO builders to one TO builder (first
900      * from list) which contains the remaining builders as its enclosing TO.
901      *
902      * @param typeName new type identifier
903      * @param typedef type definition which should be of type {@link UnionTypeDefinition}
904      * @return generated TO builder with the list of enclosed generated TO builders
905      */
906     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
907             final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
908         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
909             parentNode);
910         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
911
912         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
913         builders.forEach(resultTOBuilder::addEnclosingTransferObject);
914         return resultTOBuilder;
915     }
916
917     /**
918      * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
919      * <code>typedef</code> is added to generated TO builder as property.
920      *
921      * @param typeName new type identifier
922      * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
923      * @return generated TO builder which represents <code>typedef</code>
924      * @throws NullPointerException
925      *             <ul>
926      *             <li>if <code>basePackageName</code> is null</li>
927      *             <li>if <code>typedef</code> is null</li>
928      *             <li>if Qname of <code>typedef</code> is null</li>
929      *             </ul>
930      */
931     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
932             final UnionTypeDefinition typedef, final SchemaNode parentNode) {
933         requireNonNull(typedef, "Type Definition cannot be NULL!");
934         requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
935
936         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
937         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
938         final Module module = findParentModule(schemaContext, parentNode);
939
940         final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
941         unionGenTOBuilder.setIsUnion(true);
942         unionGenTOBuilder.setSchemaPath(typedef.getPath());
943         unionGenTOBuilder.setModuleName(module.getName());
944         unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
945         addCodegenInformation(unionGenTOBuilder, typedef);
946         generatedTOBuilders.add(unionGenTOBuilder);
947
948         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
949         // also negation information and hence guarantees uniqueness.
950         final Map<String, String> expressions = new HashMap<>();
951         for (TypeDefinition<?> unionType : unionTypes) {
952             final String unionTypeName = unionType.getQName().getLocalName();
953
954             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
955             // do not follow type encapsulation -- we use the general case for that.
956             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
957                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
958             } else if (unionType instanceof UnionTypeDefinition) {
959                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
960                     (UnionTypeDefinition) unionType, parentNode));
961             } else if (unionType instanceof EnumTypeDefinition) {
962                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
963                         unionTypeName, unionGenTOBuilder);
964                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
965             } else {
966                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
967                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
968             }
969         }
970         addStringRegExAsConstant(unionGenTOBuilder, expressions);
971
972         storeGenTO(typedef, unionGenTOBuilder, parentNode);
973
974         return generatedTOBuilders;
975     }
976
977     /**
978      * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
979      *
980      * <p>
981      * In this case the new generated TO is created for union subtype (recursive call of method
982      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
983      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
984      * created property which type is equal to new generated TO.
985      *
986      * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
987      * @param basePackageName string with the name of the module package
988      * @param unionSubtype type definition which represents union subtype
989      * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
990      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
991      */
992     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
993             final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
994         final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
995             provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
996         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
997             newTOBuilderName, unionSubtype, parentNode);
998
999         final GeneratedPropertyBuilder propertyBuilder;
1000         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
1001             newTOBuilderName.simpleName()));
1002         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
1003         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1004         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1005
1006         return subUnionGenTOBUilders;
1007     }
1008
1009     /**
1010      * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
1011      * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
1012      * the base type is used for the property creation.
1013      *
1014      * @param parentUnionGenTOBuilder generated TO builder in which new property is created
1015      * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
1016      * @param expressions list of strings with the regular expressions
1017      * @param parentNode parent Schema Node for Extended Subtype
1018      */
1019     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1020             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1021         final String unionTypeName = unionSubtype.getQName().getLocalName();
1022         final Type genTO = findGenTO(unionTypeName, unionSubtype);
1023         if (genTO != null) {
1024             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1025             return;
1026         }
1027
1028         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1029         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1030             final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
1031                 BindingGeneratorUtil.getRestrictions(unionSubtype));
1032             if (javaType != null) {
1033                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1034             }
1035         } else if (baseType instanceof LeafrefTypeDefinition) {
1036             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1037             boolean typeExist = false;
1038             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1039                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1040                 if (origType != null && javaType != null && javaType == origType) {
1041                     typeExist = true;
1042                     break;
1043                 }
1044             }
1045             if (!typeExist && javaType != null) {
1046                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1047                     javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1048             }
1049         }
1050         if (baseType instanceof StringTypeDefinition) {
1051             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1052         }
1053     }
1054
1055     /**
1056      * Searches for generated TO for <code>searchedTypeDef</code> type  definition
1057      * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1058      *
1059      * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1060      * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1061      */
1062     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1063         final Module typeModule = findParentModule(schemaContext, parentNode);
1064         if (typeModule != null && typeModule.getName() != null) {
1065             final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1066                 typeModule.getName());
1067             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1068             if (genTOs != null) {
1069                 return genTOs.get(searchedTypeName);
1070             }
1071         }
1072         return null;
1073     }
1074
1075     /**
1076      * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1077      * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1078      *
1079      * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1080      * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1081      */
1082     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1083             final SchemaNode parentNode) {
1084         if (!(newTypeDef instanceof UnionTypeDefinition)) {
1085             final Module parentModule = findParentModule(schemaContext, parentNode);
1086             if (parentModule != null && parentModule.getName() != null) {
1087                 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1088                     parentModule.getName());
1089                 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1090                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1091             }
1092         }
1093     }
1094
1095     /**
1096      * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1097      * to <code>unonGenTransObject</code>.
1098      *
1099      * @param unionGenTransObject generated TO to which should be property added
1100      * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1101      * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1102      */
1103     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1104             final String propertyName) {
1105         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1106             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1107                     .addProperty(BindingMapping.getPropertyName(propertyName));
1108             propBuilder.setReturnType(type);
1109
1110             unionGenTransObject.addEqualsIdentity(propBuilder);
1111             unionGenTransObject.addHashIdentity(propBuilder);
1112             unionGenTransObject.addToStringProperty(propBuilder);
1113         }
1114     }
1115
1116     /**
1117      * Converts <code>typedef</code> to the generated TO builder.
1118      *
1119      * @param basePackageName string with name of package to which the module belongs
1120      * @param typedef type definition from which is the generated TO builder created
1121      * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1122      */
1123     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1124             final TypeDefinition<?> typedef, final String moduleName) {
1125         JavaTypeName name = renames.get(typedef);
1126         if (name == null) {
1127             name = JavaTypeName.create(
1128                 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1129                 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1130         }
1131
1132         final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1133         newType.setSchemaPath(typedef.getPath());
1134         newType.setModuleName(moduleName);
1135         addCodegenInformation(newType, typedef);
1136         return newType;
1137     }
1138
1139     /**
1140      * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1141      * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1142      * properties.
1143      *
1144      * @param typeName new type identifier
1145      * @param typeDef type definition from which is the generated TO builder created
1146      * @return generated TO builder which represents <code>typeDef</code>
1147      * @throws IllegalArgumentException
1148      *             <ul>
1149      *             <li>if <code>typeDef</code> equals null</li>
1150      *             <li>if <code>basePackageName</code> equals null</li>
1151      *             </ul>
1152      */
1153     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1154             final BitsTypeDefinition typeDef, final String moduleName) {
1155         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1156         genTOBuilder.setSchemaPath(typeDef.getPath());
1157         genTOBuilder.setModuleName(moduleName);
1158         genTOBuilder.setBaseType(typeDef);
1159         genTOBuilder.addImplementsType(TYPE_OBJECT);
1160         addCodegenInformation(genTOBuilder, typeDef);
1161
1162         for (Bit bit : typeDef.getBits()) {
1163             final String name = bit.getName();
1164             GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
1165                 BindingMapping.getPropertyName(name));
1166             genPropertyBuilder.setReadOnly(true);
1167             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1168
1169             genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1170             genTOBuilder.addHashIdentity(genPropertyBuilder);
1171             genTOBuilder.addToStringProperty(genPropertyBuilder);
1172         }
1173
1174         return genTOBuilder;
1175     }
1176
1177     /**
1178      * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1179      * the <code>regularExpressions</code>.
1180      *
1181      * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1182      * @param expressions list of string which represent regular expressions
1183      */
1184     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1185             final Map<String, String> expressions) {
1186         if (!expressions.isEmpty()) {
1187             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1188                 ImmutableMap.copyOf(expressions));
1189         }
1190     }
1191
1192     /**
1193      * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1194      * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1195      *
1196      * <p>
1197      * It is assumed that <code>innerExtendedType</code> is already present in
1198      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1199      * for the returning generated TO.
1200      *
1201      * @param typedef Type Definition
1202      * @param innerExtendedType extended type which is part of some other extended type
1203      * @param basePackageName string with the package name of the module
1204      * @param moduleName Module Name
1205      * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1206      * @throws IllegalArgumentException
1207      *             <ul>
1208      *             <li>if <code>extendedType</code> equals null</li>
1209      *             <li>if <code>basePackageName</code> equals null</li>
1210      *             <li>if <code>typedefName</code> equals null</li>
1211      *             </ul>
1212      */
1213     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1214             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1215         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1216         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1217
1218         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1219             BindingMapping.getClassName(typedef.getQName())));
1220         genTOBuilder.setSchemaPath(typedef.getPath());
1221         genTOBuilder.setModuleName(moduleName);
1222         genTOBuilder.setTypedef(true);
1223         addCodegenInformation(genTOBuilder, typedef);
1224
1225         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1226         genTOBuilder.setRestrictions(r);
1227         addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1228
1229         if (typedef.getStatus() == Status.DEPRECATED) {
1230             genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
1231         }
1232
1233         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1234             genTOBuilder.setIsUnion(true);
1235         }
1236
1237         Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1238         Map<String, Type> typeMap = null;
1239         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1240         if (parentModule != null) {
1241             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1242             typeMap = modulesByDate.get(parentModule.getRevision());
1243         }
1244
1245         if (typeMap != null) {
1246             final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1247             final Type type = typeMap.get(innerTypeDef);
1248             if (type instanceof GeneratedTransferObject) {
1249                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1250             }
1251         }
1252         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1253         makeSerializable(genTOBuilder);
1254
1255         return genTOBuilder.build();
1256     }
1257
1258     /**
1259      * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1260      * property.
1261      *
1262      * @param gto transfer object which needs to be made serializable
1263      */
1264     private static void makeSerializable(final GeneratedTOBuilder gto) {
1265         gto.addImplementsType(Types.serializableType());
1266         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1267         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1268         gto.setSUID(prop);
1269     }
1270
1271     /**
1272      * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1273      * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1274      * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1275      * type definitions are in the list behind all type definitions on which depends.
1276      *
1277      * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1278      * @return list of type definitions sorted according their each other dependencies (type definitions which are
1279      *              dependent on other type definitions are in list behind them).
1280      */
1281     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1282             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1283         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1284
1285         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1286         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1287             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1288             List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1289                 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1290             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1291         }
1292
1293         // SortedMap guarantees order corresponding to keys in ascending order
1294         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1295             sortedTypeDefinition.addAll(v);
1296         }
1297
1298         return sortedTypeDefinition;
1299     }
1300
1301     /**
1302      * Returns how many immersion is necessary to get from the type definition to the base type.
1303      *
1304      * @param typeDefinition type definition for which is depth sought.
1305      * @return number of immersions which are necessary to get from the type definition to the base type
1306      */
1307     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1308         // FIXME: rewrite this in a non-recursive manner
1309         if (typeDefinition == null) {
1310             return 1;
1311         }
1312         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1313         if (baseType == null) {
1314             return 1;
1315         }
1316
1317         int depth = 1;
1318         if (baseType.getBaseType() != null) {
1319             depth = depth + getTypeDefinitionDepth(baseType);
1320         } else if (baseType instanceof UnionTypeDefinition) {
1321             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1322             int maxChildDepth = 0;
1323             int childDepth = 1;
1324             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1325                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1326                 if (childDepth > maxChildDepth) {
1327                     maxChildDepth = childDepth;
1328                 }
1329             }
1330             return maxChildDepth;
1331         }
1332         return depth;
1333     }
1334
1335     /**
1336      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1337      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1338      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1339      *
1340      * @param name string with name of augmented node
1341      * @return string with the number suffix incremented by one (or 1 is added)
1342      */
1343     private static String provideAvailableNameForGenTOBuilder(final String name) {
1344         final int dollar = name.indexOf('$');
1345         if (dollar == -1) {
1346             return name + "$1";
1347         }
1348
1349         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1350         Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1351         return name.substring(0, dollar + 1) + newSuffix;
1352     }
1353
1354     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1355         if (!Strings.isNullOrEmpty(units)) {
1356             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1357             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1358             prop.setReturnType(Types.STRING);
1359             to.addToStringProperty(prop);
1360         }
1361     }
1362
1363     @Override
1364     public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1365         return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1366     }
1367
1368     public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1369         final TypeDefinition<?> type = CompatUtils.compatType(node);
1370         final QName typeQName = type.getQName();
1371         final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1372         requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1373         requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1374             + node);
1375
1376         final StringBuilder sb = new StringBuilder();
1377         String result = null;
1378         if (base instanceof BinaryTypeDefinition) {
1379             result = binaryToDef(defaultValue);
1380         } else if (base instanceof BitsTypeDefinition) {
1381             String parentName;
1382             String className;
1383             final Module parent = getParentModule(node);
1384             final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1385             path.next();
1386             if (!path.hasNext()) {
1387                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1388                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1389                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1390             } else {
1391                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1392                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1393                     type.getPath());
1394                 parentName = BindingMapping.getClassName(parent.getName());
1395                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1396             }
1397             result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1398         } else if (base instanceof BooleanTypeDefinition) {
1399             result = typeToBooleanDef(defaultValue);
1400         } else if (base instanceof DecimalTypeDefinition) {
1401             result = typeToDef(BigDecimal.class, defaultValue);
1402         } else if (base instanceof EmptyTypeDefinition) {
1403             result = typeToBooleanDef(defaultValue);
1404         } else if (base instanceof EnumTypeDefinition) {
1405             final char[] defValArray = defaultValue.toCharArray();
1406             final char first = Character.toUpperCase(defaultValue.charAt(0));
1407             defValArray[0] = first;
1408             final String newDefVal = new String(defValArray);
1409             String className;
1410             if (type.getBaseType() != null) {
1411                 final Module m = getParentModule(type);
1412                 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1413                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1414                     type.getPath());
1415                 className = packageName + "." + BindingMapping.getClassName(typeQName);
1416             } else {
1417                 final Module parentModule = getParentModule(node);
1418                 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1419                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1420                     node.getPath());
1421                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1422             }
1423             result = className + "." + newDefVal;
1424         } else if (base instanceof IdentityrefTypeDefinition) {
1425             throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1426         } else if (base instanceof InstanceIdentifierTypeDefinition) {
1427             throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1428         } else if (isInt8(base)) {
1429             result = typeToValueOfDef(Byte.class, defaultValue);
1430         } else if (isInt16(base)) {
1431             result = typeToValueOfDef(Short.class, defaultValue);
1432         } else if (isInt32(base)) {
1433             result = typeToValueOfDef(Integer.class, defaultValue);
1434         } else if (isInt64(base)) {
1435             result = typeToValueOfDef(Long.class, defaultValue);
1436         } else if (base instanceof LeafrefTypeDefinition) {
1437             result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1438         } else if (base instanceof StringTypeDefinition) {
1439             result = "\"" + defaultValue + "\"";
1440         } else if (isUint8(base)) {
1441             result = typeToValueOfDef(Uint8.class, defaultValue);
1442         } else if (isUint16(base)) {
1443             result = typeToValueOfDef(Uint16.class, defaultValue);
1444         } else if (isUint32(base)) {
1445             result = typeToValueOfDef(Uint32.class, defaultValue);
1446         } else if (isUint64(base)) {
1447             result = typeToValueOfDef(Uint64.class, defaultValue);
1448         } else if (base instanceof UnionTypeDefinition) {
1449             result = unionToDef(node);
1450         } else {
1451             result = "";
1452         }
1453         sb.append(result);
1454
1455         if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1456                 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1457             final Module m = getParentModule(type);
1458             final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1459             final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1460                 type.getPath());
1461             final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1462             sb.insert(0, "new " + className + "(");
1463             sb.insert(sb.length(), ')');
1464         }
1465
1466         return sb.toString();
1467     }
1468
1469
1470     /**
1471      * Check if a particular type definition represents the built-in int8 type.
1472      *
1473      * @param type Type definition
1474      * @return True if the definition is the built-in int8 type.
1475      */
1476     private static boolean isInt8(final TypeDefinition<?> type) {
1477         return BaseTypes.int8Type().getPath().equals(type.getPath());
1478     }
1479
1480     /**
1481      * Check if a particular type definition represents the built-in int16 type.
1482      *
1483      * @param type Type definition
1484      * @return True if the definition is the built-in int16 type.
1485      */
1486     private static boolean isInt16(final TypeDefinition<?> type) {
1487         return BaseTypes.int16Type().getPath().equals(type.getPath());
1488     }
1489
1490     /**
1491      * Check if a particular type definition represents the built-in int32 type.
1492      *
1493      * @param type Type definition
1494      * @return True if the definition is the built-in int32 type.
1495      */
1496     private static boolean isInt32(final TypeDefinition<?> type) {
1497         return BaseTypes.int32Type().getPath().equals(type.getPath());
1498     }
1499
1500     /**
1501      * Check if a particular type definition represents the built-in int64 type.
1502      *
1503      * @param type Type definition
1504      * @return True if the definition is the built-in int64 type.
1505      */
1506     private static boolean isInt64(final TypeDefinition<?> type) {
1507         return BaseTypes.int64Type().getPath().equals(type.getPath());
1508     }
1509
1510     /**
1511      * Check if a particular type is the base type for uint8.
1512      *
1513      * @param type The type to check
1514      * @return If the type corresponds to the base uint8 type.
1515      * @throws NullPointerException if type is null
1516      */
1517     private static boolean isUint8(final TypeDefinition<?> type) {
1518         return BaseTypes.uint8Type().getPath().equals(type.getPath());
1519     }
1520
1521     /**
1522      * Check if a particular type is the base type for uint16.
1523      *
1524      * @param type The type to check
1525      * @return If the type corresponds to the base uint16 type.
1526      * @throws NullPointerException if type is null
1527      */
1528     private static boolean isUint16(final TypeDefinition<?> type) {
1529         return BaseTypes.uint16Type().getPath().equals(type.getPath());
1530     }
1531
1532     /**
1533      * Check if a particular type is the base type for uint32.
1534      *
1535      * @param type The type to check
1536      * @return If the type corresponds to the base uint32 type.
1537      * @throws NullPointerException if type is null
1538      */
1539     private static boolean isUint32(final TypeDefinition<?> type) {
1540         return BaseTypes.uint32Type().getPath().equals(type.getPath());
1541     }
1542
1543     /**
1544      * Check if a particular type is the base type for uint64.
1545      *
1546      * @param type The type to check
1547      * @return If the type corresponds to the base uint64 type.
1548      * @throws NullPointerException if type is null
1549      */
1550     private static boolean isUint64(final TypeDefinition<?> type) {
1551         return BaseTypes.uint64Type().getPath().equals(type.getPath());
1552     }
1553
1554     private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1555         return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1556     }
1557
1558     private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1559         return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1560     }
1561
1562     private static String typeToBooleanDef(final String defaultValue) {
1563         switch (defaultValue) {
1564             case "false":
1565                 return "java.lang.Boolean.FALSE";
1566             case "true":
1567                 return "java.lang.Boolean.TRUE";
1568             default:
1569                 return typeToValueOfDef(Boolean.class, defaultValue);
1570         }
1571     }
1572
1573     private static String binaryToDef(final String defaultValue) {
1574         final StringBuilder sb = new StringBuilder();
1575         final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1576         sb.append("new byte[] {");
1577         for (int i = 0; i < encoded.length; i++) {
1578             sb.append(encoded[i]);
1579             if (i != encoded.length - 1) {
1580                 sb.append(", ");
1581             }
1582         }
1583         sb.append('}');
1584         return sb.toString();
1585     }
1586
1587     private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1588
1589     private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1590             final boolean isExt) {
1591         final List<Bit> bits = new ArrayList<>(type.getBits());
1592         bits.sort(BIT_NAME_COMPARATOR);
1593         final StringBuilder sb = new StringBuilder();
1594         if (!isExt) {
1595             sb.append("new ").append(className).append('(');
1596         }
1597         for (int i = 0; i < bits.size(); i++) {
1598             sb.append(bits.get(i).getName().equals(defaultValue));
1599             if (i != bits.size() - 1) {
1600                 sb.append(", ");
1601             }
1602         }
1603         if (!isExt) {
1604             sb.append(')');
1605         }
1606         return sb.toString();
1607     }
1608
1609     private Module getParentModule(final SchemaNode node) {
1610         final QName qname = node.getPath().getPathFromRoot().iterator().next();
1611         return schemaContext.findModule(qname.getModule()).orElse(null);
1612     }
1613
1614     private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1615             final String defaultValue) {
1616         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1617         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1618                 "The Path Statement for Leafref Type Definition cannot be NULL!");
1619
1620         final PathExpression xpath = leafrefType.getPathStatement();
1621         final String strXPath = xpath.getOriginalString();
1622
1623         if (strXPath != null) {
1624             if (strXPath.indexOf('[') == -1) {
1625                 final Module module = findParentModule(schemaContext, parentNode);
1626                 if (module != null) {
1627                     final SchemaNode dataNode;
1628                     if (xpath.isAbsolute()) {
1629                         dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
1630                     } else {
1631                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1632                     }
1633                     final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1634                     return result;
1635                 }
1636             } else {
1637                 return "new java.lang.Object()";
1638             }
1639         }
1640
1641         return null;
1642     }
1643
1644     private String unionToDef(final LeafSchemaNode node) {
1645         final TypeDefinition<?> type = CompatUtils.compatType(node);
1646         String parentName;
1647         String className;
1648
1649         if (type.getBaseType() != null) {
1650             final QName typeQName = type.getQName();
1651             Module module = null;
1652             final Collection<? extends Module> modules = schemaContext.findModules(typeQName.getNamespace());
1653             if (modules.size() > 1) {
1654                 for (Module m : modules) {
1655                     if (m.getRevision().equals(typeQName.getRevision())) {
1656                         module = m;
1657                         break;
1658                     }
1659                 }
1660                 if (module == null) {
1661                     final List<Module> modulesList = new ArrayList<>(modules);
1662                     modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1663                     module = modulesList.get(0);
1664                 }
1665             } else {
1666                 module = modules.iterator().next();
1667             }
1668
1669             final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1670             className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1671         } else {
1672             final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1673             final QName first = path.next();
1674             final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1675             final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1676             if (!path.hasNext()) {
1677                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1678                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1679             } else {
1680                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1681                     UNION_PATH);
1682                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1683             }
1684         }
1685         return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1686     }
1687
1688     private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1689         return new StringBuilder()
1690                 .append("new ").append(className).append("(\"").append(defaultValue).append("\".toCharArray())")
1691                 .toString();
1692     }
1693
1694     @Override
1695     public String getConstructorPropertyName(final SchemaNode node) {
1696         return node instanceof TypeDefinition<?> ? TypeConstants.VALUE_PROP : "";
1697     }
1698
1699     @Override
1700     public String getParamNameFromType(final TypeDefinition<?> type) {
1701         return BindingMapping.getPropertyName(type.getQName().getLocalName());
1702     }
1703 }