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