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