2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.moduleNamespaceToPackageName;
11 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
12 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.parseToClassName;
13 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.parseToValidParamName;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
15 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
16 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
18 import java.util.ArrayList;
19 import java.util.HashMap;
20 import java.util.List;
23 import java.util.TreeMap;
24 import java.util.regex.Matcher;
25 import java.util.regex.Pattern;
27 import org.apache.commons.lang.StringEscapeUtils;
28 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
29 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
30 import org.opendaylight.yangtools.binding.generator.util.Types;
31 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
32 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
33 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
34 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
35 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
36 import org.opendaylight.yangtools.sal.binding.model.api.Type;
37 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
38 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
39 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
40 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.Module;
47 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
48 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
51 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
53 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
54 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
58 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
59 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
60 import org.opendaylight.yangtools.yang.model.util.StringType;
61 import org.opendaylight.yangtools.yang.model.util.UnionType;
62 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
64 import com.google.common.base.Preconditions;
66 public final class TypeProviderImpl implements TypeProvider {
68 * Contains the schema data red from YANG files.
70 private final SchemaContext schemaContext;
73 * The outter map maps module names to the map of the types for the module.
74 * The inner map maps the name of the concrete type to the JAVA
75 * <code>Type</code> (usually it is generated TO).
77 private Map<String, Map<String, Type>> genTypeDefsContextMap;
80 * The map which maps schema paths to JAVA <code>Type</code>.
82 private final Map<SchemaPath, Type> referencedTypes;
85 * Creates new instance of class <code>TypeProviderImpl</code>.
87 * @param schemaContext
88 * contains the schema data red from YANG files
89 * @throws IllegalArgumentException
90 * if <code>schemaContext</code> equal null.
92 public TypeProviderImpl(final SchemaContext schemaContext) {
93 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
95 this.schemaContext = schemaContext;
96 this.genTypeDefsContextMap = new HashMap<>();
97 this.referencedTypes = new HashMap<>();
98 resolveTypeDefsFromContext();
102 * Puts <code>refType</code> to map with key <code>refTypePath</code>
105 * schema path used as the map key
107 * type which represents the map value
108 * @throws IllegalArgumentException
110 * <li>if <code>refTypePath</code> equal null</li>
111 * <li>if <code>refType</code> equal null</li>
115 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
116 Preconditions.checkArgument(refTypePath != null,
117 "Path reference of Enumeration Type Definition cannot be NULL!");
119 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
120 referencedTypes.put(refTypePath, refType);
125 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
128 * string with YANG name of type
129 * @returns JAVA <code>Type</code> for YANG type <code>type</code>
130 * @see org.opendaylight.controller.yang.model.type.provider.TypeProvider#
131 * javaTypeForYangType(java.lang.String)
134 public Type javaTypeForYangType(String type) {
135 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
139 * Converts schema definition type <code>typeDefinition</code> to JAVA
142 * @param typeDefinition
143 * type definition which is converted to JAVA type
144 * @throws IllegalArgumentException
146 * <li>if <code>typeDefinition</code> equal null</li>
147 * <li>if Q name of <code>typeDefinition</code> equal null</li>
148 * <li>if name of <code>typeDefinition</code> equal null</li>
152 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
153 Type returnType = null;
154 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
155 if (typeDefinition.getQName() == null) {
156 throw new IllegalArgumentException(
157 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
159 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
160 "Type Definitions Local Name cannot be NULL!");
162 if (typeDefinition instanceof ExtendedType) {
163 returnType = javaTypeForExtendedType(typeDefinition);
165 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
166 if (returnType == null) {
167 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
171 // TODO: add throw exception when we will be able to resolve ALL yang
173 // if (returnType == null) {
174 // throw new IllegalArgumentException("Type Provider can't resolve " +
175 // "type for specified Type Definition " + typedefName);
181 * Returns JAVA <code>Type</code> for instances of the type
182 * <code>LeafrefTypeDefinition</code> or
183 * <code>IdentityrefTypeDefinition</code>.
185 * @param typeDefinition
186 * type definition which is converted to JAVA <code>Type</code>
187 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
189 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
190 if (typeDefinition instanceof LeafrefTypeDefinition) {
191 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
192 return provideTypeForLeafref(leafref, parentNode);
193 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
194 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
195 return provideTypeForIdentityref(idref);
202 * Returns JAVA <code>Type</code> for instances of the type
203 * <code>ExtendedType</code>.
205 * @param typeDefinition
206 * type definition which is converted to JAVA <code>Type</code>
207 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
209 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
210 final String typedefName = typeDefinition.getQName().getLocalName();
211 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
212 Type returnType = null;
213 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
214 if (returnType == null) {
215 if (baseTypeDef instanceof EnumTypeDefinition) {
216 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
217 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
219 final Module module = findParentModule(schemaContext, typeDefinition);
220 if (module != null) {
221 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
222 if (genTOs != null) {
223 returnType = genTOs.get(typedefName);
225 if (returnType == null) {
226 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
227 baseTypeDef, typeDefinition);
233 // TODO: add throw exception when we will be able to resolve ALL yang
235 // if (returnType == null) {
236 // throw new IllegalArgumentException("Type Provider can't resolve " +
237 // "type for specified Type Definition " + typedefName);
242 * Seeks for identity reference <code>idref</code> the JAVA
243 * <code>type</code>.<br />
247 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
248 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
251 * identityref type definition for which JAVA <code>Type</code>
253 * @return JAVA <code>Type</code> of the identity which is refrenced through
256 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
257 QName baseIdQName = idref.getIdentity();
258 Module module = schemaContext.findModuleByNamespace(baseIdQName.getNamespace());
259 IdentitySchemaNode identity = null;
260 for (IdentitySchemaNode id : module.getIdentities()) {
261 if (id.getQName().equals(baseIdQName)) {
265 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
267 final String basePackageName = moduleNamespaceToPackageName(module);
268 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
269 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
271 Type baseType = Types.typeForClass(Class.class);
272 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
273 return Types.parameterizedTypeFor(baseType, paramType);
277 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
279 * @param typeDefinition
280 * type definition which should be converted to JAVA
282 * @return JAVA <code>Type</code> which represents
283 * <code>typeDefinition</code>
284 * @throws IllegalArgumentException
286 * <li>if <code>typeDefinition</code> equal null</li>
287 * <li>if Q name of <code>typeDefinition</code></li>
288 * <li>if name of <code>typeDefinition</code></li>
291 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
292 final SchemaNode parentNode) {
293 Type returnType = null;
294 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
295 if (typeDefinition.getQName() == null) {
296 throw new IllegalArgumentException(
297 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
299 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
300 "Type Definitions Local Name cannot be NULL!");
302 final String typedefName = typeDefinition.getQName().getLocalName();
303 if (typeDefinition instanceof ExtendedType) {
304 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
306 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
307 final Module module = findParentModule(schemaContext, parentNode);
309 if (module != null) {
310 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
311 if (genTOs != null) {
312 returnType = genTOs.get(typedefName);
321 * Gets base type definition for <code>extendTypeDef</code>. The method is
322 * recursivelly called until non <code>ExtendedType</code> type is found.
324 * @param extendTypeDef
325 * type definition for which is the base type definition sought
326 * @return type definition which is base type for <code>extendTypeDef</code>
327 * @throws IllegalArgumentException
328 * if <code>extendTypeDef</code> equal null
330 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
331 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
332 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
333 if (baseTypeDef instanceof ExtendedType) {
334 return baseTypeDefForExtendedType(baseTypeDef);
342 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
344 * The path of <code>leafrefType</code> is followed to find referenced node
345 * and its <code>Type</code> is returned.
348 * leafref type definition for which is the type sought
349 * @return JAVA <code>Type</code> of data schema node which is referenced in
350 * <code>leafrefType</code>
351 * @throws IllegalArgumentException
353 * <li>if <code>leafrefType</code> equal null</li>
354 * <li>if path statement of <code>leafrefType</code> equal null</li>
358 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
359 Type returnType = null;
360 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
362 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
363 "The Path Statement for Leafref Type Definition cannot be NULL!");
365 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
366 final String strXPath = xpath.toString();
368 if (strXPath != null) {
369 if (strXPath.contains("[")) {
370 returnType = Types.typeForClass(Object.class);
372 final Module module = findParentModule(schemaContext, parentNode);
373 if (module != null) {
374 final SchemaNode dataNode;
375 if (xpath.isAbsolute()) {
376 dataNode = findDataSchemaNode(schemaContext, module, xpath);
378 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
381 if (leafContainsEnumDefinition(dataNode)) {
382 returnType = referencedTypes.get(dataNode.getPath());
383 } else if (leafListContainsEnumDefinition(dataNode)) {
384 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
386 returnType = resolveTypeFromDataSchemaNode(dataNode);
395 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
396 * so then checks if it is of type <code>EnumTypeDefinition</code>.
399 * data schema node for which is checked if it is leaf and if it
401 * @return boolean value
403 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
404 * <li>false - other cases</li>
407 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
408 if (dataNode instanceof LeafSchemaNode) {
409 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
410 if (leaf.getType() instanceof EnumTypeDefinition) {
418 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
419 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
422 * data schema node for which is checked if it is leaflist and if
424 * @return boolean value
426 * <li>true - if <code>dataNode</code> is leaflist of type
428 * <li>false - other cases</li>
431 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
432 if (dataNode instanceof LeafListSchemaNode) {
433 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
434 if (leafList.getType() instanceof EnumTypeDefinition) {
442 * Converts <code>enumTypeDef</code> to
443 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
447 * enumeration type definition which is converted to enumeration
449 * string with name which is used as the enumeration name
450 * @return enumeration type which is built with data (name, enum values)
451 * from <code>enumTypeDef</code>
452 * @throws IllegalArgumentException
454 * <li>if <code>enumTypeDef</code> equals null</li>
455 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
456 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
457 * <li>if name of <code>enumTypeDef</code> equal null</li>
460 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
461 final SchemaNode parentNode) {
462 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
463 Preconditions.checkArgument(enumTypeDef.getValues() != null,
464 "EnumTypeDefinition MUST contain at least ONE value definition!");
465 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
466 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
467 "Local Name in EnumTypeDefinition QName cannot be NULL!");
469 final String enumerationName = parseToClassName(enumName);
471 Module module = findParentModule(schemaContext, parentNode);
472 final String basePackageName = moduleNamespaceToPackageName(module);
474 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
475 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
476 return enumBuilder.toInstance(null);
480 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
481 * taken from <code>enumTypeDef</code>.
484 * enumeration type definition is source of enumeration data for
485 * <code>typeBuilder</code>
487 * string with the name of enumeration
489 * generated type builder to which is enumeration added
490 * @return enumeration type which contains enumeration data form
491 * <code>enumTypeDef</code>
492 * @throws IllegalArgumentException
494 * <li>if <code>enumTypeDef</code> equals null</li>
495 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
496 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
497 * <li>if name of <code>enumTypeDef</code> equal null</li>
498 * <li>if name of <code>typeBuilder</code> equal null</li>
502 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
503 final GeneratedTypeBuilderBase<?> typeBuilder) {
504 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
505 Preconditions.checkArgument(enumTypeDef.getValues() != null,
506 "EnumTypeDefinition MUST contain at least ONE value definition!");
507 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
508 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
509 "Local Name in EnumTypeDefinition QName cannot be NULL!");
510 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
512 final String enumerationName = parseToClassName(enumName);
514 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
515 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
516 return enumBuilder.toInstance(enumBuilder);
520 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
523 * contains information about YANG type
524 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
526 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
527 Type returnType = null;
528 if (dataNode != null) {
529 if (dataNode instanceof LeafSchemaNode) {
530 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
531 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
532 } else if (dataNode instanceof LeafListSchemaNode) {
533 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
534 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
541 * Passes through all modules and through all its type definitions and
542 * convert it to generated types.
544 * The modules are firstly sorted by mutual dependencies. The modules are
545 * sequentially passed. All type definitions of a module are at the
546 * beginning sorted so that type definition with less amount of references
547 * to other type definition are processed first.<br />
548 * For each module is created mapping record in the map
549 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
550 * which map current module name to the map which maps type names to
551 * returned types (generated types).
554 private void resolveTypeDefsFromContext() {
555 final Set<Module> modules = schemaContext.getModules();
556 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
557 final Module[] modulesArray = new Module[modules.size()];
559 for (Module modul : modules) {
560 modulesArray[i++] = modul;
562 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
564 for (final Module module : modulesSortedByDependency) {
565 if (module == null) {
568 final String moduleName = module.getName();
569 final String basePackageName = moduleNamespaceToPackageName(module);
571 final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
572 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
574 final Map<String, Type> typeMap = new HashMap<>();
575 genTypeDefsContextMap.put(moduleName, typeMap);
577 if ((listTypeDefinitions != null) && (basePackageName != null)) {
578 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
579 typedefToGeneratedType(basePackageName, moduleName, typedef);
587 * @param basePackageName
588 * string with name of package to which the module belongs
590 * string with the name of the module for to which the
591 * <code>typedef</code> belongs
593 * type definition of the node for which should be creted JAVA
594 * <code>Type</code> (usually generated TO)
595 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
596 * <code>null</code> value if <code>basePackageName</code> or
597 * <code>modulName</code> or <code>typedef</code> or Q name of
598 * <code>typedef</code> equals <code>null</code>
600 private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
601 final TypeDefinition<?> typedef) {
602 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
604 final String typedefName = typedef.getQName().getLocalName();
605 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
606 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
607 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
608 Type returnType = null;
609 if (innerTypeDefinition instanceof ExtendedType) {
610 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
611 returnType = provideGeneratedTOFromExtendedType(innerExtendedType, basePackageName, typedefName);
612 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
613 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
614 typedef, typedefName, typedef);
615 returnType = genTOBuilder.toInstance();
616 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
617 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
618 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
620 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
621 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
622 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
623 basePackageName, bitsTypeDefinition, typedefName);
624 returnType = genTOBuilder.toInstance();
627 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
628 innerTypeDefinition, typedef);
630 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
632 if (returnType != null) {
633 final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
634 if (typeMap != null) {
635 typeMap.put(typedefName, returnType);
645 * Wraps base YANG type to generated TO.
647 * @param basePackageName
648 * string with name of package to which the module belongs
650 * type definition which is converted to the TO
652 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
653 * @return generated transfer object which represent<code>javaType</code>
655 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
656 final Type javaType) {
657 if (javaType != null) {
658 final String propertyName = "value";
660 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
661 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
662 genPropBuilder.setReturnType(javaType);
663 genTOBuilder.addEqualsIdentity(genPropBuilder);
664 genTOBuilder.addHashIdentity(genPropBuilder);
665 genTOBuilder.addToStringProperty(genPropBuilder);
666 if (javaType == BaseYangTypes.STRING_TYPE && typedef instanceof ExtendedType) {
667 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
668 addStringRegExAsConstant(genTOBuilder, regExps);
670 return genTOBuilder.toInstance();
676 * Converts output list of generated TO builders to one TO builder (first
677 * from list) which contains the remaining builders as its enclosing TO.
679 * @param basePackageName
680 * string with name of package to which the module belongs
682 * type definition which should be of type
683 * <code>UnionTypeDefinition</code>
685 * string with name for generated TO
686 * @return generated TO builder with the list of enclosed generated TO
689 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
690 final TypeDefinition<?> typedef, String typeDefName, SchemaNode parentNode) {
691 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
692 typedef, typeDefName, parentNode);
693 GeneratedTOBuilder resultTOBuilder = null;
694 if (!genTOBuilders.isEmpty()) {
695 resultTOBuilder = genTOBuilders.get(0);
696 genTOBuilders.remove(0);
697 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
698 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
701 return resultTOBuilder;
705 * Converts <code>typedef</code> to generated TO with
706 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
707 * added to generated TO builder as property.
709 * @param basePackageName
710 * string with name of package to which the module belongs
712 * type definition which should be of type
713 * <code>UnionTypeDefinition</code>
715 * string with name for generated TO
716 * @return generated TO builder which represents <code>typedef</code>
717 * @throws IllegalArgumentException
719 * <li>if <code>basePackageName</code> equals null</li>
720 * <li>if <code>typedef</code> equals null</li>
721 * <li>if Q name of <code>typedef</code> equals null</li>
724 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
725 final TypeDefinition<?> typedef, final String typeDefName, final SchemaNode parentNode) {
726 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
727 Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
728 Preconditions.checkArgument(typedef.getQName() != null,
729 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
731 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
733 final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
734 if ((baseTypeDefinition != null) && (baseTypeDefinition instanceof UnionTypeDefinition)) {
735 final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
736 final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
738 final GeneratedTOBuilder unionGenTOBuilder;
739 if (typeDefName != null && !typeDefName.isEmpty()) {
740 final String typeName = parseToClassName(typeDefName);
741 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
743 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
745 generatedTOBuilders.add(unionGenTOBuilder);
746 unionGenTOBuilder.setIsUnion(true);
747 final List<String> regularExpressions = new ArrayList<String>();
748 for (final TypeDefinition<?> unionType : unionTypes) {
749 final String unionTypeName = unionType.getQName().getLocalName();
750 if (unionType instanceof UnionType) {
751 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, unionType,
752 basePackageName, parentNode));
753 } else if (unionType instanceof ExtendedType) {
754 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
755 regularExpressions, parentNode);
756 } else if (unionType instanceof EnumTypeDefinition) {
757 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
758 unionTypeName, unionGenTOBuilder);
759 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
761 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
762 unionType, parentNode);
763 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
766 if (!regularExpressions.isEmpty()) {
767 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
770 storeGenTO(typedef, unionGenTOBuilder, parentNode);
772 return generatedTOBuilders;
776 * Wraps code which handle case when union subtype is also of the type
777 * <code>UnionType</code>.
779 * In this case the new generated TO is created for union subtype (recursive
781 * {@link #provideGeneratedTOBuilderForUnionTypeDef(String, TypeDefinition, String)
782 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
783 * <code>parentUnionGenTOBuilder</code> is created property which type is
784 * equal to new generated TO.
786 * @param parentUnionGenTOBuilder
787 * generated TO builder to which is the property with the child
788 * union subtype added
789 * @param basePackageName
790 * string with the name of the module package
791 * @param unionSubtype
792 * type definition which represents union subtype
793 * @return list of generated TO builders. The number of the builders can be
794 * bigger one due to recursive call of
795 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
797 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
798 final TypeDefinition<?> unionSubtype, final String basePackageName, final SchemaNode parentNode) {
799 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
800 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
801 basePackageName, unionSubtype, newTOBuilderName, parentNode);
803 final GeneratedPropertyBuilder propertyBuilder;
804 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
805 .parseToValidParamName(newTOBuilderName));
806 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
807 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
808 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
810 return subUnionGenTOBUilders;
814 * Wraps code which handle case when union subtype is of the type
815 * <code>ExtendedType</code>.
817 * If TO for this type already exists it is used for the creation of the
818 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
819 * type is used for the property creation.
821 * @param parentUnionGenTOBuilder
822 * generated TO builder in which new property is created
823 * @param unionSubtype
824 * type definition of the <code>ExtendedType</code> type which
825 * represents union subtype
826 * @param unionTypeName
827 * string with the name for <code>unionSubtype</code>
828 * @param regularExpressions
829 * list of strings with the regular expressions
831 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
832 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
833 final SchemaNode parentNode) {
834 final Type genTO = findGenTO(unionTypeName, parentNode);
836 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
838 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
839 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
840 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
842 if (javaType != null) {
843 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
846 if (baseType instanceof StringType) {
847 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
853 * Searches for generated TO for <code>searchedTypeDef</code> type
854 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
856 * @param searchedTypeName
857 * string with name of <code>searchedTypeDef</code>
858 * @return generated TO for <code>searchedTypeDef</code> or
859 * <code>null</code> it it doesn't exist
861 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
862 final Module typeModule = findParentModule(schemaContext, parentNode);
863 if (typeModule != null && typeModule.getName() != null) {
864 final Map<String, Type> genTOs = genTypeDefsContextMap.get(typeModule.getName());
865 if (genTOs != null) {
866 return genTOs.get(searchedTypeName);
873 * Stores generated TO created from <code>genTOBuilder</code> for
874 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
875 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
878 * type definition for which is <code>genTOBuilder</code> created
879 * @param genTOBuilder
880 * generated TO builder which is converted to generated TO and
883 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
884 if (!(newTypeDef instanceof UnionType)) {
885 Map<String, Type> genTOsMap = null;
886 final Module parentModule = findParentModule(schemaContext, parentNode);
887 if (parentModule != null && parentModule.getName() != null) {
888 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
889 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
895 * Adds a new property with the name <code>propertyName</code> and with type
896 * <code>type</code> to <code>unonGenTransObject</code>.
898 * @param unionGenTransObject
899 * generated TO to which should be property added
901 * JAVA <code>type</code> of the property which should be added
902 * to <code>unionGentransObject</code>
903 * @param propertyName
904 * string with name of property which should be added to
905 * <code>unionGentransObject</code>
907 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
908 final String propertyName) {
909 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
910 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
911 .addProperty(parseToValidParamName(propertyName));
912 propBuilder.setReturnType(type);
914 unionGenTransObject.addEqualsIdentity(propBuilder);
915 unionGenTransObject.addHashIdentity(propBuilder);
916 unionGenTransObject.addToStringProperty(propBuilder);
921 * Converts <code>typedef</code> to the generated TO builder.
923 * @param basePackageName
924 * string with name of package to which the module belongs
926 * type definition from which is the generated TO builder created
927 * @return generated TO builder which contains data from
928 * <code>typedef</code> and <code>basePackageName</code>
930 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
932 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
933 final String typeDefTOName = typedef.getQName().getLocalName();
935 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
936 final String genTOName = parseToClassName(typeDefTOName);
937 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
938 newType.addComment(typedef.getDescription());
945 * Converts <code>typeDef</code> which should be of the type
946 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
948 * All the bits of the typeDef are added to returning generated TO as
951 * @param basePackageName
952 * string with name of package to which the module belongs
954 * type definition from which is the generated TO builder created
956 * string with the name for generated TO builder
957 * @return generated TO builder which represents <code>typeDef</code>
958 * @throws IllegalArgumentException
960 * <li>if <code>typeDef</code> equals null</li>
961 * <li>if <code>basePackageName</code> equals null</li>
964 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
965 final TypeDefinition<?> typeDef, String typeDefName) {
967 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
968 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
970 if (typeDef instanceof BitsTypeDefinition) {
971 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
973 final String typeName = parseToClassName(typeDefName);
974 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
976 final List<Bit> bitList = bitsTypeDefinition.getBits();
977 GeneratedPropertyBuilder genPropertyBuilder;
978 for (final Bit bit : bitList) {
979 String name = bit.getName();
980 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
981 genPropertyBuilder.setReadOnly(true);
982 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
984 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
985 genTOBuilder.addHashIdentity(genPropertyBuilder);
986 genTOBuilder.addToStringProperty(genPropertyBuilder);
995 * Converts the pattern constraints from <code>typedef</code> to the list of
996 * the strings which represents these constraints.
999 * extended type in which are the pattern constraints sought
1000 * @return list of strings which represents the constraint patterns
1001 * @throws IllegalArgumentException
1002 * if <code>typedef</code> equals null
1005 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
1006 final List<String> regExps = new ArrayList<String>();
1007 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1008 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1009 if (strTypeDef instanceof StringType) {
1010 final List<PatternConstraint> patternConstraints = typedef.getPatterns();
1011 if (!patternConstraints.isEmpty()) {
1013 String modifiedRegEx;
1014 for (PatternConstraint patternConstraint : patternConstraints) {
1015 regEx = patternConstraint.getRegularExpression();
1016 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1017 regExps.add(modifiedRegEx);
1026 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1027 * expressions from the <code>regularExpressions</code>
1029 * @param genTOBuilder
1030 * generated TO builder to which are
1031 * <code>regular expressions</code> added
1032 * @param regularExpressions
1033 * list of string which represent regular expressions
1034 * @throws IllegalArgumentException
1036 * <li>if <code>genTOBuilder</code> equals null</li>
1037 * <li>if <code>regularExpressions</code> equals null</li>
1040 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1041 if (genTOBuilder == null) {
1042 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1044 if (regularExpressions == null) {
1045 throw new IllegalArgumentException("List of regular expressions can't be null");
1047 if (!regularExpressions.isEmpty()) {
1048 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1049 regularExpressions);
1054 * Creates generated TO with data about inner extended type
1055 * <code>innerExtendedType</code>, about the package name
1056 * <code>typedefName</code> and about the generated TO name
1057 * <code>typedefName</code>.
1059 * It is supposed that <code>innerExtendedType</code> is already present in
1060 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1061 * be possible set it as extended type for the returning generated TO.
1063 * @param innerExtendedType
1064 * extended type which is part of some other extended type
1065 * @param basePackageName
1066 * string with the package name of the module
1067 * @param typedefName
1068 * string with the name for the generated TO
1069 * @return generated TO which extends generated TO for
1070 * <code>innerExtendedType</code>
1071 * @throws IllegalArgumentException
1073 * <li>if <code>extendedType</code> equals null</li>
1074 * <li>if <code>basePackageName</code> equals null</li>
1075 * <li>if <code>typedefName</code> equals null</li>
1078 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
1079 final String basePackageName, final String typedefName) {
1081 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1082 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1083 Preconditions.checkArgument(typedefName != null, "String with type definition name cannot be NULL!");
1085 final String classTypedefName = parseToClassName(typedefName);
1086 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1087 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1089 Map<String, Type> typeMap = null;
1090 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1091 if (parentModule != null) {
1092 typeMap = genTypeDefsContextMap.get(parentModule.getName());
1095 if (typeMap != null) {
1096 Type type = typeMap.get(innerTypeDef);
1097 if (type instanceof GeneratedTransferObject) {
1098 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1102 return genTOBuilder.toInstance();
1106 * Finds out for each type definition how many immersion (depth) is
1107 * necessary to get to the base type. Every type definition is inserted to
1108 * the map which key is depth and value is list of type definitions with
1109 * equal depth. In next step are lists from this map concatenated to one
1110 * list in ascending order according to their depth. All type definitions
1111 * are in the list behind all type definitions on which depends.
1113 * @param unsortedTypeDefinitions
1114 * list of type definitions which should be sorted by depth
1115 * @return list of type definitions sorted according their each other
1116 * dependencies (type definitions which are depend on other type
1117 * definitions are in list behind them).
1119 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1120 final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
1121 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1123 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1124 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1125 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1126 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1127 if (typeDefinitionsConcreteDepth == null) {
1128 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1129 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1131 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1133 // keys are in ascending order
1134 Set<Integer> depths = typeDefinitionsDepths.keySet();
1135 for (Integer depth : depths) {
1136 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1139 return sortedTypeDefinition;
1143 * Returns how many immersion is necessary to get from the type definition
1146 * @param typeDefinition
1147 * type definition for which is depth sought.
1148 * @return number of immersions which are necessary to get from the type
1149 * definition to the base type
1151 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1152 Preconditions.checkArgument(typeDefinition != null, "Type definition can't be null");
1154 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1156 if (baseType instanceof ExtendedType) {
1157 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1158 } else if (baseType instanceof UnionType) {
1159 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1160 int maxChildDepth = 0;
1162 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1163 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1164 if (childDepth > maxChildDepth) {
1165 maxChildDepth = childDepth;
1168 return maxChildDepth;
1174 * Returns string which contains the same value as <code>name</code> but
1175 * integer suffix is incremented by one. If <code>name</code> contains no
1176 * number suffix then number 1 is added.
1179 * string with name of augmented node
1180 * @return string with the number suffix incremented by one (or 1 is added)
1182 private String provideAvailableNameForGenTOBuilder(String name) {
1183 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1184 Matcher mtch = searchedPattern.matcher(name);
1186 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1187 return name.substring(0, mtch.start()) + newSuffix;