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