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