BUG-869: added proper handling of nullable parameter
[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 java.io.Serializable;
18 import java.math.BigDecimal;
19 import java.math.BigInteger;
20 import java.net.URI;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.Comparator;
25 import java.util.Date;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Set;
31 import java.util.TreeMap;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
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.IdentitySchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.Module;
61 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
63 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
65 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
69 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
77 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
80 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
81 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
82 import org.opendaylight.yangtools.yang.model.util.Int16;
83 import org.opendaylight.yangtools.yang.model.util.Int32;
84 import org.opendaylight.yangtools.yang.model.util.Int64;
85 import org.opendaylight.yangtools.yang.model.util.Int8;
86 import org.opendaylight.yangtools.yang.model.util.StringType;
87 import org.opendaylight.yangtools.yang.model.util.Uint16;
88 import org.opendaylight.yangtools.yang.model.util.Uint32;
89 import org.opendaylight.yangtools.yang.model.util.Uint64;
90 import org.opendaylight.yangtools.yang.model.util.Uint8;
91 import org.opendaylight.yangtools.yang.model.util.UnionType;
92
93 import com.google.common.base.Preconditions;
94 import com.google.common.collect.Sets;
95 import com.google.common.io.BaseEncoding;
96
97 public final class TypeProviderImpl implements TypeProvider {
98     private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
99
100     /**
101      * Contains the schema data red from YANG files.
102      */
103     private final SchemaContext schemaContext;
104
105     /**
106      * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
107      */
108     private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
109
110     /**
111      * The map which maps schema paths to JAVA <code>Type</code>.
112      */
113     private final Map<SchemaPath, Type> referencedTypes;
114     private final Map<Module, Set<Type>> additionalTypes;
115
116     /**
117      * Creates new instance of class <code>TypeProviderImpl</code>.
118      *
119      * @param schemaContext
120      *            contains the schema data red from YANG files
121      * @throws IllegalArgumentException
122      *             if <code>schemaContext</code> equal null.
123      */
124     public TypeProviderImpl(final SchemaContext schemaContext) {
125         Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
126
127         this.schemaContext = schemaContext;
128         this.genTypeDefsContextMap = new HashMap<>();
129         this.referencedTypes = new HashMap<>();
130         this.additionalTypes = new HashMap<>();
131         resolveTypeDefsFromContext();
132     }
133
134     /**
135      * Puts <code>refType</code> to map with key <code>refTypePath</code>
136      *
137      * @param refTypePath
138      *            schema path used as the map key
139      * @param refType
140      *            type which represents the map value
141      * @throws IllegalArgumentException
142      *             <ul>
143      *             <li>if <code>refTypePath</code> equal null</li>
144      *             <li>if <code>refType</code> equal null</li>
145      *             </ul>
146      *
147      */
148     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
149         Preconditions.checkArgument(refTypePath != null,
150                 "Path reference of Enumeration Type Definition cannot be NULL!");
151         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
152         referencedTypes.put(refTypePath, refType);
153     }
154
155     public Map<Module, Set<Type>> getAdditionalTypes() {
156         return additionalTypes;
157     }
158
159     /**
160      *
161      * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
162      *
163      * @param type
164      *            string with YANG name of type
165      * @return JAVA <code>Type</code> for YANG type <code>type</code>
166      * @see TypeProvider#javaTypeForYangType(String)
167      */
168     @Override
169     @Deprecated
170     public Type javaTypeForYangType(final String type) {
171         return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
172     }
173
174     @Override
175     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
176         return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
177     }
178
179     /**
180      * Converts schema definition type <code>typeDefinition</code> to JAVA
181      * <code>Type</code>
182      *
183      * @param typeDefinition
184      *            type definition which is converted to JAVA type
185      * @throws IllegalArgumentException
186      *             <ul>
187      *             <li>if <code>typeDefinition</code> equal null</li>
188      *             <li>if Qname of <code>typeDefinition</code> equal null</li>
189      *             <li>if name of <code>typeDefinition</code> equal null</li>
190      *             </ul>
191      */
192     @Override
193     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
194             final Restrictions r) {
195         Type returnType = null;
196         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
197         Preconditions.checkArgument(typeDefinition.getQName() != null,
198                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
199         String typedefName = typeDefinition.getQName().getLocalName();
200         Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
201
202         if (typeDefinition instanceof ExtendedType) {
203             returnType = javaTypeForExtendedType(typeDefinition);
204             if (r != null && returnType instanceof GeneratedTransferObject) {
205                 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
206                 Module module = findParentModule(schemaContext, parentNode);
207                 String basePackageName = moduleNamespaceToPackageName(module);
208                 String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
209                 String genTOName = BindingMapping.getClassName(typedefName);
210                 String name = packageName + "." + genTOName;
211                 if (!(returnType.getFullyQualifiedName().equals(name))) {
212                     returnType = shadedTOWithRestrictions(gto, r);
213                 }
214             }
215         } else {
216             returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
217             if (returnType == null) {
218                 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
219                         .getLocalName());
220             }
221         }
222         // TODO: add throw exception when we will be able to resolve ALL yang
223         // types!
224         // if (returnType == null) {
225         // throw new IllegalArgumentException("Type Provider can't resolve " +
226         // "type for specified Type Definition " + typedefName);
227         // }
228         return returnType;
229     }
230
231     private GeneratedTransferObject shadedTOWithRestrictions(GeneratedTransferObject gto, Restrictions r) {
232         GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
233         GeneratedTransferObject parent = gto.getSuperType();
234         if (parent != null) {
235             gtob.setExtendsType(parent);
236         }
237         gtob.setRestrictions(r);
238         for (GeneratedProperty gp : gto.getProperties()) {
239             GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
240             gpb.setValue(gp.getValue());
241             gpb.setReadOnly(gp.isReadOnly());
242             gpb.setAccessModifier(gp.getAccessModifier());
243             gpb.setReturnType(gp.getReturnType());
244             gpb.setFinal(gp.isFinal());
245             gpb.setStatic(gp.isStatic());
246         }
247         return gtob.toInstance();
248     }
249
250     /**
251      * Returns JAVA <code>Type</code> for instances of the type
252      * <code>LeafrefTypeDefinition</code> or
253      * <code>IdentityrefTypeDefinition</code>.
254      *
255      * @param typeDefinition
256      *            type definition which is converted to JAVA <code>Type</code>
257      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
258      */
259     private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
260         if (typeDefinition instanceof LeafrefTypeDefinition) {
261             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
262             return provideTypeForLeafref(leafref, parentNode);
263         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
264             final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
265             return provideTypeForIdentityref(idref);
266         } else {
267             return null;
268         }
269     }
270
271     /**
272      * Returns JAVA <code>Type</code> for instances of the type
273      * <code>ExtendedType</code>.
274      *
275      * @param typeDefinition
276      *            type definition which is converted to JAVA <code>Type</code>
277      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
278      */
279     private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
280         final String typedefName = typeDefinition.getQName().getLocalName();
281         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
282         Type returnType = null;
283         returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
284         if (returnType == null) {
285             if (baseTypeDef instanceof EnumTypeDefinition) {
286                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
287                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
288             } else {
289                 final Module module = findParentModule(schemaContext, typeDefinition);
290                 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
291                 if (module != null) {
292                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
293                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
294                     if (genTOs != null) {
295                         returnType = genTOs.get(typedefName);
296                     }
297                     if (returnType == null) {
298                         returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
299                                 baseTypeDef, typeDefinition, r);
300                     }
301                 }
302             }
303         }
304         return returnType;
305         // TODO: add throw exception when we will be able to resolve ALL yang
306         // types!
307         // if (returnType == null) {
308         // throw new IllegalArgumentException("Type Provider can't resolve " +
309         // "type for specified Type Definition " + typedefName);
310         // }
311     }
312
313     /**
314      * Seeks for identity reference <code>idref</code> the JAVA
315      * <code>type</code>.<br />
316      * <br />
317      *
318      * <i>Example:<br />
319      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
320      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
321      *
322      * @param idref
323      *            identityref type definition for which JAVA <code>Type</code>
324      *            is sought
325      * @return JAVA <code>Type</code> of the identity which is refrenced through
326      *         <code>idref</code>
327      */
328     private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
329         QName baseIdQName = idref.getIdentity().getQName();
330         Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
331                 baseIdQName.getRevision());
332         IdentitySchemaNode identity = null;
333         for (IdentitySchemaNode id : module.getIdentities()) {
334             if (id.getQName().equals(baseIdQName)) {
335                 identity = id;
336             }
337         }
338         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
339
340         final String basePackageName = moduleNamespaceToPackageName(module);
341         final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
342         final String genTypeName = BindingMapping.getClassName(identity.getQName());
343
344         Type baseType = Types.typeForClass(Class.class);
345         Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
346         return Types.parameterizedTypeFor(baseType, paramType);
347     }
348
349     /**
350      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
351      *
352      * @param typeDefinition
353      *            type definition which should be converted to JAVA
354      *            <code>Type</code>
355      * @return JAVA <code>Type</code> which represents
356      *         <code>typeDefinition</code>
357      * @throws IllegalArgumentException
358      *             <ul>
359      *             <li>if <code>typeDefinition</code> equal null</li>
360      *             <li>if Q name of <code>typeDefinition</code></li>
361      *             <li>if name of <code>typeDefinition</code></li>
362      *             </ul>
363      */
364     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
365             final SchemaNode parentNode) {
366         Type returnType = null;
367         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
368         if (typeDefinition.getQName() == null) {
369             throw new IllegalArgumentException(
370                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
371         }
372         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
373                 "Type Definitions Local Name cannot be NULL!");
374
375         final String typedefName = typeDefinition.getQName().getLocalName();
376         if (typeDefinition instanceof ExtendedType) {
377             final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
378
379             if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
380                 final Module module = findParentModule(schemaContext, parentNode);
381
382                 if (module != null) {
383                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
384                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
385                     if (genTOs != null) {
386                         returnType = genTOs.get(typedefName);
387                     }
388                 }
389             }
390         }
391         return returnType;
392     }
393
394     /**
395      * Gets base type definition for <code>extendTypeDef</code>. The method is
396      * recursivelly called until non <code>ExtendedType</code> type is found.
397      *
398      * @param extendTypeDef
399      *            type definition for which is the base type definition sought
400      * @return type definition which is base type for <code>extendTypeDef</code>
401      * @throws IllegalArgumentException
402      *             if <code>extendTypeDef</code> equal null
403      */
404     private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
405         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
406         final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
407         if (baseTypeDef == null) {
408             return extendTypeDef;
409         } else if (baseTypeDef instanceof ExtendedType) {
410             return baseTypeDefForExtendedType(baseTypeDef);
411         } else {
412             return baseTypeDef;
413         }
414
415     }
416
417     /**
418      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
419      *
420      * The path of <code>leafrefType</code> is followed to find referenced node
421      * and its <code>Type</code> is returned.
422      *
423      * @param leafrefType
424      *            leafref type definition for which is the type sought
425      * @return JAVA <code>Type</code> of data schema node which is referenced in
426      *         <code>leafrefType</code>
427      * @throws IllegalArgumentException
428      *             <ul>
429      *             <li>if <code>leafrefType</code> equal null</li>
430      *             <li>if path statement of <code>leafrefType</code> equal null</li>
431      *             </ul>
432      *
433      */
434     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
435         Type returnType = null;
436         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
437
438         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
439                 "The Path Statement for Leafref Type Definition cannot be NULL!");
440
441         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
442         final String strXPath = xpath.toString();
443
444         if (strXPath != null) {
445             if (strXPath.indexOf('[') == -1) {
446                 final Module module = findParentModule(schemaContext, parentNode);
447                 if (module != null) {
448                     final SchemaNode dataNode;
449                     if (xpath.isAbsolute()) {
450                         dataNode = findDataSchemaNode(schemaContext, module, xpath);
451                     } else {
452                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
453                     }
454
455                     if (leafContainsEnumDefinition(dataNode)) {
456                         returnType = referencedTypes.get(dataNode.getPath());
457                     } else if (leafListContainsEnumDefinition(dataNode)) {
458                         returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
459                     } else {
460                         returnType = resolveTypeFromDataSchemaNode(dataNode);
461                     }
462                 }
463             } else {
464                 returnType = Types.typeForClass(Object.class);
465             }
466         }
467         if (returnType == null) {
468             throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
469         }
470         return returnType;
471     }
472
473     /**
474      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
475      * so then checks if it is of type <code>EnumTypeDefinition</code>.
476      *
477      * @param dataNode
478      *            data schema node for which is checked if it is leaf and if it
479      *            is of enum type
480      * @return boolean value
481      *         <ul>
482      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
483      *         <li>false - other cases</li>
484      *         </ul>
485      */
486     private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
487         if (dataNode instanceof LeafSchemaNode) {
488             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
489             if (leaf.getType() instanceof EnumTypeDefinition) {
490                 return true;
491             }
492         }
493         return false;
494     }
495
496     /**
497      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
498      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
499      *
500      * @param dataNode
501      *            data schema node for which is checked if it is leaflist and if
502      *            it is of enum type
503      * @return boolean value
504      *         <ul>
505      *         <li>true - if <code>dataNode</code> is leaflist of type
506      *         enumeration</li>
507      *         <li>false - other cases</li>
508      *         </ul>
509      */
510     private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
511         if (dataNode instanceof LeafListSchemaNode) {
512             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
513             if (leafList.getType() instanceof EnumTypeDefinition) {
514                 return true;
515             }
516         }
517         return false;
518     }
519
520     /**
521      * Converts <code>enumTypeDef</code> to
522      * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
523      * enumeration}.
524      *
525      * @param enumTypeDef
526      *            enumeration type definition which is converted to enumeration
527      * @param enumName
528      *            string with name which is used as the enumeration name
529      * @return enumeration type which is built with data (name, enum values)
530      *         from <code>enumTypeDef</code>
531      * @throws IllegalArgumentException
532      *             <ul>
533      *             <li>if <code>enumTypeDef</code> equals null</li>
534      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
535      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
536      *             <li>if name of <code>enumTypeDef</code> equal null</li>
537      *             </ul>
538      */
539     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
540             final SchemaNode parentNode) {
541         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
542         Preconditions.checkArgument(enumTypeDef.getValues() != null,
543                 "EnumTypeDefinition MUST contain at least ONE value definition!");
544         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
545         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
546                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
547
548         final String enumerationName = BindingMapping.getClassName(enumName);
549
550         Module module = findParentModule(schemaContext, parentNode);
551         final String basePackageName = moduleNamespaceToPackageName(module);
552
553         final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
554         enumBuilder.setDescription(enumTypeDef.getDescription());
555         enumBuilder.setReference(enumTypeDef.getReference());
556         enumBuilder.setModuleName(module.getName());
557         enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
558         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
559         return enumBuilder.toInstance(null);
560     }
561
562     /**
563      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
564      * taken from <code>enumTypeDef</code>.
565      *
566      * @param enumTypeDef
567      *            enumeration type definition is source of enumeration data for
568      *            <code>typeBuilder</code>
569      * @param enumName
570      *            string with the name of enumeration
571      * @param typeBuilder
572      *            generated type builder to which is enumeration added
573      * @return enumeration type which contains enumeration data form
574      *         <code>enumTypeDef</code>
575      * @throws IllegalArgumentException
576      *             <ul>
577      *             <li>if <code>enumTypeDef</code> equals null</li>
578      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
579      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
580      *             <li>if name of <code>enumTypeDef</code> equal null</li>
581      *             <li>if name of <code>typeBuilder</code> equal null</li>
582      *             </ul>
583      *
584      */
585     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
586             final GeneratedTypeBuilderBase<?> typeBuilder) {
587         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
588         Preconditions.checkArgument(enumTypeDef.getValues() != null,
589                 "EnumTypeDefinition MUST contain at least ONE value definition!");
590         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
591         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
592                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
593         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
594
595         final String enumerationName = BindingMapping.getClassName(enumName);
596
597         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
598         enumBuilder.setDescription(enumTypeDef.getDescription());
599         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
600         return enumBuilder.toInstance(enumBuilder);
601     }
602
603     /**
604      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
605      *
606      * @param dataNode
607      *            contains information about YANG type
608      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
609      */
610     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
611         Type returnType = null;
612         if (dataNode != null) {
613             if (dataNode instanceof LeafSchemaNode) {
614                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
615                 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
616             } else if (dataNode instanceof LeafListSchemaNode) {
617                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
618                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
619             }
620         }
621         return returnType;
622     }
623
624     /**
625      * Passes through all modules and through all its type definitions and
626      * convert it to generated types.
627      *
628      * The modules are firstly sorted by mutual dependencies. The modules are
629      * sequentially passed. All type definitions of a module are at the
630      * beginning sorted so that type definition with less amount of references
631      * to other type definition are processed first.<br />
632      * For each module is created mapping record in the map
633      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
634      * which map current module name to the map which maps type names to
635      * returned types (generated types).
636      *
637      */
638     private void resolveTypeDefsFromContext() {
639         final Set<Module> modules = schemaContext.getModules();
640         Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
641         final Module[] modulesArray = new Module[modules.size()];
642         int i = 0;
643         for (Module modul : modules) {
644             modulesArray[i++] = modul;
645         }
646         final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
647                 .sort(modulesArray);
648
649         for (final Module module : modulesSortedByDependency) {
650             Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
651             if (dateTypeMap == null) {
652                 dateTypeMap = new HashMap<>();
653             }
654             final Map<String, Type> typeMap = new HashMap<>();
655             dateTypeMap.put(module.getRevision(), typeMap);
656             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
657         }
658
659         for (final Module module : modulesSortedByDependency) {
660             if (module == null) {
661                 continue;
662             }
663             final String basePackageName = moduleNamespaceToPackageName(module);
664
665             final DataNodeIterator it = new DataNodeIterator(module);
666             final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
667             final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
668
669             if ((listTypeDefinitions != null) && (basePackageName != null)) {
670                 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
671                     typedefToGeneratedType(basePackageName, module, typedef);
672                 }
673             }
674         }
675     }
676
677     /**
678      *
679      * @param basePackageName
680      *            string with name of package to which the module belongs
681      * @param moduleName
682      *            string with the name of the module for to which the
683      *            <code>typedef</code> belongs
684      * @param typedef
685      *            type definition of the node for which should be creted JAVA
686      *            <code>Type</code> (usually generated TO)
687      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
688      *         <code>null</code> value if <code>basePackageName</code> or
689      *         <code>modulName</code> or <code>typedef</code> or Q name of
690      *         <code>typedef</code> equals <code>null</code>
691      */
692     private Type typedefToGeneratedType(final String basePackageName, final Module module,
693             final TypeDefinition<?> typedef) {
694         final String moduleName = module.getName();
695         final Date moduleRevision = module.getRevision();
696         if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
697             final String typedefName = typedef.getQName().getLocalName();
698             final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
699             if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
700                     && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
701                 Type returnType = null;
702                 if (innerTypeDefinition instanceof ExtendedType) {
703                     ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
704                     returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName,
705                             module.getName());
706                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
707                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
708                             (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
709                     genTOBuilder.setTypedef(true);
710                     genTOBuilder.setIsUnion(true);
711                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
712                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
713                     returnType = genTOBuilder.toInstance();
714                     // union builder
715                     GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
716                             genTOBuilder.getName() + "Builder");
717                     unionBuilder.setIsUnionBuilder(true);
718                     MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
719                     method.setReturnType(returnType);
720                     method.addParameter(Types.STRING, "defaultValue");
721                     method.setAccessModifier(AccessModifier.PUBLIC);
722                     method.setStatic(true);
723                     Set<Type> types = additionalTypes.get(module);
724                     if (types == null) {
725                         types = Sets.<Type> newHashSet(unionBuilder.toInstance());
726                         additionalTypes.put(module, types);
727                     } else {
728                         types.add(unionBuilder.toInstance());
729                     }
730                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
731                     // enums are automatically Serializable
732                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
733                     // TODO units for typedef enum
734                     returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
735                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
736                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
737                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
738                             basePackageName, bitsTypeDefinition, typedefName, module.getName());
739                     genTOBuilder.setTypedef(true);
740                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
741                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
742                     returnType = genTOBuilder.toInstance();
743                 } else {
744                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
745                             innerTypeDefinition, typedef);
746                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
747                 }
748                 if (returnType != null) {
749                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
750                     final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
751                     if (typeMap != null) {
752                         typeMap.put(typedefName, returnType);
753                     }
754                     return returnType;
755                 }
756             }
757         }
758         return null;
759     }
760
761     /**
762      * Wraps base YANG type to generated TO.
763      *
764      * @param basePackageName
765      *            string with name of package to which the module belongs
766      * @param typedef
767      *            type definition which is converted to the TO
768      * @param javaType
769      *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
770      * @return generated transfer object which represent<code>javaType</code>
771      */
772     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
773             final Type javaType, final String moduleName) {
774         Preconditions.checkNotNull(javaType, "javaType cannot be null");
775         final String propertyName = "value";
776
777         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
778         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
779         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
780         genPropBuilder.setReturnType(javaType);
781         genTOBuilder.addEqualsIdentity(genPropBuilder);
782         genTOBuilder.addHashIdentity(genPropBuilder);
783         genTOBuilder.addToStringProperty(genPropBuilder);
784         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
785             final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
786             addStringRegExAsConstant(genTOBuilder, regExps);
787         }
788         addUnitsToGenTO(genTOBuilder, typedef.getUnits());
789         genTOBuilder.setTypedef(true);
790         makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
791         return genTOBuilder.toInstance();
792     }
793
794     /**
795      * Converts output list of generated TO builders to one TO builder (first
796      * from list) which contains the remaining builders as its enclosing TO.
797      *
798      * @param basePackageName
799      *            string with name of package to which the module belongs
800      * @param typedef
801      *            type definition which should be of type
802      *            <code>UnionTypeDefinition</code>
803      * @param typeDefName
804      *            string with name for generated TO
805      * @return generated TO builder with the list of enclosed generated TO
806      *         builders
807      */
808     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
809             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
810         final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
811                 typedef, typeDefName, parentNode);
812         GeneratedTOBuilder resultTOBuilder = null;
813         if (!genTOBuilders.isEmpty()) {
814             resultTOBuilder = genTOBuilders.remove(0);
815             for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
816                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
817             }
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) && (typedef != 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         // keys are in ascending order
1303         Set<Integer> depths = typeDefinitionsDepths.keySet();
1304         for (Integer depth : depths) {
1305             sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
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 }