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