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