Refactored base yang-java types.
[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.TypeConstants;
22 import org.opendaylight.yangtools.binding.generator.util.Types;
23 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
24 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
25 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
26 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
27 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
28 import org.opendaylight.yangtools.sal.binding.model.api.Type;
29 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
30 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
31 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
32 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
33 import org.opendaylight.yangtools.yang.common.QName;
34 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
35 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
36 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
37 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
38 import org.opendaylight.yangtools.yang.model.api.Module;
39 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
42 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
43 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
44 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
45 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
46 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
47 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
48 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
49 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
50 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
51 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
52 import org.opendaylight.yangtools.yang.model.util.StringType;
53 import org.opendaylight.yangtools.yang.model.util.UnionType;
54 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
55
56 public final class TypeProviderImpl implements TypeProvider {
57     /**
58      * Contains the schema data red from YANG files.
59      */
60     private final SchemaContext schemaContext;
61
62     /**
63      * The outter map maps module names to the map of the types for the module.
64      * The inner map maps the name of the concrete type to the JAVA
65      * <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 Module parentModule = findParentModuleForTypeDefinition(schemaContext, typedef);
636                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDefinition(
637                             basePackageName, typedef, typedefName, parentModule);
638                     returnType = genTOBuilder.toInstance();
639                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
640                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
641                     returnType = provideTypeForEnum(enumTypeDef, typedefName);
642
643                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
644                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
645                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
646                             basePackageName, bitsTypeDefinition, typedefName);
647                     returnType = genTOBuilder.toInstance();
648
649                 } else {
650                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
651                             .javaTypeForSchemaDefinitionType(innerTypeDefinition);
652
653                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
654                 }
655                 if (returnType != null) {
656                     final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
657                     if (typeMap != null) {
658                         typeMap.put(typedefName, returnType);
659                     }
660                     return returnType;
661                 }
662             }
663         }
664         return null;
665     }
666
667     /**
668      * Wraps base YANG type to generated TO.
669      *
670      * @param basePackageName
671      *            string with name of package to which the module belongs
672      * @param typedef
673      *            type definition which is converted to the TO
674      * @param javaType
675      *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
676      * @return generated transfer object which represent<code>javaType</code>
677      */
678     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
679             final Type javaType) {
680         if (javaType != null) {
681             final String typedefName = typedef.getQName().getLocalName();
682             final String propertyName = parseToValidParamName(typedefName);
683
684             final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
685
686             final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
687
688             genPropBuilder.setReturnType(javaType);
689             genTOBuilder.addEqualsIdentity(genPropBuilder);
690             genTOBuilder.addHashIdentity(genPropBuilder);
691             genTOBuilder.addToStringProperty(genPropBuilder);
692             if (javaType == BaseYangTypes.STRING_TYPE) {
693                 if (typedef instanceof ExtendedType) {
694                     final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
695                     addStringRegExAsConstant(genTOBuilder, regExps);
696                 }
697             }
698             return genTOBuilder.toInstance();
699         }
700         return null;
701     }
702
703     /**
704      * Converts <code>typedef</code> to generated TO with
705      * <code>typeDefName</code>. Every union type from <code>typedef</code> is
706      * added to generated TO builder as property.
707      *
708      * @param basePackageName
709      *            string with name of package to which the module belongs
710      * @param typedef
711      *            type definition which should be of type
712      *            <code>UnionTypeDefinition</code>
713      * @param typeDefName
714      *            string with name for generated TO
715      * @return generated TO builder which represents <code>typedef</code>
716      * @throws IllegalArgumentException
717      *             <ul>
718      *             <li>if <code>basePackageName</code> equals null</li>
719      *             <li>if <code>typedef</code> equals null</li>
720      *             <li>if Q name of <code>typedef</code> equals null</li>
721      *             </ul>
722      */
723     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDefinition(final String basePackageName,
724             final TypeDefinition<?> typedef, final String typeDefName, final Module parentModule) {
725         if (basePackageName == null) {
726             throw new IllegalArgumentException("Base Package Name cannot be NULL!");
727         }
728         if (typedef == null) {
729             throw new IllegalArgumentException("Type Definition cannot be NULL!");
730         }
731         if (typedef.getQName() == null) {
732             throw new IllegalArgumentException(
733                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
734         }
735
736         final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
737         if ((baseTypeDefinition != null) && (baseTypeDefinition instanceof UnionTypeDefinition)) {
738             final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
739             final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
740
741             final GeneratedTOBuilder unionGenTransObject;
742             if (typeDefName != null && !typeDefName.isEmpty()) {
743                 final String typeName = parseToClassName(typeDefName);
744                 unionGenTransObject = new GeneratedTOBuilderImpl(basePackageName, typeName);
745             } else {
746                 unionGenTransObject = typedefToTransferObject(basePackageName, typedef);
747             }
748             unionGenTransObject.setIsUnion(true);
749
750             final List<String> regularExpressions = new ArrayList<String>();
751             for (final TypeDefinition<?> unionType : unionTypes) {
752                 final String typeName = unionType.getQName().getLocalName();
753                 if (unionType instanceof ExtendedType) {
754                     final Module unionTypeModule = findParentModuleForTypeDefinition(schemaContext, unionType);
755                     if (unionTypeModule != null && unionTypeModule.getName() != null) {
756                         final Map<String, Type> innerGenTOs = genTypeDefsContextMap.get(unionTypeModule.getName());
757                         Type genTransferObject = null;
758                         if (innerGenTOs != null) {
759                             genTransferObject = innerGenTOs.get(typeName);
760                         }
761                         if (genTransferObject != null) {
762                             updateUnionTypeAsProperty(unionGenTransObject, genTransferObject,
763                                     genTransferObject.getName());
764                         } else {
765                             final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionType);
766                             if (typeName.equals(baseType.getQName().getLocalName())) {
767                                 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
768                                         .javaTypeForSchemaDefinitionType(baseType);
769                                 if (javaType != null) {
770                                     updateUnionTypeAsProperty(unionGenTransObject, javaType, typeName);
771                                 }
772                             }
773                             if (baseType instanceof StringType) {
774                                 regularExpressions.addAll(resolveRegExpressionsFromTypedef((ExtendedType) unionType));
775                             }
776                         }
777                     }
778                 } else if (unionType instanceof EnumTypeDefinition) {
779                     final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
780                             typeName, unionGenTransObject);
781                     updateUnionTypeAsProperty(unionGenTransObject, enumeration, typeName);
782                 } else {
783                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
784                             .javaTypeForSchemaDefinitionType(unionType);
785                     if (javaType != null) {
786                         updateUnionTypeAsProperty(unionGenTransObject, javaType, typeName);
787                     }
788                 }
789             }
790             if (!regularExpressions.isEmpty()) {
791                 addStringRegExAsConstant(unionGenTransObject, regularExpressions);
792             }
793
794             Map<String, Type> genTOsMap = null;
795             // final Module parentModule =
796             // findParentModuleForTypeDefinition(schemaContext, typedef);
797             if (parentModule != null && parentModule.getName() != null) {
798                 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
799                 genTOsMap.put(typedef.getQName().getLocalName(), unionGenTransObject.toInstance());
800             }
801
802             return unionGenTransObject;
803         }
804         return null;
805     }
806
807     /**
808      * Adds a new property with the name <code>propertyName</code> and with type
809      * <code>type</code> to <code>unonGenTransObject</code>.
810      *
811      * @param unionGenTransObject
812      *            generated TO to which should be property added
813      * @param type
814      *            JAVA <code>type</code> of the property which should be added
815      *            to <code>unionGentransObject</code>
816      * @param propertyName
817      *            string with name of property which should be added to
818      *            <code>unionGentransObject</code>
819      */
820     private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
821             final String propertyName) {
822         if (unionGenTransObject != null && type != null) {
823             if (!unionGenTransObject.containsProperty(propertyName)) {
824                 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
825                         .addProperty(parseToValidParamName(propertyName));
826                 propBuilder.setReturnType(type);
827
828                 unionGenTransObject.addEqualsIdentity(propBuilder);
829                 unionGenTransObject.addHashIdentity(propBuilder);
830                 unionGenTransObject.addToStringProperty(propBuilder);
831             }
832         }
833     }
834
835     /**
836      * Converts <code>typedef</code> to the generated TO builder.
837      *
838      * @param basePackageName
839      *            string with name of package to which the module belongs
840      * @param typedef
841      *            type definition from which is the generated TO builder created
842      * @return generated TO builder which contains data from
843      *         <code>typedef</code> and <code>basePackageName</code>
844      */
845     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
846
847         final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
848         final String typeDefTOName = typedef.getQName().getLocalName();
849
850         if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
851             final String genTOName = parseToClassName(typeDefTOName);
852             final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
853
854             return newType;
855         }
856         return null;
857     }
858
859     /**
860      * Converts <code>typeDef</code> which should be of the type
861      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
862      *
863      * All the bits of the typeDef are added to returning generated TO as
864      * properties.
865      *
866      * @param basePackageName
867      *            string with name of package to which the module belongs
868      * @param typeDef
869      *            type definition from which is the generated TO builder created
870      * @param typeDefName
871      *            string with the name for generated TO builder
872      * @return generated TO builder which represents <code>typeDef</code>
873      * @throws IllegalArgumentException
874      *             <ul>
875      *             <li>if <code>typeDef</code> equals null</li>
876      *             <li>if <code>basePackageName</code> equals null</li>
877      *             </ul>
878      */
879     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
880             final TypeDefinition<?> typeDef, String typeDefName) {
881
882         if (typeDef == null) {
883             throw new IllegalArgumentException("typeDef cannot be NULL!");
884         }
885         if (basePackageName == null) {
886             throw new IllegalArgumentException("Base Package Name cannot be NULL!");
887         }
888
889         if (typeDef instanceof BitsTypeDefinition) {
890             BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
891
892             final String typeName = parseToClassName(typeDefName);
893             final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
894
895             final List<Bit> bitList = bitsTypeDefinition.getBits();
896             GeneratedPropertyBuilder genPropertyBuilder;
897             for (final Bit bit : bitList) {
898                 String name = bit.getName();
899                 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
900                 genPropertyBuilder.setReadOnly(true);
901                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
902
903                 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
904                 genTOBuilder.addHashIdentity(genPropertyBuilder);
905                 genTOBuilder.addToStringProperty(genPropertyBuilder);
906             }
907
908             return genTOBuilder;
909         }
910         return null;
911     }
912
913     /**
914      * Converts the pattern constraints from <code>typedef</code> to the list of
915      * the strings which represents these constraints.
916      *
917      * @param typedef
918      *            extended type in which are the pattern constraints sought
919      * @return list of strings which represents the constraint patterns
920      * @throws IllegalArgumentException
921      *             if <code>typedef</code> equals null
922      *
923      */
924     private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
925         final List<String> regExps = new ArrayList<String>();
926         if (typedef == null) {
927             throw new IllegalArgumentException("typedef can't be null");
928         }
929         final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
930         if (strTypeDef instanceof StringType) {
931             final List<PatternConstraint> patternConstraints = typedef.getPatterns();
932             if (!patternConstraints.isEmpty()) {
933                 String regEx;
934                 String modifiedRegEx;
935                 for (PatternConstraint patternConstraint : patternConstraints) {
936                     regEx = patternConstraint.getRegularExpression();
937                     modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
938                     regExps.add(modifiedRegEx);
939                 }
940             }
941         }
942         return regExps;
943     }
944
945     /**
946      *
947      * Adds to the <code>genTOBuilder</code> the constant which contains regular
948      * expressions from the <code>regularExpressions</code>
949      *
950      * @param genTOBuilder
951      *            generated TO builder to which are
952      *            <code>regular expressions</code> added
953      * @param regularExpressions
954      *            list of string which represent regular expressions
955      * @throws IllegalArgumentException
956      *             <ul>
957      *             <li>if <code>genTOBuilder</code> equals null</li>
958      *             <li>if <code>regularExpressions</code> equals null</li>
959      *             </ul>
960      */
961     private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
962         if (genTOBuilder == null)
963             throw new IllegalArgumentException("genTOBuilder can't be null");
964         if (regularExpressions == null)
965             throw new IllegalArgumentException("regularExpressions can't be null");
966
967         if (!regularExpressions.isEmpty()) {
968             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
969                     regularExpressions);
970         }
971     }
972
973     /**
974      * Creates generated TO with data about inner extended type
975      * <code>innerExtendedType</code>, about the package name
976      * <code>typedefName</code> and about the generated TO name
977      * <code>typedefName</code>.
978      *
979      * It is supposed that <code>innerExtendedType</code> is already present in
980      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
981      * be possible set it as extended type for the returning generated TO.
982      *
983      * @param innerExtendedType
984      *            extended type which is part of some other extended type
985      * @param basePackageName
986      *            string with the package name of the module
987      * @param typedefName
988      *            string with the name for the generated TO
989      * @return generated TO which extends generated TO for
990      *         <code>innerExtendedType</code>
991      * @throws IllegalArgumentException
992      *             <ul>
993      *             <li>if <code>extendedType</code> equals null</li>
994      *             <li>if <code>basePackageName</code> equals null</li>
995      *             <li>if <code>typedefName</code> equals null</li>
996      *             </ul>
997      */
998     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
999             final String basePackageName, final String typedefName) {
1000
1001         if (innerExtendedType == null) {
1002             throw new IllegalArgumentException("Extended type cannot be NULL!");
1003         }
1004         if (basePackageName == null) {
1005             throw new IllegalArgumentException("String with base package name cannot be NULL!");
1006         }
1007         if (typedefName == null) {
1008             throw new IllegalArgumentException("String with type definition name cannot be NULL!");
1009         }
1010
1011         final String classTypedefName = parseToClassName(typedefName);
1012         final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1013         final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1014
1015         Map<String, Type> typeMap = null;
1016         final Module parentModule = findParentModuleForTypeDefinition(schemaContext, innerExtendedType);
1017         if (parentModule != null) {
1018             typeMap = genTypeDefsContextMap.get(parentModule.getName());
1019         }
1020
1021         if (typeMap != null) {
1022             Type type = typeMap.get(innerTypeDef);
1023             if (type instanceof GeneratedTransferObject) {
1024                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1025             }
1026         }
1027
1028         return genTOBuilder.toInstance();
1029     }
1030
1031     /**
1032      * Finds out for each type definition how many immersion (depth) is
1033      * necessary to get to the base type. Every type definition is inserted to
1034      * the map which key is depth and value is list of type definitions with
1035      * equal depth. In next step are lists from this map concatenated to one
1036      * list in ascending order according to their depth. All type definitions
1037      * are in the list behind all type definitions on which depends.
1038      *
1039      * @param unsortedTypeDefinitions
1040      *            list of type definitions which should be sorted by depth
1041      * @return list of type definitions sorted according their each other
1042      *         dependencies (type definitions which are depend on other type
1043      *         definitions are in list behind them).
1044      */
1045     private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1046             final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
1047         List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1048
1049         Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1050         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1051             final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1052             List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1053             if (typeDefinitionsConcreteDepth == null) {
1054                 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1055                 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1056             }
1057             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1058         }
1059
1060         Set<Integer> depths = typeDefinitionsDepths.keySet(); // keys are in
1061                                                               // ascending order
1062         for (Integer depth : depths) {
1063             sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1064         }
1065
1066         return sortedTypeDefinition;
1067     }
1068
1069     /**
1070      * Returns how many immersion is necessary to get from the type definition
1071      * to the base type.
1072      *
1073      * @param typeDefinition
1074      *            type definition for which is depth sought.
1075      * @return number of immersions which are necessary to get from the type
1076      *         definition to the base type
1077      */
1078     private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1079         if (typeDefinition == null) {
1080             throw new IllegalArgumentException("Type definition can't be null");
1081         }
1082         int depth = 1;
1083         TypeDefinition<?> baseType = typeDefinition.getBaseType();
1084
1085         if (baseType instanceof ExtendedType) {
1086             depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1087         } else if (baseType instanceof UnionType) {
1088             List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1089             int maxChildDepth = 0;
1090             int childDepth = 1;
1091             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1092                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1093                 if (childDepth > maxChildDepth) {
1094                     maxChildDepth = childDepth;
1095                 }
1096             }
1097             return maxChildDepth;
1098         }
1099         return depth;
1100     }
1101
1102 }