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