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