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