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