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