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