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