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