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