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