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