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