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