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