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