9078ae72e132cb6398e1e819437fa29f0c6a3cb7
[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.mdsal.binding.spec.naming.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         return Types.classType(Types.wildcardTypeFor(identifier));
398     }
399
400     /**
401      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
402      *
403      * @param typeDefinition
404      *            type definition which should be converted to JAVA
405      *            <code>Type</code>
406      * @return JAVA <code>Type</code> which represents
407      *         <code>typeDefinition</code>
408      * @throws IllegalArgumentException
409      *             <ul>
410      *             <li>if <code>typeDefinition</code> equal null</li>
411      *             <li>if Q name of <code>typeDefinition</code></li>
412      *             <li>if name of <code>typeDefinition</code></li>
413      *             </ul>
414      */
415     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
416         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
417         if (typeDefinition.getQName() == null) {
418             throw new IllegalArgumentException(
419                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
420         }
421         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
422                 "Type Definitions Local Name cannot be NULL!");
423
424         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
425         if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
426             /*
427              * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
428              * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
429              * this:
430              *
431              *     identity iden;
432              *
433              *     container foo {
434              *         leaf foo {
435              *             type identityref {
436              *                 base iden;
437              *             }
438              *         }
439              *     }
440              *
441              * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
442              * dicey when we throw in:
443              *
444              *     typedef bar-ref {
445              *         type identityref {
446              *             base iden;
447              *         }
448              *     }
449              *
450              *     container bar {
451              *         leaf bar {
452              *             type bar-ref;
453              *         }
454              *     }
455              *
456              * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
457              * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
458              * is formed.
459              *
460              * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
461              * an encapsulation for identityref typedefs.
462              *
463              * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
464              * option, as it would look as though it is the product of a different construct:
465              *
466              *     identity bar-ref {
467              *         base iden;
468              *     }
469              *
470              * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
471              * sub-identities of iden.
472              *
473              * The story behind leafrefs is probably similar, but that needs to be ascertained.
474              */
475             return null;
476         }
477
478         final Module module = findParentModule(schemaContext, parentNode);
479         if (module != null) {
480             final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
481                 module.getName());
482             final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
483             if (genTOs != null) {
484                 return genTOs.get(typeDefinition.getQName().getLocalName());
485             }
486         }
487         return null;
488     }
489
490     /**
491      * Gets base type definition for <code>extendTypeDef</code>. The method is
492      * recursively called until non <code>ExtendedType</code> type is found.
493      *
494      * @param extendTypeDef
495      *            type definition for which is the base type definition sought
496      * @return type definition which is base type for <code>extendTypeDef</code>
497      * @throws IllegalArgumentException
498      *             if <code>extendTypeDef</code> equal null
499      */
500     private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
501         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
502
503         TypeDefinition<?> ret = extendTypeDef;
504         while (ret.getBaseType() != null) {
505             ret = ret.getBaseType();
506         }
507
508         return ret;
509     }
510
511     /**
512      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
513      *
514      * The path of <code>leafrefType</code> is followed to find referenced node
515      * and its <code>Type</code> is returned.
516      *
517      * @param leafrefType
518      *            leafref type definition for which is the type sought
519      * @return JAVA <code>Type</code> of data schema node which is referenced in
520      *         <code>leafrefType</code>
521      * @throws IllegalArgumentException
522      *             <ul>
523      *             <li>if <code>leafrefType</code> equal null</li>
524      *             <li>if path statement of <code>leafrefType</code> equal null</li>
525      *             </ul>
526      *
527      */
528     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
529         Type returnType = null;
530         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
531
532         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
533                 "The Path Statement for Leafref Type Definition cannot be NULL!");
534
535         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
536         final String strXPath = xpath.toString();
537
538         if (strXPath != null) {
539             if (strXPath.indexOf('[') == -1) {
540                 final Module module = findParentModule(schemaContext, parentNode);
541                 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
542
543                 final SchemaNode dataNode;
544                 if (xpath.isAbsolute()) {
545                     dataNode = findDataSchemaNode(schemaContext, module, xpath);
546                 } else {
547                     dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
548                 }
549                 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
550                         strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
551
552                 if (leafContainsEnumDefinition(dataNode)) {
553                     returnType = referencedTypes.get(dataNode.getPath());
554                 } else if (leafListContainsEnumDefinition(dataNode)) {
555                     returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
556                 } else {
557                     returnType = resolveTypeFromDataSchemaNode(dataNode);
558                 }
559             } else {
560                 returnType = Types.objectType();
561             }
562         }
563         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
564                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
565         return returnType;
566     }
567
568     /**
569      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
570      * so then checks if it is of type <code>EnumTypeDefinition</code>.
571      *
572      * @param dataNode
573      *            data schema node for which is checked if it is leaf and if it
574      *            is of enum type
575      * @return boolean value
576      *         <ul>
577      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
578      *         <li>false - other cases</li>
579      *         </ul>
580      */
581     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
582         if (dataNode instanceof LeafSchemaNode) {
583             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
584             if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
585                 return true;
586             }
587         }
588         return false;
589     }
590
591     /**
592      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
593      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
594      *
595      * @param dataNode
596      *            data schema node for which is checked if it is leaflist and if
597      *            it is of enum type
598      * @return boolean value
599      *         <ul>
600      *         <li>true - if <code>dataNode</code> is leaflist of type
601      *         enumeration</li>
602      *         <li>false - other cases</li>
603      *         </ul>
604      */
605     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
606         if (dataNode instanceof LeafListSchemaNode) {
607             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
608             if (leafList.getType() instanceof EnumTypeDefinition) {
609                 return true;
610             }
611         }
612         return false;
613     }
614
615     /**
616      * Converts <code>enumTypeDef</code> to
617      * {@link Enumeration
618      * enumeration}.
619      *
620      * @param enumTypeDef
621      *            enumeration type definition which is converted to enumeration
622      * @param enumName
623      *            string with name which is used as the enumeration name
624      * @return enumeration type which is built with data (name, enum values)
625      *         from <code>enumTypeDef</code>
626      * @throws IllegalArgumentException
627      *             <ul>
628      *             <li>if <code>enumTypeDef</code> equals null</li>
629      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
630      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
631      *             <li>if name of <code>enumTypeDef</code> equal null</li>
632      *             </ul>
633      */
634     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
635             final SchemaNode parentNode) {
636         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
637         Preconditions.checkArgument(enumTypeDef.getValues() != null,
638                 "EnumTypeDefinition MUST contain at least ONE value definition!");
639         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
640         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
641                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
642
643         final Module module = findParentModule(schemaContext, parentNode);
644         final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
645             BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
646         addEnumDescription(enumBuilder, enumTypeDef);
647         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
648         enumBuilder.setModuleName(module.getName());
649         enumBuilder.setSchemaPath(enumTypeDef.getPath());
650         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
651         return enumBuilder.toInstance(null);
652     }
653
654     /**
655      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
656      * taken from <code>enumTypeDef</code>.
657      *
658      * @param enumTypeDef
659      *            enumeration type definition is source of enumeration data for
660      *            <code>typeBuilder</code>
661      * @param enumName
662      *            string with the name of enumeration
663      * @param typeBuilder
664      *            generated type builder to which is enumeration added
665      * @return enumeration type which contains enumeration data form
666      *         <code>enumTypeDef</code>
667      * @throws IllegalArgumentException
668      *             <ul>
669      *             <li>if <code>enumTypeDef</code> equals null</li>
670      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
671      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
672      *             <li>if name of <code>enumTypeDef</code> equal null</li>
673      *             <li>if name of <code>typeBuilder</code> equal null</li>
674      *             </ul>
675      *
676      */
677     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
678             final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
679         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
680         Preconditions.checkArgument(enumTypeDef.getValues() != null,
681                 "EnumTypeDefinition MUST contain at least ONE value definition!");
682         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
683         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
684                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
685         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
686
687         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
688
689         addEnumDescription(enumBuilder, enumTypeDef);
690         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
691         return enumBuilder.toInstance(enumBuilder);
692     }
693
694     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
695
696     public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
697
698     public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
699
700     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
701
702     /**
703      * Converts the pattern constraints to the list of the strings which represents these constraints.
704      *
705      * @param patternConstraints list of pattern constraints
706      * @return list of strings which represents the constraint patterns
707      */
708     public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
709
710     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
711
712     /**
713      * Converts the pattern constraints from <code>typedef</code> to the list of
714      * the strings which represents these constraints.
715      *
716      * @param typedef
717      *            extended type in which are the pattern constraints sought
718      * @return list of strings which represents the constraint patterns
719      * @throws IllegalArgumentException
720      *             if <code>typedef</code> equals null
721      *
722      */
723     private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
724         if (!(typedef instanceof StringTypeDefinition)) {
725             return ImmutableMap.of();
726         }
727
728         // TODO: run diff against base ?
729         return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
730     }
731
732     /**
733      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
734      *
735      * @param dataNode
736      *            contains information about YANG type
737      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
738      */
739     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
740         Type returnType = null;
741         if (dataNode != null) {
742             if (dataNode instanceof LeafSchemaNode) {
743                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
744                 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
745                 returnType = javaTypeForSchemaDefinitionType(type, leaf);
746             } else if (dataNode instanceof LeafListSchemaNode) {
747                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
748                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
749             }
750         }
751         return returnType;
752     }
753
754     /**
755      * Passes through all modules and through all its type definitions and
756      * convert it to generated types.
757      *
758      * The modules are firstly sorted by mutual dependencies. The modules are
759      * sequentially passed. All type definitions of a module are at the
760      * beginning sorted so that type definition with less amount of references
761      * to other type definition are processed first.<br />
762      * For each module is created mapping record in the map
763      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
764      * which map current module name to the map which maps type names to
765      * returned types (generated types).
766      *
767      */
768     private void resolveTypeDefsFromContext() {
769         final Set<Module> modules = schemaContext.getModules();
770         Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
771         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
772
773         for (Module module : modulesSortedByDependency) {
774             Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
775                 module.getName(), key -> new HashMap<>());
776             dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
777             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
778         }
779
780         for (Module module : modulesSortedByDependency) {
781             if (module != null) {
782                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
783                 if (basePackageName != null) {
784                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
785                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
786                         typedefToGeneratedType(basePackageName, module, typedef);
787                     }
788                 }
789             }
790         }
791     }
792
793     /**
794      *
795      * @param basePackageName
796      *            string with name of package to which the module belongs
797      * @param module
798      *            string with the name of the module for to which the
799      *            <code>typedef</code> belongs
800      * @param typedef
801      *            type definition of the node for which should be created JAVA <code>Type</code> (usually generated TO)
802      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
803      *         <code>null</code> value if <code>basePackageName</code> or
804      *         <code>modulName</code> or <code>typedef</code> or Q name of
805      *         <code>typedef</code> equals <code>null</code>
806      */
807     private Type typedefToGeneratedType(final String basePackageName, final Module module,
808             final TypeDefinition<?> typedef) {
809         final TypeDefinition<?> baseTypedef = typedef.getBaseType();
810
811         // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
812         if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
813             return null;
814         }
815
816         final String typedefName = typedef.getQName().getLocalName();
817
818         final Type returnType;
819         if (baseTypedef.getBaseType() != null) {
820             returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
821                 module.getName());
822         } else if (baseTypedef instanceof UnionTypeDefinition) {
823             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
824                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
825                 (UnionTypeDefinition) baseTypedef, typedef);
826             genTOBuilder.setTypedef(true);
827             genTOBuilder.setIsUnion(true);
828             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
829             makeSerializable(genTOBuilder);
830             returnType = genTOBuilder.build();
831
832             // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
833             // so we are placing the builder alongside the union.
834             final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
835                 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
836             unionBuilder.setIsUnionBuilder(true);
837             final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
838             method.setReturnType(returnType);
839             method.addParameter(Types.STRING, "defaultValue");
840             method.setAccessModifier(AccessModifier.PUBLIC);
841             method.setStatic(true);
842             Set<Type> types = additionalTypes.get(module);
843             if (types == null) {
844                 types = Sets.<Type> newHashSet(unionBuilder.build());
845                 additionalTypes.put(module, types);
846             } else {
847                 types.add(unionBuilder.build());
848             }
849         } else if (baseTypedef instanceof EnumTypeDefinition) {
850             // enums are automatically Serializable
851             final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
852             // TODO units for typedef enum
853             returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
854         } else if (baseTypedef instanceof BitsTypeDefinition) {
855             final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
856                 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
857                 (BitsTypeDefinition) baseTypedef, module.getName());
858             genTOBuilder.setTypedef(true);
859             addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
860             makeSerializable(genTOBuilder);
861             returnType = genTOBuilder.build();
862         } else {
863             final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
864             returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
865         }
866         if (returnType != null) {
867             final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
868                     genTypeDefsContextMap.get(module.getName());
869             final Optional<Revision> moduleRevision = module.getRevision();
870             Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
871             if (typeMap != null) {
872                 if (typeMap.isEmpty()) {
873                     typeMap = new HashMap<>(4);
874                     modulesByDate.put(moduleRevision, typeMap);
875                 }
876                 typeMap.put(typedefName, returnType);
877             }
878             return returnType;
879         }
880         return null;
881     }
882
883     /**
884      * Wraps base YANG type to generated TO.
885      *
886      * @param basePackageName
887      *            string with name of package to which the module belongs
888      * @param typedef
889      *            type definition which is converted to the TO
890      * @param javaType
891      *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
892      * @return generated transfer object which represent<code>javaType</code>
893      */
894     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
895             final Type javaType, final String moduleName) {
896         Preconditions.checkNotNull(javaType, "javaType cannot be null");
897         final String propertyName = "value";
898
899         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
900         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
901         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
902         genPropBuilder.setReturnType(javaType);
903         genTOBuilder.addEqualsIdentity(genPropBuilder);
904         genTOBuilder.addHashIdentity(genPropBuilder);
905         genTOBuilder.addToStringProperty(genPropBuilder);
906         if (typedef.getStatus() == Status.DEPRECATED) {
907             genTOBuilder.addAnnotation("java.lang", "Deprecated");
908         }
909         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
910             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
911         }
912         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
913         genTOBuilder.setTypedef(true);
914         makeSerializable(genTOBuilder);
915         return genTOBuilder.build();
916     }
917
918     /**
919      * Converts output list of generated TO builders to one TO builder (first
920      * from list) which contains the remaining builders as its enclosing TO.
921      *
922      * @param typeName new type identifier
923      * @param typedef type definition which should be of type {@link UnionTypeDefinition}
924      * @return generated TO builder with the list of enclosed generated TO builders
925      */
926     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
927             final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
928         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
929             parentNode);
930         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
931
932         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
933         builders.forEach(resultTOBuilder::addEnclosingTransferObject);
934         return resultTOBuilder;
935     }
936
937     /**
938      * Converts <code>typedef</code> to generated TO with
939      * <code>typeDefName</code>. Every union type from <code>typedef</code> is
940      * added to generated TO builder as property.
941      *
942      * @param typeName new type identifier
943      * @param typedef
944      *            type definition which should be of type
945      *            <code>UnionTypeDefinition</code>
946      * @return generated TO builder which represents <code>typedef</code>
947      * @throws NullPointerException
948      *             <ul>
949      *             <li>if <code>basePackageName</code> is null</li>
950      *             <li>if <code>typedef</code> is null</li>
951      *             <li>if Qname of <code>typedef</code> is null</li>
952      *             </ul>
953      */
954     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
955             final UnionTypeDefinition typedef, final SchemaNode parentNode) {
956         Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
957         Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
958
959         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
960         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
961         final Module module = findParentModule(schemaContext, parentNode);
962
963         final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
964         unionGenTOBuilder.setSchemaPath(typedef.getPath());
965         unionGenTOBuilder.setModuleName(module.getName());
966         addCodegenInformation(unionGenTOBuilder, typedef);
967
968         generatedTOBuilders.add(unionGenTOBuilder);
969         unionGenTOBuilder.setIsUnion(true);
970
971         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
972         // also negation information and hence guarantees uniqueness.
973         final Map<String, String> expressions = new HashMap<>();
974         for (TypeDefinition<?> unionType : unionTypes) {
975             final String unionTypeName = unionType.getQName().getLocalName();
976
977             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
978             // do not follow type encapsulation -- we use the general case for that.
979             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
980                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
981             } else if (unionType instanceof UnionTypeDefinition) {
982                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
983                     (UnionTypeDefinition) unionType, parentNode));
984             } else if (unionType instanceof EnumTypeDefinition) {
985                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
986                         unionTypeName, unionGenTOBuilder);
987                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
988             } else {
989                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
990                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
991             }
992         }
993         addStringRegExAsConstant(unionGenTOBuilder, expressions);
994
995         storeGenTO(typedef, unionGenTOBuilder, parentNode);
996
997         return generatedTOBuilders;
998     }
999
1000     /**
1001      * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
1002      *
1003      * In this case the new generated TO is created for union subtype (recursive call of method
1004      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
1005      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
1006      * created property which type is 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 SchemaNode parentNode) {
1021         final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
1022             provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
1023         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1024             newTOBuilderName, unionSubtype, parentNode);
1025
1026         final GeneratedPropertyBuilder propertyBuilder;
1027         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
1028             newTOBuilderName.simpleName()));
1029         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
1030         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1031         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1032
1033         return subUnionGenTOBUilders;
1034     }
1035
1036     /**
1037      * Wraps code which handle case when union subtype is of the type
1038      * <code>ExtendedType</code>.
1039      *
1040      * If TO for this type already exists it is used for the creation of the
1041      * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1042      * type is used for the property creation.
1043      *
1044      * @param parentUnionGenTOBuilder
1045      *            generated TO builder in which new property is created
1046      * @param unionSubtype
1047      *            type definition of the <code>ExtendedType</code> type which
1048      *            represents union subtype
1049      * @param expressions
1050      *            list of strings with the regular expressions
1051      * @param parentNode
1052      *            parent Schema Node for Extended Subtype
1053      *
1054      */
1055     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1056             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1057         final String unionTypeName = unionSubtype.getQName().getLocalName();
1058         final Type genTO = findGenTO(unionTypeName, unionSubtype);
1059         if (genTO != null) {
1060             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1061             return;
1062         }
1063
1064         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1065         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1066             final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1067                 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1068             if (javaType != null) {
1069                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1070             }
1071         } else if (baseType instanceof LeafrefTypeDefinition) {
1072             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1073             boolean typeExist = false;
1074             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1075                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1076                 if (origType != null && javaType != null && javaType == origType) {
1077                     typeExist = true;
1078                     break;
1079                 }
1080             }
1081             if (!typeExist && javaType != null) {
1082                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1083                     javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1084             }
1085         }
1086         if (baseType instanceof StringTypeDefinition) {
1087             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1088         }
1089     }
1090
1091     /**
1092      * Searches for generated TO for <code>searchedTypeDef</code> type
1093      * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1094      *
1095      * @param searchedTypeName
1096      *            string with name of <code>searchedTypeDef</code>
1097      * @return generated TO for <code>searchedTypeDef</code> or
1098      *         <code>null</code> it it doesn't exist
1099      */
1100     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1101         final Module typeModule = findParentModule(schemaContext, parentNode);
1102         if (typeModule != null && typeModule.getName() != null) {
1103             final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1104             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1105             if (genTOs != null) {
1106                 return genTOs.get(searchedTypeName);
1107             }
1108         }
1109         return null;
1110     }
1111
1112     /**
1113      * Stores generated TO created from <code>genTOBuilder</code> for
1114      * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1115      * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1116      *
1117      * @param newTypeDef
1118      *            type definition for which is <code>genTOBuilder</code> created
1119      * @param genTOBuilder
1120      *            generated TO builder which is converted to generated TO and
1121      *            stored
1122      */
1123     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1124         if (!(newTypeDef instanceof UnionTypeDefinition)) {
1125             final Module parentModule = findParentModule(schemaContext, parentNode);
1126             if (parentModule != null && parentModule.getName() != null) {
1127                 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1128                 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1129                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1130             }
1131         }
1132     }
1133
1134     /**
1135      * Adds a new property with the name <code>propertyName</code> and with type
1136      * <code>type</code> to <code>unonGenTransObject</code>.
1137      *
1138      * @param unionGenTransObject
1139      *            generated TO to which should be property added
1140      * @param type
1141      *            JAVA <code>type</code> of the property which should be added
1142      *            to <code>unionGentransObject</code>
1143      * @param propertyName
1144      *            string with name of property which should be added to
1145      *            <code>unionGentransObject</code>
1146      */
1147     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1148         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1149             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1150                     .addProperty(BindingMapping.getPropertyName(propertyName));
1151             propBuilder.setReturnType(type);
1152
1153             unionGenTransObject.addEqualsIdentity(propBuilder);
1154             unionGenTransObject.addHashIdentity(propBuilder);
1155             unionGenTransObject.addToStringProperty(propBuilder);
1156         }
1157     }
1158
1159     /**
1160      * Converts <code>typedef</code> to the generated TO builder.
1161      *
1162      * @param basePackageName
1163      *            string with name of package to which the module belongs
1164      * @param typedef
1165      *            type definition from which is the generated TO builder created
1166      * @return generated TO builder which contains data from
1167      *         <code>typedef</code> and <code>basePackageName</code>
1168      */
1169     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1170             final TypeDefinition<?> typedef, final String moduleName) {
1171         final GeneratedTOBuilder newType = newGeneratedTOBuilder(JavaTypeName.create(
1172             BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1173             BindingMapping.getClassName(typedef.getQName().getLocalName())));
1174         newType.setSchemaPath(typedef.getPath());
1175         newType.setModuleName(moduleName);
1176         addCodegenInformation(newType, typedef);
1177         return newType;
1178     }
1179
1180     /**
1181      * Converts <code>typeDef</code> which should be of the type
1182      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1183      *
1184      * All the bits of the typeDef are added to returning generated TO as
1185      * properties.
1186      *
1187      * @param typeName new type identifier
1188      * @param typeDef
1189      *            type definition from which is the generated TO builder created
1190      * @return generated TO builder which represents <code>typeDef</code>
1191      * @throws IllegalArgumentException
1192      *             <ul>
1193      *             <li>if <code>typeDef</code> equals null</li>
1194      *             <li>if <code>basePackageName</code> equals null</li>
1195      *             </ul>
1196      */
1197     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1198             final BitsTypeDefinition typeDef, final String moduleName) {
1199         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1200         genTOBuilder.setSchemaPath(typeDef.getPath());
1201         genTOBuilder.setModuleName(moduleName);
1202         genTOBuilder.setBaseType(typeDef);
1203         addCodegenInformation(genTOBuilder, typeDef);
1204
1205         final List<Bit> bitList = typeDef.getBits();
1206         GeneratedPropertyBuilder genPropertyBuilder;
1207         for (Bit bit : bitList) {
1208             final String name = bit.getName();
1209             genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1210             genPropertyBuilder.setReadOnly(true);
1211             genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1212
1213             genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1214             genTOBuilder.addHashIdentity(genPropertyBuilder);
1215             genTOBuilder.addToStringProperty(genPropertyBuilder);
1216         }
1217
1218         return genTOBuilder;
1219     }
1220
1221     /**
1222      *
1223      * Adds to the <code>genTOBuilder</code> the constant which contains regular
1224      * expressions from the <code>regularExpressions</code>
1225      *
1226      * @param genTOBuilder
1227      *            generated TO builder to which are
1228      *            <code>regular expressions</code> added
1229      * @param expressions
1230      *            list of string which represent regular expressions
1231      */
1232     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1233             final Map<String, String> expressions) {
1234         if (!expressions.isEmpty()) {
1235             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1236                 ImmutableMap.copyOf(expressions));
1237         }
1238     }
1239
1240     /**
1241      * Creates generated TO with data about inner extended type
1242      * <code>innerExtendedType</code>, about the package name
1243      * <code>typedefName</code> and about the generated TO name
1244      * <code>typedefName</code>.
1245      *
1246      * It is supposed that <code>innerExtendedType</code> is already present in
1247      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1248      * be possible set it as extended type for the returning generated TO.
1249      *
1250      * @param typedef
1251      *            Type Definition
1252      * @param innerExtendedType
1253      *            extended type which is part of some other extended type
1254      * @param basePackageName
1255      *            string with the package name of the module
1256      * @param moduleName
1257      *            Module Name
1258      * @return generated TO which extends generated TO for
1259      *         <code>innerExtendedType</code>
1260      * @throws IllegalArgumentException
1261      *             <ul>
1262      *             <li>if <code>extendedType</code> equals null</li>
1263      *             <li>if <code>basePackageName</code> equals null</li>
1264      *             <li>if <code>typedefName</code> equals null</li>
1265      *             </ul>
1266      */
1267     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1268             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1269         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1270         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1271
1272         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1273             BindingMapping.getClassName(typedef.getQName())));
1274         genTOBuilder.setSchemaPath(typedef.getPath());
1275         genTOBuilder.setModuleName(moduleName);
1276         genTOBuilder.setTypedef(true);
1277         addCodegenInformation(genTOBuilder, typedef);
1278
1279         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1280         genTOBuilder.setRestrictions(r);
1281         addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1282
1283         if (typedef.getStatus() == Status.DEPRECATED) {
1284             genTOBuilder.addAnnotation("java.lang", "Deprecated");
1285         }
1286
1287         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1288             genTOBuilder.setIsUnion(true);
1289         }
1290
1291         Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1292         Map<String, Type> typeMap = null;
1293         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1294         if (parentModule != null) {
1295             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1296             typeMap = modulesByDate.get(parentModule.getRevision());
1297         }
1298
1299         if (typeMap != null) {
1300             final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1301             final Type type = typeMap.get(innerTypeDef);
1302             if (type instanceof GeneratedTransferObject) {
1303                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1304             }
1305         }
1306         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1307         makeSerializable(genTOBuilder);
1308
1309         return genTOBuilder.build();
1310     }
1311
1312     /**
1313      * Add {@link Serializable} to implemented interfaces of this TO. Also
1314      * compute and add serialVersionUID property.
1315      *
1316      * @param gto
1317      *            transfer object which needs to be serializable
1318      */
1319     private static void makeSerializable(final GeneratedTOBuilder gto) {
1320         gto.addImplementsType(Types.serializableType());
1321         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1322         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1323         gto.setSUID(prop);
1324     }
1325
1326     /**
1327      * Finds out for each type definition how many immersion (depth) is
1328      * necessary to get to the base type. Every type definition is inserted to
1329      * the map which key is depth and value is list of type definitions with
1330      * equal depth. In next step are lists from this map concatenated to one
1331      * list in ascending order according to their depth. All type definitions
1332      * are in the list behind all type definitions on which depends.
1333      *
1334      * @param unsortedTypeDefinitions
1335      *            list of type definitions which should be sorted by depth
1336      * @return list of type definitions sorted according their each other
1337      *         dependencies (type definitions which are depend on other type
1338      *         definitions are in list behind them).
1339      */
1340     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1341             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1342         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1343
1344         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1345         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1346             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1347             List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1348             if (typeDefinitionsConcreteDepth == null) {
1349                 typeDefinitionsConcreteDepth = new ArrayList<>();
1350                 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1351             }
1352             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1353         }
1354
1355         // SortedMap guarantees order corresponding to keys in ascending order
1356         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1357             sortedTypeDefinition.addAll(v);
1358         }
1359
1360         return sortedTypeDefinition;
1361     }
1362
1363     /**
1364      * Returns how many immersion is necessary to get from the type definition
1365      * to the base type.
1366      *
1367      * @param typeDefinition
1368      *            type definition for which is depth sought.
1369      * @return number of immersions which are necessary to get from the type
1370      *         definition to the base type
1371      */
1372     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1373         // FIXME: rewrite this in a non-recursive manner
1374         if (typeDefinition == null) {
1375             return 1;
1376         }
1377         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1378         if (baseType == null) {
1379             return 1;
1380         }
1381
1382         int depth = 1;
1383         if (baseType.getBaseType() != null) {
1384             depth = depth + getTypeDefinitionDepth(baseType);
1385         } else if (baseType instanceof UnionTypeDefinition) {
1386             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1387             int maxChildDepth = 0;
1388             int childDepth = 1;
1389             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1390                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1391                 if (childDepth > maxChildDepth) {
1392                     maxChildDepth = childDepth;
1393                 }
1394             }
1395             return maxChildDepth;
1396         }
1397         return depth;
1398     }
1399
1400     /**
1401      * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1402      * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1403      * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1404      *
1405      * @param name string with name of augmented node
1406      * @return string with the number suffix incremented by one (or 1 is added)
1407      */
1408     private static String provideAvailableNameForGenTOBuilder(final String name) {
1409         final int dollar = name.indexOf('$');
1410         if (dollar == -1) {
1411             return name + "$1";
1412         }
1413
1414         final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1415         Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1416         return name.substring(0, dollar + 1) + newSuffix;
1417     }
1418
1419     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1420         if (!Strings.isNullOrEmpty(units)) {
1421             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1422             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1423             prop.setReturnType(Types.STRING);
1424             to.addToStringProperty(prop);
1425         }
1426     }
1427
1428     @Override
1429     public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1430         return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1431     }
1432
1433     public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1434         final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1435         final QName typeQName = type.getQName();
1436         final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1437         Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1438         Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1439                 node);
1440
1441         final StringBuilder sb = new StringBuilder();
1442         String result = null;
1443         if (base instanceof BinaryTypeDefinition) {
1444             result = binaryToDef(defaultValue);
1445         } else if (base instanceof BitsTypeDefinition) {
1446             String parentName;
1447             String className;
1448             final Module parent = getParentModule(node);
1449             final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1450             path.next();
1451             if (!path.hasNext()) {
1452                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1453                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1454                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1455             } else {
1456                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1457                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1458                 parentName = BindingMapping.getClassName(parent.getName());
1459                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1460             }
1461             result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1462         } else if (base instanceof BooleanTypeDefinition) {
1463             result = typeToBooleanDef(defaultValue);
1464         } else if (base instanceof DecimalTypeDefinition) {
1465             result = typeToDef(BigDecimal.class, defaultValue);
1466         } else if (base instanceof EmptyTypeDefinition) {
1467             result = typeToBooleanDef(defaultValue);
1468         } else if (base instanceof EnumTypeDefinition) {
1469             final char[] defValArray = defaultValue.toCharArray();
1470             final char first = Character.toUpperCase(defaultValue.charAt(0));
1471             defValArray[0] = first;
1472             final String newDefVal = new String(defValArray);
1473             String className;
1474             if (type.getBaseType() != null) {
1475                 final Module m = getParentModule(type);
1476                 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1477                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1478                 className = packageName + "." + BindingMapping.getClassName(typeQName);
1479             } else {
1480                 final Module parentModule = getParentModule(node);
1481                 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1482                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1483                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1484             }
1485             result = className + "." + newDefVal;
1486         } else if (base instanceof IdentityrefTypeDefinition) {
1487             throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1488         } else if (base instanceof InstanceIdentifierTypeDefinition) {
1489             throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1490         } else if (BaseTypes.isInt8(base)) {
1491             result = typeToValueOfDef(Byte.class, defaultValue);
1492         } else if (BaseTypes.isInt16(base)) {
1493             result = typeToValueOfDef(Short.class, defaultValue);
1494         } else if (BaseTypes.isInt32(base)) {
1495             result = typeToValueOfDef(Integer.class, defaultValue);
1496         } else if (BaseTypes.isInt64(base)) {
1497             result = typeToValueOfDef(Long.class, defaultValue);
1498         } else if (base instanceof LeafrefTypeDefinition) {
1499             result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1500         } else if (base instanceof StringTypeDefinition) {
1501             result = "\"" + defaultValue + "\"";
1502         } else if (BaseTypes.isUint8(base)) {
1503             result = typeToValueOfDef(Short.class, defaultValue);
1504         } else if (BaseTypes.isUint16(base)) {
1505             result = typeToValueOfDef(Integer.class, defaultValue);
1506         } else if (BaseTypes.isUint32(base)) {
1507             result = typeToValueOfDef(Long.class, defaultValue);
1508         } else if (BaseTypes.isUint64(base)) {
1509             switch (defaultValue) {
1510                 case "0":
1511                     result = "java.math.BigInteger.ZERO";
1512                     break;
1513                 case "1":
1514                     result = "java.math.BigInteger.ONE";
1515                     break;
1516                 case "10":
1517                     result = "java.math.BigInteger.TEN";
1518                     break;
1519                 default:
1520                     result = typeToDef(BigInteger.class, defaultValue);
1521             }
1522         } else if (base instanceof UnionTypeDefinition) {
1523             result = unionToDef(node);
1524         } else {
1525             result = "";
1526         }
1527         sb.append(result);
1528
1529         if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1530                 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1531             final Module m = getParentModule(type);
1532             final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1533             final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1534             final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1535             sb.insert(0, "new " + className + "(");
1536             sb.insert(sb.length(), ')');
1537         }
1538
1539         return sb.toString();
1540     }
1541
1542     private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1543         return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1544     }
1545
1546     private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1547         return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1548     }
1549
1550     private static String typeToBooleanDef(final String defaultValue) {
1551         switch (defaultValue) {
1552             case "false":
1553                 return "java.lang.Boolean.FALSE";
1554             case "true":
1555                 return "java.lang.Boolean.TRUE";
1556             default:
1557                 return typeToValueOfDef(Boolean.class, defaultValue);
1558         }
1559     }
1560
1561     private static String binaryToDef(final String defaultValue) {
1562         final StringBuilder sb = new StringBuilder();
1563         final BaseEncoding en = BaseEncoding.base64();
1564         final byte[] encoded = en.decode(defaultValue);
1565         sb.append("new byte[] {");
1566         for (int i = 0; i < encoded.length; i++) {
1567             sb.append(encoded[i]);
1568             if (i != encoded.length - 1) {
1569                 sb.append(", ");
1570             }
1571         }
1572         sb.append('}');
1573         return sb.toString();
1574     }
1575
1576     private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1577
1578     private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1579         final List<Bit> bits = new ArrayList<>(type.getBits());
1580         Collections.sort(bits, BIT_NAME_COMPARATOR);
1581         final StringBuilder sb = new StringBuilder();
1582         if (!isExt) {
1583             sb.append("new ");
1584             sb.append(className);
1585             sb.append('(');
1586         }
1587         for (int i = 0; i < bits.size(); i++) {
1588             if (bits.get(i).getName().equals(defaultValue)) {
1589                 sb.append(true);
1590             } else {
1591                 sb.append(false);
1592             }
1593             if (i != bits.size() - 1) {
1594                 sb.append(", ");
1595             }
1596         }
1597         if (!isExt) {
1598             sb.append(')');
1599         }
1600         return sb.toString();
1601     }
1602
1603     private Module getParentModule(final SchemaNode node) {
1604         final QName qname = node.getPath().getPathFromRoot().iterator().next();
1605         return schemaContext.findModule(qname.getModule()).orElse(null);
1606     }
1607
1608     private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1609         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1610         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1611                 "The Path Statement for Leafref Type Definition cannot be NULL!");
1612
1613         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1614         final String strXPath = xpath.toString();
1615
1616         if (strXPath != null) {
1617             if (strXPath.indexOf('[') == -1) {
1618                 final Module module = findParentModule(schemaContext, parentNode);
1619                 if (module != null) {
1620                     final SchemaNode dataNode;
1621                     if (xpath.isAbsolute()) {
1622                         dataNode = findDataSchemaNode(schemaContext, module, xpath);
1623                     } else {
1624                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1625                     }
1626                     final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1627                     return result;
1628                 }
1629             } else {
1630                 return "new java.lang.Object()";
1631             }
1632         }
1633
1634         return null;
1635     }
1636
1637     private String unionToDef(final LeafSchemaNode node) {
1638         final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1639         String parentName;
1640         String className;
1641
1642         if (type.getBaseType() != null) {
1643             final QName typeQName = type.getQName();
1644             Module module = null;
1645             final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1646             if (modules.size() > 1) {
1647                 for (Module m : modules) {
1648                     if (m.getRevision().equals(typeQName.getRevision())) {
1649                         module = m;
1650                         break;
1651                     }
1652                 }
1653                 if (module == null) {
1654                     final List<Module> modulesList = new ArrayList<>(modules);
1655                     Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1656                     module = modulesList.get(0);
1657                 }
1658             } else {
1659                 module = modules.iterator().next();
1660             }
1661
1662             final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1663             className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1664         } else {
1665             final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1666             final QName first = path.next();
1667             final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1668             final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1669             if (!path.hasNext()) {
1670                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1671                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1672             } else {
1673                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1674                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1675             }
1676         }
1677         return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1678     }
1679
1680     private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1681         final StringBuilder sb = new StringBuilder();
1682         sb.append("new ");
1683         sb.append(className);
1684         sb.append("(\"");
1685         sb.append(defaultValue);
1686         sb.append("\".toCharArray())");
1687         return sb.toString();
1688     }
1689
1690     @Override
1691     public String getConstructorPropertyName(final SchemaNode node) {
1692         return node instanceof TypeDefinition<?> ? "value" : "";
1693     }
1694
1695     @Override
1696     public String getParamNameFromType(final TypeDefinition<?> type) {
1697         return BindingMapping.getPropertyName(type.getQName().getLocalName());
1698     }
1699 }