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