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