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