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