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