BUG 1131: untangling package cyclic dependencies in yang-parser-impl
[yangtools.git] / code-generator / binding-type-provider / src / main / java / org / opendaylight / yangtools / sal / binding / yang / types / TypeProviderImpl.java
1 /*
2  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.sal.binding.yang.types;
9
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.moduleNamespaceToPackageName;
11 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
12 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.parseToValidParamName;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
15 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
16
17 import java.math.BigDecimal;
18 import java.math.BigInteger;
19 import java.net.URI;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Collections;
23 import java.util.Comparator;
24 import java.util.Date;
25 import java.util.HashMap;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.Map;
29 import java.util.Set;
30 import java.util.TreeMap;
31 import java.util.regex.Matcher;
32 import java.util.regex.Pattern;
33
34 import org.apache.commons.lang3.StringEscapeUtils;
35 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
36 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
39 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
40 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
41 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
42 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
43 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
44 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
45 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
46 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
47 import org.opendaylight.yangtools.sal.binding.model.api.Type;
48 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
49 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
50 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
51 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
53 import org.opendaylight.yangtools.yang.binding.BindingMapping;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
67 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
75 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
78 import org.opendaylight.yangtools.yang.model.util.EnumerationType;
79 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
80 import org.opendaylight.yangtools.yang.model.util.Int16;
81 import org.opendaylight.yangtools.yang.model.util.Int32;
82 import org.opendaylight.yangtools.yang.model.util.Int64;
83 import org.opendaylight.yangtools.yang.model.util.Int8;
84 import org.opendaylight.yangtools.yang.model.util.StringType;
85 import org.opendaylight.yangtools.yang.model.util.Uint16;
86 import org.opendaylight.yangtools.yang.model.util.Uint32;
87 import org.opendaylight.yangtools.yang.model.util.Uint64;
88 import org.opendaylight.yangtools.yang.model.util.Uint8;
89 import org.opendaylight.yangtools.yang.model.util.UnionType;
90
91 import com.google.common.base.Preconditions;
92 import com.google.common.collect.Sets;
93 import com.google.common.io.BaseEncoding;
94
95
96 public final class TypeProviderImpl implements TypeProvider {
97     private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
98
99     /**
100      * Contains the schema data red from YANG files.
101      */
102     private final SchemaContext schemaContext;
103
104     /**
105      * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
106      */
107     private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
108
109     /**
110      * The map which maps schema paths to JAVA <code>Type</code>.
111      */
112     private final Map<SchemaPath, Type> referencedTypes;
113     private final Map<Module, Set<Type>> additionalTypes;
114
115     /**
116      * Creates new instance of class <code>TypeProviderImpl</code>.
117      *
118      * @param schemaContext
119      *            contains the schema data red from YANG files
120      * @throws IllegalArgumentException
121      *             if <code>schemaContext</code> equal null.
122      */
123     public TypeProviderImpl(final SchemaContext schemaContext) {
124         Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
125
126         this.schemaContext = schemaContext;
127         this.genTypeDefsContextMap = new HashMap<>();
128         this.referencedTypes = new HashMap<>();
129         this.additionalTypes = new HashMap<>();
130         resolveTypeDefsFromContext();
131     }
132
133     /**
134      * Puts <code>refType</code> to map with key <code>refTypePath</code>
135      *
136      * @param refTypePath
137      *            schema path used as the map key
138      * @param refType
139      *            type which represents the map value
140      * @throws IllegalArgumentException
141      *             <ul>
142      *             <li>if <code>refTypePath</code> equal null</li>
143      *             <li>if <code>refType</code> equal null</li>
144      *             </ul>
145      *
146      */
147     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
148         Preconditions.checkArgument(refTypePath != null,
149                 "Path reference of Enumeration Type Definition cannot be NULL!");
150         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
151         referencedTypes.put(refTypePath, refType);
152     }
153
154     public Map<Module, Set<Type>> getAdditionalTypes() {
155         return additionalTypes;
156     }
157
158     /**
159      *
160      * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
161      *
162      * @param type
163      *            string with YANG name of type
164      * @return JAVA <code>Type</code> for YANG type <code>type</code>
165      * @see TypeProvider#javaTypeForYangType(String)
166      */
167     @Override
168     public Type javaTypeForYangType(final String type) {
169         return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
170     }
171
172     @Override
173     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
174         return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
175     }
176
177     /**
178      * Converts schema definition type <code>typeDefinition</code> to JAVA
179      * <code>Type</code>
180      *
181      * @param typeDefinition
182      *            type definition which is converted to JAVA type
183      * @throws IllegalArgumentException
184      *             <ul>
185      *             <li>if <code>typeDefinition</code> equal null</li>
186      *             <li>if Qname of <code>typeDefinition</code> equal null</li>
187      *             <li>if name of <code>typeDefinition</code> equal null</li>
188      *             </ul>
189      */
190     @Override
191     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
192             final Restrictions r) {
193         Type returnType = null;
194         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
195         if (typeDefinition.getQName() == null) {
196             throw new IllegalArgumentException(
197                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
198         }
199         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
200                 "Type Definitions Local Name cannot be NULL!");
201
202         if (typeDefinition instanceof ExtendedType) {
203             returnType = javaTypeForExtendedType(typeDefinition);
204         } else {
205             returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
206             if (returnType == null) {
207                 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName()
208                         .getLocalName());
209             }
210         }
211         // TODO: add throw exception when we will be able to resolve ALL yang
212         // types!
213         // if (returnType == null) {
214         // throw new IllegalArgumentException("Type Provider can't resolve " +
215         // "type for specified Type Definition " + typedefName);
216         // }
217         return returnType;
218     }
219
220     /**
221      * Returns JAVA <code>Type</code> for instances of the type
222      * <code>LeafrefTypeDefinition</code> or
223      * <code>IdentityrefTypeDefinition</code>.
224      *
225      * @param typeDefinition
226      *            type definition which is converted to JAVA <code>Type</code>
227      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
228      */
229     private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
230         if (typeDefinition instanceof LeafrefTypeDefinition) {
231             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
232             return provideTypeForLeafref(leafref, parentNode);
233         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
234             final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
235             return provideTypeForIdentityref(idref);
236         } else {
237             return null;
238         }
239     }
240
241     /**
242      * Returns JAVA <code>Type</code> for instances of the type
243      * <code>ExtendedType</code>.
244      *
245      * @param typeDefinition
246      *            type definition which is converted to JAVA <code>Type</code>
247      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
248      */
249     private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
250         final String typedefName = typeDefinition.getQName().getLocalName();
251         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
252         Type returnType = null;
253         returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
254         if (returnType == null) {
255             if (baseTypeDef instanceof EnumTypeDefinition) {
256                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
257                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
258             } else {
259                 final Module module = findParentModule(schemaContext, typeDefinition);
260                 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
261                 if (module != null) {
262                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
263                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
264                     if (genTOs != null) {
265                         returnType = genTOs.get(typedefName);
266                     }
267                     if (returnType == null) {
268                         returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
269                                 baseTypeDef, typeDefinition, r);
270                     }
271                 }
272             }
273         }
274         return returnType;
275         // TODO: add throw exception when we will be able to resolve ALL yang
276         // types!
277         // if (returnType == null) {
278         // throw new IllegalArgumentException("Type Provider can't resolve " +
279         // "type for specified Type Definition " + typedefName);
280         // }
281     }
282
283     /**
284      * Seeks for identity reference <code>idref</code> the JAVA
285      * <code>type</code>.<br />
286      * <br />
287      *
288      * <i>Example:<br />
289      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
290      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
291      *
292      * @param idref
293      *            identityref type definition for which JAVA <code>Type</code>
294      *            is sought
295      * @return JAVA <code>Type</code> of the identity which is refrenced through
296      *         <code>idref</code>
297      */
298     private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
299         QName baseIdQName = idref.getIdentity().getQName();
300         Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
301                 baseIdQName.getRevision());
302         IdentitySchemaNode identity = null;
303         for (IdentitySchemaNode id : module.getIdentities()) {
304             if (id.getQName().equals(baseIdQName)) {
305                 identity = id;
306             }
307         }
308         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
309
310         final String basePackageName = moduleNamespaceToPackageName(module);
311         final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
312         final String genTypeName = BindingMapping.getClassName(identity.getQName());
313
314         Type baseType = Types.typeForClass(Class.class);
315         Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
316         return Types.parameterizedTypeFor(baseType, paramType);
317     }
318
319     /**
320      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
321      *
322      * @param typeDefinition
323      *            type definition which should be converted to JAVA
324      *            <code>Type</code>
325      * @return JAVA <code>Type</code> which represents
326      *         <code>typeDefinition</code>
327      * @throws IllegalArgumentException
328      *             <ul>
329      *             <li>if <code>typeDefinition</code> equal null</li>
330      *             <li>if Q name of <code>typeDefinition</code></li>
331      *             <li>if name of <code>typeDefinition</code></li>
332      *             </ul>
333      */
334     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
335             final SchemaNode parentNode) {
336         Type returnType = null;
337         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
338         if (typeDefinition.getQName() == null) {
339             throw new IllegalArgumentException(
340                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
341         }
342         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
343                 "Type Definitions Local Name cannot be NULL!");
344
345         final String typedefName = typeDefinition.getQName().getLocalName();
346         if (typeDefinition instanceof ExtendedType) {
347             final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
348
349             if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
350                 final Module module = findParentModule(schemaContext, parentNode);
351
352                 if (module != null) {
353                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
354                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
355                     if (genTOs != null) {
356                         returnType = genTOs.get(typedefName);
357                     }
358                 }
359             }
360         }
361         return returnType;
362     }
363
364     /**
365      * Gets base type definition for <code>extendTypeDef</code>. The method is
366      * recursivelly called until non <code>ExtendedType</code> type is found.
367      *
368      * @param extendTypeDef
369      *            type definition for which is the base type definition sought
370      * @return type definition which is base type for <code>extendTypeDef</code>
371      * @throws IllegalArgumentException
372      *             if <code>extendTypeDef</code> equal null
373      */
374     private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
375         Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
376         final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
377         if (baseTypeDef == null) {
378             return extendTypeDef;
379         } else if (baseTypeDef instanceof ExtendedType) {
380             return baseTypeDefForExtendedType(baseTypeDef);
381         } else {
382             return baseTypeDef;
383         }
384
385     }
386
387     /**
388      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
389      *
390      * The path of <code>leafrefType</code> is followed to find referenced node
391      * and its <code>Type</code> is returned.
392      *
393      * @param leafrefType
394      *            leafref type definition for which is the type sought
395      * @return JAVA <code>Type</code> of data schema node which is referenced in
396      *         <code>leafrefType</code>
397      * @throws IllegalArgumentException
398      *             <ul>
399      *             <li>if <code>leafrefType</code> equal null</li>
400      *             <li>if path statement of <code>leafrefType</code> equal null</li>
401      *             </ul>
402      *
403      */
404     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
405         Type returnType = null;
406         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
407
408         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
409                 "The Path Statement for Leafref Type Definition cannot be NULL!");
410
411         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
412         final String strXPath = xpath.toString();
413
414         if (strXPath != null) {
415             if (strXPath.contains("[")) {
416                 returnType = Types.typeForClass(Object.class);
417             } else {
418                 final Module module = findParentModule(schemaContext, parentNode);
419                 if (module != null) {
420                     final SchemaNode dataNode;
421                     if (xpath.isAbsolute()) {
422                         dataNode = findDataSchemaNode(schemaContext, module, xpath);
423                     } else {
424                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
425                     }
426
427                     if (leafContainsEnumDefinition(dataNode)) {
428                         returnType = referencedTypes.get(dataNode.getPath());
429                     } else if (leafListContainsEnumDefinition(dataNode)) {
430                         returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
431                     } else {
432                         returnType = resolveTypeFromDataSchemaNode(dataNode);
433                     }
434                 }
435             }
436         }
437         if (returnType == null) {
438             throw new IllegalArgumentException("Failed to find leafref target: " + strXPath);
439         }
440         return returnType;
441     }
442
443     /**
444      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
445      * so then checks if it is of type <code>EnumTypeDefinition</code>.
446      *
447      * @param dataNode
448      *            data schema node for which is checked if it is leaf and if it
449      *            is of enum type
450      * @return boolean value
451      *         <ul>
452      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
453      *         <li>false - other cases</li>
454      *         </ul>
455      */
456     private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
457         if (dataNode instanceof LeafSchemaNode) {
458             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
459             if (leaf.getType() instanceof EnumTypeDefinition) {
460                 return true;
461             }
462         }
463         return false;
464     }
465
466     /**
467      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
468      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
469      *
470      * @param dataNode
471      *            data schema node for which is checked if it is leaflist and if
472      *            it is of enum type
473      * @return boolean value
474      *         <ul>
475      *         <li>true - if <code>dataNode</code> is leaflist of type
476      *         enumeration</li>
477      *         <li>false - other cases</li>
478      *         </ul>
479      */
480     private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
481         if (dataNode instanceof LeafListSchemaNode) {
482             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
483             if (leafList.getType() instanceof EnumTypeDefinition) {
484                 return true;
485             }
486         }
487         return false;
488     }
489
490     /**
491      * Converts <code>enumTypeDef</code> to
492      * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
493      * enumeration}.
494      *
495      * @param enumTypeDef
496      *            enumeration type definition which is converted to enumeration
497      * @param enumName
498      *            string with name which is used as the enumeration name
499      * @return enumeration type which is built with data (name, enum values)
500      *         from <code>enumTypeDef</code>
501      * @throws IllegalArgumentException
502      *             <ul>
503      *             <li>if <code>enumTypeDef</code> equals null</li>
504      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
505      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
506      *             <li>if name of <code>enumTypeDef</code> equal null</li>
507      *             </ul>
508      */
509     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
510             final SchemaNode parentNode) {
511         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
512         Preconditions.checkArgument(enumTypeDef.getValues() != null,
513                 "EnumTypeDefinition MUST contain at least ONE value definition!");
514         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
515         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
516                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
517
518         final String enumerationName = BindingMapping.getClassName(enumName);
519
520         Module module = findParentModule(schemaContext, parentNode);
521         final String basePackageName = moduleNamespaceToPackageName(module);
522
523         final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
524         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
525         return enumBuilder.toInstance(null);
526     }
527
528     /**
529      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
530      * taken from <code>enumTypeDef</code>.
531      *
532      * @param enumTypeDef
533      *            enumeration type definition is source of enumeration data for
534      *            <code>typeBuilder</code>
535      * @param enumName
536      *            string with the name of enumeration
537      * @param typeBuilder
538      *            generated type builder to which is enumeration added
539      * @return enumeration type which contains enumeration data form
540      *         <code>enumTypeDef</code>
541      * @throws IllegalArgumentException
542      *             <ul>
543      *             <li>if <code>enumTypeDef</code> equals null</li>
544      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
545      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
546      *             <li>if name of <code>enumTypeDef</code> equal null</li>
547      *             <li>if name of <code>typeBuilder</code> equal null</li>
548      *             </ul>
549      *
550      */
551     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
552             final GeneratedTypeBuilderBase<?> typeBuilder) {
553         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
554         Preconditions.checkArgument(enumTypeDef.getValues() != null,
555                 "EnumTypeDefinition MUST contain at least ONE value definition!");
556         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
557         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
558                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
559         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
560
561         final String enumerationName = BindingMapping.getClassName(enumName);
562
563         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
564         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
565         return enumBuilder.toInstance(enumBuilder);
566     }
567
568     /**
569      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
570      *
571      * @param dataNode
572      *            contains information about YANG type
573      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
574      */
575     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
576         Type returnType = null;
577         if (dataNode != null) {
578             if (dataNode instanceof LeafSchemaNode) {
579                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
580                 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
581             } else if (dataNode instanceof LeafListSchemaNode) {
582                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
583                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
584             }
585         }
586         return returnType;
587     }
588
589     /**
590      * Passes through all modules and through all its type definitions and
591      * convert it to generated types.
592      *
593      * The modules are firstly sorted by mutual dependencies. The modules are
594      * sequentially passed. All type definitions of a module are at the
595      * beginning sorted so that type definition with less amount of references
596      * to other type definition are processed first.<br />
597      * For each module is created mapping record in the map
598      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
599      * which map current module name to the map which maps type names to
600      * returned types (generated types).
601      *
602      */
603     private void resolveTypeDefsFromContext() {
604         final Set<Module> modules = schemaContext.getModules();
605         Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
606         final Module[] modulesArray = new Module[modules.size()];
607         int i = 0;
608         for (Module modul : modules) {
609             modulesArray[i++] = modul;
610         }
611         final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort.sort(modulesArray);
612
613         for (final Module module : modulesSortedByDependency) {
614             Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
615             if (dateTypeMap == null) {
616                 dateTypeMap = new HashMap<>();
617             }
618             final Map<String, Type> typeMap = new HashMap<>();
619             dateTypeMap.put(module.getRevision(), typeMap);
620             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
621         }
622
623         for (final Module module : modulesSortedByDependency) {
624             if (module == null) {
625                 continue;
626             }
627             final String basePackageName = moduleNamespaceToPackageName(module);
628
629             final DataNodeIterator it = new DataNodeIterator(module);
630             final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
631             final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
632
633             if ((listTypeDefinitions != null) && (basePackageName != null)) {
634                 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
635                     typedefToGeneratedType(basePackageName, module, typedef);
636                 }
637             }
638         }
639     }
640
641     /**
642      *
643      * @param basePackageName
644      *            string with name of package to which the module belongs
645      * @param moduleName
646      *            string with the name of the module for to which the
647      *            <code>typedef</code> belongs
648      * @param typedef
649      *            type definition of the node for which should be creted JAVA
650      *            <code>Type</code> (usually generated TO)
651      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
652      *         <code>null</code> value if <code>basePackageName</code> or
653      *         <code>modulName</code> or <code>typedef</code> or Q name of
654      *         <code>typedef</code> equals <code>null</code>
655      */
656     private Type typedefToGeneratedType(final String basePackageName, final Module module,
657             final TypeDefinition<?> typedef) {
658         final String moduleName = module.getName();
659         final Date moduleRevision = module.getRevision();
660         if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
661
662             final String typedefName = typedef.getQName().getLocalName();
663             final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
664             if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
665                     && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
666                 Type returnType = null;
667                 if (innerTypeDefinition instanceof ExtendedType) {
668                     ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
669                     returnType = provideGeneratedTOFromExtendedType(typedef, innerExtendedType, basePackageName);
670                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
671                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
672                             (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
673                     genTOBuilder.setTypedef(true);
674                     genTOBuilder.setIsUnion(true);
675                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
676                     BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
677                     returnType = genTOBuilder.toInstance();
678                     // union builder
679                     GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
680                             genTOBuilder.getName() + "Builder");
681                     unionBuilder.setIsUnionBuilder(true);
682                     MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
683                     method.setReturnType(returnType);
684                     method.addParameter(Types.STRING, "defaultValue");
685                     method.setAccessModifier(AccessModifier.PUBLIC);
686                     method.setStatic(true);
687                     Set<Type> types = additionalTypes.get(module);
688                     if (types == null) {
689                         types = Sets.<Type> newHashSet(unionBuilder.toInstance());
690                         additionalTypes.put(module, types);
691                     } else {
692                         types.add(unionBuilder.toInstance());
693                     }
694                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
695                     // enums are automatically Serializable
696                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
697                     // TODO units for typedef enum
698                     returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
699                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
700                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
701                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
702                             basePackageName, bitsTypeDefinition, typedefName);
703                     genTOBuilder.setTypedef(true);
704                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
705                     BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
706                     returnType = genTOBuilder.toInstance();
707                 } else {
708                     final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
709                             innerTypeDefinition, typedef);
710                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
711                 }
712                 if (returnType != null) {
713                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
714                     final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
715                     if (typeMap != null) {
716                         typeMap.put(typedefName, returnType);
717                     }
718                     return returnType;
719                 }
720             }
721         }
722         return null;
723     }
724
725     /**
726      * Wraps base YANG type to generated TO.
727      *
728      * @param basePackageName
729      *            string with name of package to which the module belongs
730      * @param typedef
731      *            type definition which is converted to the TO
732      * @param javaType
733      *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
734      * @return generated transfer object which represent<code>javaType</code>
735      */
736     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
737             final Type javaType) {
738         Preconditions.checkNotNull(javaType, "javaType cannot be null");
739         final String propertyName = "value";
740
741         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
742         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
743         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
744         genPropBuilder.setReturnType(javaType);
745         genTOBuilder.addEqualsIdentity(genPropBuilder);
746         genTOBuilder.addHashIdentity(genPropBuilder);
747         genTOBuilder.addToStringProperty(genPropBuilder);
748         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef instanceof ExtendedType) {
749             final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
750             addStringRegExAsConstant(genTOBuilder, regExps);
751         }
752         addUnitsToGenTO(genTOBuilder, typedef.getUnits());
753         genTOBuilder.setTypedef(true);
754         BindingGeneratorUtil.makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
755         return genTOBuilder.toInstance();
756     }
757
758     /**
759      * Converts output list of generated TO builders to one TO builder (first
760      * from list) which contains the remaining builders as its enclosing TO.
761      *
762      * @param basePackageName
763      *            string with name of package to which the module belongs
764      * @param typedef
765      *            type definition which should be of type
766      *            <code>UnionTypeDefinition</code>
767      * @param typeDefName
768      *            string with name for generated TO
769      * @return generated TO builder with the list of enclosed generated TO
770      *         builders
771      */
772     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
773             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
774         final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
775                 typedef, typeDefName, parentNode);
776         GeneratedTOBuilder resultTOBuilder = null;
777         if (!genTOBuilders.isEmpty()) {
778             resultTOBuilder = genTOBuilders.remove(0);
779             for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
780                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
781             }
782         }
783
784         final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
785         genPropBuilder.setReturnType(Types.primitiveType("char[]", null));
786         resultTOBuilder.addEqualsIdentity(genPropBuilder);
787         resultTOBuilder.addHashIdentity(genPropBuilder);
788         resultTOBuilder.addToStringProperty(genPropBuilder);
789
790         return resultTOBuilder;
791     }
792
793     /**
794      * Converts <code>typedef</code> to generated TO with
795      * <code>typeDefName</code>. Every union type from <code>typedef</code> is
796      * added to generated TO builder as property.
797      *
798      * @param basePackageName
799      *            string with name of package to which the module belongs
800      * @param typedef
801      *            type definition which should be of type
802      *            <code>UnionTypeDefinition</code>
803      * @param typeDefName
804      *            string with name for generated TO
805      * @return generated TO builder which represents <code>typedef</code>
806      * @throws NullPointerException
807      *             <ul>
808      *             <li>if <code>basePackageName</code> is null</li>
809      *             <li>if <code>typedef</code> is null</li>
810      *             <li>if Qname of <code>typedef</code> is null</li>
811      *             </ul>
812      */
813     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
814             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
815         Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
816         Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
817         Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
818
819         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
820         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
821
822         final GeneratedTOBuilder unionGenTOBuilder;
823         if (typeDefName != null && !typeDefName.isEmpty()) {
824             final String typeName = BindingMapping.getClassName(typeDefName);
825             unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
826         } else {
827             unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
828         }
829
830         generatedTOBuilders.add(unionGenTOBuilder);
831         unionGenTOBuilder.setIsUnion(true);
832         final List<String> regularExpressions = new ArrayList<String>();
833         for (final TypeDefinition<?> unionType : unionTypes) {
834             final String unionTypeName = unionType.getQName().getLocalName();
835             if (unionType instanceof UnionType) {
836                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionType) unionType,
837                         basePackageName, parentNode));
838             } else if (unionType instanceof ExtendedType) {
839                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, regularExpressions,
840                         parentNode);
841             } else if (unionType instanceof EnumTypeDefinition) {
842                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
843                         unionTypeName, unionGenTOBuilder);
844                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
845             } else {
846                 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
847                         parentNode);
848                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
849             }
850         }
851         if (!regularExpressions.isEmpty()) {
852             addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
853         }
854
855         storeGenTO(typedef, unionGenTOBuilder, parentNode);
856
857         return generatedTOBuilders;
858     }
859
860     /**
861      * Wraps code which handle case when union subtype is also of the type
862      * <code>UnionType</code>.
863      *
864      * In this case the new generated TO is created for union subtype (recursive
865      * call of method
866      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, TypeDefinition, String)
867      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
868      * <code>parentUnionGenTOBuilder</code> is created property which type is
869      * equal to new generated TO.
870      *
871      * @param parentUnionGenTOBuilder
872      *            generated TO builder to which is the property with the child
873      *            union subtype added
874      * @param basePackageName
875      *            string with the name of the module package
876      * @param unionSubtype
877      *            type definition which represents union subtype
878      * @return list of generated TO builders. The number of the builders can be
879      *         bigger one due to recursive call of
880      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
881      */
882     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
883             final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
884         final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
885         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
886                 basePackageName, unionSubtype, newTOBuilderName, parentNode);
887
888         final GeneratedPropertyBuilder propertyBuilder;
889         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
890                 .parseToValidParamName(newTOBuilderName));
891         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
892         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
893         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
894
895         return subUnionGenTOBUilders;
896     }
897
898     /**
899      * Wraps code which handle case when union subtype is of the type
900      * <code>ExtendedType</code>.
901      *
902      * If TO for this type already exists it is used for the creation of the
903      * property in <code>parentUnionGenTOBuilder</code>. In other case the base
904      * type is used for the property creation.
905      *
906      * @param parentUnionGenTOBuilder
907      *            generated TO builder in which new property is created
908      * @param unionSubtype
909      *            type definition of the <code>ExtendedType</code> type which
910      *            represents union subtype
911      * @param unionTypeName
912      *            string with the name for <code>unionSubtype</code>
913      * @param regularExpressions
914      *            list of strings with the regular expressions
915      */
916     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
917             final ExtendedType unionSubtype, final List<String> regularExpressions,
918             final SchemaNode parentNode) {
919         final String unionTypeName = unionSubtype.getQName().getLocalName();
920         final Type genTO = findGenTO(unionTypeName, unionSubtype);
921         if (genTO != null) {
922             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
923         } else {
924             final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
925             if (unionTypeName.equals(baseType.getQName().getLocalName())) {
926                 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
927                         parentNode);
928                 if (javaType != null) {
929                     updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
930                 }
931             }
932             if (baseType instanceof StringType) {
933                 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
934             }
935         }
936     }
937
938     /**
939      * Searches for generated TO for <code>searchedTypeDef</code> type
940      * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
941      *
942      * @param searchedTypeName
943      *            string with name of <code>searchedTypeDef</code>
944      * @return generated TO for <code>searchedTypeDef</code> or
945      *         <code>null</code> it it doesn't exist
946      */
947     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
948         final Module typeModule = findParentModule(schemaContext, parentNode);
949         if (typeModule != null && typeModule.getName() != null) {
950             final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
951             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
952             if (genTOs != null) {
953                 return genTOs.get(searchedTypeName);
954             }
955         }
956         return null;
957     }
958
959     /**
960      * Stores generated TO created from <code>genTOBuilder</code> for
961      * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
962      * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
963      *
964      * @param newTypeDef
965      *            type definition for which is <code>genTOBuilder</code> created
966      * @param genTOBuilder
967      *            generated TO builder which is converted to generated TO and
968      *            stored
969      */
970     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
971         if (!(newTypeDef instanceof UnionType)) {
972
973             final Module parentModule = findParentModule(schemaContext, parentNode);
974             if (parentModule != null && parentModule.getName() != null) {
975                 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
976                 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
977                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
978             }
979         }
980     }
981
982     /**
983      * Adds a new property with the name <code>propertyName</code> and with type
984      * <code>type</code> to <code>unonGenTransObject</code>.
985      *
986      * @param unionGenTransObject
987      *            generated TO to which should be property added
988      * @param type
989      *            JAVA <code>type</code> of the property which should be added
990      *            to <code>unionGentransObject</code>
991      * @param propertyName
992      *            string with name of property which should be added to
993      *            <code>unionGentransObject</code>
994      */
995     private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
996             final String propertyName) {
997         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
998             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
999                     .addProperty(parseToValidParamName(propertyName));
1000             propBuilder.setReturnType(type);
1001
1002             unionGenTransObject.addEqualsIdentity(propBuilder);
1003             unionGenTransObject.addHashIdentity(propBuilder);
1004             unionGenTransObject.addToStringProperty(propBuilder);
1005         }
1006     }
1007
1008     /**
1009      * Converts <code>typedef</code> to the generated TO builder.
1010      *
1011      * @param basePackageName
1012      *            string with name of package to which the module belongs
1013      * @param typedef
1014      *            type definition from which is the generated TO builder created
1015      * @return generated TO builder which contains data from
1016      *         <code>typedef</code> and <code>basePackageName</code>
1017      */
1018     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
1019
1020         final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
1021         final String typeDefTOName = typedef.getQName().getLocalName();
1022
1023         if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
1024             final String genTOName = BindingMapping.getClassName(typeDefTOName);
1025             final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1026             newType.addComment(typedef.getDescription());
1027             return newType;
1028         }
1029         return null;
1030     }
1031
1032     /**
1033      * Converts <code>typeDef</code> which should be of the type
1034      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1035      *
1036      * All the bits of the typeDef are added to returning generated TO as
1037      * properties.
1038      *
1039      * @param basePackageName
1040      *            string with name of package to which the module belongs
1041      * @param typeDef
1042      *            type definition from which is the generated TO builder created
1043      * @param typeDefName
1044      *            string with the name for generated TO builder
1045      * @return generated TO builder which represents <code>typeDef</code>
1046      * @throws IllegalArgumentException
1047      *             <ul>
1048      *             <li>if <code>typeDef</code> equals null</li>
1049      *             <li>if <code>basePackageName</code> equals null</li>
1050      *             </ul>
1051      */
1052     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1053             final TypeDefinition<?> typeDef, final String typeDefName) {
1054
1055         Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1056         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1057
1058         if (typeDef instanceof BitsTypeDefinition) {
1059             BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1060
1061             final String typeName = BindingMapping.getClassName(typeDefName);
1062             final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1063
1064             final List<Bit> bitList = bitsTypeDefinition.getBits();
1065             GeneratedPropertyBuilder genPropertyBuilder;
1066             for (final Bit bit : bitList) {
1067                 String name = bit.getName();
1068                 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
1069                 genPropertyBuilder.setReadOnly(true);
1070                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1071
1072                 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1073                 genTOBuilder.addHashIdentity(genPropertyBuilder);
1074                 genTOBuilder.addToStringProperty(genPropertyBuilder);
1075             }
1076
1077             return genTOBuilder;
1078         }
1079         return null;
1080     }
1081
1082     /**
1083      * Converts the pattern constraints from <code>typedef</code> to the list of
1084      * the strings which represents these constraints.
1085      *
1086      * @param typedef
1087      *            extended type in which are the pattern constraints sought
1088      * @return list of strings which represents the constraint patterns
1089      * @throws IllegalArgumentException
1090      *             if <code>typedef</code> equals null
1091      *
1092      */
1093     private List<String> resolveRegExpressionsFromTypedef(final ExtendedType typedef) {
1094         final List<String> regExps = new ArrayList<String>();
1095         Preconditions.checkArgument(typedef != null, "typedef can't be null");
1096         final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1097         if (strTypeDef instanceof StringType) {
1098             final List<PatternConstraint> patternConstraints = typedef.getPatternConstraints();
1099             if (!patternConstraints.isEmpty()) {
1100                 String regEx;
1101                 String modifiedRegEx;
1102                 for (PatternConstraint patternConstraint : patternConstraints) {
1103                     regEx = patternConstraint.getRegularExpression();
1104                     modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1105                     regExps.add(modifiedRegEx);
1106                 }
1107             }
1108         }
1109         return regExps;
1110     }
1111
1112     /**
1113      *
1114      * Adds to the <code>genTOBuilder</code> the constant which contains regular
1115      * expressions from the <code>regularExpressions</code>
1116      *
1117      * @param genTOBuilder
1118      *            generated TO builder to which are
1119      *            <code>regular expressions</code> added
1120      * @param regularExpressions
1121      *            list of string which represent regular expressions
1122      * @throws IllegalArgumentException
1123      *             <ul>
1124      *             <li>if <code>genTOBuilder</code> equals null</li>
1125      *             <li>if <code>regularExpressions</code> equals null</li>
1126      *             </ul>
1127      */
1128     private void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1129         if (genTOBuilder == null) {
1130             throw new IllegalArgumentException("Generated transfer object builder can't be null");
1131         }
1132         if (regularExpressions == null) {
1133             throw new IllegalArgumentException("List of regular expressions can't be null");
1134         }
1135         if (!regularExpressions.isEmpty()) {
1136             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1137                     regularExpressions);
1138         }
1139     }
1140
1141     /**
1142      * Creates generated TO with data about inner extended type
1143      * <code>innerExtendedType</code>, about the package name
1144      * <code>typedefName</code> and about the generated TO name
1145      * <code>typedefName</code>.
1146      *
1147      * It is supposed that <code>innerExtendedType</code> is already present in
1148      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1149      * be possible set it as extended type for the returning generated TO.
1150      *
1151      * @param innerExtendedType
1152      *            extended type which is part of some other extended type
1153      * @param basePackageName
1154      *            string with the package name of the module
1155      * @param typedefName
1156      *            string with the name for the generated TO
1157      * @return generated TO which extends generated TO for
1158      *         <code>innerExtendedType</code>
1159      * @throws IllegalArgumentException
1160      *             <ul>
1161      *             <li>if <code>extendedType</code> equals null</li>
1162      *             <li>if <code>basePackageName</code> equals null</li>
1163      *             <li>if <code>typedefName</code> equals null</li>
1164      *             </ul>
1165      */
1166     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1167             final ExtendedType innerExtendedType, final String basePackageName) {
1168         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1169         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1170
1171         final String typedefName = typedef.getQName().getLocalName();
1172         final String classTypedefName = BindingMapping.getClassName(typedefName);
1173         final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1174         final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1175         genTOBuilder.setTypedef(true);
1176         Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1177         genTOBuilder.setRestrictions(r);
1178
1179         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1180             genTOBuilder.setIsUnion(true);
1181         }
1182
1183         Map<Date, Map<String, Type>> modulesByDate = null;
1184         Map<String, Type> typeMap = null;
1185         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1186         if (parentModule != null) {
1187             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1188             typeMap = modulesByDate.get(parentModule.getRevision());
1189         }
1190
1191         if (typeMap != null) {
1192             Type type = typeMap.get(innerTypeDef);
1193             if (type instanceof GeneratedTransferObject) {
1194                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1195             }
1196         }
1197         addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1198         BindingGeneratorUtil.makeSerializable(genTOBuilder);
1199
1200         return genTOBuilder.toInstance();
1201     }
1202
1203     /**
1204      * Finds out for each type definition how many immersion (depth) is
1205      * necessary to get to the base type. Every type definition is inserted to
1206      * the map which key is depth and value is list of type definitions with
1207      * equal depth. In next step are lists from this map concatenated to one
1208      * list in ascending order according to their depth. All type definitions
1209      * are in the list behind all type definitions on which depends.
1210      *
1211      * @param unsortedTypeDefinitions
1212      *            list of type definitions which should be sorted by depth
1213      * @return list of type definitions sorted according their each other
1214      *         dependencies (type definitions which are depend on other type
1215      *         definitions are in list behind them).
1216      */
1217     private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1218             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1219         List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1220
1221         Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1222         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1223             final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1224             List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1225             if (typeDefinitionsConcreteDepth == null) {
1226                 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1227                 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1228             }
1229             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1230         }
1231         // keys are in ascending order
1232         Set<Integer> depths = typeDefinitionsDepths.keySet();
1233         for (Integer depth : depths) {
1234             sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1235         }
1236
1237         return sortedTypeDefinition;
1238     }
1239
1240     /**
1241      * Returns how many immersion is necessary to get from the type definition
1242      * to the base type.
1243      *
1244      * @param typeDefinition
1245      *            type definition for which is depth sought.
1246      * @return number of immersions which are necessary to get from the type
1247      *         definition to the base type
1248      */
1249     private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1250         if (typeDefinition == null) {
1251             return 1;
1252         }
1253         int depth = 1;
1254         TypeDefinition<?> baseType = typeDefinition.getBaseType();
1255
1256         if (baseType instanceof ExtendedType) {
1257             depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1258         } else if (baseType instanceof UnionType) {
1259             List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1260             int maxChildDepth = 0;
1261             int childDepth = 1;
1262             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1263                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1264                 if (childDepth > maxChildDepth) {
1265                     maxChildDepth = childDepth;
1266                 }
1267             }
1268             return maxChildDepth;
1269         }
1270         return depth;
1271     }
1272
1273     /**
1274      * Returns string which contains the same value as <code>name</code> but
1275      * integer suffix is incremented by one. If <code>name</code> contains no
1276      * number suffix then number 1 is added.
1277      *
1278      * @param name
1279      *            string with name of augmented node
1280      * @return string with the number suffix incremented by one (or 1 is added)
1281      */
1282     private String provideAvailableNameForGenTOBuilder(final String name) {
1283         Matcher mtch = NUMBERS_PATTERN.matcher(name);
1284         if (mtch.find()) {
1285             final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1286             return name.substring(0, mtch.start()) + newSuffix;
1287         } else {
1288             return name + 1;
1289         }
1290     }
1291
1292     public void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1293         if (units != null && !units.isEmpty()) {
1294             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1295             GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1296             prop.setReturnType(Types.STRING);
1297             to.addToStringProperty(prop);
1298         }
1299     }
1300
1301     @Override
1302     public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1303         return getTypeDefaultConstruction(node, node.getDefault());
1304     }
1305
1306     public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1307         TypeDefinition<?> type = node.getType();
1308         QName typeQName = type.getQName();
1309         TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1310         Preconditions.checkNotNull(type, "Cannot provide default construction for null type of " + node);
1311         Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of "
1312                 + node);
1313
1314         StringBuilder sb = new StringBuilder();
1315         String result = null;
1316         if (base instanceof BinaryTypeDefinition) {
1317             result = binaryToDef(defaultValue);
1318         } else if (base instanceof BitsTypeDefinition) {
1319             String parentName;
1320             String className;
1321             Module parent = getParentModule(node);
1322             Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1323             path.next();
1324             if (!(path.hasNext())) {
1325                 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1326                 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1327                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1328             } else {
1329                 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1330                 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1331                 parentName = BindingMapping.getClassName(((SchemaNode) parent).getQName());
1332                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1333             }
1334             result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type instanceof ExtendedType);
1335         } else if (base instanceof BooleanTypeDefinition) {
1336             result = typeToDef(Boolean.class, defaultValue);
1337         } else if (base instanceof DecimalTypeDefinition) {
1338             result = typeToDef(BigDecimal.class, defaultValue);
1339         } else if (base instanceof EmptyTypeDefinition) {
1340             result = typeToDef(Boolean.class, defaultValue);
1341         } else if (base instanceof EnumTypeDefinition) {
1342             char[] defValArray = defaultValue.toCharArray();
1343             char first = Character.toUpperCase(defaultValue.charAt(0));
1344             defValArray[0] = first;
1345             String newDefVal = new String(defValArray);
1346             String className;
1347             if (type instanceof ExtendedType) {
1348                 Module m = getParentModule(type);
1349                 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1350                 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1351                 className = packageName + "." + BindingMapping.getClassName(typeQName);
1352             } else {
1353                 Module parentModule = getParentModule(node);
1354                 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1355                 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
1356                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1357             }
1358             result = className + "." + newDefVal;
1359         } else if (base instanceof IdentityrefTypeDefinition) {
1360             throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1361         } else if (base instanceof InstanceIdentifierTypeDefinition) {
1362             throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1363         } else if (base instanceof Int8) {
1364             result = typeToDef(Byte.class, defaultValue);
1365         } else if (base instanceof Int16) {
1366             result = typeToDef(Short.class, defaultValue);
1367         } else if (base instanceof Int32) {
1368             result = typeToDef(Integer.class, defaultValue);
1369         } else if (base instanceof Int64) {
1370             result = typeToDef(Long.class, defaultValue);
1371         } else if (base instanceof LeafrefTypeDefinition) {
1372             result = leafrefToDef(node, (LeafrefTypeDefinition) base);
1373         } else if (base instanceof StringTypeDefinition) {
1374             result = "\"" + defaultValue + "\"";
1375         } else if (base instanceof Uint8) {
1376             result = typeToDef(Short.class, defaultValue);
1377         } else if (base instanceof Uint16) {
1378             result = typeToDef(Integer.class, defaultValue);
1379         } else if (base instanceof Uint32) {
1380             result = typeToDef(Long.class, defaultValue);
1381         } else if (base instanceof Uint64) {
1382             result = typeToDef(BigInteger.class, defaultValue);
1383         } else if (base instanceof UnionTypeDefinition) {
1384             result = unionToDef(node);
1385         } else {
1386             result = "";
1387         }
1388         sb.append(result);
1389
1390         if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
1391                 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
1392             Module m = getParentModule(type);
1393             String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
1394             String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
1395             String className = packageName + "." + BindingMapping.getClassName(typeQName);
1396             sb.insert(0, "new " + className + "(");
1397             sb.insert(sb.length(), ")");
1398         }
1399
1400         return sb.toString();
1401     }
1402
1403     private String typeToDef(final Class<?> clazz, final String defaultValue) {
1404         return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1405     }
1406
1407     private String binaryToDef(final String defaultValue) {
1408         StringBuilder sb = new StringBuilder();
1409         BaseEncoding en = BaseEncoding.base64();
1410         byte[] encoded = en.decode(defaultValue);
1411         sb.append("new byte[] {");
1412         for (int i = 0; i < encoded.length; i++) {
1413             sb.append(encoded[i]);
1414             if (i != encoded.length - 1) {
1415                 sb.append(", ");
1416             }
1417         }
1418         sb.append("}");
1419         return sb.toString();
1420     }
1421
1422     private String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1423         List<Bit> bits = new ArrayList<>(type.getBits());
1424         Collections.sort(bits, new Comparator<Bit>() {
1425             @Override
1426             public int compare(final Bit o1, final Bit o2) {
1427                 return o1.getName().compareTo(o2.getName());
1428             }
1429         });
1430         StringBuilder sb = new StringBuilder();
1431         sb.append(isExt ? "" : "new " + className + "(");
1432         for (int i = 0; i < bits.size(); i++) {
1433             if (bits.get(i).getName().equals(defaultValue)) {
1434                 sb.append(true);
1435             } else {
1436                 sb.append(false);
1437             }
1438             if (i != bits.size() - 1) {
1439                 sb.append(", ");
1440             }
1441         }
1442         sb.append(isExt ? "" : ")");
1443         return sb.toString();
1444     }
1445
1446     private Module getParentModule(final SchemaNode node) {
1447         QName qname = node.getPath().getPathFromRoot().iterator().next();
1448         URI namespace = qname.getNamespace();
1449         Date revision = qname.getRevision();
1450         return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1451     }
1452
1453     private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType) {
1454         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1455         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1456                 "The Path Statement for Leafref Type Definition cannot be NULL!");
1457
1458         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1459         final String strXPath = xpath.toString();
1460
1461         if (strXPath != null) {
1462             if (strXPath.contains("[")) {
1463                 return "new java.lang.Object()";
1464             } else {
1465                 final Module module = findParentModule(schemaContext, parentNode);
1466                 if (module != null) {
1467                     final SchemaNode dataNode;
1468                     if (xpath.isAbsolute()) {
1469                         dataNode = findDataSchemaNode(schemaContext, module, xpath);
1470                     } else {
1471                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1472                     }
1473                     String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, parentNode.getDefault());
1474                     return result;
1475                 }
1476             }
1477         }
1478
1479         return null;
1480     }
1481
1482     private String unionToDef(final LeafSchemaNode node) {
1483         String parentName;
1484         String className;
1485
1486         if (node.getType() instanceof ExtendedType) {
1487             ExtendedType type = (ExtendedType) node.getType();
1488             QName typeQName = type.getQName();
1489             Module module = null;
1490             Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1491             if (modules.size() > 1) {
1492                 for (Module m : modules) {
1493                     if (m.getRevision().equals(typeQName.getRevision())) {
1494                         module = m;
1495                         break;
1496                     }
1497                 }
1498                 if (module == null) {
1499                     List<Module> modulesList = new ArrayList<>(modules);
1500                     Collections.sort(modulesList, new Comparator<Module>() {
1501                         @Override
1502                         public int compare(final Module o1, final Module o2) {
1503                             return o1.getRevision().compareTo(o2.getRevision());
1504                         }
1505                     });
1506                     module = modulesList.get(0);
1507                 }
1508             } else {
1509                 module = modules.iterator().next();
1510             }
1511
1512             String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
1513             className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1514         } else {
1515             Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1516             QName first = path.next();
1517             if (!(path.hasNext())) {
1518                 URI namespace = first.getNamespace();
1519                 Date revision = first.getRevision();
1520                 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1521                 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1522                 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
1523                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1524             } else {
1525                 URI namespace = first.getNamespace();
1526                 Date revision = first.getRevision();
1527                 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1528                 String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
1529                 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
1530                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1531             }
1532         }
1533         return union(className, node.getDefault(), node);
1534     }
1535
1536     private String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1537         StringBuilder sb = new StringBuilder();
1538         sb.append("new " + className + "(");
1539         sb.append("\"");
1540         sb.append(defaultValue);
1541         sb.append("\"");
1542         sb.append(".toCharArray()");
1543         sb.append(")");
1544         return sb.toString();
1545     }
1546
1547     @Override
1548     public String getConstructorPropertyName(final SchemaNode node) {
1549         if (node instanceof TypeDefinition<?>) {
1550             return "value";
1551         } else {
1552             return "";
1553         }
1554     }
1555
1556     @Override
1557     public String getParamNameFromType(final TypeDefinition<?> type) {
1558         return BindingGeneratorUtil.parseToValidParamName(type.getQName().getLocalName());
1559     }
1560
1561 }