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