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