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