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