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