26ef65b2d1b8ae438b909d74a3e09614156ed977
[mdsal.git] / binding2 / mdsal-binding2-generator-impl / src / main / java / org / opendaylight / mdsal / binding / javav2 / generator / yang / types / TypeProviderImpl.java
1 /*
2  * Copyright (c) 2017 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
9 package org.opendaylight.mdsal.binding.javav2.generator.yang.types;
10
11 import static org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
12 import static org.opendaylight.mdsal.binding.javav2.generator.util.Types.getOuterClassPackageName;
13 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.addStringRegExAsConstant;
14 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.baseTypeDefForExtendedType;
15 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.getAllTypedefs;
16 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.getParentModule;
17 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.makeSerializable;
18 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.provideGeneratedTOFromExtendedType;
19 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.provideTypeForEnum;
20 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.resolveRegExpressionsFromTypedef;
21 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.sortTypeDefinitionAccordingDepth;
22 import static org.opendaylight.mdsal.binding.javav2.generator.yang.types.TypeGenHelper.wrapJavaTypeIntoTO;
23 import static org.opendaylight.mdsal.binding.javav2.util.BindingMapping.getRootPackageName;
24 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
25 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
26 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
27
28 import com.google.common.annotations.Beta;
29 import com.google.common.base.Preconditions;
30 import com.google.common.base.Strings;
31 import com.google.common.collect.Sets;
32 import java.util.ArrayList;
33 import java.util.Collections;
34 import java.util.Date;
35 import java.util.HashMap;
36 import java.util.Iterator;
37 import java.util.List;
38 import java.util.Map;
39 import java.util.Set;
40 import java.util.regex.Matcher;
41 import java.util.regex.Pattern;
42 import org.opendaylight.mdsal.binding.javav2.generator.spi.TypeProvider;
43 import org.opendaylight.mdsal.binding.javav2.generator.util.BindingGeneratorUtil;
44 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
45 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
46 import org.opendaylight.mdsal.binding.javav2.generator.util.Types;
47 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
48 import org.opendaylight.mdsal.binding.javav2.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
49 import org.opendaylight.mdsal.binding.javav2.model.api.AccessModifier;
50 import org.opendaylight.mdsal.binding.javav2.model.api.Enumeration;
51 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedProperty;
52 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedTransferObject;
53 import org.opendaylight.mdsal.binding.javav2.model.api.Restrictions;
54 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
55 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.EnumBuilder;
56 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedPropertyBuilder;
57 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTOBuilder;
58 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilderBase;
59 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.MethodSignatureBuilder;
60 import org.opendaylight.mdsal.binding.javav2.spec.runtime.BindingNamespaceType;
61 import org.opendaylight.mdsal.binding.javav2.util.BindingMapping;
62 import org.opendaylight.yangtools.yang.common.QName;
63 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
64 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
73 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
76 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
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.LeafrefTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
83 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
84 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87
88 @Beta
89 public final class TypeProviderImpl implements TypeProvider {
90
91     private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
92     private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
93
94     /**
95      * Contains the schema data red from YANG files.
96      */
97     private final SchemaContext schemaContext;
98
99     /**
100      * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
101      */
102     private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
103
104     /**
105      * Map which maps schema paths to JAVA <code>Type</code>.
106      */
107     private final Map<SchemaPath, Type> referencedTypes;
108
109     /**
110      * Map for additional types e.g unions
111      */
112     private final Map<Module, Set<Type>> additionalTypes;
113
114     /**
115      * Creates new instance of class <code>TypeProviderImpl</code>.
116      *
117      * @param schemaContext
118      *            contains the schema data red from YANG files
119      * @throws IllegalArgumentException
120      *             if <code>schemaContext</code> equal null.
121      */
122     public TypeProviderImpl(final SchemaContext schemaContext) {
123         this.schemaContext = schemaContext;
124         this.genTypeDefsContextMap = new HashMap<>();
125         this.referencedTypes = new HashMap<>();
126         this.additionalTypes = new HashMap<>();
127         resolveTypeDefsFromContext(schemaContext, this.genTypeDefsContextMap, this.additionalTypes);
128     }
129
130     @Override
131     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode) {
132         return javaTypeForSchemaDefinitionType(type, parentNode, null);
133     }
134
135     /**
136      * Converts schema definition type <code>typeDefinition</code> to JAVA
137      * <code>Type</code>
138      *
139      * @param type
140      *            type definition which is converted to JAVA type
141      * @throws IllegalArgumentException
142      *             <ul>
143      *             <li>if <code>typeDefinition</code> equal null</li>
144      *             <li>if QName of <code>typeDefinition</code> equal null</li>
145      *             <li>if name of <code>typeDefinition</code> equal null</li>
146      *             </ul>
147      */
148     @Override
149     public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode, final Restrictions restrictions) {
150         return javaTypeForSchemaDefType(type, parentNode, restrictions, this.schemaContext, this.genTypeDefsContextMap);
151     }
152
153     @Override
154     public String getTypeDefaultConstruction(final LeafSchemaNode node) {
155         return null;
156     }
157
158     @Override
159     public String getConstructorPropertyName(final SchemaNode node) {
160         return null;
161     }
162
163     @Override
164     public String getParamNameFromType(final TypeDefinition<?> type) {
165         return null;
166     }
167
168     public Map<String, Map<Date, Map<String, Type>>> getGenTypeDefsContextMap() {
169         return this.genTypeDefsContextMap;
170     }
171
172     /**
173      * Passes through all modules and through all its type definitions and
174      * convert it to generated types.
175      *
176      * The modules are firstly sorted by mutual dependencies. The modules are
177      * sequentially passed. All type definitions of a module are at the
178      * beginning sorted so that type definition with less amount of references
179      * to other type definition are processed first.<br />
180      * For each module is created mapping record in the map
181      * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
182      * which map current module name to the map which maps type names to
183      * returned types (generated types).
184      *
185      */
186     private void resolveTypeDefsFromContext(final SchemaContext schemaContext, final Map<String, Map<Date, Map<String,
187             Type>>> genTypeDefsContextMap,  final Map<Module, Set<Type>> additionalTypes) {
188
189         final Set<Module> modules = schemaContext.getModules();
190         Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
191         final Module[] modulesArray = new Module[modules.size()];
192         int i = 0;
193         for (final Module modul : modules) {
194             modulesArray[i++] = modul;
195         }
196         final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
197                 .sort(modulesArray);
198
199         for (final Module module : modulesSortedByDependency) {
200             Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
201             if (dateTypeMap == null) {
202                 dateTypeMap = new HashMap<>();
203             }
204             dateTypeMap.put(module.getRevision(), Collections.emptyMap());
205             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
206         }
207
208         modulesSortedByDependency.stream().filter(module -> module != null).forEach(module -> {
209             final String basePackageName = getRootPackageName(module);
210             final List<TypeDefinition<?>> typeDefinitions = getAllTypedefs(module);
211             final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
212             if (listTypeDefinitions != null) {
213                 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
214                     typedefToGeneratedType(basePackageName, module, typedef, genTypeDefsContextMap,
215                             additionalTypes, schemaContext);
216                 }
217             }
218         });
219     }
220
221     /**
222      * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
223      *
224      * @param typeDefinition
225      *            type definition which should be converted to JAVA
226      *            <code>Type</code>
227      * @return JAVA <code>Type</code> which represents
228      *         <code>typeDefinition</code>
229      * @throws IllegalArgumentException
230      *             <ul>
231      *             <li>if <code>typeDefinition</code> equal null</li>
232      *             <li>if Q name of <code>typeDefinition</code></li>
233      *             <li>if name of <code>typeDefinition</code></li>
234      *             </ul>
235      */
236     public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
237         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
238         Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
239                 "Type Definitions Local Name cannot be NULL!");
240
241         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
242         if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
243             final Module module = findParentModule(this.schemaContext, parentNode);
244
245             if (module != null) {
246                 final Map<Date, Map<String, Type>> modulesByDate = this.genTypeDefsContextMap.get(module.getName());
247                 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
248                 if (genTOs != null) {
249                     return genTOs.get(typeDefinition.getQName().getLocalName());
250                 }
251             }
252         }
253         return null;
254     }
255
256     /**
257      * Puts <code>refType</code> to map with key <code>refTypePath</code>
258      *
259      * @param refTypePath
260      *            schema path used as the map key
261      * @param refType
262      *            type which represents the map value
263      * @throws IllegalArgumentException
264      *             <ul>
265      *             <li>if <code>refTypePath</code> equal null</li>
266      *             <li>if <code>refType</code> equal null</li>
267      *             </ul>
268      *
269      */
270     public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
271         Preconditions.checkArgument(refTypePath != null,
272                 "Path reference of Enumeration Type Definition cannot be NULL!");
273         Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
274         this.referencedTypes.put(refTypePath, refType);
275     }
276
277     /**
278      * Converts <code>typeDef</code> which should be of the type
279      * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
280      *
281      * All the bits of the typeDef are added to returning generated TO as
282      * properties.
283      *
284      * @param basePackageName
285      *            string with name of package to which the module belongs
286      * @param typeDef
287      *            type definition from which is the generated TO builder created
288      * @param typeDefName
289      *            string with the name for generated TO builder
290      * @return generated TO builder which represents <code>typeDef</code>
291      * @throws IllegalArgumentException
292      *             <ul>
293      *             <li>if <code>typeDef</code> equals null</li>
294      *             <li>if <code>basePackageName</code> equals null</li>
295      *             </ul>
296      */
297     @SuppressWarnings({ "rawtypes", "unchecked" })
298     public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final
299     TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
300
301         Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
302         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
303
304         if (typeDef instanceof BitsTypeDefinition) {
305             final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
306
307             final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName, true, false);
308             final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
309
310             genTOBuilder.setDescription(typedefDescription);
311             genTOBuilder.setReference(typeDef.getReference());
312             genTOBuilder.setSchemaPath((List) typeDef.getPath().getPathFromRoot());
313             genTOBuilder.setModuleName(moduleName);
314             genTOBuilder.setBaseType(typeDef);
315
316             final List<Bit> bitList = bitsTypeDefinition.getBits();
317             GeneratedPropertyBuilder genPropertyBuilder;
318             for (final Bit bit : bitList) {
319                 final String name = bit.getName();
320                 genPropertyBuilder =
321                         genTOBuilder.addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(name, JavaIdentifier.METHOD));
322                 genPropertyBuilder.setReadOnly(true);
323                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
324
325                 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
326                 genTOBuilder.addHashIdentity(genPropertyBuilder);
327                 genTOBuilder.addToStringProperty(genPropertyBuilder);
328             }
329
330             return genTOBuilder;
331         }
332         return null;
333     }
334
335     /**
336      * Converts <code>typedef</code> to generated TO with
337      * <code>typeDefName</code>. Every union type from <code>typedef</code> is
338      * added to generated TO builder as property.
339      *
340      * @param basePackageName
341      *            string with name of package to which the module belongs
342      * @param typedef
343      *            type definition which should be of type
344      *            <code>UnionTypeDefinition</code>
345      * @param typeDefName
346      *            string with name for generated TO
347      * @return generated TO builder which represents <code>typedef</code>
348      * @throws NullPointerException
349      *             <ul>
350      *             <li>if <code>basePackageName</code> is null</li>
351      *             <li>if <code>typedef</code> is null</li>
352      *             <li>if QName of <code>typedef</code> is null</li>
353      *             </ul>
354      */
355     @SuppressWarnings({ "rawtypes", "unchecked" })
356     public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
357         final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode, final SchemaContext
358          schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
359         Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
360         Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
361         Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
362
363         final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
364         final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
365         final Module module = findParentModule(schemaContext, parentNode);
366
367         final GeneratedTOBuilderImpl unionGenTOBuilder;
368         if (typeDefName != null && !typeDefName.isEmpty()) {
369             unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName, true, false);
370             final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
371             unionGenTOBuilder.setDescription(typedefDescription);
372             unionGenTOBuilder.setReference(typedef.getReference());
373             unionGenTOBuilder.setSchemaPath((List) typedef.getPath().getPathFromRoot());
374             unionGenTOBuilder.setModuleName(module.getName());
375         } else {
376             unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
377         }
378
379         generatedTOBuilders.add(unionGenTOBuilder);
380         unionGenTOBuilder.setIsUnion(true);
381         final List<String> regularExpressions = new ArrayList<>();
382         for (final TypeDefinition<?> unionType : unionTypes) {
383             final String unionTypeName = unionType.getQName().getLocalName();
384             if (unionType.getBaseType() != null) {
385                 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
386                         parentNode, schemaContext, genTypeDefsContextMap);
387             } else if (unionType instanceof UnionTypeDefinition) {
388                 generatedTOBuilders.add(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
389                         unionGenTOBuilder.getFullyQualifiedName(), parentNode, schemaContext, genTypeDefsContextMap));
390             } else if (unionType instanceof EnumTypeDefinition) {
391                 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
392                         unionTypeName, unionGenTOBuilder);
393                 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
394             } else {
395                 final Type javaType = javaTypeForSchemaDefType(unionType, parentNode, null, schemaContext,
396                         genTypeDefsContextMap);
397                 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
398             }
399         }
400         if (!regularExpressions.isEmpty()) {
401             addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
402         }
403
404         //storeGenTO(typedef, unionGenTOBuilder, parentNode);
405
406         return generatedTOBuilders;
407     }
408
409     public Map<Module, Set<Type>> getAdditionalTypes() {
410         return this.additionalTypes;
411     }
412
413     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
414         if (!Strings.isNullOrEmpty(units)) {
415             to.addConstant(Types.STRING, "Units", "\"" + units + "\"");
416             final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
417             prop.setReturnType(Types.STRING);
418             to.addToStringProperty(prop);
419         }
420     }
421
422     private Type javaTypeForSchemaDefType(final TypeDefinition<?> typeDefinition, final SchemaNode
423             parentNode, final Restrictions r, final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
424         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
425         final String typedefName = typeDefinition.getQName().getLocalName();
426         Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
427
428         // Deal with base types
429         if (typeDefinition.getBaseType() == null) {
430             // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
431             // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
432             // a base type which holds these constraints.
433             if (typeDefinition instanceof DecimalTypeDefinition) {
434                 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
435                 if (ret != null) {
436                     return ret;
437                 }
438             }
439
440             // Deal with leafrefs/identityrefs
441             Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, schemaContext, genTypeDefsContextMap);
442             if (ret != null) {
443                 return ret;
444             }
445
446             ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode);
447             if (ret == null) {
448                 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
449             }
450
451             return ret;
452         }
453
454         Type returnType = javaTypeForExtendedType(typeDefinition, schemaContext, genTypeDefsContextMap);
455         if (r != null && !r.isEmpty() && returnType instanceof GeneratedTransferObject) {
456             final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
457             final Module module = findParentModule(schemaContext, parentNode);
458             final String basePackageName = BindingMapping.getRootPackageName(module);
459             final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition
460                     .getPath(), BindingNamespaceType.Typedef);
461             final String genTOName =
462                     JavaIdentifierNormalizer.normalizeSpecificIdentifier(typedefName, JavaIdentifier.CLASS);
463             final String name = packageName + "." + genTOName;
464             if (!(returnType.getFullyQualifiedName().equals(name))) {
465                 returnType = shadedTOWithRestrictions(gto, r);
466             }
467         }
468         return returnType;
469     }
470
471     /**
472      *
473      * @param basePackageName
474      *            string with name of package to which the module belongs
475      * @param module
476      *            string with the name of the module for to which the
477      *            <code>typedef</code> belongs
478      * @param typedef
479      *            type definition of the node for which should be creted JAVA
480      *            <code>Type</code> (usually generated TO)
481      * @return JAVA <code>Type</code> representation of <code>typedef</code> or
482      *         <code>null</code> value if <code>basePackageName</code> or
483      *         <code>modulName</code> or <code>typedef</code> or Q name of
484      *         <code>typedef</code> equals <code>null</code>
485      */
486     private Type typedefToGeneratedType(final String basePackageName, final Module module, final
487     TypeDefinition<?> typedef, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap, final Map<Module,
488             Set<Type>> additionalTypes, final SchemaContext schemaContext) {
489         final String moduleName = module.getName();
490         final Date moduleRevision = module.getRevision();
491         if ((basePackageName != null) && (moduleName != null) && (typedef != null)) {
492             final String typedefName = typedef.getQName().getLocalName();
493             final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
494             if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
495                     && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
496                 Type returnType;
497                 if (innerTypeDefinition.getBaseType() != null) {
498                     returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
499                             module.getName(), schemaContext, genTypeDefsContextMap);
500                 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
501                     final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
502                             (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef, schemaContext, genTypeDefsContextMap);
503                     genTOBuilder.setTypedef(true);
504                     genTOBuilder.setIsUnion(true);
505                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
506                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
507                     returnType = genTOBuilder.toInstance();
508                 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
509                     // enums are automatically Serializable
510                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
511                     // TODO units for typedef enum
512                     returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef, schemaContext);
513                 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
514                     final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
515                     final GeneratedTOBuilder genTOBuilder =
516                             provideGeneratedTOBuilderForBitsTypeDefinition(
517                                     basePackageName, bitsTypeDefinition, typedefName, module.getName());
518                     genTOBuilder.setTypedef(true);
519                     addUnitsToGenTO(genTOBuilder, typedef.getUnits());
520                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
521                     returnType = genTOBuilder.toInstance();
522                 } else {
523                     final Type javaType = javaTypeForSchemaDefType(innerTypeDefinition, typedef, null,
524                             schemaContext, genTypeDefsContextMap);
525                     returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
526                 }
527                 if (returnType != null) {
528                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
529                     Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
530                     if (typeMap != null) {
531                         if (typeMap.isEmpty()) {
532                             typeMap = new HashMap<>(4);
533                             modulesByDate.put(moduleRevision, typeMap);
534                         }
535                         typeMap.put(typedefName, returnType);
536                     }
537                     return returnType;
538                 }
539             }
540         }
541         return null;
542     }
543
544     /**
545      * Returns JAVA <code>Type</code> for instances of the type
546      * <code>ExtendedType</code>.
547      *
548      * @param typeDefinition
549      *            type definition which is converted to JAVA <code>Type</code>
550      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
551      */
552     private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final SchemaContext
553             schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
554
555         final String typedefName = typeDefinition.getQName().getLocalName();
556         final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
557         Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, schemaContext, genTypeDefsContextMap);
558         if (returnType == null) {
559             if (baseTypeDef instanceof EnumTypeDefinition) {
560                 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
561                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition, schemaContext);
562             } else {
563                 final Module module = findParentModule(schemaContext, typeDefinition);
564                 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
565                 if (module != null) {
566                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
567                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
568                     if (genTOs != null) {
569                         returnType = genTOs.get(typedefName);
570                     }
571                     if (returnType == null) {
572                         returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
573                                 baseTypeDef, typeDefinition, r);
574                     }
575                 }
576             }
577         }
578         return returnType;
579     }
580
581     /**
582      * Returns JAVA <code>Type</code> for instances of the type
583      * <code>LeafrefTypeDefinition</code> or
584      * <code>IdentityrefTypeDefinition</code>.
585      *
586      * @param typeDefinition
587      *            type definition which is converted to JAVA <code>Type</code>
588      * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
589      */
590     private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
591             final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
592         if (typeDefinition instanceof LeafrefTypeDefinition) {
593             final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
594             if (isLeafRefSelfReference(leafref, parentNode, schemaContext)) {
595                 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
596                         " StackOverFlowError detected.");
597             }
598             return provideTypeForLeafref(leafref, parentNode, schemaContext, genTypeDefsContextMap);
599         } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
600             final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
601             return provideTypeForIdentityref(idref, schemaContext);
602         } else {
603             return null;
604         }
605     }
606
607     /**
608      * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
609      *
610      * The path of <code>leafrefType</code> is followed to find referenced node
611      * and its <code>Type</code> is returned.
612      *
613      * @param leafrefType
614      *            leafref type definition for which is the type sought
615      * @return JAVA <code>Type</code> of data schema node which is referenced in
616      *         <code>leafrefType</code>
617      * @throws IllegalArgumentException
618      *             <ul>
619      *             <li>if <code>leafrefType</code> equal null</li>
620      *             <li>if path statement of <code>leafrefType</code> equal null</li>
621      *             </ul>
622      *
623      */
624     public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
625             final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
626
627         Type returnType = null;
628         Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
629
630         Preconditions.checkArgument(leafrefType.getPathStatement() != null,
631                 "The Path Statement for Leafref Type Definition cannot be NULL!");
632
633         final RevisionAwareXPath xpath = leafrefType.getPathStatement();
634         final String strXPath = xpath.toString();
635
636         if (strXPath != null) {
637             if (strXPath.indexOf('[') == -1) {
638                 final Module module = findParentModule(schemaContext, parentNode);
639                 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
640
641                 final SchemaNode dataNode;
642                 if (xpath.isAbsolute()) {
643                     dataNode = findDataSchemaNode(schemaContext, module, xpath);
644                 } else {
645                     dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
646                 }
647                 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
648                         strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName().getModule());
649
650                 if (leafContainsEnumDefinition(dataNode)) {
651                     returnType = this.referencedTypes.get(dataNode.getPath());
652                 } else if (leafListContainsEnumDefinition(dataNode)) {
653                     returnType = Types.listTypeFor(this.referencedTypes.get(dataNode.getPath()));
654                 } else {
655                     returnType = resolveTypeFromDataSchemaNode(dataNode, schemaContext, genTypeDefsContextMap);
656                 }
657             } else {
658                 returnType = Types.typeForClass(Object.class);
659             }
660         }
661         Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
662                 strXPath, getParentModule(parentNode, schemaContext).getName(), parentNode.getQName().getModule());
663         return returnType;
664     }
665
666     /**
667      * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
668      * so then checks if it is of type <code>EnumTypeDefinition</code>.
669      *
670      * @param dataNode
671      *            data schema node for which is checked if it is leaf and if it
672      *            is of enum type
673      * @return boolean value
674      *         <ul>
675      *         <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
676      *         <li>false - other cases</li>
677      *         </ul>
678      */
679     private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
680         if (dataNode instanceof LeafSchemaNode) {
681             final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
682             //CompatUtils is not used here anymore
683             if (leaf.getType() instanceof EnumTypeDefinition) {
684                 return true;
685             }
686         }
687         return false;
688     }
689
690     /**
691      * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
692      * it so then checks if it is of type <code>EnumTypeDefinition</code>.
693      *
694      * @param dataNode
695      *            data schema node for which is checked if it is leaflist and if
696      *            it is of enum type
697      * @return boolean value
698      *         <ul>
699      *         <li>true - if <code>dataNode</code> is leaflist of type
700      *         enumeration</li>
701      *         <li>false - other cases</li>
702      *         </ul>
703      */
704     private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
705         if (dataNode instanceof LeafListSchemaNode) {
706             final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
707             if (leafList.getType() instanceof EnumTypeDefinition) {
708                 return true;
709             }
710         }
711         return false;
712     }
713
714     /**
715      * Converts <code>dataNode</code> to JAVA <code>Type</code>.
716      *
717      * @param dataNode
718      *            contains information about YANG type
719      * @return JAVA <code>Type</code> representation of <code>dataNode</code>
720      */
721     private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final SchemaContext schemaContext,
722         final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
723         Type returnType = null;
724         if (dataNode != null) {
725             if (dataNode instanceof LeafSchemaNode) {
726                 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
727                 //not using CompatUtils here anymore
728                 final TypeDefinition<?> type = leaf.getType();
729                 returnType = javaTypeForSchemaDefType(type, leaf, null, schemaContext, genTypeDefsContextMap);
730             } else if (dataNode instanceof LeafListSchemaNode) {
731                 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
732                 returnType = javaTypeForSchemaDefType(leafList.getType(), leafList, null, schemaContext, genTypeDefsContextMap);
733             }
734         }
735         return returnType;
736     }
737
738     /**
739      * Seeks for identity reference <code>idref</code> the JAVA
740      * <code>type</code>.<br />
741      * <br />
742      *
743      * <i>Example:<br />
744      * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
745      * then returning type is <b>{@code Class<? extends Idn>}</b></i>
746      *
747      * @param idref
748      *            identityref type definition for which JAVA <code>Type</code>
749      *            is sought
750      * @return JAVA <code>Type</code> of the identity which is refrenced through
751      *         <code>idref</code>
752      */
753     private static Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref, final SchemaContext schemaContext) {
754         //TODO: incompatibility with Binding spec v2, get first or only one
755         final QName baseIdQName = idref.getIdentities().iterator().next().getQName();
756         final Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
757                 baseIdQName.getRevision());
758         IdentitySchemaNode identity = null;
759         for (final IdentitySchemaNode id : module.getIdentities()) {
760             if (id.getQName().equals(baseIdQName)) {
761                 identity = id;
762             }
763         }
764         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
765
766         final String basePackageName = BindingMapping.getRootPackageName(module);
767         final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath
768                 (), BindingNamespaceType.Typedef);
769         final String genTypeName =
770                 JavaIdentifierNormalizer.normalizeClassIdentifier(packageName, identity.getQName().getLocalName());
771
772         final Type baseType = Types.typeForClass(Class.class);
773         final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
774         return Types.parameterizedTypeFor(baseType, paramType);
775     }
776
777     /**
778      * Converts <code>typedef</code> to the generated TO builder.
779      *
780      * @param basePackageName
781      *            string with name of package to which the module belongs
782      * @param typedef
783      *            type definition from which is the generated TO builder created
784      * @return generated TO builder which contains data from
785      *         <code>typedef</code> and <code>basePackageName</code>
786      */
787     @SuppressWarnings({ "rawtypes", "unchecked" })
788     private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
789
790         final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath
791                 (), BindingNamespaceType.Typedef);
792         final String typeDefTOName = typedef.getQName().getLocalName();
793
794         if ((packageName != null) && (typeDefTOName != null)) {
795             final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, typeDefTOName);
796             final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
797
798             newType.setDescription(typedefDescription);
799             newType.setReference(typedef.getReference());
800             newType.setSchemaPath((List) typedef.getPath().getPathFromRoot());
801             newType.setModuleName(moduleName);
802
803             return newType;
804         }
805         return null;
806     }
807
808     private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
809         final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
810         final GeneratedTransferObject parent = gto.getSuperType();
811         if (parent != null) {
812             gtob.setExtendsType(parent);
813         }
814         gtob.setRestrictions(r);
815         for (final GeneratedProperty gp : gto.getProperties()) {
816             final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
817             gpb.setValue(gp.getValue());
818             gpb.setReadOnly(gp.isReadOnly());
819             gpb.setAccessModifier(gp.getAccessModifier());
820             gpb.setReturnType(gp.getReturnType());
821             gpb.setFinal(gp.isFinal());
822             gpb.setStatic(gp.isStatic());
823         }
824         return gtob.toInstance();
825     }
826
827     /**
828      * Adds a new property with the name <code>propertyName</code> and with type
829      * <code>type</code> to <code>unonGenTransObject</code>.
830      *
831      * @param unionGenTransObject
832      *            generated TO to which should be property added
833      * @param type
834      *            JAVA <code>type</code> of the property which should be added
835      *            to <code>unionGentransObject</code>
836      * @param propertyName
837      *            string with name of property which should be added to
838      *            <code>unionGentransObject</code>
839      */
840     private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
841         if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
842             final GeneratedPropertyBuilder propBuilder = unionGenTransObject
843                     .addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(propertyName, JavaIdentifier.METHOD));
844             propBuilder.setReturnType(type);
845
846             unionGenTransObject.addEqualsIdentity(propBuilder);
847             unionGenTransObject.addHashIdentity(propBuilder);
848             unionGenTransObject.addToStringProperty(propBuilder);
849         }
850     }
851
852     /**
853      * Wraps code which handle case when union subtype is also of the type
854      * <code>UnionType</code>.
855      *
856      * In this case the new generated TO is created for union subtype (recursive
857      * call of method
858      * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
859      * String, SchemaNode, SchemaContext, Map)}
860      * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
861      * <code>parentUnionGenTOBuilder</code> is created property which type is
862      * equal to new generated TO.
863      *
864      * @param parentUnionGenTOBuilder
865      *            generated TO builder to which is the property with the child
866      *            union subtype added
867      * @param basePackageName
868      *            string with the name of the module package
869      * @param unionSubtype
870      *            type definition which represents union subtype
871      * @return list of generated TO builders. The number of the builders can be
872      *         bigger one due to recursive call of
873      *         <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
874      */
875     private GeneratedTOBuilder resolveUnionSubtypeAsUnion(final GeneratedTOBuilder
876         parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName,
877         final SchemaNode parentNode, final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
878
879         final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
880         final GeneratedTOBuilder subUnionGenTOBUilder = provideGeneratedTOBuilderForUnionTypeDef(
881                 basePackageName, unionSubtype, newTOBuilderName, parentNode, schemaContext, genTypeDefsContextMap);
882
883         final GeneratedPropertyBuilder propertyBuilder;
884         propertyBuilder = parentUnionGenTOBuilder
885                 .addProperty(JavaIdentifierNormalizer.normalizeSpecificIdentifier(newTOBuilderName, JavaIdentifier.METHOD));
886         propertyBuilder.setReturnType(subUnionGenTOBUilder);
887         parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
888         parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
889
890         return subUnionGenTOBUilder;
891     }
892
893     /**
894      * Converts output list of generated TO builders to one TO builder (first
895      * from list) which contains the remaining builders as its enclosing TO.
896      *
897      * @param basePackageName
898      *            string with name of package to which the module belongs
899      * @param typedef
900      *            type definition which should be of type
901      *            <code>UnionTypeDefinition</code>
902      * @param typeDefName
903      *            string with name for generated TO
904      * @return generated TO builder with the list of enclosed generated TO
905      *         builders
906      */
907     public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
908         final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode, final SchemaContext
909               schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
910
911         final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
912                 typedef, typeDefName, parentNode, schemaContext, genTypeDefsContextMap);
913         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
914
915         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
916         for (final GeneratedTOBuilder genTOBuilder : builders) {
917             resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
918         }
919
920         final GeneratedPropertyBuilder genPropBuilder;
921
922         genPropBuilder = resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY).setReadOnly(false);
923         resultTOBuilder.addEqualsIdentity(genPropBuilder);
924         resultTOBuilder.addHashIdentity(genPropBuilder);
925         resultTOBuilder.addToStringProperty(genPropBuilder);
926
927         provideGeneratedTOBuilderForUnionBuilder(findParentModule(schemaContext, parentNode), resultTOBuilder);
928
929         return resultTOBuilder;
930     }
931
932
933     private GeneratedTOBuilder provideGeneratedTOBuilderForUnionBuilder(final Module parentModule,
934                                                  final GeneratedTOBuilder genTOBuilder) {
935         final String outerCls = Types.getOuterClassName(genTOBuilder);
936         final StringBuilder name;
937         if (outerCls != null) {
938             name = new StringBuilder(outerCls);
939         } else {
940             name = new StringBuilder();
941         }
942         name.append(genTOBuilder.getName());
943         name.append("Builder");
944         final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(getOuterClassPackageName(genTOBuilder),
945                 name.toString(), true);
946         unionBuilder.setIsUnionBuilder(true);
947
948         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
949         method.setReturnType(genTOBuilder);
950         method.addParameter(Types.STRING, "defaultValue");
951         method.setAccessModifier(AccessModifier.PUBLIC);
952         method.setStatic(true);
953
954         final Set<Type> types = this.getAdditionalTypes().get(parentModule);
955         if (types == null) {
956             this.getAdditionalTypes().put(parentModule,
957                     Sets.newHashSet(unionBuilder.toInstance()));
958         } else {
959             types.add(unionBuilder.toInstance());
960         }
961
962         return unionBuilder;
963     }
964
965     /**
966      * Wraps code which handle case when union subtype is of the type
967      * <code>ExtendedType</code>.
968      *
969      * If TO for this type already exists it is used for the creation of the
970      * property in <code>parentUnionGenTOBuilder</code>. In other case the base
971      * type is used for the property creation.
972      *
973      * @param parentUnionGenTOBuilder
974      *            generated TO builder in which new property is created
975      * @param unionSubtype
976      *            type definition of the <code>ExtendedType</code> type which
977      *            represents union subtype
978      * @param regularExpressions
979      *            list of strings with the regular expressions
980      * @param parentNode
981      *            parent Schema Node for Extended Subtype
982      *
983      */
984     private static void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final
985         TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode,
986         final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
987
988         final String unionTypeName = unionSubtype.getQName().getLocalName();
989         final Type genTO = findGenTO(unionTypeName, unionSubtype, schemaContext, genTypeDefsContextMap);
990         if (genTO != null) {
991             updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
992         } else {
993             final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
994             if (unionTypeName.equals(baseType.getQName().getLocalName())) {
995                 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
996                         parentNode);
997                 if (javaType != null) {
998                     updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
999                 }
1000             }
1001             if (baseType instanceof StringTypeDefinition) {
1002                 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1003             }
1004         }
1005     }
1006
1007     /**
1008      * Returns string which contains the same value as <code>name</code> but
1009      * integer suffix is incremented by one. If <code>name</code> contains no
1010      * number suffix then number 1 is added.
1011      *
1012      * @param name
1013      *            string with name of augmented node
1014      * @return string with the number suffix incremented by one (or 1 is added)
1015      */
1016     private static String provideAvailableNameForGenTOBuilder(final String name) {
1017         final Matcher mtch = NUMBERS_PATTERN.matcher(name);
1018         if (mtch.find()) {
1019             final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1020             return name.substring(0, mtch.start()) + newSuffix;
1021         } else {
1022             return name + 1;
1023         }
1024     }
1025
1026     /**
1027      * Searches for generated TO for <code>searchedTypeDef</code> type
1028      * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1029      *
1030      * @param searchedTypeName
1031      *            string with name of <code>searchedTypeDef</code>
1032      * @return generated TO for <code>searchedTypeDef</code> or
1033      *         <code>null</code> it it doesn't exist
1034      */
1035     private static Type findGenTO(final String searchedTypeName, final SchemaNode parentNode,
1036         final SchemaContext schemaContext, final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap) {
1037
1038         final Module typeModule = findParentModule(schemaContext, parentNode);
1039         if (typeModule != null && typeModule.getName() != null) {
1040             final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1041             final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1042             if (genTOs != null) {
1043                 return genTOs.get(searchedTypeName);
1044             }
1045         }
1046         return null;
1047     }
1048
1049     /**
1050      * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
1051      * taken from <code>enumTypeDef</code>.
1052      *
1053      * @param enumTypeDef
1054      *            enumeration type definition is source of enumeration data for
1055      *            <code>typeBuilder</code>
1056      * @param enumName
1057      *            string with the name of enumeration
1058      * @param typeBuilder
1059      *            generated type builder to which is enumeration added
1060      * @return enumeration type which contains enumeration data form
1061      *         <code>enumTypeDef</code>
1062      * @throws IllegalArgumentException
1063      *             <ul>
1064      *             <li>if <code>enumTypeDef</code> equals null</li>
1065      *             <li>if enum values of <code>enumTypeDef</code> equal null</li>
1066      *             <li>if Q name of <code>enumTypeDef</code> equal null</li>
1067      *             <li>if name of <code>enumTypeDef</code> equal null</li>
1068      *             <li>if name of <code>typeBuilder</code> equal null</li>
1069      *             </ul>
1070      *
1071      */
1072     private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
1073         Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
1074         Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
1075                 "Local Name in EnumTypeDefinition QName cannot be NULL!");
1076         Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
1077
1078         final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumName);
1079         final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
1080         enumBuilder.setDescription(enumTypedefDescription);
1081         enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
1082         return enumBuilder.toInstance(enumBuilder);
1083     }
1084
1085     private static boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode,
1086                                                   final SchemaContext schemaContext) {
1087         final SchemaNode leafRefValueNode;
1088         final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
1089         final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
1090                 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
1091
1092         ///// skip leafrefs in augments - they're checked once augments are resolved
1093         final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
1094         boolean isAugmenting = false;
1095         DataNodeContainer current = null;
1096         DataSchemaNode dataChildByName;
1097
1098         while (iterator.hasNext() && !isAugmenting) {
1099             final QName next = iterator.next();
1100             if (current == null) {
1101                 dataChildByName = schemaContext.getDataChildByName(next);
1102             } else {
1103                 dataChildByName = current.getDataChildByName(next);
1104             }
1105             if (dataChildByName != null) {
1106                 isAugmenting = dataChildByName.isAugmenting();
1107             } else {
1108                 return false;
1109             }
1110             if (dataChildByName instanceof DataNodeContainer) {
1111                 current = (DataNodeContainer) dataChildByName;
1112             }
1113         }
1114         if (isAugmenting) {
1115             return false;
1116         }
1117         /////
1118
1119         final Module parentModule = getParentModule(parentNode, schemaContext);
1120         if (!leafRefStrippedXPath.isAbsolute()) {
1121             leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
1122                     parentNode, leafRefStrippedXPath);
1123         } else {
1124             leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
1125         }
1126         return (leafRefValueNode != null) && leafRefValueNode.equals(parentNode);
1127     }
1128
1129
1130 }