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