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