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