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