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