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