6cb6ff926e493cd5c10fd7895f4bf46817f33228
[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.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.StringTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
83 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
84 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
85 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
86 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
87 import org.slf4j.Logger;
88 import org.slf4j.LoggerFactory;
89
90 @Beta
91 public abstract class AbstractTypeProvider implements TypeProvider {
92     private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
93     private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
94     private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
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.getPackageName(), gto.getName());
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 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
396             identity.getPath());
397         final String genTypeName = BindingMapping.getClassName(identity.getQName());
398
399         final Type baseType = Types.typeForClass(Class.class);
400         final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
401         return Types.parameterizedTypeFor(baseType, paramType);
402     }
403
404     /**
405      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
406      *
407      * @param typeDefinition
408      *            type definition which should be converted to JAVA
409      *            <code>Type</code>
410      * @return JAVA <code>Type</code> which represents
411      *         <code>typeDefinition</code>
412      * @throws IllegalArgumentException
413      *             <ul>
414      *             <li>if <code>typeDefinition</code> equal null</li>
415      *             <li>if Q name of <code>typeDefinition</code></li>
416      *             <li>if name of <code>typeDefinition</code></li>
417      *             </ul>
418      */
419     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
420         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
421         if (typeDefinition.getQName() == null) {
422             throw new IllegalArgumentException(
423                     "Type Definition cannot have non specified QName (QName cannot be NULL!)");
424         }
425         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
426                 "Type Definitions Local Name cannot be NULL!");
427
428         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
429         if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
430             /*
431              * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
432              * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
433              * this:
434              *
435              *     identity iden;
436              *
437              *     container foo {
438              *         leaf foo {
439              *             type identityref {
440              *                 base iden;
441              *             }
442              *         }
443              *     }
444              *
445              * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
446              * dicey when we throw in:
447              *
448              *     typedef bar-ref {
449              *         type identityref {
450              *             base iden;
451              *         }
452              *     }
453              *
454              *     container bar {
455              *         leaf bar {
456              *             type bar-ref;
457              *         }
458              *     }
459              *
460              * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
461              * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
462              * is formed.
463              *
464              * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
465              * an encapsulation for identityref typedefs.
466              *
467              * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
468              * option, as it would look as though it is the product of a different construct:
469              *
470              *     identity bar-ref {
471              *         base iden;
472              *     }
473              *
474              * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
475              * sub-identities of iden.
476              *
477              * The story behind leafrefs is probably similar, but that needs to be ascertained.
478              */
479             return null;
480         }
481
482         final Module module = findParentModule(schemaContext, parentNode);
483         if (module != null) {
484             final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
485                 module.getName());
486             final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
487             if (genTOs != null) {
488                 return genTOs.get(typeDefinition.getQName().getLocalName());
489             }
490         }
491         return null;
492     }
493
494     /**
495      * Gets base type definition for <code>extendTypeDef</code>. The method is
496      * recursively called until non <code>ExtendedType</code> type is found.
497      *
498      * @param extendTypeDef
499      *            type definition for which is the base type definition sought
500      * @return type definition which is base type for <code>extendTypeDef</code>
501      * @throws IllegalArgumentException
502      *             if <code>extendTypeDef</code> equal null
503      */
504     private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
505         Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
506
507         TypeDefinition<?> ret = extendTypeDef;
508         while (ret.getBaseType() != null) {
509             ret = ret.getBaseType();
510         }
511
512         return ret;
513     }
514
515     /**
516      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
517      *
518      * The path of <code>leafrefType</code> is followed to find referenced node
519      * and its <code>Type</code> is returned.
520      *
521      * @param leafrefType
522      *            leafref type definition for which is the type sought
523      * @return JAVA <code>Type</code> of data schema node which is referenced in
524      *         <code>leafrefType</code>
525      * @throws IllegalArgumentException
526      *             <ul>
527      *             <li>if <code>leafrefType</code> equal null</li>
528      *             <li>if path statement of <code>leafrefType</code> equal null</li>
529      *             </ul>
530      *
531      */
532     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
533         Type returnType = null;
534         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
535
536         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
537                 "The Path Statement for Leafref Type Definition cannot be NULL!");
538
539         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
540         final String strXPath = xpath.toString();
541
542         if (strXPath != null) {
543             if (strXPath.indexOf('[') == -1) {
544                 final Module module = findParentModule(schemaContext, parentNode);
545                 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
546
547                 final SchemaNode dataNode;
548                 if (xpath.isAbsolute()) {
549                     dataNode = findDataSchemaNode(schemaContext, module, xpath);
550                 } else {
551                     dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
552                 }
553                 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
554                         strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
555
556                 if (leafContainsEnumDefinition(dataNode)) {
557                     returnType = referencedTypes.get(dataNode.getPath());
558                 } else if (leafListContainsEnumDefinition(dataNode)) {
559                     returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
560                 } else {
561                     returnType = resolveTypeFromDataSchemaNode(dataNode);
562                 }
563             } else {
564                 returnType = Types.typeForClass(Object.class);
565             }
566         }
567         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
568                 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
569         return returnType;
570     }
571
572     /**
573      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
574      * so then checks if it is of type <code>EnumTypeDefinition</code>.
575      *
576      * @param dataNode
577      *            data schema node for which is checked if it is leaf and if it
578      *            is of enum type
579      * @return boolean value
580      *         <ul>
581      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
582      *         <li>false - other cases</li>
583      *         </ul>
584      */
585     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
586         if (dataNode instanceof LeafSchemaNode) {
587             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
588             if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
589                 return true;
590             }
591         }
592         return false;
593     }
594
595     /**
596      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
597      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
598      *
599      * @param dataNode
600      *            data schema node for which is checked if it is leaflist and if
601      *            it is of enum type
602      * @return boolean value
603      *         <ul>
604      *         <li>true - if <code>dataNode</code> is leaflist of type
605      *         enumeration</li>
606      *         <li>false - other cases</li>
607      *         </ul>
608      */
609     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
610         if (dataNode instanceof LeafListSchemaNode) {
611             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
612             if (leafList.getType() instanceof EnumTypeDefinition) {
613                 return true;
614             }
615         }
616         return false;
617     }
618
619     /**
620      * Converts <code>enumTypeDef</code> to
621      * {@link Enumeration
622      * enumeration}.
623      *
624      * @param enumTypeDef
625      *            enumeration type definition which is converted to enumeration
626      * @param enumName
627      *            string with name which is used as the enumeration name
628      * @return enumeration type which is built with data (name, enum values)
629      *         from <code>enumTypeDef</code>
630      * @throws IllegalArgumentException
631      *             <ul>
632      *             <li>if <code>enumTypeDef</code> equals null</li>
633      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
634      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
635      *             <li>if name of <code>enumTypeDef</code> equal null</li>
636      *             </ul>
637      */
638     private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
639             final SchemaNode parentNode) {
640         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
641         Preconditions.checkArgument(enumTypeDef.getValues() != null,
642                 "EnumTypeDefinition MUST contain at least ONE value definition!");
643         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
644         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
645                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
646
647         final String enumerationName = BindingMapping.getClassName(enumName);
648
649         final Module module = findParentModule(schemaContext, parentNode);
650         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
651
652         final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(basePackageName, enumerationName);
653         addEnumDescription(enumBuilder, enumTypeDef);
654         enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
655         enumBuilder.setModuleName(module.getName());
656         enumBuilder.setSchemaPath(enumTypeDef.getPath());
657         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
658         return enumBuilder.toInstance(null);
659     }
660
661     /**
662      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
663      * taken from <code>enumTypeDef</code>.
664      *
665      * @param enumTypeDef
666      *            enumeration type definition is source of enumeration data for
667      *            <code>typeBuilder</code>
668      * @param enumName
669      *            string with the name of enumeration
670      * @param typeBuilder
671      *            generated type builder to which is enumeration added
672      * @return enumeration type which contains enumeration data form
673      *         <code>enumTypeDef</code>
674      * @throws IllegalArgumentException
675      *             <ul>
676      *             <li>if <code>enumTypeDef</code> equals null</li>
677      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
678      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
679      *             <li>if name of <code>enumTypeDef</code> equal null</li>
680      *             <li>if name of <code>typeBuilder</code> equal null</li>
681      *             </ul>
682      *
683      */
684     private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
685             final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
686         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
687         Preconditions.checkArgument(enumTypeDef.getValues() != null,
688                 "EnumTypeDefinition MUST contain at least ONE value definition!");
689         Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
690         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
691                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
692         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
693
694         final String enumerationName = BindingMapping.getClassName(enumName);
695
696         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
697
698         addEnumDescription(enumBuilder, enumTypeDef);
699         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
700         return enumBuilder.toInstance(enumBuilder);
701     }
702
703     public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
704
705     public abstract AbstractEnumerationBuilder newEnumerationBuilder(String packageName, String name);
706
707     public abstract GeneratedTOBuilder newGeneratedTOBuilder(String packageName, String name);
708
709     public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(String packageName, String name);
710
711     abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
712
713     /**
714      * Converts the pattern constraints from <code>typedef</code> to the list of
715      * the strings which represents these constraints.
716      *
717      * @param typedef
718      *            extended type in which are the pattern constraints sought
719      * @return list of strings which represents the constraint patterns
720      * @throws IllegalArgumentException
721      *             if <code>typedef</code> equals null
722      *
723      */
724     abstract Map<String, String> resolveRegExpressionsFromTypedef(TypeDefinition<?> typedef);
725
726     /**
727      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
728      *
729      * @param dataNode
730      *            contains information about YANG type
731      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
732      */
733     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
734         Type returnType = null;
735         if (dataNode != null) {
736             if (dataNode instanceof LeafSchemaNode) {
737                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
738                 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
739                 returnType = javaTypeForSchemaDefinitionType(type, leaf);
740             } else if (dataNode instanceof LeafListSchemaNode) {
741                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
742                 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
743             }
744         }
745         return returnType;
746     }
747
748     /**
749      * Passes through all modules and through all its type definitions and
750      * convert it to generated types.
751      *
752      * The modules are firstly sorted by mutual dependencies. The modules are
753      * sequentially passed. All type definitions of a module are at the
754      * beginning sorted so that type definition with less amount of references
755      * to other type definition are processed first.<br />
756      * For each module is created mapping record in the map
757      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
758      * which map current module name to the map which maps type names to
759      * returned types (generated types).
760      *
761      */
762     private void resolveTypeDefsFromContext() {
763         final Set<Module> modules = schemaContext.getModules();
764         Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
765         final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
766
767         for (Module module : modulesSortedByDependency) {
768             Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
769             if (dateTypeMap == null) {
770                 dateTypeMap = new HashMap<>();
771             }
772             dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
773             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
774         }
775
776         for (Module module : modulesSortedByDependency) {
777             if (module != null) {
778                 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
779                 if (basePackageName != null) {
780                     final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
781                     for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
782                         typedefToGeneratedType(basePackageName, module, typedef);
783                     }
784                 }
785             }
786         }
787     }
788
789     /**
790      *
791      * @param basePackageName
792      *            string with name of package to which the module belongs
793      * @param module
794      *            string with the name of the module for to which the
795      *            <code>typedef</code> belongs
796      * @param typedef
797      *            type definition of the node for which should be creted JAVA
798      *            <code>Type</code> (usually generated TO)
799      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
800      *         <code>null</code> value if <code>basePackageName</code> or
801      *         <code>modulName</code> or <code>typedef</code> or Q name of
802      *         <code>typedef</code> equals <code>null</code>
803      */
804     private Type typedefToGeneratedType(final String basePackageName, final Module module,
805             final TypeDefinition<?> typedef) {
806         final String moduleName = module.getName();
807         final Optional<Revision> moduleRevision = module.getRevision();
808         if (basePackageName != null && moduleName != null && typedef != null && typedef.getQName() != null) {
809             final String typedefName = typedef.getQName().getLocalName();
810             final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
811             // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
812             if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
813                     && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
814                 Type returnType = null;
815                 if (innerTypeDefinition.getBaseType() != null) {
816                     returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
817                         module.getName());
818                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
819                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
820                             (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
821                     genTOBuilder.setTypedef(true);
822                     genTOBuilder.setIsUnion(true);
823                     addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
824                     makeSerializable(genTOBuilder);
825                     returnType = genTOBuilder.build();
826                     // union builder
827                     final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(genTOBuilder.getPackageName(),
828                             genTOBuilder.getName() + "Builder");
829                     unionBuilder.setIsUnionBuilder(true);
830                     final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
831                     method.setReturnType(returnType);
832                     method.addParameter(Types.STRING, "defaultValue");
833                     method.setAccessModifier(AccessModifier.PUBLIC);
834                     method.setStatic(true);
835                     Set<Type> types = additionalTypes.get(module);
836                     if (types == null) {
837                         types = Sets.<Type> newHashSet(unionBuilder.build());
838                         additionalTypes.put(module, types);
839                     } else {
840                         types.add(unionBuilder.build());
841                     }
842                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
843                     // enums are automatically Serializable
844                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
845                     // TODO units for typedef enum
846                     returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
847                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
848                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
849                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
850                             basePackageName, bitsTypeDefinition, typedefName, module.getName());
851                     genTOBuilder.setTypedef(true);
852                     addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
853                     makeSerializable(genTOBuilder);
854                     returnType = genTOBuilder.build();
855                 } else {
856                     final Type javaType = javaTypeForSchemaDefinitionType(innerTypeDefinition, typedef);
857                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
858                 }
859                 if (returnType != null) {
860                     final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
861                             genTypeDefsContextMap.get(moduleName);
862                     Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
863                     if (typeMap != null) {
864                         if (typeMap.isEmpty()) {
865                             typeMap = new HashMap<>(4);
866                             modulesByDate.put(moduleRevision, typeMap);
867                         }
868                         typeMap.put(typedefName, returnType);
869                     }
870                     return returnType;
871                 }
872             }
873         }
874         return null;
875     }
876
877     /**
878      * Wraps base YANG type to generated TO.
879      *
880      * @param basePackageName
881      *            string with name of package to which the module belongs
882      * @param typedef
883      *            type definition which is converted to the TO
884      * @param javaType
885      *            JAVA <code>Type</code> to which is <code>typedef</code> mapped
886      * @return generated transfer object which represent<code>javaType</code>
887      */
888     private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
889             final Type javaType, final String moduleName) {
890         Preconditions.checkNotNull(javaType, "javaType cannot be null");
891         final String propertyName = "value";
892
893         final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
894         genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
895         final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
896         genPropBuilder.setReturnType(javaType);
897         genTOBuilder.addEqualsIdentity(genPropBuilder);
898         genTOBuilder.addHashIdentity(genPropBuilder);
899         genTOBuilder.addToStringProperty(genPropBuilder);
900         if (typedef.getStatus() == Status.DEPRECATED) {
901             genTOBuilder.addAnnotation("", "Deprecated");
902         }
903         if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
904             addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
905         }
906         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
907         genTOBuilder.setTypedef(true);
908         makeSerializable(genTOBuilder);
909         return genTOBuilder.build();
910     }
911
912     /**
913      * Converts output list of generated TO builders to one TO builder (first
914      * from list) which contains the remaining builders as its enclosing TO.
915      *
916      * @param basePackageName
917      *            string with name of package to which the module belongs
918      * @param typedef
919      *            type definition which should be of type
920      *            <code>UnionTypeDefinition</code>
921      * @param typeDefName
922      *            string with name for generated TO
923      * @return generated TO builder with the list of enclosed generated TO
924      *         builders
925      */
926     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
927             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
928         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
929                 typedef, typeDefName, 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 basePackageName
945      *            string with name of package to which the module belongs
946      * @param typedef
947      *            type definition which should be of type
948      *            <code>UnionTypeDefinition</code>
949      * @param typeDefName
950      *            string with name for generated TO
951      * @return generated TO builder which represents <code>typedef</code>
952      * @throws NullPointerException
953      *             <ul>
954      *             <li>if <code>basePackageName</code> is null</li>
955      *             <li>if <code>typedef</code> is null</li>
956      *             <li>if Qname of <code>typedef</code> is null</li>
957      *             </ul>
958      */
959     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
960             final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
961         Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
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;
970         if (typeDefName != null && !typeDefName.isEmpty()) {
971             final String typeName = BindingMapping.getClassName(typeDefName);
972             unionGenTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
973             unionGenTOBuilder.setSchemaPath(typedef.getPath());
974             unionGenTOBuilder.setModuleName(module.getName());
975             addCodegenInformation(unionGenTOBuilder, typedef);
976         } else {
977             unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
978         }
979
980         generatedTOBuilders.add(unionGenTOBuilder);
981         unionGenTOBuilder.setIsUnion(true);
982
983         // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
984         // also negation information and hence guarantees uniqueness.
985         final Map<String, String> expressions = new HashMap<>();
986         for (TypeDefinition<?> unionType : unionTypes) {
987             final String unionTypeName = unionType.getQName().getLocalName();
988
989             // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
990             // do not follow type encapsulation -- we use the general case for that.
991             if (unionType.getBaseType() != null  && !(unionType instanceof IdentityrefTypeDefinition)) {
992                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
993             } else if (unionType instanceof UnionTypeDefinition) {
994                 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
995                     (UnionTypeDefinition) unionType, basePackageName, parentNode));
996             } else if (unionType instanceof EnumTypeDefinition) {
997                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
998                         unionTypeName, unionGenTOBuilder);
999                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
1000             } else {
1001                 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
1002                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
1003             }
1004         }
1005         addStringRegExAsConstant(unionGenTOBuilder, expressions);
1006
1007         storeGenTO(typedef, unionGenTOBuilder, parentNode);
1008
1009         return generatedTOBuilders;
1010     }
1011
1012     /**
1013      * Wraps code which handle case when union subtype is also of the type
1014      * <code>UnionType</code>.
1015      *
1016      * In this case the new generated TO is created for union subtype (recursive
1017      * call of method
1018      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
1019      * String, SchemaNode)}
1020      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
1021      * <code>parentUnionGenTOBuilder</code> is created property which type is
1022      * equal to new generated TO.
1023      *
1024      * @param parentUnionGenTOBuilder
1025      *            generated TO builder to which is the property with the child
1026      *            union subtype added
1027      * @param basePackageName
1028      *            string with the name of the module package
1029      * @param unionSubtype
1030      *            type definition which represents union subtype
1031      * @return list of generated TO builders. The number of the builders can be
1032      *         bigger one due to recursive call of
1033      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
1034      */
1035     private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1036             final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
1037         final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
1038         final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1039                 basePackageName, unionSubtype, newTOBuilderName, parentNode);
1040
1041         final GeneratedPropertyBuilder propertyBuilder;
1042         propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
1043         propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
1044         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1045         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1046
1047         return subUnionGenTOBUilders;
1048     }
1049
1050     /**
1051      * Wraps code which handle case when union subtype is of the type
1052      * <code>ExtendedType</code>.
1053      *
1054      * If TO for this type already exists it is used for the creation of the
1055      * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1056      * type is used for the property creation.
1057      *
1058      * @param parentUnionGenTOBuilder
1059      *            generated TO builder in which new property is created
1060      * @param unionSubtype
1061      *            type definition of the <code>ExtendedType</code> type which
1062      *            represents union subtype
1063      * @param expressions
1064      *            list of strings with the regular expressions
1065      * @param parentNode
1066      *            parent Schema Node for Extended Subtype
1067      *
1068      */
1069     private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1070             final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1071         final String unionTypeName = unionSubtype.getQName().getLocalName();
1072         final Type genTO = findGenTO(unionTypeName, unionSubtype);
1073         if (genTO != null) {
1074             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1075             return;
1076         }
1077
1078         final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1079         if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1080             final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1081                 parentNode);
1082             if (javaType != null) {
1083                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1084             }
1085         } else if (baseType instanceof LeafrefTypeDefinition) {
1086             final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1087             boolean typeExist = false;
1088             for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1089                 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1090                 if (origType != null && javaType != null && javaType == origType) {
1091                     typeExist = true;
1092                     break;
1093                 }
1094             }
1095             if (!typeExist && javaType != null) {
1096                 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1097                     javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1098             }
1099         }
1100         if (baseType instanceof StringTypeDefinition) {
1101             expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1102         }
1103     }
1104
1105     /**
1106      * Searches for generated TO for <code>searchedTypeDef</code> type
1107      * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1108      *
1109      * @param searchedTypeName
1110      *            string with name of <code>searchedTypeDef</code>
1111      * @return generated TO for <code>searchedTypeDef</code> or
1112      *         <code>null</code> it it doesn't exist
1113      */
1114     private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1115         final Module typeModule = findParentModule(schemaContext, parentNode);
1116         if (typeModule != null && typeModule.getName() != null) {
1117             final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1118             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1119             if (genTOs != null) {
1120                 return genTOs.get(searchedTypeName);
1121             }
1122         }
1123         return null;
1124     }
1125
1126     /**
1127      * Stores generated TO created from <code>genTOBuilder</code> for
1128      * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1129      * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1130      *
1131      * @param newTypeDef
1132      *            type definition for which is <code>genTOBuilder</code> created
1133      * @param genTOBuilder
1134      *            generated TO builder which is converted to generated TO and
1135      *            stored
1136      */
1137     private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1138         if (!(newTypeDef instanceof UnionTypeDefinition)) {
1139             final Module parentModule = findParentModule(schemaContext, parentNode);
1140             if (parentModule != null && parentModule.getName() != null) {
1141                 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1142                 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1143                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1144             }
1145         }
1146     }
1147
1148     /**
1149      * Adds a new property with the name <code>propertyName</code> and with type
1150      * <code>type</code> to <code>unonGenTransObject</code>.
1151      *
1152      * @param unionGenTransObject
1153      *            generated TO to which should be property added
1154      * @param type
1155      *            JAVA <code>type</code> of the property which should be added
1156      *            to <code>unionGentransObject</code>
1157      * @param propertyName
1158      *            string with name of property which should be added to
1159      *            <code>unionGentransObject</code>
1160      */
1161     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1162         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1163             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1164                     .addProperty(BindingMapping.getPropertyName(propertyName));
1165             propBuilder.setReturnType(type);
1166
1167             unionGenTransObject.addEqualsIdentity(propBuilder);
1168             unionGenTransObject.addHashIdentity(propBuilder);
1169             unionGenTransObject.addToStringProperty(propBuilder);
1170         }
1171     }
1172
1173     /**
1174      * Converts <code>typedef</code> to the generated TO builder.
1175      *
1176      * @param basePackageName
1177      *            string with name of package to which the module belongs
1178      * @param typedef
1179      *            type definition from which is the generated TO builder created
1180      * @return generated TO builder which contains data from
1181      *         <code>typedef</code> and <code>basePackageName</code>
1182      */
1183     private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1184             final TypeDefinition<?> typedef, final String moduleName) {
1185
1186         final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1187         final String typeDefTOName = typedef.getQName().getLocalName();
1188
1189         if (packageName != null && typeDefTOName != null) {
1190             final String genTOName = BindingMapping.getClassName(typeDefTOName);
1191             final GeneratedTOBuilder newType = newGeneratedTOBuilder(packageName, genTOName);
1192             newType.setSchemaPath(typedef.getPath());
1193             newType.setModuleName(moduleName);
1194             addCodegenInformation(newType, typedef);
1195             return newType;
1196         }
1197         return null;
1198     }
1199
1200     /**
1201      * Converts <code>typeDef</code> which should be of the type
1202      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1203      *
1204      * All the bits of the typeDef are added to returning generated TO as
1205      * properties.
1206      *
1207      * @param basePackageName
1208      *            string with name of package to which the module belongs
1209      * @param typeDef
1210      *            type definition from which is the generated TO builder created
1211      * @param typeDefName
1212      *            string with the name for generated TO builder
1213      * @return generated TO builder which represents <code>typeDef</code>
1214      * @throws IllegalArgumentException
1215      *             <ul>
1216      *             <li>if <code>typeDef</code> equals null</li>
1217      *             <li>if <code>basePackageName</code> equals null</li>
1218      *             </ul>
1219      */
1220     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1221             final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1222
1223         Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1224         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1225
1226         if (typeDef instanceof BitsTypeDefinition) {
1227             final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1228
1229             final String typeName = BindingMapping.getClassName(typeDefName);
1230             final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
1231             genTOBuilder.setSchemaPath(typeDef.getPath());
1232             genTOBuilder.setModuleName(moduleName);
1233             genTOBuilder.setBaseType(typeDef);
1234             addCodegenInformation(genTOBuilder, typeDef);
1235
1236             final List<Bit> bitList = bitsTypeDefinition.getBits();
1237             GeneratedPropertyBuilder genPropertyBuilder;
1238             for (Bit bit : bitList) {
1239                 final String name = bit.getName();
1240                 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1241                 genPropertyBuilder.setReadOnly(true);
1242                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1243
1244                 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1245                 genTOBuilder.addHashIdentity(genPropertyBuilder);
1246                 genTOBuilder.addToStringProperty(genPropertyBuilder);
1247             }
1248
1249             return genTOBuilder;
1250         }
1251         return null;
1252     }
1253
1254     /**
1255      *
1256      * Adds to the <code>genTOBuilder</code> the constant which contains regular
1257      * expressions from the <code>regularExpressions</code>
1258      *
1259      * @param genTOBuilder
1260      *            generated TO builder to which are
1261      *            <code>regular expressions</code> added
1262      * @param expressions
1263      *            list of string which represent regular expressions
1264      */
1265     private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1266             final Map<String, String> expressions) {
1267         if (!expressions.isEmpty()) {
1268             genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1269                 ImmutableMap.copyOf(expressions));
1270         }
1271     }
1272
1273     /**
1274      * Creates generated TO with data about inner extended type
1275      * <code>innerExtendedType</code>, about the package name
1276      * <code>typedefName</code> and about the generated TO name
1277      * <code>typedefName</code>.
1278      *
1279      * It is supposed that <code>innerExtendedType</code> is already present in
1280      * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1281      * be possible set it as extended type for the returning generated TO.
1282      *
1283      * @param typedef
1284      *            Type Definition
1285      * @param innerExtendedType
1286      *            extended type which is part of some other extended type
1287      * @param basePackageName
1288      *            string with the package name of the module
1289      * @param moduleName
1290      *            Module Name
1291      * @return generated TO which extends generated TO for
1292      *         <code>innerExtendedType</code>
1293      * @throws IllegalArgumentException
1294      *             <ul>
1295      *             <li>if <code>extendedType</code> equals null</li>
1296      *             <li>if <code>basePackageName</code> equals null</li>
1297      *             <li>if <code>typedefName</code> equals null</li>
1298      *             </ul>
1299      */
1300     private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1301             final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1302         Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1303         Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1304
1305         final String typedefName = typedef.getQName().getLocalName();
1306         final String classTypedefName = BindingMapping.getClassName(typedefName);
1307         final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1308         final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, classTypedefName);
1309         genTOBuilder.setSchemaPath(typedef.getPath());
1310         genTOBuilder.setModuleName(moduleName);
1311         genTOBuilder.setTypedef(true);
1312         addCodegenInformation(genTOBuilder, typedef);
1313
1314         final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1315         genTOBuilder.setRestrictions(r);
1316         if (typedef.getStatus() == Status.DEPRECATED) {
1317             genTOBuilder.addAnnotation("", "Deprecated");
1318         }
1319
1320         if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1321             genTOBuilder.setIsUnion(true);
1322         }
1323
1324         Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1325         Map<String, Type> typeMap = null;
1326         final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1327         if (parentModule != null) {
1328             modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1329             typeMap = modulesByDate.get(parentModule.getRevision());
1330         }
1331
1332         if (typeMap != null) {
1333             final Type type = typeMap.get(innerTypeDef);
1334             if (type instanceof GeneratedTransferObject) {
1335                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1336             }
1337         }
1338         addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1339         makeSerializable(genTOBuilder);
1340
1341         return genTOBuilder.build();
1342     }
1343
1344     /**
1345      * Add {@link Serializable} to implemented interfaces of this TO. Also
1346      * compute and add serialVersionUID property.
1347      *
1348      * @param gto
1349      *            transfer object which needs to be serializable
1350      */
1351     private static void makeSerializable(final GeneratedTOBuilder gto) {
1352         gto.addImplementsType(Types.typeForClass(Serializable.class));
1353         final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1354         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1355         gto.setSUID(prop);
1356     }
1357
1358     /**
1359      * Finds out for each type definition how many immersion (depth) is
1360      * necessary to get to the base type. Every type definition is inserted to
1361      * the map which key is depth and value is list of type definitions with
1362      * equal depth. In next step are lists from this map concatenated to one
1363      * list in ascending order according to their depth. All type definitions
1364      * are in the list behind all type definitions on which depends.
1365      *
1366      * @param unsortedTypeDefinitions
1367      *            list of type definitions which should be sorted by depth
1368      * @return list of type definitions sorted according their each other
1369      *         dependencies (type definitions which are depend on other type
1370      *         definitions are in list behind them).
1371      */
1372     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1373             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1374         final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1375
1376         final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1377         for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1378             final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1379             List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1380             if (typeDefinitionsConcreteDepth == null) {
1381                 typeDefinitionsConcreteDepth = new ArrayList<>();
1382                 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1383             }
1384             typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1385         }
1386
1387         // SortedMap guarantees order corresponding to keys in ascending order
1388         for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1389             sortedTypeDefinition.addAll(v);
1390         }
1391
1392         return sortedTypeDefinition;
1393     }
1394
1395     /**
1396      * Returns how many immersion is necessary to get from the type definition
1397      * to the base type.
1398      *
1399      * @param typeDefinition
1400      *            type definition for which is depth sought.
1401      * @return number of immersions which are necessary to get from the type
1402      *         definition to the base type
1403      */
1404     private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1405         // FIXME: rewrite this in a non-recursive manner
1406         if (typeDefinition == null) {
1407             return 1;
1408         }
1409         final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1410         if (baseType == null) {
1411             return 1;
1412         }
1413
1414         int depth = 1;
1415         if (baseType.getBaseType() != null) {
1416             depth = depth + getTypeDefinitionDepth(baseType);
1417         } else if (baseType instanceof UnionTypeDefinition) {
1418             final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1419             int maxChildDepth = 0;
1420             int childDepth = 1;
1421             for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1422                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1423                 if (childDepth > maxChildDepth) {
1424                     maxChildDepth = childDepth;
1425                 }
1426             }
1427             return maxChildDepth;
1428         }
1429         return depth;
1430     }
1431
1432     /**
1433      * Returns string which contains the same value as <code>name</code> but
1434      * integer suffix is incremented by one. If <code>name</code> contains no
1435      * number suffix then number 1 is added.
1436      *
1437      * @param name
1438      *            string with name of augmented node
1439      * @return string with the number suffix incremented by one (or 1 is added)
1440      */
1441     private static String provideAvailableNameForGenTOBuilder(final String name) {
1442         final Matcher mtch = NUMBERS_PATTERN.matcher(name);
1443         if (mtch.find()) {
1444             final int newSuffix = Integer.parseInt(name.substring(mtch.start())) + 1;
1445             return name.substring(0, mtch.start()) + newSuffix;
1446         }
1447
1448         return name + 1;
1449     }
1450
1451     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1452         if (!Strings.isNullOrEmpty(units)) {
1453             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1454             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1455             prop.setReturnType(Types.STRING);
1456             to.addToStringProperty(prop);
1457         }
1458     }
1459
1460     @Override
1461     public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1462         return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1463     }
1464
1465     public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1466         final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1467         final QName typeQName = type.getQName();
1468         final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1469         Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1470         Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1471                 node);
1472
1473         final StringBuilder sb = new StringBuilder();
1474         String result = null;
1475         if (base instanceof BinaryTypeDefinition) {
1476             result = binaryToDef(defaultValue);
1477         } else if (base instanceof BitsTypeDefinition) {
1478             String parentName;
1479             String className;
1480             final Module parent = getParentModule(node);
1481             final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1482             path.next();
1483             if (!path.hasNext()) {
1484                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1485                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1486                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1487             } else {
1488                 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1489                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1490                 parentName = BindingMapping.getClassName(parent.getName());
1491                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1492             }
1493             result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1494         } else if (base instanceof BooleanTypeDefinition) {
1495             result = typeToBooleanDef(defaultValue);
1496         } else if (base instanceof DecimalTypeDefinition) {
1497             result = typeToDef(BigDecimal.class, defaultValue);
1498         } else if (base instanceof EmptyTypeDefinition) {
1499             result = typeToBooleanDef(defaultValue);
1500         } else if (base instanceof EnumTypeDefinition) {
1501             final char[] defValArray = defaultValue.toCharArray();
1502             final char first = Character.toUpperCase(defaultValue.charAt(0));
1503             defValArray[0] = first;
1504             final String newDefVal = new String(defValArray);
1505             String className;
1506             if (type.getBaseType() != null) {
1507                 final Module m = getParentModule(type);
1508                 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1509                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1510                 className = packageName + "." + BindingMapping.getClassName(typeQName);
1511             } else {
1512                 final Module parentModule = getParentModule(node);
1513                 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1514                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1515                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1516             }
1517             result = className + "." + newDefVal;
1518         } else if (base instanceof IdentityrefTypeDefinition) {
1519             throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1520         } else if (base instanceof InstanceIdentifierTypeDefinition) {
1521             throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1522         } else if (BaseTypes.isInt8(base)) {
1523             result = typeToValueOfDef(Byte.class, defaultValue);
1524         } else if (BaseTypes.isInt16(base)) {
1525             result = typeToValueOfDef(Short.class, defaultValue);
1526         } else if (BaseTypes.isInt32(base)) {
1527             result = typeToValueOfDef(Integer.class, defaultValue);
1528         } else if (BaseTypes.isInt64(base)) {
1529             result = typeToValueOfDef(Long.class, defaultValue);
1530         } else if (base instanceof LeafrefTypeDefinition) {
1531             result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1532         } else if (base instanceof StringTypeDefinition) {
1533             result = "\"" + defaultValue + "\"";
1534         } else if (BaseTypes.isUint8(base)) {
1535             result = typeToValueOfDef(Short.class, defaultValue);
1536         } else if (BaseTypes.isUint16(base)) {
1537             result = typeToValueOfDef(Integer.class, defaultValue);
1538         } else if (BaseTypes.isUint32(base)) {
1539             result = typeToValueOfDef(Long.class, defaultValue);
1540         } else if (BaseTypes.isUint64(base)) {
1541             switch (defaultValue) {
1542                 case "0":
1543                     result = "java.math.BigInteger.ZERO";
1544                     break;
1545                 case "1":
1546                     result = "java.math.BigInteger.ONE";
1547                     break;
1548                 case "10":
1549                     result = "java.math.BigInteger.TEN";
1550                     break;
1551                 default:
1552                     result = typeToDef(BigInteger.class, defaultValue);
1553             }
1554         } else if (base instanceof UnionTypeDefinition) {
1555             result = unionToDef(node);
1556         } else {
1557             result = "";
1558         }
1559         sb.append(result);
1560
1561         if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1562                 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1563             final Module m = getParentModule(type);
1564             final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1565             final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1566             final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1567             sb.insert(0, "new " + className + "(");
1568             sb.insert(sb.length(), ')');
1569         }
1570
1571         return sb.toString();
1572     }
1573
1574     private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1575         return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1576     }
1577
1578     private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1579         return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1580     }
1581
1582     private static String typeToBooleanDef(final String defaultValue) {
1583         switch (defaultValue) {
1584             case "false":
1585                 return "java.lang.Boolean.FALSE";
1586             case "true":
1587                 return "java.lang.Boolean.TRUE";
1588             default:
1589                 return typeToValueOfDef(Boolean.class, defaultValue);
1590         }
1591     }
1592
1593     private static String binaryToDef(final String defaultValue) {
1594         final StringBuilder sb = new StringBuilder();
1595         final BaseEncoding en = BaseEncoding.base64();
1596         final byte[] encoded = en.decode(defaultValue);
1597         sb.append("new byte[] {");
1598         for (int i = 0; i < encoded.length; i++) {
1599             sb.append(encoded[i]);
1600             if (i != encoded.length - 1) {
1601                 sb.append(", ");
1602             }
1603         }
1604         sb.append('}');
1605         return sb.toString();
1606     }
1607
1608     private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1609
1610     private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1611         final List<Bit> bits = new ArrayList<>(type.getBits());
1612         Collections.sort(bits, BIT_NAME_COMPARATOR);
1613         final StringBuilder sb = new StringBuilder();
1614         if (!isExt) {
1615             sb.append("new ");
1616             sb.append(className);
1617             sb.append('(');
1618         }
1619         for (int i = 0; i < bits.size(); i++) {
1620             if (bits.get(i).getName().equals(defaultValue)) {
1621                 sb.append(true);
1622             } else {
1623                 sb.append(false);
1624             }
1625             if (i != bits.size() - 1) {
1626                 sb.append(", ");
1627             }
1628         }
1629         if (!isExt) {
1630             sb.append(')');
1631         }
1632         return sb.toString();
1633     }
1634
1635     private Module getParentModule(final SchemaNode node) {
1636         final QName qname = node.getPath().getPathFromRoot().iterator().next();
1637         return schemaContext.findModule(qname.getModule()).orElse(null);
1638     }
1639
1640     private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1641         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1642         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1643                 "The Path Statement for Leafref Type Definition cannot be NULL!");
1644
1645         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1646         final String strXPath = xpath.toString();
1647
1648         if (strXPath != null) {
1649             if (strXPath.indexOf('[') == -1) {
1650                 final Module module = findParentModule(schemaContext, parentNode);
1651                 if (module != null) {
1652                     final SchemaNode dataNode;
1653                     if (xpath.isAbsolute()) {
1654                         dataNode = findDataSchemaNode(schemaContext, module, xpath);
1655                     } else {
1656                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1657                     }
1658                     final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1659                     return result;
1660                 }
1661             } else {
1662                 return "new java.lang.Object()";
1663             }
1664         }
1665
1666         return null;
1667     }
1668
1669     private String unionToDef(final LeafSchemaNode node) {
1670         final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1671         String parentName;
1672         String className;
1673
1674         if (type.getBaseType() != null) {
1675             final QName typeQName = type.getQName();
1676             Module module = null;
1677             final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1678             if (modules.size() > 1) {
1679                 for (Module m : modules) {
1680                     if (m.getRevision().equals(typeQName.getRevision())) {
1681                         module = m;
1682                         break;
1683                     }
1684                 }
1685                 if (module == null) {
1686                     final List<Module> modulesList = new ArrayList<>(modules);
1687                     Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1688                     module = modulesList.get(0);
1689                 }
1690             } else {
1691                 module = modules.iterator().next();
1692             }
1693
1694             final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1695             className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1696         } else {
1697             final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1698             final QName first = path.next();
1699             final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1700             final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1701             if (!path.hasNext()) {
1702                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1703                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1704             } else {
1705                 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1706                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1707             }
1708         }
1709         return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1710     }
1711
1712     private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1713         final StringBuilder sb = new StringBuilder();
1714         sb.append("new ");
1715         sb.append(className);
1716         sb.append("(\"");
1717         sb.append(defaultValue);
1718         sb.append("\".toCharArray())");
1719         return sb.toString();
1720     }
1721
1722     @Override
1723     public String getConstructorPropertyName(final SchemaNode node) {
1724         return node instanceof TypeDefinition<?> ? "value" : "";
1725     }
1726
1727     @Override
1728     public String getParamNameFromType(final TypeDefinition<?> type) {
1729         return BindingMapping.getPropertyName(type.getQName().getLocalName());
1730     }
1731 }