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