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.IdentitySchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.Module;
46 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
47 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
50 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
51 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
52 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
53 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
54 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
57 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
59 import org.opendaylight.yangtools.yang.model.util.StringType;
60 import org.opendaylight.yangtools.yang.model.util.UnionType;
61 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
63 import com.google.common.base.Preconditions;
65 public final class TypeProviderImpl implements TypeProvider {
67 * Contains the schema data red from YANG files.
69 private final SchemaContext schemaContext;
72 * The outter map maps module names to the map of the types for the module.
73 * The inner map maps the name of the concrete type to the JAVA
74 * <code>Type</code> (usually it is generated TO).
76 private Map<String, Map<String, Type>> genTypeDefsContextMap;
79 * The map which maps schema paths to JAVA <code>Type</code>.
81 private final Map<SchemaPath, Type> referencedTypes;
84 * Creates new instance of class <code>TypeProviderImpl</code>.
86 * @param schemaContext
87 * contains the schema data red from YANG files
88 * @throws IllegalArgumentException
89 * if <code>schemaContext</code> equal null.
91 public TypeProviderImpl(final SchemaContext schemaContext) {
92 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
94 this.schemaContext = schemaContext;
95 this.genTypeDefsContextMap = new HashMap<>();
96 this.referencedTypes = new HashMap<>();
97 resolveTypeDefsFromContext();
101 * Puts <code>refType</code> to map with key <code>refTypePath</code>
104 * schema path used as the map key
106 * type which represents the map value
107 * @throws IllegalArgumentException
109 * <li>if <code>refTypePath</code> equal null</li>
110 * <li>if <code>refType</code> equal null</li>
114 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
115 Preconditions.checkArgument(refTypePath != null,
116 "Path reference of Enumeration Type Definition cannot be NULL!");
118 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
119 referencedTypes.put(refTypePath, refType);
124 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
127 * string with YANG name of type
128 * @returns JAVA <code>Type</code> for YANG type <code>type</code>
129 * @see org.opendaylight.controller.yang.model.type.provider.TypeProvider#
130 * javaTypeForYangType(java.lang.String)
133 public Type javaTypeForYangType(String type) {
134 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
138 * Converts schema definition type <code>typeDefinition</code> to JAVA
141 * @param typeDefinition
142 * type definition which is converted to JAVA type
143 * @throws IllegalArgumentException
145 * <li>if <code>typeDefinition</code> equal null</li>
146 * <li>if Q name of <code>typeDefinition</code> equal null</li>
147 * <li>if name of <code>typeDefinition</code> equal null</li>
151 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
152 Type returnType = null;
153 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
154 if (typeDefinition.getQName() == null) {
155 throw new IllegalArgumentException(
156 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
158 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
159 "Type Definitions Local Name cannot be NULL!");
161 if (typeDefinition instanceof ExtendedType) {
162 returnType = javaTypeForExtendedType(typeDefinition);
164 returnType = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
165 if (returnType == null) {
166 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
170 // TODO: add throw exception when we will be able to resolve ALL yang
172 // if (returnType == null) {
173 // throw new IllegalArgumentException("Type Provider can't resolve " +
174 // "type for specified Type Definition " + typedefName);
180 * Returns JAVA <code>Type</code> for instances of the type
181 * <code>LeafrefTypeDefinition</code> or
182 * <code>IdentityrefTypeDefinition</code>.
184 * @param typeDefinition
185 * type definition which is converted to JAVA <code>Type</code>
186 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
188 private Type javaTypeForLeafrefOrIdentityRef(TypeDefinition<?> typeDefinition, SchemaNode parentNode) {
189 if (typeDefinition instanceof LeafrefTypeDefinition) {
190 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
191 return provideTypeForLeafref(leafref, parentNode);
192 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
193 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
194 return provideTypeForIdentityref(idref);
201 * Returns JAVA <code>Type</code> for instances of the type
202 * <code>ExtendedType</code>.
204 * @param typeDefinition
205 * type definition which is converted to JAVA <code>Type</code>
206 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
208 private Type javaTypeForExtendedType(TypeDefinition<?> typeDefinition) {
209 final String typedefName = typeDefinition.getQName().getLocalName();
210 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
211 Type returnType = null;
212 returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
213 if (returnType == null) {
214 if (baseTypeDef instanceof EnumTypeDefinition) {
215 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
216 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
218 final Module module = findParentModule(schemaContext, typeDefinition);
219 if (module != null) {
220 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
221 if (genTOs != null) {
222 returnType = genTOs.get(typedefName);
224 if (returnType == null) {
225 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
226 baseTypeDef, typeDefinition);
232 // TODO: add throw exception when we will be able to resolve ALL yang
234 // if (returnType == null) {
235 // throw new IllegalArgumentException("Type Provider can't resolve " +
236 // "type for specified Type Definition " + typedefName);
241 * Seeks for identity reference <code>idref</code> the JAVA
242 * <code>type</code>.<br />
246 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
247 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
250 * identityref type definition for which JAVA <code>Type</code>
252 * @return JAVA <code>Type</code> of the identity which is refrenced through
255 private Type provideTypeForIdentityref(IdentityrefTypeDefinition idref) {
256 QName baseIdQName = idref.getIdentity();
257 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),baseIdQName.getRevision());
258 IdentitySchemaNode identity = null;
259 for (IdentitySchemaNode id : module.getIdentities()) {
260 if (id.getQName().equals(baseIdQName)) {
264 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
266 final String basePackageName = moduleNamespaceToPackageName(module);
267 final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
268 final String genTypeName = parseToClassName(identity.getQName().getLocalName());
270 Type baseType = Types.typeForClass(Class.class);
271 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
272 return Types.parameterizedTypeFor(baseType, paramType);
276 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
278 * @param typeDefinition
279 * type definition which should be converted to JAVA
281 * @return JAVA <code>Type</code> which represents
282 * <code>typeDefinition</code>
283 * @throws IllegalArgumentException
285 * <li>if <code>typeDefinition</code> equal null</li>
286 * <li>if Q name of <code>typeDefinition</code></li>
287 * <li>if name of <code>typeDefinition</code></li>
290 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
291 final SchemaNode parentNode) {
292 Type returnType = null;
293 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
294 if (typeDefinition.getQName() == null) {
295 throw new IllegalArgumentException(
296 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
298 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
299 "Type Definitions Local Name cannot be NULL!");
301 final String typedefName = typeDefinition.getQName().getLocalName();
302 if (typeDefinition instanceof ExtendedType) {
303 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
305 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
306 final Module module = findParentModule(schemaContext, parentNode);
308 if (module != null) {
309 final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
310 if (genTOs != null) {
311 returnType = genTOs.get(typedefName);
320 * Gets base type definition for <code>extendTypeDef</code>. The method is
321 * recursivelly called until non <code>ExtendedType</code> type is found.
323 * @param extendTypeDef
324 * type definition for which is the base type definition sought
325 * @return type definition which is base type for <code>extendTypeDef</code>
326 * @throws IllegalArgumentException
327 * if <code>extendTypeDef</code> equal null
329 private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
330 Preconditions.checkArgument(extendTypeDef != null, "Type Definiition reference cannot be NULL!");
331 final TypeDefinition<?> baseTypeDef = extendTypeDef.getBaseType();
332 if (baseTypeDef instanceof ExtendedType) {
333 return baseTypeDefForExtendedType(baseTypeDef);
341 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
343 * The path of <code>leafrefType</code> is followed to find referenced node
344 * and its <code>Type</code> is returned.
347 * leafref type definition for which is the type sought
348 * @return JAVA <code>Type</code> of data schema node which is referenced in
349 * <code>leafrefType</code>
350 * @throws IllegalArgumentException
352 * <li>if <code>leafrefType</code> equal null</li>
353 * <li>if path statement of <code>leafrefType</code> equal null</li>
357 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
358 Type returnType = null;
359 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
361 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
362 "The Path Statement for Leafref Type Definition cannot be NULL!");
364 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
365 final String strXPath = xpath.toString();
367 if (strXPath != null) {
368 if (strXPath.contains("[")) {
369 returnType = Types.typeForClass(Object.class);
371 final Module module = findParentModule(schemaContext, parentNode);
372 if (module != null) {
373 final SchemaNode dataNode;
374 if (xpath.isAbsolute()) {
375 dataNode = findDataSchemaNode(schemaContext, module, xpath);
377 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
380 if (leafContainsEnumDefinition(dataNode)) {
381 returnType = referencedTypes.get(dataNode.getPath());
382 } else if (leafListContainsEnumDefinition(dataNode)) {
383 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
385 returnType = resolveTypeFromDataSchemaNode(dataNode);
394 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
395 * so then checks if it is of type <code>EnumTypeDefinition</code>.
398 * data schema node for which is checked if it is leaf and if it
400 * @return boolean value
402 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
403 * <li>false - other cases</li>
406 private boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
407 if (dataNode instanceof LeafSchemaNode) {
408 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
409 if (leaf.getType() instanceof EnumTypeDefinition) {
417 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
418 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
421 * data schema node for which is checked if it is leaflist and if
423 * @return boolean value
425 * <li>true - if <code>dataNode</code> is leaflist of type
427 * <li>false - other cases</li>
430 private boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
431 if (dataNode instanceof LeafListSchemaNode) {
432 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
433 if (leafList.getType() instanceof EnumTypeDefinition) {
441 * Converts <code>enumTypeDef</code> to
442 * {@link org.opendaylight.yangtools.sal.binding.model.api.Enumeration
446 * enumeration type definition which is converted to enumeration
448 * string with name which is used as the enumeration name
449 * @return enumeration type which is built with data (name, enum values)
450 * from <code>enumTypeDef</code>
451 * @throws IllegalArgumentException
453 * <li>if <code>enumTypeDef</code> equals null</li>
454 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
455 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
456 * <li>if name of <code>enumTypeDef</code> equal null</li>
459 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
460 final SchemaNode parentNode) {
461 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
462 Preconditions.checkArgument(enumTypeDef.getValues() != null,
463 "EnumTypeDefinition MUST contain at least ONE value definition!");
464 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
465 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
466 "Local Name in EnumTypeDefinition QName cannot be NULL!");
468 final String enumerationName = parseToClassName(enumName);
470 Module module = findParentModule(schemaContext, parentNode);
471 final String basePackageName = moduleNamespaceToPackageName(module);
473 final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
474 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
475 return enumBuilder.toInstance(null);
479 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
480 * taken from <code>enumTypeDef</code>.
483 * enumeration type definition is source of enumeration data for
484 * <code>typeBuilder</code>
486 * string with the name of enumeration
488 * generated type builder to which is enumeration added
489 * @return enumeration type which contains enumeration data form
490 * <code>enumTypeDef</code>
491 * @throws IllegalArgumentException
493 * <li>if <code>enumTypeDef</code> equals null</li>
494 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
495 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
496 * <li>if name of <code>enumTypeDef</code> equal null</li>
497 * <li>if name of <code>typeBuilder</code> equal null</li>
501 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName,
502 final GeneratedTypeBuilderBase<?> typeBuilder) {
503 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
504 Preconditions.checkArgument(enumTypeDef.getValues() != null,
505 "EnumTypeDefinition MUST contain at least ONE value definition!");
506 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
507 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
508 "Local Name in EnumTypeDefinition QName cannot be NULL!");
509 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
511 final String enumerationName = parseToClassName(enumName);
513 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
514 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
515 return enumBuilder.toInstance(enumBuilder);
519 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
522 * contains information about YANG type
523 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
525 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
526 Type returnType = null;
527 if (dataNode != null) {
528 if (dataNode instanceof LeafSchemaNode) {
529 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
530 returnType = javaTypeForSchemaDefinitionType(leaf.getType(), leaf);
531 } else if (dataNode instanceof LeafListSchemaNode) {
532 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
533 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
540 * Passes through all modules and through all its type definitions and
541 * convert it to generated types.
543 * The modules are firstly sorted by mutual dependencies. The modules are
544 * sequentially passed. All type definitions of a module are at the
545 * beginning sorted so that type definition with less amount of references
546 * to other type definition are processed first.<br />
547 * For each module is created mapping record in the map
548 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
549 * which map current module name to the map which maps type names to
550 * returned types (generated types).
553 private void resolveTypeDefsFromContext() {
554 final Set<Module> modules = schemaContext.getModules();
555 Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
556 final Module[] modulesArray = new Module[modules.size()];
558 for (Module modul : modules) {
559 modulesArray[i++] = modul;
561 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modulesArray);
563 for (final Module module : modulesSortedByDependency) {
564 if (module == null) {
567 final String moduleName = module.getName();
568 final String basePackageName = moduleNamespaceToPackageName(module);
570 final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
571 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
573 final Map<String, Type> typeMap = new HashMap<>();
574 genTypeDefsContextMap.put(moduleName, typeMap);
576 if ((listTypeDefinitions != null) && (basePackageName != null)) {
577 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
578 typedefToGeneratedType(basePackageName, moduleName, typedef);
586 * @param basePackageName
587 * string with name of package to which the module belongs
589 * string with the name of the module for to which the
590 * <code>typedef</code> belongs
592 * type definition of the node for which should be creted JAVA
593 * <code>Type</code> (usually generated TO)
594 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
595 * <code>null</code> value if <code>basePackageName</code> or
596 * <code>modulName</code> or <code>typedef</code> or Q name of
597 * <code>typedef</code> equals <code>null</code>
599 private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
600 final TypeDefinition<?> typedef) {
601 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
603 final String typedefName = typedef.getQName().getLocalName();
604 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
605 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
606 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
607 Type returnType = null;
608 if (innerTypeDefinition instanceof ExtendedType) {
609 ExtendedType innerExtendedType = (ExtendedType) innerTypeDefinition;
610 returnType = provideGeneratedTOFromExtendedType(innerExtendedType, basePackageName, typedefName);
611 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
612 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
613 typedef, typedefName, typedef);
614 returnType = genTOBuilder.toInstance();
615 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
616 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
617 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
619 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
620 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
621 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
622 basePackageName, bitsTypeDefinition, typedefName);
623 returnType = genTOBuilder.toInstance();
626 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
627 innerTypeDefinition, typedef);
629 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
631 if (returnType != null) {
632 final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
633 if (typeMap != null) {
634 typeMap.put(typedefName, returnType);
644 * Wraps base YANG type to generated TO.
646 * @param basePackageName
647 * string with name of package to which the module belongs
649 * type definition which is converted to the TO
651 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
652 * @return generated transfer object which represent<code>javaType</code>
654 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
655 final Type javaType) {
656 if (javaType != null) {
657 final String propertyName = "value";
659 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
660 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
661 genPropBuilder.setReturnType(javaType);
662 genTOBuilder.addEqualsIdentity(genPropBuilder);
663 genTOBuilder.addHashIdentity(genPropBuilder);
664 genTOBuilder.addToStringProperty(genPropBuilder);
665 if (javaType == BaseYangTypes.STRING_TYPE && typedef instanceof ExtendedType) {
666 final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
667 addStringRegExAsConstant(genTOBuilder, regExps);
669 return genTOBuilder.toInstance();
675 * Converts output list of generated TO builders to one TO builder (first
676 * from list) which contains the remaining builders as its enclosing TO.
678 * @param basePackageName
679 * string with name of package to which the module belongs
681 * type definition which should be of type
682 * <code>UnionTypeDefinition</code>
684 * string with name for generated TO
685 * @return generated TO builder with the list of enclosed generated TO
688 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
689 final TypeDefinition<?> typedef, String typeDefName, SchemaNode parentNode) {
690 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
691 typedef, typeDefName, parentNode);
692 GeneratedTOBuilder resultTOBuilder = null;
693 if (!genTOBuilders.isEmpty()) {
694 resultTOBuilder = genTOBuilders.get(0);
695 genTOBuilders.remove(0);
696 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
697 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
700 return resultTOBuilder;
704 * Converts <code>typedef</code> to generated TO with
705 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
706 * added to generated TO builder as property.
708 * @param basePackageName
709 * string with name of package to which the module belongs
711 * type definition which should be of type
712 * <code>UnionTypeDefinition</code>
714 * string with name for generated TO
715 * @return generated TO builder which represents <code>typedef</code>
716 * @throws IllegalArgumentException
718 * <li>if <code>basePackageName</code> equals null</li>
719 * <li>if <code>typedef</code> equals null</li>
720 * <li>if Q name of <code>typedef</code> equals null</li>
723 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
724 final TypeDefinition<?> typedef, final String typeDefName, final SchemaNode parentNode) {
725 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
726 Preconditions.checkArgument(typedef != null, "Type Definition cannot be NULL!");
727 Preconditions.checkArgument(typedef.getQName() != null,
728 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
730 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
732 final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
733 if ((baseTypeDefinition != null) && (baseTypeDefinition instanceof UnionTypeDefinition)) {
734 final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
735 final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
737 final GeneratedTOBuilder unionGenTOBuilder;
738 if (typeDefName != null && !typeDefName.isEmpty()) {
739 final String typeName = parseToClassName(typeDefName);
740 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
742 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef);
744 generatedTOBuilders.add(unionGenTOBuilder);
745 unionGenTOBuilder.setIsUnion(true);
746 final List<String> regularExpressions = new ArrayList<String>();
747 for (final TypeDefinition<?> unionType : unionTypes) {
748 final String unionTypeName = unionType.getQName().getLocalName();
749 if (unionType instanceof UnionType) {
750 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, unionType,
751 basePackageName, parentNode));
752 } else if (unionType instanceof ExtendedType) {
753 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, (ExtendedType) unionType, unionTypeName,
754 regularExpressions, parentNode);
755 } else if (unionType instanceof EnumTypeDefinition) {
756 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
757 unionTypeName, unionGenTOBuilder);
758 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
760 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
761 unionType, parentNode);
762 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
765 if (!regularExpressions.isEmpty()) {
766 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
769 storeGenTO(typedef, unionGenTOBuilder, parentNode);
771 return generatedTOBuilders;
775 * Wraps code which handle case when union subtype is also of the type
776 * <code>UnionType</code>.
778 * In this case the new generated TO is created for union subtype (recursive
780 * {@link #provideGeneratedTOBuilderForUnionTypeDef(String, TypeDefinition, String)
781 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
782 * <code>parentUnionGenTOBuilder</code> is created property which type is
783 * equal to new generated TO.
785 * @param parentUnionGenTOBuilder
786 * generated TO builder to which is the property with the child
787 * union subtype added
788 * @param basePackageName
789 * string with the name of the module package
790 * @param unionSubtype
791 * type definition which represents union subtype
792 * @return list of generated TO builders. The number of the builders can be
793 * bigger one due to recursive call of
794 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
796 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
797 final TypeDefinition<?> unionSubtype, final String basePackageName, final SchemaNode parentNode) {
798 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
799 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
800 basePackageName, unionSubtype, newTOBuilderName, parentNode);
802 final GeneratedPropertyBuilder propertyBuilder;
803 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingGeneratorUtil
804 .parseToValidParamName(newTOBuilderName));
805 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
806 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
807 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
809 return subUnionGenTOBUilders;
813 * Wraps code which handle case when union subtype is of the type
814 * <code>ExtendedType</code>.
816 * If TO for this type already exists it is used for the creation of the
817 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
818 * type is used for the property creation.
820 * @param parentUnionGenTOBuilder
821 * generated TO builder in which new property is created
822 * @param unionSubtype
823 * type definition of the <code>ExtendedType</code> type which
824 * represents union subtype
825 * @param unionTypeName
826 * string with the name for <code>unionSubtype</code>
827 * @param regularExpressions
828 * list of strings with the regular expressions
830 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
831 final ExtendedType unionSubtype, final String unionTypeName, final List<String> regularExpressions,
832 final SchemaNode parentNode) {
833 final Type genTO = findGenTO(unionTypeName, parentNode);
835 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
837 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
838 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
839 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
841 if (javaType != null) {
842 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
845 if (baseType instanceof StringType) {
846 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
852 * Searches for generated TO for <code>searchedTypeDef</code> type
853 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
855 * @param searchedTypeName
856 * string with name of <code>searchedTypeDef</code>
857 * @return generated TO for <code>searchedTypeDef</code> or
858 * <code>null</code> it it doesn't exist
860 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
861 final Module typeModule = findParentModule(schemaContext, parentNode);
862 if (typeModule != null && typeModule.getName() != null) {
863 final Map<String, Type> genTOs = genTypeDefsContextMap.get(typeModule.getName());
864 if (genTOs != null) {
865 return genTOs.get(searchedTypeName);
872 * Stores generated TO created from <code>genTOBuilder</code> for
873 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
874 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
877 * type definition for which is <code>genTOBuilder</code> created
878 * @param genTOBuilder
879 * generated TO builder which is converted to generated TO and
882 private void storeGenTO(TypeDefinition<?> newTypeDef, GeneratedTOBuilder genTOBuilder, SchemaNode parentNode) {
883 if (!(newTypeDef instanceof UnionType)) {
884 Map<String, Type> genTOsMap = null;
885 final Module parentModule = findParentModule(schemaContext, parentNode);
886 if (parentModule != null && parentModule.getName() != null) {
887 genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
888 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
894 * Adds a new property with the name <code>propertyName</code> and with type
895 * <code>type</code> to <code>unonGenTransObject</code>.
897 * @param unionGenTransObject
898 * generated TO to which should be property added
900 * JAVA <code>type</code> of the property which should be added
901 * to <code>unionGentransObject</code>
902 * @param propertyName
903 * string with name of property which should be added to
904 * <code>unionGentransObject</code>
906 private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
907 final String propertyName) {
908 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
909 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
910 .addProperty(parseToValidParamName(propertyName));
911 propBuilder.setReturnType(type);
913 unionGenTransObject.addEqualsIdentity(propBuilder);
914 unionGenTransObject.addHashIdentity(propBuilder);
915 unionGenTransObject.addToStringProperty(propBuilder);
920 * Converts <code>typedef</code> to the generated TO builder.
922 * @param basePackageName
923 * string with name of package to which the module belongs
925 * type definition from which is the generated TO builder created
926 * @return generated TO builder which contains data from
927 * <code>typedef</code> and <code>basePackageName</code>
929 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
931 final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
932 final String typeDefTOName = typedef.getQName().getLocalName();
934 if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
935 final String genTOName = parseToClassName(typeDefTOName);
936 final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
937 newType.addComment(typedef.getDescription());
944 * Converts <code>typeDef</code> which should be of the type
945 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
947 * All the bits of the typeDef are added to returning generated TO as
950 * @param basePackageName
951 * string with name of package to which the module belongs
953 * type definition from which is the generated TO builder created
955 * string with the name for generated TO builder
956 * @return generated TO builder which represents <code>typeDef</code>
957 * @throws IllegalArgumentException
959 * <li>if <code>typeDef</code> equals null</li>
960 * <li>if <code>basePackageName</code> equals null</li>
963 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
964 final TypeDefinition<?> typeDef, String typeDefName) {
966 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
967 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
969 if (typeDef instanceof BitsTypeDefinition) {
970 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
972 final String typeName = parseToClassName(typeDefName);
973 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
975 final List<Bit> bitList = bitsTypeDefinition.getBits();
976 GeneratedPropertyBuilder genPropertyBuilder;
977 for (final Bit bit : bitList) {
978 String name = bit.getName();
979 genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
980 genPropertyBuilder.setReadOnly(true);
981 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
983 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
984 genTOBuilder.addHashIdentity(genPropertyBuilder);
985 genTOBuilder.addToStringProperty(genPropertyBuilder);
994 * Converts the pattern constraints from <code>typedef</code> to the list of
995 * the strings which represents these constraints.
998 * extended type in which are the pattern constraints sought
999 * @return list of strings which represents the constraint patterns
1000 * @throws IllegalArgumentException
1001 * if <code>typedef</code> equals null
1004 private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
1005 final List<String> regExps = new ArrayList<String>();
1006 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1007 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1008 if (strTypeDef instanceof StringType) {
1009 final List<PatternConstraint> patternConstraints = typedef.getPatterns();
1010 if (!patternConstraints.isEmpty()) {
1012 String modifiedRegEx;
1013 for (PatternConstraint patternConstraint : patternConstraints) {
1014 regEx = patternConstraint.getRegularExpression();
1015 modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1016 regExps.add(modifiedRegEx);
1025 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1026 * expressions from the <code>regularExpressions</code>
1028 * @param genTOBuilder
1029 * generated TO builder to which are
1030 * <code>regular expressions</code> added
1031 * @param regularExpressions
1032 * list of string which represent regular expressions
1033 * @throws IllegalArgumentException
1035 * <li>if <code>genTOBuilder</code> equals null</li>
1036 * <li>if <code>regularExpressions</code> equals null</li>
1039 private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
1040 if (genTOBuilder == null) {
1041 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1043 if (regularExpressions == null) {
1044 throw new IllegalArgumentException("List of regular expressions can't be null");
1046 if (!regularExpressions.isEmpty()) {
1047 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1048 regularExpressions);
1053 * Creates generated TO with data about inner extended type
1054 * <code>innerExtendedType</code>, about the package name
1055 * <code>typedefName</code> and about the generated TO name
1056 * <code>typedefName</code>.
1058 * It is supposed that <code>innerExtendedType</code> is already present in
1059 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1060 * be possible set it as extended type for the returning generated TO.
1062 * @param innerExtendedType
1063 * extended type which is part of some other extended type
1064 * @param basePackageName
1065 * string with the package name of the module
1066 * @param typedefName
1067 * string with the name for the generated TO
1068 * @return generated TO which extends generated TO for
1069 * <code>innerExtendedType</code>
1070 * @throws IllegalArgumentException
1072 * <li>if <code>extendedType</code> equals null</li>
1073 * <li>if <code>basePackageName</code> equals null</li>
1074 * <li>if <code>typedefName</code> equals null</li>
1077 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final ExtendedType innerExtendedType,
1078 final String basePackageName, final String typedefName) {
1080 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1081 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1082 Preconditions.checkArgument(typedefName != null, "String with type definition name cannot be NULL!");
1084 final String classTypedefName = parseToClassName(typedefName);
1085 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1086 final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1088 Map<String, Type> typeMap = null;
1089 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1090 if (parentModule != null) {
1091 typeMap = genTypeDefsContextMap.get(parentModule.getName());
1094 if (typeMap != null) {
1095 Type type = typeMap.get(innerTypeDef);
1096 if (type instanceof GeneratedTransferObject) {
1097 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1101 return genTOBuilder.toInstance();
1105 * Finds out for each type definition how many immersion (depth) is
1106 * necessary to get to the base type. Every type definition is inserted to
1107 * the map which key is depth and value is list of type definitions with
1108 * equal depth. In next step are lists from this map concatenated to one
1109 * list in ascending order according to their depth. All type definitions
1110 * are in the list behind all type definitions on which depends.
1112 * @param unsortedTypeDefinitions
1113 * list of type definitions which should be sorted by depth
1114 * @return list of type definitions sorted according their each other
1115 * dependencies (type definitions which are depend on other type
1116 * definitions are in list behind them).
1118 private List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1119 final Set<TypeDefinition<?>> unsortedTypeDefinitions) {
1120 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1122 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1123 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1124 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1125 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1126 if (typeDefinitionsConcreteDepth == null) {
1127 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1128 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1130 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1132 // keys are in ascending order
1133 Set<Integer> depths = typeDefinitionsDepths.keySet();
1134 for (Integer depth : depths) {
1135 sortedTypeDefinition.addAll(typeDefinitionsDepths.get(depth));
1138 return sortedTypeDefinition;
1142 * Returns how many immersion is necessary to get from the type definition
1145 * @param typeDefinition
1146 * type definition for which is depth sought.
1147 * @return number of immersions which are necessary to get from the type
1148 * definition to the base type
1150 private int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1151 Preconditions.checkArgument(typeDefinition != null, "Type definition can't be null");
1153 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1155 if (baseType instanceof ExtendedType) {
1156 depth = depth + getTypeDefinitionDepth(typeDefinition.getBaseType());
1157 } else if (baseType instanceof UnionType) {
1158 List<TypeDefinition<?>> childTypeDefinitions = ((UnionType) baseType).getTypes();
1159 int maxChildDepth = 0;
1161 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1162 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition.getBaseType());
1163 if (childDepth > maxChildDepth) {
1164 maxChildDepth = childDepth;
1167 return maxChildDepth;
1173 * Returns string which contains the same value as <code>name</code> but
1174 * integer suffix is incremented by one. If <code>name</code> contains no
1175 * number suffix then number 1 is added.
1178 * string with name of augmented node
1179 * @return string with the number suffix incremented by one (or 1 is added)
1181 private String provideAvailableNameForGenTOBuilder(String name) {
1182 Pattern searchedPattern = Pattern.compile("[0-9]+\\z");
1183 Matcher mtch = searchedPattern.matcher(name);
1185 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1186 return name.substring(0, mtch.start()) + newSuffix;