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