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