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