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