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