Refactored implementation of getBaseType method for yang built-in types.
[yangtools.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / yang / types / TypeProviderImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.sal.binding.yang.types;
9
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.*;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.*;
12
13 import java.util.ArrayList;
14 import java.util.HashMap;
15 import java.util.List;
16 import java.util.Map;
17 import java.util.Set;
18 import java.util.TreeMap;
19 import java.util.regex.Matcher;
20 import java.util.regex.Pattern;
21
22 import org.apache.commons.lang.StringEscapeUtils;
23 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
24 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
25 import org.opendaylight.yangtools.binding.generator.util.Types;
26 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
27 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
28 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
29 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
30 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
31 import org.opendaylight.yangtools.sal.binding.model.api.Type;
32 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
33 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
34 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
36 import org.opendaylight.yangtools.yang.common.QName;
37 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
40 import org.opendaylight.yangtools.yang.model.api.Module;
41 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
45 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
47 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
48 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
52 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
54 import org.opendaylight.yangtools.yang.model.util.StringType;
55 import org.opendaylight.yangtools.yang.model.util.UnionType;
56 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
57
58 import com.google.common.base.Preconditions;
59
60 public final class TypeProviderImpl implements TypeProvider {
61     /**
62      * Contains the schema data red from YANG files.
63      */
64     private final SchemaContext schemaContext;
65
66     /**
67      * The outter map maps module names to the map of the types for the module.
68      * The inner map maps the name of the concrete type to the JAVA
69      * <code>Type</code> (usually it is generated TO).
70      */
71     private Map<String, Map<String, Type>> genTypeDefsContextMap;
72
73     /**
74      * The map which maps schema paths to JAVA <code>Type</code>.
75      */
76     private final Map<SchemaPath, Type> referencedTypes;
77
78     /**
79      * Creates new instance of class <code>TypeProviderImpl</code>.
80      *
81      * @param schemaContext
82      *            contains the schema data red from YANG files
83      * @throws IllegalArgumentException
84      *             if <code>schemaContext</code> equal null.
85      */
86     public TypeProviderImpl(final SchemaContext schemaContext) {
87         Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
88
89         this.schemaContext = schemaContext;
90         this.genTypeDefsContextMap = new HashMap<>();
91         this.referencedTypes = new HashMap<>();
92         resolveTypeDefsFromContext();
93     }
94
95     /**
96      * Puts <code>refType</code> to map with key <code>refTypePath</code>
97      *
98      * @param refTypePath
99      *            schema path used as the map key
100      * @param refType
101      *            type which represents the map value
102      * @throws IllegalArgumentException
103      *             <ul>
104      *             <li>if <code>refTypePath</code> equal null</li>
105      *             <li>if <code>refType</code> equal null</li>
106      *             </ul>
107      *
108      */
109     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
110         Preconditions.checkArgument(refTypePath != null,
111                 "Path reference of Enumeration Type Definition cannot be NULL!");
112         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
113         referencedTypes.put(refTypePath, refType);
114     }
115
116     /**
117      *
118      * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
119      *
120      * @param type
121      *            string with YANG name of type
122      * @returns JAVA <code>Type</code> for YANG type <code>type</code>
123      * @see org.opendaylight.controller.yang.model.type.provider.TypeProvider#
124      *      javaTypeForYangType(java.lang.String)
125      */
126     @Override
127     public Type javaTypeForYangType(String type) {
128         return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
129     }
130
131     /**
132      * Converts schema definition type <code>typeDefinition</code> to JAVA
133      * <code>Type</code>
134      *
135      * @param typeDefinition
136      *            type definition which is converted to JAVA type
137      * @throws IllegalArgumentException
138      *             <ul>
139      *             <li>if <code>typeDefinition</code> equal null</li>
140      *             <li>if Q name of <code>typeDefinition</code> equal null</li>
141      *             <li>if name of <code>typeDefinition</code> equal null</li>
142      *             </ul>
143      */
144     @Override
145     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
146         Type returnType = null;
147         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
148         if (typeDefinition.getQName() == null) {
149             throw new IllegalArgumentException(
150                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
151         }
152         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
153                 "Type Definitions Local Name cannot be NULL!");
154
155         if (typeDefinition instanceof ExtendedType) {
156             returnType = javaTypeForExtendedType(typeDefinition);
157         } else {
158             returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
159             if (returnType == null) {
160                 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
161                         parentNode);
162             }
163         }
164         // TODO: add throw exception when we will be able to resolve ALL yang
165         // types!
166         // if (returnType == null) {
167         // throw new IllegalArgumentException("Type Provider can't resolve " +
168         // "type for specified Type Definition " + typedefName);
169         // }
170         return returnType;
171     }
172
173     /**
174      * Returns JAVA <code>Type</code> for instances of the type
175      * <code>LeafrefTypeDefinition</code> or
176      * <code>IdentityrefTypeDefinition</code>.
177      *
178      * @param typeDefinition
179      *            type definition which is converted to JAVA <code>Type</code>
180      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
181      */
182     private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
183         if (typeDefinition instanceof LeafrefTypeDefinition) {
184             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
185             return provideTypeForLeafref(leafref, parentNode);
186         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
187             final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
188             return provideTypeForIdentityref(idref);
189         } else {
190             return null;
191         }
192     }
193
194     /**
195      * Returns JAVA <code>Type</code> for instances of the type
196      * <code>ExtendedType</code>.
197      *
198      * @param typeDefinition
199      *            type definition which is converted to JAVA <code>Type</code>
200      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
201      */
202     private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
203         final String typedefName = typeDefinition.getQName().getLocalName();
204         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
205         Type returnType = null;
206         returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
207         if (returnType == null) {
208             if (baseTypeDef instanceof EnumTypeDefinition) {
209                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
210                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
211             } else {
212                 final Module module = findParentModule(schemaContext, typeDefinition);
213                 if (module != null) {
214                     final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
215                     if (genTOs != null) {
216                         returnType = genTOs.get(typedefName);
217                     }
218                     if (returnType == null) {
219                         returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
220                                 baseTypeDef, typeDefinition);
221                     }
222                 }
223             }
224         }
225         return returnType;
226         // TODO: add throw exception when we will be able to resolve ALL yang
227         // types!
228         // if (returnType == null) {
229         // throw new IllegalArgumentException("Type Provider can't resolve " +
230         // "type for specified Type Definition " + typedefName);
231         // }
232     }
233
234     /**
235      * Seeks for identity reference <code>idref</code> the JAVA
236      * <code>type</code>.<br />
237      * <br />
238      *
239      * <i>Example:<br />
240      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
241      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
242      *
243      * @param idref
244      *            identityref type definition for which JAVA <code>Type</code>
245      *            is sought
246      * @return JAVA <code>Type</code> of the identity which is refrenced through
247      *         <code>idref</code>
248      */
249     private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
250         QName baseIdQName = idref.getIdentity();
251         Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
252                 baseIdQName.getRevision());
253         IdentitySchemaNode identity = null;
254         for (IdentitySchemaNode id : module.getIdentities()) {
255             if (id.getQName().equals(baseIdQName)) {
256                 identity = id;
257             }
258         }
259         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
260
261         final String basePackageName = moduleNamespaceToPackageName(module);
262         final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
263         final String genTypeName = parseToClassName(identity.getQName().getLocalName());
264
265         Type baseType = Types.typeForClass(Class.class);
266         Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
267         return Types.parameterizedTypeFor(baseType, paramType);
268     }
269
270     /**
271      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
272      *
273      * @param typeDefinition
274      *            type definition which should be converted to JAVA
275      *            <code>Type</code>
276      * @return JAVA <code>Type</code> which represents
277      *         <code>typeDefinition</code>
278      * @throws IllegalArgumentException
279      *             <ul>
280      *             <li>if <code>typeDefinition</code> equal null</li>
281      *             <li>if Q name of <code>typeDefinition</code></li>
282      *             <li>if name of <code>typeDefinition</code></li>
283      *             </ul>
284      */
285     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
286             final SchemaNode parentNode) {
287         Type returnType = null;
288         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
289         if (typeDefinition.getQName() == null) {
290             throw new IllegalArgumentException(
291                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
292         }
293         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
294                 "Type Definitions Local Name cannot be NULL!");
295
296         final String typedefName = typeDefinition.getQName().getLocalName();
297         if (typeDefinition instanceof ExtendedType) {
298             final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
299
300             if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
301                 final Module module = findParentModule(schemaContext, parentNode);
302
303                 if (module != null) {
304                     final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
305                     if (genTOs != null) {
306                         returnType = genTOs.get(typedefName);
307                     }
308                 }
309             }
310         }
311         return returnType;
312     }
313
314     /**
315      * Gets base type definition for <code>extendTypeDef</code>. The method is
316      * recursivelly called until non <code>ExtendedType</code> type is found.
317      *
318      * @param extendTypeDef
319      *            type definition for which is the base type definition sought
320      * @return type definition which is base type for <code>extendTypeDef</code>
321      * @throws IllegalArgumentException
322      *             if <code>extendTypeDef</code> equal null
323      */
324     private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
325         Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
326         final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
327         if (baseTypeDef instanceof ExtendedType) {
328             return baseTypeDefForExtendedType(baseTypeDef);
329         } else {
330             return baseTypeDef;
331         }
332
333     }
334
335     /**
336      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
337      *
338      * The path of <code>leafrefType</code> is followed to find referenced node
339      * and its <code>Type</code> is returned.
340      *
341      * @param leafrefType
342      *            leafref type definition for which is the type sought
343      * @return JAVA <code>Type</code> of data schema node which is referenced in
344      *         <code>leafrefType</code>
345      * @throws IllegalArgumentException
346      *             <ul>
347      *             <li>if <code>leafrefType</code> equal null</li>
348      *             <li>if path statement of <code>leafrefType</code> equal null</li>
349      *             </ul>
350      *
351      */
352     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
353         Type returnType = null;
354         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
355
356         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
357                 "The Path Statement for Leafref Type Definition cannot be NULL!");
358
359         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
360         final String strXPath = xpath.toString();
361
362         if (strXPath != null) {
363             if (strXPath.contains("[")) {
364                 returnType = Types.typeForClass(Object.class);
365             } else {
366                 final Module module = findParentModule(schemaContext, parentNode);
367                 if (module != null) {
368                     final SchemaNode dataNode;
369                     if (xpath.isAbsolute()) {
370                         dataNode = findDataSchemaNode(schemaContext, module, xpath);
371                     } else {
372                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
373                     }
374
375                     if (leafContainsEnumDefinition(dataNode)) {
376                         returnType = referencedTypes.get(dataNode.getPath());
377                     } else if (leafListContainsEnumDefinition(dataNode)) {
378                         returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
379                     } else {
380                         returnType = resolveTypeFromDataSchemaNode(dataNode);
381                     }
382                 }
383             }
384         }
385         return returnType;
386     }
387
388     /**
389      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
390      * so then checks if it is of type <code>EnumTypeDefinition</code>.
391      *
392      * @param dataNode
393      *            data schema node for which is checked if it is leaf and if it
394      *            is of enum type
395      * @return boolean value
396      *         <ul>
397      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
398      *         <li>false - other cases</li>
399      *         </ul>
400      */
401     private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
402         if (dataNode instanceof LeafSchemaNode) {
403             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
404             if (leaf.getType() instanceof EnumTypeDefinition) {
405                 return true;
406             }
407         }
408         return false;
409     }
410
411     /**
412      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
413      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
414      *
415      * @param dataNode
416      *            data schema node for which is checked if it is leaflist and if
417      *            it is of enum type
418      * @return boolean value
419      *         <ul>
420      *         <li>true - if <code>dataNode</code> is leaflist of type
421      *         enumeration</li>
422      *         <li>false - other cases</li>
423      *         </ul>
424      */
425     private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
426         if (dataNode instanceof LeafListSchemaNode) {
427             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
428             if (leafList.getType() instanceof EnumTypeDefinition) {
429                 return true;
430             }
431         }
432         return false;
433     }
434
435     /**
436      * Converts <code>enumTypeDef</code> to
437      * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
438      * enumeration}.
439      *
440      * @param enumTypeDef
441      *            enumeration type definition which is converted to enumeration
442      * @param enumName
443      *            string with name which is used as the enumeration name
444      * @return enumeration type which is built with data (name, enum values)
445      *         from <code>enumTypeDef</code>
446      * @throws IllegalArgumentException
447      *             <ul>
448      *             <li>if <code>enumTypeDef</code> equals null</li>
449      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
450      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
451      *             <li>if name of <code>enumTypeDef</code> equal null</li>
452      *             </ul>
453      */
454     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
455             final SchemaNode parentNode) {
456         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
457         Preconditions.checkArgument(enumTypeDef.getValues() != null,
458                 "EnumTypeDefinition MUST contain at least ONE value definition!");
459         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
460         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
461                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
462
463         final String enumerationName = parseToClassName(enumName);
464
465         Module module = findParentModule(schemaContext, parentNode);
466         final String basePackageName = moduleNamespaceToPackageName(module);
467
468         final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
469         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
470         return enumBuilder.toInstance(null);
471     }
472
473     /**
474      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
475      * taken from <code>enumTypeDef</code>.
476      *
477      * @param enumTypeDef
478      *            enumeration type definition is source of enumeration data for
479      *            <code>typeBuilder</code>
480      * @param enumName
481      *            string with the name of enumeration
482      * @param typeBuilder
483      *            generated type builder to which is enumeration added
484      * @return enumeration type which contains enumeration data form
485      *         <code>enumTypeDef</code>
486      * @throws IllegalArgumentException
487      *             <ul>
488      *             <li>if <code>enumTypeDef</code> equals null</li>
489      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
490      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
491      *             <li>if name of <code>enumTypeDef</code> equal null</li>
492      *             <li>if name of <code>typeBuilder</code> equal null</li>
493      *             </ul>
494      *
495      */
496     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
497             final GeneratedTypeBuilderBase<?> typeBuilder) {
498         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
499         Preconditions.checkArgument(enumTypeDef.getValues() != null,
500                 "EnumTypeDefinition MUST contain at least ONE value definition!");
501         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
502         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
503                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
504         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
505
506         final String enumerationName = parseToClassName(enumName);
507
508         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
509         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
510         return enumBuilder.toInstance(enumBuilder);
511     }
512
513     /**
514      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
515      *
516      * @param dataNode
517      *            contains information about YANG type
518      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
519      */
520     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
521         Type returnType = null;
522         if (dataNode != null) {
523             if (dataNode instanceof LeafSchemaNode) {
524                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
525                 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
526             } else if (dataNode instanceof LeafListSchemaNode) {
527                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
528                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
529             }
530         }
531         return returnType;
532     }
533
534     /**
535      * Passes through all modules and through all its type definitions and
536      * convert it to generated types.
537      *
538      * The modules are firstly sorted by mutual dependencies. The modules are
539      * sequentially passed. All type definitions of a module are at the
540      * beginning sorted so that type definition with less amount of references
541      * to other type definition are processed first.<br />
542      * For each module is created mapping record in the map
543      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
544      * which map current module name to the map which maps type names to
545      * returned types (generated types).
546      *
547      */
548     private void resolveTypeDefsFromContext() {
549         final Set<Module> modules = schemaContext.getModules();
550         Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
551         final Module[] modulesArray = new Module[modules.size()];
552         int i = 0;
553         for (Module modul : modules) {
554             modulesArray[i++] = modul;
555         }
556         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
557
558         for (final Module module : modulesSortedByDependency) {
559             if (module == null) {
560                 continue;
561             }
562             final String moduleName = module.getName();
563             final String basePackageName = moduleNamespaceToPackageName(module);
564
565             final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
566             final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
567
568             final Map<String, Type> typeMap = new HashMap<>();
569             genTypeDefsContextMap.put(moduleName, typeMap);
570
571             if ((listTypeDefinitions != null) && (basePackageName != null)) {
572                 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
573                     typedefToGeneratedType(basePackageName, moduleName, typedef);
574                 }
575             }
576         }
577     }
578
579     /**
580      *
581      * @param basePackageName
582      *            string with name of package to which the module belongs
583      * @param moduleName
584      *            string with the name of the module for to which the
585      *            <code>typedef</code> belongs
586      * @param typedef
587      *            type definition of the node for which should be creted JAVA
588      *            <code>Type</code> (usually generated TO)
589      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
590      *         <code>null</code> value if <code>basePackageName</code> or
591      *         <code>modulName</code> or <code>typedef</code> or Q name of
592      *         <code>typedef</code> equals <code>null</code>
593      */
594     private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
595             final TypeDefinition<?> typedef) {
596         if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
597
598             final String typedefName = typedef.getQName().getLocalName();
599             final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
600             if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
601                     && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
602                 Type returnType = null;
603                 if (innerTypeDefinition instanceof ExtendedType) {
604                     ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
605                     returnType = provideGeneratedTOFromExtendedType(innerExtendedType, basePackageName, typedefName);
606                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
607                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
608                             (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
609                     returnType = genTOBuilder.toInstance();
610                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
611                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
612                     returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
613
614                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
615                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
616                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
617                             basePackageName, bitsTypeDefinition, typedefName);
618                     returnType = genTOBuilder.toInstance();
619
620                 } else {
621                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
622                             innerTypeDefinition, typedef);
623
624                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
625                 }
626                 if (returnType != null) {
627                     final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
628                     if (typeMap != null) {
629                         typeMap.put(typedefName, returnType);
630                     }
631                     return returnType;
632                 }
633             }
634         }
635         return null;
636     }
637
638     /**
639      * Wraps base YANG type to generated TO.
640      *
641      * @param basePackageName
642      *            string with name of package to which the module belongs
643      * @param typedef
644      *            type definition which is converted to the TO
645      * @param javaType
646      *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
647      * @return generated transfer object which represent<code>javaType</code>
648      */
649     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
650             final Type javaType) {
651         if (javaType != null) {
652             final String propertyName = "value";
653
654             final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
655             final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
656             genPropBuilder.setReturnType(javaType);
657             genTOBuilder.addEqualsIdentity(genPropBuilder);
658             genTOBuilder.addHashIdentity(genPropBuilder);
659             genTOBuilder.addToStringProperty(genPropBuilder);
660             if (javaType == BaseYangTypes.STRING_TYPE && typedef instanceof ExtendedType) {
661                 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
662                 addStringRegExAsConstant(genTOBuilder, regExps);
663             }
664             return genTOBuilder.toInstance();
665         }
666         return null;
667     }
668
669     /**
670      * Converts output list of generated TO builders to one TO builder (first
671      * from list) which contains the remaining builders as its enclosing TO.
672      *
673      * @param basePackageName
674      *            string with name of package to which the module belongs
675      * @param typedef
676      *            type definition which should be of type
677      *            <code>UnionTypeDefinition</code>
678      * @param typeDefName
679      *            string with name for generated TO
680      * @return generated TO builder with the list of enclosed generated TO
681      *         builders
682      */
683     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
684             final UnionTypeDefinition typedef, String typeDefName, SchemaNode parentNode) {
685         final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
686                 typedef, typeDefName, parentNode);
687         GeneratedTOBuilder resultTOBuilder = null;
688         if (!genTOBuilders.isEmpty()) {
689             resultTOBuilder = genTOBuilders.get(0);
690             genTOBuilders.remove(0);
691             for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
692                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
693             }
694         }
695         return resultTOBuilder;
696     }
697
698     /**
699      * Converts <code>typedef</code> to generated TO with
700      * <code>typeDefName</code>. Every union type from <code>typedef</code> is
701      * added to generated TO builder as property.
702      *
703      * @param basePackageName
704      *            string with name of package to which the module belongs
705      * @param typedef
706      *            type definition which should be of type
707      *            <code>UnionTypeDefinition</code>
708      * @param typeDefName
709      *            string with name for generated TO
710      * @return generated TO builder which represents <code>typedef</code>
711      * @throws IllegalArgumentException
712      *             <ul>
713      *             <li>if <code>basePackageName</code> equals null</li>
714      *             <li>if <code>typedef</code> equals null</li>
715      *             <li>if Q name of <code>typedef</code> equals null</li>
716      *             </ul>
717      */
718     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
719             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
720         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
721         Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
722         Preconditions.checkArgument(typedef.getQName() != null,
723                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
724
725         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
726
727         if (typedef != null) {
728             final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
729
730             final GeneratedTOBuilder unionGenTOBuilder;
731             if (typeDefName != null && !typeDefName.isEmpty()) {
732                 final String typeName = parseToClassName(typeDefName);
733                 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
734             } else {
735                 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
736             }
737             generatedTOBuilders.add(unionGenTOBuilder);
738             unionGenTOBuilder.setIsUnion(true);
739             final List<String> regularExpressions = new ArrayList<String>();
740             for (final TypeDefinition<?> unionType : unionTypes) {
741                 final String unionTypeName = unionType.getQName().getLocalName();
742                 if (unionType instanceof UnionType) {
743                     generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
744                             basePackageName, parentNode));
745                 } else if (unionType instanceof ExtendedType) {
746                     resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
747                             regularExpressions, parentNode);
748                 } else if (unionType instanceof EnumTypeDefinition) {
749                     final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
750                             unionTypeName, unionGenTOBuilder);
751                     updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
752                 } else {
753                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
754                             unionType, parentNode);
755                     updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
756                 }
757             }
758             if (!regularExpressions.isEmpty()) {
759                 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
760             }
761
762             storeGenTO(typedef, unionGenTOBuilder, parentNode);
763         }
764         return generatedTOBuilders;
765     }
766
767     /**
768      * Wraps code which handle case when union subtype is also of the type
769      * <code>UnionType</code>.
770      *
771      * In this case the new generated TO is created for union subtype (recursive
772      * call of method
773      * {@link #provideGeneratedTOBuilderForUnionTypeDef(String, TypeDefinition, String)
774      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
775      * <code>parentUnionGenTOBuilder</code> is created property which type is
776      * equal to new generated TO.
777      *
778      * @param parentUnionGenTOBuilder
779      *            generated TO builder to which is the property with the child
780      *            union subtype added
781      * @param basePackageName
782      *            string with the name of the module package
783      * @param unionSubtype
784      *            type definition which represents union subtype
785      * @return list of generated TO builders. The number of the builders can be
786      *         bigger one due to recursive call of
787      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
788      */
789     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
790             final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
791         final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
792         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
793                 basePackageName, unionSubtype, newTOBuilderName, parentNode);
794
795         final GeneratedPropertyBuilder propertyBuilder;
796         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
797                 .parseToValidParamName(newTOBuilderName));
798         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
799         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
800         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
801
802         return subUnionGenTOBUilders;
803     }
804
805     /**
806      * Wraps code which handle case when union subtype is of the type
807      * <code>ExtendedType</code>.
808      *
809      * If TO for this type already exists it is used for the creation of the
810      * property in <code>parentUnionGenTOBuilder</code>. In other case the base
811      * type is used for the property creation.
812      *
813      * @param parentUnionGenTOBuilder
814      *            generated TO builder in which new property is created
815      * @param unionSubtype
816      *            type definition of the <code>ExtendedType</code> type which
817      *            represents union subtype
818      * @param unionTypeName
819      *            string with the name for <code>unionSubtype</code>
820      * @param regularExpressions
821      *            list of strings with the regular expressions
822      */
823     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
824             final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
825             final SchemaNode parentNode) {
826         final Type genTO = findGenTO(unionTypeName, parentNode);
827         if (genTO != null) {
828             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
829         } else {
830             final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
831             if (unionTypeName.equals(baseType.getQName().getLocalName())) {
832                 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
833                         parentNode);
834                 if (javaType != null) {
835                     updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
836                 }
837             }
838             if (baseType instanceof StringType) {
839                 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
840             }
841         }
842     }
843
844     /**
845      * Searches for generated TO for <code>searchedTypeDef</code> type
846      * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
847      *
848      * @param searchedTypeName
849      *            string with name of <code>searchedTypeDef</code>
850      * @return generated TO for <code>searchedTypeDef</code> or
851      *         <code>null</code> it it doesn't exist
852      */
853     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
854         final Module typeModule = findParentModule(schemaContext, parentNode);
855         if (typeModule != null && typeModule.getName() != null) {
856             final Map<String, Type> genTOs = genTypeDefsContextMap.get(typeModule.getName());
857             if (genTOs != null) {
858                 return genTOs.get(searchedTypeName);
859             }
860         }
861         return null;
862     }
863
864     /**
865      * Stores generated TO created from <code>genTOBuilder</code> for
866      * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
867      * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
868      *
869      * @param newTypeDef
870      *            type definition for which is <code>genTOBuilder</code> created
871      * @param genTOBuilder
872      *            generated TO builder which is converted to generated TO and
873      *            stored
874      */
875     private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
876         if (!(newTypeDef instanceof UnionType)) {
877             Map<String, Type> genTOsMap = null;
878             final Module parentModule = findParentModule(schemaContext, parentNode);
879             if (parentModule != null && parentModule.getName() != null) {
880                 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
881                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
882             }
883         }
884     }
885
886     /**
887      * Adds a new property with the name <code>propertyName</code> and with type
888      * <code>type</code> to <code>unonGenTransObject</code>.
889      *
890      * @param unionGenTransObject
891      *            generated TO to which should be property added
892      * @param type
893      *            JAVA <code>type</code> of the property which should be added
894      *            to <code>unionGentransObject</code>
895      * @param propertyName
896      *            string with name of property which should be added to
897      *            <code>unionGentransObject</code>
898      */
899     private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
900             final String propertyName) {
901         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
902             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
903                     .addProperty(parseToValidParamName(propertyName));
904             propBuilder.setReturnType(type);
905
906             unionGenTransObject.addEqualsIdentity(propBuilder);
907             unionGenTransObject.addHashIdentity(propBuilder);
908             unionGenTransObject.addToStringProperty(propBuilder);
909         }
910     }
911
912     /**
913      * Converts <code>typedef</code> to the generated TO builder.
914      *
915      * @param basePackageName
916      *            string with name of package to which the module belongs
917      * @param typedef
918      *            type definition from which is the generated TO builder created
919      * @return generated TO builder which contains data from
920      *         <code>typedef</code> and <code>basePackageName</code>
921      */
922     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
923
924         final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
925         final String typeDefTOName = typedef.getQName().getLocalName();
926
927         if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
928             final String genTOName = parseToClassName(typeDefTOName);
929             final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
930             newType.addComment(typedef.getDescription());
931             return newType;
932         }
933         return null;
934     }
935
936     /**
937      * Converts <code>typeDef</code> which should be of the type
938      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
939      *
940      * All the bits of the typeDef are added to returning generated TO as
941      * properties.
942      *
943      * @param basePackageName
944      *            string with name of package to which the module belongs
945      * @param typeDef
946      *            type definition from which is the generated TO builder created
947      * @param typeDefName
948      *            string with the name for generated TO builder
949      * @return generated TO builder which represents <code>typeDef</code>
950      * @throws IllegalArgumentException
951      *             <ul>
952      *             <li>if <code>typeDef</code> equals null</li>
953      *             <li>if <code>basePackageName</code> equals null</li>
954      *             </ul>
955      */
956     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
957             final TypeDefinition<?> typeDef, String typeDefName) {
958
959         Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
960         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
961
962         if (typeDef instanceof BitsTypeDefinition) {
963             BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
964
965             final String typeName = parseToClassName(typeDefName);
966             final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
967
968             final List<Bit> bitList = bitsTypeDefinition.getBits();
969             GeneratedPropertyBuilder genPropertyBuilder;
970             for (final Bit bit : bitList) {
971                 String name = bit.getName();
972                 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
973                 genPropertyBuilder.setReadOnly(true);
974                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
975
976                 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
977                 genTOBuilder.addHashIdentity(genPropertyBuilder);
978                 genTOBuilder.addToStringProperty(genPropertyBuilder);
979             }
980
981             return genTOBuilder;
982         }
983         return null;
984     }
985
986     /**
987      * Converts the pattern constraints from <code>typedef</code> to the list of
988      * the strings which represents these constraints.
989      *
990      * @param typedef
991      *            extended type in which are the pattern constraints sought
992      * @return list of strings which represents the constraint patterns
993      * @throws IllegalArgumentException
994      *             if <code>typedef</code> equals null
995      *
996      */
997     private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
998         final List<String> regExps = new ArrayList<String>();
999         Preconditions.checkArgument(typedef != null, "typedef can't be null");
1000         final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1001         if (strTypeDef instanceof StringType) {
1002             final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1003             if (!patternConstraints.isEmpty()) {
1004                 String regEx;
1005                 String modifiedRegEx;
1006                 for (PatternConstraint patternConstraint : patternConstraints) {
1007                     regEx = patternConstraint.getRegularExpression();
1008                     modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1009                     regExps.add(modifiedRegEx);
1010                 }
1011             }
1012         }
1013         return regExps;
1014     }
1015
1016     /**
1017      *
1018      * Adds to the <code>genTOBuilder</code> the constant which contains regular
1019      * expressions from the <code>regularExpressions</code>
1020      *
1021      * @param genTOBuilder
1022      *            generated TO builder to which are
1023      *            <code>regular expressions</code> added
1024      * @param regularExpressions
1025      *            list of string which represent regular expressions
1026      * @throws IllegalArgumentException
1027      *             <ul>
1028      *             <li>if <code>genTOBuilder</code> equals null</li>
1029      *             <li>if <code>regularExpressions</code> equals null</li>
1030      *             </ul>
1031      */
1032     private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1033         if (genTOBuilder == null) {
1034             throw new IllegalArgumentException("Generated transfer object builder can't be null");
1035         }
1036         if (regularExpressions == null) {
1037             throw new IllegalArgumentException("List of regular expressions can't be null");
1038         }
1039         if (!regularExpressions.isEmpty()) {
1040             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1041                     regularExpressions);
1042         }
1043     }
1044
1045     /**
1046      * Creates generated TO with data about inner extended type
1047      * <code>innerExtendedType</code>, about the package name
1048      * <code>typedefName</code> and about the generated TO name
1049      * <code>typedefName</code>.
1050      *
1051      * It is supposed that <code>innerExtendedType</code> is already present in
1052      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1053      * be possible set it as extended type for the returning generated TO.
1054      *
1055      * @param innerExtendedType
1056      *            extended type which is part of some other extended type
1057      * @param basePackageName
1058      *            string with the package name of the module
1059      * @param typedefName
1060      *            string with the name for the generated TO
1061      * @return generated TO which extends generated TO for
1062      *         <code>innerExtendedType</code>
1063      * @throws IllegalArgumentException
1064      *             <ul>
1065      *             <li>if <code>extendedType</code> equals null</li>
1066      *             <li>if <code>basePackageName</code> equals null</li>
1067      *             <li>if <code>typedefName</code> equals null</li>
1068      *             </ul>
1069      */
1070     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
1071             final String basePackageName, final String typedefName) {
1072
1073         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1074         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1075         Preconditions.checkArgument(typedefName != null, "String with type definition name cannot be NULL!");
1076
1077         final String classTypedefName = parseToClassName(typedefName);
1078         final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1079         final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1080
1081         Map<String, Type> typeMap = null;
1082         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1083         if (parentModule != null) {
1084             typeMap = genTypeDefsContextMap.get(parentModule.getName());
1085         }
1086
1087         if (typeMap != null) {
1088             Type type = typeMap.get(innerTypeDef);
1089             if (type instanceof GeneratedTransferObject) {
1090                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1091             }
1092         }
1093
1094         return genTOBuilder.toInstance();
1095     }
1096
1097     /**
1098      * Finds out for each type definition how many immersion (depth) is
1099      * necessary to get to the base type. Every type definition is inserted to
1100      * the map which key is depth and value is list of type definitions with
1101      * equal depth. In next step are lists from this map concatenated to one
1102      * list in ascending order according to their depth. All type definitions
1103      * are in the list behind all type definitions on which depends.
1104      *
1105      * @param unsortedTypeDefinitions
1106      *            list of type definitions which should be sorted by depth
1107      * @return list of type definitions sorted according their each other
1108      *         dependencies (type definitions which are depend on other type
1109      *         definitions are in list behind them).
1110      */
1111     private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1112             final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
1113         List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1114
1115         Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1116         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1117             final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1118             List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1119             if (typeDefinitionsConcreteDepth == null) {
1120                 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1121                 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1122             }
1123             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1124         }
1125         // keys are in ascending order
1126         Set<Integer> depths = typeDefinitionsDepths.keySet();
1127         for (Integer depth : depths) {
1128             sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1129         }
1130
1131         return sortedTypeDefinition;
1132     }
1133
1134     /**
1135      * Returns how many immersion is necessary to get from the type definition
1136      * to the base type.
1137      *
1138      * @param typeDefinition
1139      *            type definition for which is depth sought.
1140      * @return number of immersions which are necessary to get from the type
1141      *         definition to the base type
1142      */
1143     private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1144         if (typeDefinition == null) {
1145             return 1;
1146         }
1147         int depth = 1;
1148         TypeDefinition<?> baseType = typeDefinition.getBaseType();
1149
1150         if (baseType instanceof ExtendedType) {
1151             depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1152         } else if (baseType instanceof UnionType) {
1153             List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1154             int maxChildDepth = 0;
1155             int childDepth = 1;
1156             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1157                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1158                 if (childDepth > maxChildDepth) {
1159                     maxChildDepth = childDepth;
1160                 }
1161             }
1162             return maxChildDepth;
1163         }
1164         return depth;
1165     }
1166
1167     /**
1168      * Returns string which contains the same value as <code>name</code> but
1169      * integer suffix is incremented by one. If <code>name</code> contains no
1170      * number suffix then number 1 is added.
1171      *
1172      * @param name
1173      *            string with name of augmented node
1174      * @return string with the number suffix incremented by one (or 1 is added)
1175      */
1176     private String provideAvailableNameForGenTOBuilder(String name) {
1177         Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1178         Matcher mtch = searchedPattern.matcher(name);
1179         if (mtch.find()) {
1180             final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1181             return name.substring(0, mtch.start()) + newSuffix;
1182         } else {
1183             return name + 1;
1184         }
1185     }
1186
1187 }