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.mdsal.binding.yang.types;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.TYPE_OBJECT;
13 import com.google.common.base.Preconditions;
14 import com.google.common.base.Strings;
15 import com.google.common.collect.ImmutableMap;
16 import java.util.ArrayList;
17 import java.util.Collection;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.HashSet;
21 import java.util.List;
23 import java.util.Optional;
25 import java.util.TreeMap;
26 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
27 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
28 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
29 import org.opendaylight.mdsal.binding.model.api.Enumeration;
30 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
33 import org.opendaylight.mdsal.binding.model.api.Restrictions;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
36 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
37 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
38 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
39 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
40 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
41 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
42 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
43 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
44 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
45 import org.opendaylight.mdsal.binding.model.util.Types;
46 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
47 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
48 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
49 import org.opendaylight.yangtools.yang.common.Revision;
50 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
55 import org.opendaylight.yangtools.yang.model.api.Status;
56 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
59 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
63 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
67 // FIXME: remove this class
68 @Deprecated(forRemoval = true)
69 abstract class AbstractTypeProvider implements TypeProvider {
70 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
73 * Contains the schema data red from YANG files.
75 private final SchemaContext schemaContext;
77 private final Map<String, Map<Optional<Revision>, Map<String, GeneratedType>>> genTypeDefsContextMap =
81 * The map which maps schema paths to JAVA <code>Type</code>.
83 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
84 private final Map<Module, Set<GeneratedType>> additionalTypes = new HashMap<>();
87 * Creates new instance of class <code>TypeProviderImpl</code>.
89 * @param schemaContext contains the schema data red from YANG files
90 * @param renames renaming table
91 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
93 AbstractTypeProvider(final EffectiveModelContext schemaContext) {
94 this.schemaContext = requireNonNull(schemaContext);
96 resolveTypeDefsFromContext();
100 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
102 * @param refTypePath schema path used as the map key
103 * @param refType type which represents the map value
104 * @throws IllegalArgumentException
106 * <li>if <code>refTypePath</code> equal null</li>
107 * <li>if <code>refType</code> equal null</li>
111 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
112 Preconditions.checkArgument(refTypePath != null,
113 "Path reference of Enumeration Type Definition cannot be NULL!");
114 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
115 referencedTypes.put(refTypePath, refType);
118 public Map<Module, Set<GeneratedType>> getAdditionalTypes() {
119 return additionalTypes;
123 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
124 final boolean lenientRelativeLeafrefs) {
125 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
129 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
131 * @param typeDefinition type definition which is converted to JAVA type
132 * @throws IllegalArgumentException
134 * <li>if <code>typeDefinition</code> equal null</li>
135 * <li>if Qname of <code>typeDefinition</code> equal null</li>
136 * <li>if name of <code>typeDefinition</code> equal null</li>
140 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
141 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
142 throw new UnsupportedOperationException();
146 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
148 * @param typeDefinition
149 * type definition which should be converted to JAVA
151 * @return JAVA <code>Type</code> which represents
152 * <code>typeDefinition</code>
153 * @throws IllegalArgumentException
155 * <li>if <code>typeDefinition</code> equal null</li>
156 * <li>if Q name of <code>typeDefinition</code></li>
157 * <li>if name of <code>typeDefinition</code></li>
160 public GeneratedType generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
161 final SchemaNode parentNode) {
162 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
163 if (typeDefinition.getQName() == null) {
164 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
166 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
167 "Type Definitions Local Name cannot be NULL!");
169 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
170 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
172 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
173 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
186 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
187 * dicey when we throw in:
201 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
202 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
205 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
206 * an encapsulation for identityref typedefs.
208 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
209 * option, as it would look as though it is the product of a different construct:
215 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
216 * sub-identities of iden.
218 * The story behind leafrefs is probably similar, but that needs to be ascertained.
223 final Module module = findParentModule(schemaContext, parentNode);
224 if (module != null) {
225 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
227 final Map<String, GeneratedType> genTOs = modulesByDate.get(module.getRevision());
228 if (genTOs != null) {
229 return genTOs.get(typeDefinition.getQName().getLocalName());
236 * Gets base type definition for <code>extendTypeDef</code>. The method is
237 * recursively called until non <code>ExtendedType</code> type is found.
239 * @param extendTypeDef
240 * type definition for which is the base type definition sought
241 * @return type definition which is base type for <code>extendTypeDef</code>
242 * @throws IllegalArgumentException
243 * if <code>extendTypeDef</code> equal null
245 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
246 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
248 TypeDefinition<?> ret = extendTypeDef;
249 while (ret.getBaseType() != null) {
250 ret = ret.getBaseType();
257 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
259 * @param enumTypeDef enumeration type definition which is converted to enumeration
260 * @param enumName string with name which is used as the enumeration name
261 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
262 * @throws IllegalArgumentException
264 * <li>if <code>enumTypeDef</code> equals null</li>
265 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
266 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
267 * <li>if name of <code>enumTypeDef</code> equal null</li>
270 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
271 final SchemaNode parentNode) {
272 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
273 Preconditions.checkArgument(enumTypeDef.getValues() != null,
274 "EnumTypeDefinition MUST contain at least ONE value definition!");
275 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
276 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
277 "Local Name in EnumTypeDefinition QName cannot be NULL!");
279 final Module module = findParentModule(schemaContext, parentNode);
280 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
281 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
282 addEnumDescription(enumBuilder, enumTypeDef);
283 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
284 enumBuilder.setModuleName(module.getName());
285 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
286 return enumBuilder.toInstance();
290 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
292 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
293 * @param enumName string with the name of enumeration
294 * @param typeBuilder generated type builder to which is enumeration added
295 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
296 * @throws IllegalArgumentException
298 * <li>if <code>enumTypeDef</code> equals null</li>
299 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
300 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
301 * <li>if name of <code>enumTypeDef</code> equal null</li>
302 * <li>if name of <code>typeBuilder</code> equal null</li>
306 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
307 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
308 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
309 Preconditions.checkArgument(enumTypeDef.getValues() != null,
310 "EnumTypeDefinition MUST contain at least ONE value definition!");
311 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
312 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
313 "Local Name in EnumTypeDefinition QName cannot be NULL!");
314 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
316 final EnumBuilder enumBuilder = newEnumerationBuilder(
317 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(enumName), "$"));
318 addEnumDescription(enumBuilder, enumTypeDef);
319 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
320 final Enumeration ret = enumBuilder.toInstance();
321 typeBuilder.addEnumeration(ret);
326 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
328 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
330 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
332 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
335 * Converts the pattern constraints to the list of the strings which represents these constraints.
337 * @param patternConstraints list of pattern constraints
338 * @return list of strings which represents the constraint patterns
340 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
342 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
345 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
348 * @param typedef extended type in which are the pattern constraints sought
349 * @return list of strings which represents the constraint patterns
350 * @throws IllegalArgumentException if <code>typedef</code> equals null
353 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
354 if (!(typedef instanceof StringTypeDefinition)) {
355 return ImmutableMap.of();
358 // TODO: run diff against base ?
359 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
363 * Passes through all modules and through all its type definitions and convert it to generated types.
366 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
367 * of a module are at the beginning sorted so that type definition with less amount of references to other type
368 * definition are processed first.<br>
369 * For each module is created mapping record in the map
370 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
371 * which map current module name to the map which maps type names to returned types (generated types).
373 private void resolveTypeDefsFromContext() {
374 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
376 for (Module module : modulesSortedByDependency) {
377 Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
378 module.getName(), key -> new HashMap<>());
379 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
380 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
383 for (Module module : modulesSortedByDependency) {
384 if (module != null) {
385 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
386 if (basePackageName != null) {
387 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
388 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
389 typedefToGeneratedType(basePackageName, module, typedef);
397 * Create Type for specified type definition.
399 * @param basePackageName string with name of package to which the module belongs
400 * @param module string with the name of the module for to which the <code>typedef</code> belongs
401 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
402 * (usually generated TO)
403 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
404 * <code>null</code> value if <code>basePackageName</code> or
405 * <code>modulName</code> or <code>typedef</code> or Q name of
406 * <code>typedef</code> equals <code>null</code>
408 private Type typedefToGeneratedType(final String basePackageName, final Module module,
409 final TypeDefinition<?> typedef) {
410 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
412 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
413 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
417 final String typedefName = typedef.getQName().getLocalName();
419 final GeneratedType returnType;
420 if (baseTypedef.getBaseType() != null) {
421 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
423 } else if (baseTypedef instanceof UnionTypeDefinition) {
424 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
425 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
426 (UnionTypeDefinition) baseTypedef, typedef);
427 genTOBuilder.setTypedef(true);
428 genTOBuilder.setIsUnion(true);
429 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
430 makeSerializable(genTOBuilder);
431 returnType = genTOBuilder.build();
433 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
434 // so we are placing the builder alongside the union.
435 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
436 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
437 unionBuilder.setIsUnionBuilder(true);
438 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
439 method.setReturnType(returnType);
440 method.addParameter(Types.STRING, "defaultValue");
441 method.setAccessModifier(AccessModifier.PUBLIC);
442 method.setStatic(true);
443 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
444 } else if (baseTypedef instanceof EnumTypeDefinition) {
445 // enums are automatically Serializable
446 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
447 // TODO units for typedef enum
448 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
449 } else if (baseTypedef instanceof BitsTypeDefinition) {
450 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
451 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
452 (BitsTypeDefinition) baseTypedef, module.getName());
453 genTOBuilder.setTypedef(true);
454 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
455 makeSerializable(genTOBuilder);
456 returnType = genTOBuilder.build();
458 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
459 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
461 if (returnType != null) {
462 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
463 genTypeDefsContextMap.get(module.getName());
464 final Optional<Revision> moduleRevision = module.getRevision();
465 Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
466 if (typeMap != null) {
467 if (typeMap.isEmpty()) {
468 typeMap = new HashMap<>(4);
469 modulesByDate.put(moduleRevision, typeMap);
471 typeMap.put(typedefName, returnType);
479 * Wraps base YANG type to generated TO.
481 * @param basePackageName string with name of package to which the module belongs
482 * @param typedef type definition which is converted to the TO
483 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
484 * @return generated transfer object which represent<code>javaType</code>
486 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
487 final Type javaType, final String moduleName) {
488 requireNonNull(javaType, "javaType cannot be null");
490 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
491 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
492 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
493 genPropBuilder.setReturnType(javaType);
495 genTOBuilder.addEqualsIdentity(genPropBuilder);
496 genTOBuilder.addHashIdentity(genPropBuilder);
497 genTOBuilder.addToStringProperty(genPropBuilder);
498 genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
499 if (typedef.getStatus() == Status.DEPRECATED) {
500 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
502 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
503 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
505 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
506 genTOBuilder.setTypedef(true);
507 makeSerializable(genTOBuilder);
508 return genTOBuilder.build();
512 * Converts output list of generated TO builders to one TO builder (first
513 * from list) which contains the remaining builders as its enclosing TO.
515 * @param typeName new type identifier
516 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
517 * @return generated TO builder with the list of enclosed generated TO builders
519 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
520 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
521 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
523 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
525 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
526 builders.forEach(builder -> resultTOBuilder.addEnclosingTransferObject(builder.build()));
527 return resultTOBuilder;
531 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
532 * <code>typedef</code> is added to generated TO builder as property.
534 * @param typeName new type identifier
535 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
536 * @return generated TO builder which represents <code>typedef</code>
537 * @throws NullPointerException
539 * <li>if <code>basePackageName</code> is null</li>
540 * <li>if <code>typedef</code> is null</li>
541 * <li>if Qname of <code>typedef</code> is null</li>
544 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
545 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
546 requireNonNull(typedef, "Type Definition cannot be NULL!");
547 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
549 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
550 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
551 final Module module = findParentModule(schemaContext, parentNode);
553 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
554 unionGenTOBuilder.setIsUnion(true);
555 unionGenTOBuilder.setSchemaPath(typedef.getPath());
556 unionGenTOBuilder.setModuleName(module.getName());
557 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
558 addCodegenInformation(unionGenTOBuilder, typedef);
559 generatedTOBuilders.add(unionGenTOBuilder);
561 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
562 // also negation information and hence guarantees uniqueness.
563 final Map<String, String> expressions = new HashMap<>();
564 for (TypeDefinition<?> unionType : unionTypes) {
565 final String unionTypeName = unionType.getQName().getLocalName();
567 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
568 // do not follow type encapsulation -- we use the general case for that.
569 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
570 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
571 } else if (unionType instanceof UnionTypeDefinition) {
572 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
573 (UnionTypeDefinition) unionType, parentNode));
574 } else if (unionType instanceof EnumTypeDefinition) {
575 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
576 unionTypeName, unionGenTOBuilder);
577 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
579 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
580 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
583 addStringRegExAsConstant(unionGenTOBuilder, expressions);
585 storeGenTO(typedef, unionGenTOBuilder, parentNode);
587 return generatedTOBuilders;
591 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
594 * In this case the new generated TO is created for union subtype (recursive call of method
595 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
596 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
597 * created property which type is equal to new generated TO.
599 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
600 * @param basePackageName string with the name of the module package
601 * @param unionSubtype type definition which represents union subtype
602 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
603 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
605 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
606 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
607 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
608 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
609 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
610 newTOBuilderName, unionSubtype, parentNode);
612 final GeneratedPropertyBuilder propertyBuilder;
613 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
614 newTOBuilderName.simpleName()));
615 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
616 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
617 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
619 return subUnionGenTOBUilders;
623 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
624 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
625 * the base type is used for the property creation.
627 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
628 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
629 * @param expressions list of strings with the regular expressions
630 * @param parentNode parent Schema Node for Extended Subtype
632 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
633 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
634 final String unionTypeName = unionSubtype.getQName().getLocalName();
635 final Type genTO = findGenTO(unionTypeName, unionSubtype);
637 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
641 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
642 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
643 final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
644 BindingGeneratorUtil.getRestrictions(unionSubtype));
645 if (javaType != null) {
646 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
648 } else if (baseType instanceof LeafrefTypeDefinition) {
649 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
650 boolean typeExist = false;
651 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
652 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
653 if (origType != null && javaType != null && javaType == origType) {
658 if (!typeExist && javaType != null) {
659 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
660 BindingMapping.getUnionLeafrefMemberName(parentUnionGenTOBuilder.getName(), javaType.getName()));
663 if (baseType instanceof StringTypeDefinition) {
664 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
669 * Searches for generated TO for <code>searchedTypeDef</code> type definition
670 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
672 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
673 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
675 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
676 final Module typeModule = findParentModule(schemaContext, parentNode);
677 if (typeModule != null && typeModule.getName() != null) {
678 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
679 typeModule.getName());
680 final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
681 if (genTOs != null) {
682 return genTOs.get(searchedTypeName);
689 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
690 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
692 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
693 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
695 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
696 final SchemaNode parentNode) {
697 if (!(newTypeDef instanceof UnionTypeDefinition)) {
698 final Module parentModule = findParentModule(schemaContext, parentNode);
699 if (parentModule != null && parentModule.getName() != null) {
700 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
701 parentModule.getName());
702 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
703 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
709 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
710 * to <code>unonGenTransObject</code>.
712 * @param unionGenTransObject generated TO to which should be property added
713 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
714 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
716 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
717 final String propertyName) {
718 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
719 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
720 .addProperty(BindingMapping.getPropertyName(propertyName));
721 propBuilder.setReturnType(type);
723 unionGenTransObject.addEqualsIdentity(propBuilder);
724 unionGenTransObject.addHashIdentity(propBuilder);
725 unionGenTransObject.addToStringProperty(propBuilder);
730 * Converts <code>typedef</code> to the generated TO builder.
732 * @param basePackageName string with name of package to which the module belongs
733 * @param typedef type definition from which is the generated TO builder created
734 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
736 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
737 final TypeDefinition<?> typedef, final String moduleName) {
738 final JavaTypeName name = JavaTypeName.create(
739 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
740 BindingMapping.getClassName(typedef.getQName().getLocalName()));
742 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
743 newType.setSchemaPath(typedef.getPath());
744 newType.setModuleName(moduleName);
745 addCodegenInformation(newType, typedef);
750 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
751 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
754 * @param typeName new type identifier
755 * @param typeDef type definition from which is the generated TO builder created
756 * @return generated TO builder which represents <code>typeDef</code>
757 * @throws IllegalArgumentException
759 * <li>if <code>typeDef</code> equals null</li>
760 * <li>if <code>basePackageName</code> equals null</li>
763 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
764 final BitsTypeDefinition typeDef, final String moduleName) {
765 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
766 genTOBuilder.setSchemaPath(typeDef.getPath());
767 genTOBuilder.setModuleName(moduleName);
768 genTOBuilder.setBaseType(typeDef);
769 genTOBuilder.addImplementsType(TYPE_OBJECT);
770 addCodegenInformation(genTOBuilder, typeDef);
772 for (Bit bit : typeDef.getBits()) {
773 final String name = bit.getName();
774 GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
775 BindingMapping.getPropertyName(name));
776 genPropertyBuilder.setReadOnly(true);
777 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
779 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
780 genTOBuilder.addHashIdentity(genPropertyBuilder);
781 genTOBuilder.addToStringProperty(genPropertyBuilder);
788 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
789 * the <code>regularExpressions</code>.
791 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
792 * @param expressions list of string which represent regular expressions
794 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
795 final Map<String, String> expressions) {
796 if (!expressions.isEmpty()) {
797 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
798 ImmutableMap.copyOf(expressions));
803 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
804 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
807 * It is assumed that <code>innerExtendedType</code> is already present in
808 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
809 * for the returning generated TO.
811 * @param typedef Type Definition
812 * @param innerExtendedType extended type which is part of some other extended type
813 * @param basePackageName string with the package name of the module
814 * @param moduleName Module Name
815 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
816 * @throws IllegalArgumentException
818 * <li>if <code>extendedType</code> equals null</li>
819 * <li>if <code>basePackageName</code> equals null</li>
820 * <li>if <code>typedefName</code> equals null</li>
823 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
824 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
825 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
826 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
828 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
829 BindingMapping.getClassName(typedef.getQName())));
830 genTOBuilder.setSchemaPath(typedef.getPath());
831 genTOBuilder.setModuleName(moduleName);
832 genTOBuilder.setTypedef(true);
833 addCodegenInformation(genTOBuilder, typedef);
835 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
836 genTOBuilder.setRestrictions(r);
837 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
839 if (typedef.getStatus() == Status.DEPRECATED) {
840 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
843 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
844 genTOBuilder.setIsUnion(true);
847 Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
848 Map<String, GeneratedType> typeMap = null;
849 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
850 if (parentModule != null) {
851 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
852 typeMap = modulesByDate.get(parentModule.getRevision());
855 if (typeMap != null) {
856 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
857 final GeneratedType type = typeMap.get(innerTypeDef);
858 if (type instanceof GeneratedTransferObject) {
859 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
862 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
863 makeSerializable(genTOBuilder);
865 return genTOBuilder.build();
869 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
872 * @param gto transfer object which needs to be made serializable
874 private static void makeSerializable(final GeneratedTOBuilder gto) {
875 gto.addImplementsType(Types.serializableType());
876 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
877 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
882 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
883 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
884 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
885 * type definitions are in the list behind all type definitions on which depends.
887 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
888 * @return list of type definitions sorted according their each other dependencies (type definitions which are
889 * dependent on other type definitions are in list behind them).
891 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
892 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
893 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
895 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
896 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
897 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
898 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
899 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
900 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
903 // SortedMap guarantees order corresponding to keys in ascending order
904 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
905 sortedTypeDefinition.addAll(v);
908 return sortedTypeDefinition;
912 * Returns how many immersion is necessary to get from the type definition to the base type.
914 * @param typeDefinition type definition for which is depth sought.
915 * @return number of immersions which are necessary to get from the type definition to the base type
917 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
918 // FIXME: rewrite this in a non-recursive manner
919 if (typeDefinition == null) {
922 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
923 if (baseType == null) {
928 if (baseType.getBaseType() != null) {
929 depth = depth + getTypeDefinitionDepth(baseType);
930 } else if (baseType instanceof UnionTypeDefinition) {
931 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
932 int maxChildDepth = 0;
934 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
935 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
936 if (childDepth > maxChildDepth) {
937 maxChildDepth = childDepth;
940 return maxChildDepth;
946 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
947 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
948 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
950 * @param name string with name of augmented node
951 * @return string with the number suffix incremented by one (or 1 is added)
953 private static String provideAvailableNameForGenTOBuilder(final String name) {
954 final int dollar = name.indexOf('$');
959 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
960 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
961 return name.substring(0, dollar + 1) + newSuffix;
964 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
965 if (!Strings.isNullOrEmpty(units)) {
966 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
967 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
968 prop.setReturnType(Types.STRING);
969 to.addToStringProperty(prop);
974 * Returns parent Yang Module for specified Schema Context in which Schema
975 * Node is declared. If the Schema Node is not present in Schema Context the
976 * operation will return <code>null</code>.
978 * @param context Schema Context
979 * @param schemaNode Schema Node
980 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
981 * return <code>null</code>
982 * @throws NullPointerException if any of the arguments is null
984 private static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
985 return context.findModule(schemaNode.getQName().getModule()).orElse(null);