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