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