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