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