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