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