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.ri.BindingTypes.TYPE_OBJECT;
13 import com.google.common.base.CharMatcher;
14 import com.google.common.base.Preconditions;
15 import com.google.common.base.Strings;
16 import com.google.common.collect.ImmutableMap;
17 import com.google.common.collect.Iterables;
18 import java.util.ArrayList;
19 import java.util.Collection;
20 import java.util.Collections;
21 import java.util.HashMap;
22 import java.util.HashSet;
23 import java.util.Iterator;
24 import java.util.List;
26 import java.util.Optional;
28 import java.util.TreeMap;
29 import org.opendaylight.mdsal.binding.generator.BindingGeneratorUtil;
30 import org.opendaylight.mdsal.binding.generator.impl.reactor.SerialVersionHelper;
31 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
32 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
33 import org.opendaylight.mdsal.binding.model.api.Enumeration;
34 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
35 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
36 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
37 import org.opendaylight.mdsal.binding.model.api.Restrictions;
38 import org.opendaylight.mdsal.binding.model.api.Type;
39 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
40 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
41 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
42 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
43 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
44 import org.opendaylight.mdsal.binding.model.ri.BaseYangTypes;
45 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
46 import org.opendaylight.mdsal.binding.model.ri.TypeConstants;
47 import org.opendaylight.mdsal.binding.model.ri.Types;
48 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.AbstractEnumerationBuilder;
49 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.GeneratedPropertyBuilderImpl;
50 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.common.Revision;
53 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
54 import org.opendaylight.yangtools.yang.model.api.Module;
55 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
56 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
58 import org.opendaylight.yangtools.yang.model.api.Status;
59 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
60 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
62 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
66 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
67 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
70 // FIXME: remove this class
71 @Deprecated(forRemoval = true)
72 abstract class AbstractTypeProvider {
73 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
74 private static final CharMatcher DASH_COLON_MATCHER = CharMatcher.anyOf("-:");
77 * Contains the schema data red from YANG files.
79 private final SchemaContext schemaContext;
81 private final Map<String, Map<Optional<Revision>, Map<String, GeneratedType>>> genTypeDefsContextMap =
83 private final Map<Module, Set<GeneratedType>> additionalTypes = new HashMap<>();
86 * Creates new instance of class <code>TypeProviderImpl</code>.
88 * @param schemaContext contains the schema data red from YANG files
89 * @param renames renaming table
90 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
92 AbstractTypeProvider(final EffectiveModelContext schemaContext) {
93 this.schemaContext = requireNonNull(schemaContext);
95 resolveTypeDefsFromContext();
99 * Resolve of YANG Type Definition to it's java counter part. If the Type Definition contains one of YANG primitive
100 * types the method will return {@code java.lang.} counterpart. (For example if YANG type is int32 the Java
101 * counterpart is {@link Integer}). In case that Type Definition contains extended type defined via YANG typedef
102 * statement the method SHOULD return Generated Type or Generated Transfer Object if that Type is correctly
103 * referenced to resolved imported YANG module.
106 * The method will return <code>null</code> value in situations that TypeDefinition can't be resolved (either due
107 * to missing YANG import or incorrectly specified type).
110 * {@code leafref} resolution for relative paths has two models of operation: lenient and strict. This is needed to
111 * handle the case where a grouping leaf's path points outside of the grouping tree. In such a case we cannot
112 * completely determine the correct type and need to fallback to {@link Object}.
114 * @param type Type Definition to resolve from
115 * @param lenientRelativeLeafrefs treat relative leafrefs leniently
116 * @return Resolved Type
118 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> type, final SchemaNode parentNode) {
119 return javaTypeForSchemaDefinitionType(type, parentNode, null);
123 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
125 * @param typeDefinition type definition which is converted to JAVA type
126 * @throws IllegalArgumentException
128 * <li>if <code>typeDefinition</code> equal null</li>
129 * <li>if Qname of <code>typeDefinition</code> equal null</li>
130 * <li>if name of <code>typeDefinition</code> equal null</li>
133 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
134 final Restrictions restrictions) {
135 throw new UnsupportedOperationException();
139 * Gets base type definition for <code>extendTypeDef</code>. The method is
140 * recursively called until non <code>ExtendedType</code> type is found.
142 * @param extendTypeDef
143 * type definition for which is the base type definition sought
144 * @return type definition which is base type for <code>extendTypeDef</code>
145 * @throws IllegalArgumentException
146 * if <code>extendTypeDef</code> equal null
148 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
149 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
151 TypeDefinition<?> ret = extendTypeDef;
152 while (ret.getBaseType() != null) {
153 ret = ret.getBaseType();
160 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
162 * @param enumTypeDef enumeration type definition which is converted to enumeration
163 * @param enumName string with name which is used as the enumeration name
164 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
165 * @throws IllegalArgumentException
167 * <li>if <code>enumTypeDef</code> equals null</li>
168 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
169 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
170 * <li>if name of <code>enumTypeDef</code> equal null</li>
173 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
174 final SchemaNode parentNode) {
175 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
176 Preconditions.checkArgument(enumTypeDef.getValues() != null,
177 "EnumTypeDefinition MUST contain at least ONE value definition!");
178 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
179 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
180 "Local Name in EnumTypeDefinition QName cannot be NULL!");
182 final Module module = findParentModule(schemaContext, parentNode);
183 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
184 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
185 addEnumDescription(enumBuilder, enumTypeDef);
186 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
187 enumBuilder.setModuleName(module.getName());
188 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
189 return enumBuilder.toInstance();
193 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
195 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
196 * @param enumName string with the name of enumeration
197 * @param typeBuilder generated type builder to which is enumeration added
198 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
199 * @throws IllegalArgumentException
201 * <li>if <code>enumTypeDef</code> equals null</li>
202 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
203 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
204 * <li>if name of <code>enumTypeDef</code> equal null</li>
205 * <li>if name of <code>typeBuilder</code> equal null</li>
209 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
210 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
211 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
212 Preconditions.checkArgument(enumTypeDef.getValues() != null,
213 "EnumTypeDefinition MUST contain at least ONE value definition!");
214 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
215 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
216 "Local Name in EnumTypeDefinition QName cannot be NULL!");
217 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
219 final EnumBuilder enumBuilder = newEnumerationBuilder(
220 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(enumName), "$"));
221 addEnumDescription(enumBuilder, enumTypeDef);
222 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
223 final Enumeration ret = enumBuilder.toInstance();
224 typeBuilder.addEnumeration(ret);
229 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
231 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
233 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
236 * Converts the pattern constraints to the list of the strings which represents these constraints.
238 * @param patternConstraints list of pattern constraints
239 * @return list of strings which represents the constraint patterns
241 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
243 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
246 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
249 * @param typedef extended type in which are the pattern constraints sought
250 * @return list of strings which represents the constraint patterns
251 * @throws IllegalArgumentException if <code>typedef</code> equals null
254 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
255 if (!(typedef instanceof StringTypeDefinition)) {
256 return ImmutableMap.of();
259 // TODO: run diff against base ?
260 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
264 * Passes through all modules and through all its type definitions and convert it to generated types.
267 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
268 * of a module are at the beginning sorted so that type definition with less amount of references to other type
269 * definition are processed first.<br>
270 * For each module is created mapping record in the map
271 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
272 * which map current module name to the map which maps type names to returned types (generated types).
274 private void resolveTypeDefsFromContext() {
275 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
277 for (Module module : modulesSortedByDependency) {
278 Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
279 module.getName(), key -> new HashMap<>());
280 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
281 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
284 for (Module module : modulesSortedByDependency) {
285 if (module != null) {
286 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
287 if (basePackageName != null) {
288 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
289 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
290 typedefToGeneratedType(basePackageName, module, typedef);
298 * Create Type for specified type definition.
300 * @param basePackageName string with name of package to which the module belongs
301 * @param module string with the name of the module for to which the <code>typedef</code> belongs
302 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
303 * (usually generated TO)
304 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
305 * <code>null</code> value if <code>basePackageName</code> or
306 * <code>modulName</code> or <code>typedef</code> or Q name of
307 * <code>typedef</code> equals <code>null</code>
309 private Type typedefToGeneratedType(final String basePackageName, final Module module,
310 final TypeDefinition<?> typedef) {
311 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
313 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
314 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
318 final String typedefName = typedef.getQName().getLocalName();
320 final GeneratedType returnType;
321 if (baseTypedef.getBaseType() != null) {
322 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
324 } else if (baseTypedef instanceof UnionTypeDefinition) {
325 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
326 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
327 (UnionTypeDefinition) baseTypedef, typedef);
328 genTOBuilder.setTypedef(true);
329 genTOBuilder.setIsUnion(true);
330 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
331 makeSerializable(genTOBuilder);
332 returnType = genTOBuilder.build();
334 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
335 // so we are placing the builder alongside the union.
336 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(JavaTypeName.create(
337 genTOBuilder.getPackageName(), genTOBuilder.getName() + BindingMapping.BUILDER_SUFFIX));
338 unionBuilder.setIsUnionBuilder(true);
339 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
340 method.setReturnType(returnType);
341 method.addParameter(Types.STRING, "defaultValue");
342 method.setAccessModifier(AccessModifier.PUBLIC);
343 method.setStatic(true);
344 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
345 } else if (baseTypedef instanceof EnumTypeDefinition) {
346 // enums are automatically Serializable
347 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
348 // TODO units for typedef enum
349 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
350 } else if (baseTypedef instanceof BitsTypeDefinition) {
351 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
352 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
353 (BitsTypeDefinition) baseTypedef, module.getName());
354 genTOBuilder.setTypedef(true);
355 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
356 makeSerializable(genTOBuilder);
357 returnType = genTOBuilder.build();
359 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
360 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
362 if (returnType != null) {
363 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
364 genTypeDefsContextMap.get(module.getName());
365 final Optional<Revision> moduleRevision = module.getRevision();
366 Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
367 if (typeMap != null) {
368 if (typeMap.isEmpty()) {
369 typeMap = new HashMap<>(4);
370 modulesByDate.put(moduleRevision, typeMap);
372 typeMap.put(typedefName, returnType);
380 * Wraps base YANG type to generated TO.
382 * @param basePackageName string with name of package to which the module belongs
383 * @param typedef type definition which is converted to the TO
384 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
385 * @return generated transfer object which represent<code>javaType</code>
387 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
388 final Type javaType, final String moduleName) {
389 requireNonNull(javaType, "javaType cannot be null");
391 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
392 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
393 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
394 genPropBuilder.setReturnType(javaType);
396 genTOBuilder.addEqualsIdentity(genPropBuilder);
397 genTOBuilder.addHashIdentity(genPropBuilder);
398 genTOBuilder.addToStringProperty(genPropBuilder);
399 genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
400 if (typedef.getStatus() == Status.DEPRECATED) {
401 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
403 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
404 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
406 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
407 genTOBuilder.setTypedef(true);
408 makeSerializable(genTOBuilder);
409 return genTOBuilder.build();
413 * Converts output list of generated TO builders to one TO builder (first
414 * from list) which contains the remaining builders as its enclosing TO.
416 * @param typeName new type identifier
417 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
418 * @return generated TO builder with the list of enclosed generated TO builders
420 private GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
421 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
422 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
424 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
426 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
427 builders.forEach(builder -> resultTOBuilder.addEnclosingTransferObject(builder.build()));
428 return resultTOBuilder;
432 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
433 * <code>typedef</code> is added to generated TO builder as property.
435 * @param typeName new type identifier
436 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
437 * @return generated TO builder which represents <code>typedef</code>
438 * @throws NullPointerException
440 * <li>if <code>basePackageName</code> is null</li>
441 * <li>if <code>typedef</code> is null</li>
442 * <li>if Qname of <code>typedef</code> is null</li>
445 private List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
446 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
447 requireNonNull(typedef, "Type Definition cannot be NULL!");
448 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
450 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
451 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
452 final Module module = findParentModule(schemaContext, parentNode);
454 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
455 unionGenTOBuilder.setIsUnion(true);
456 unionGenTOBuilder.setSchemaPath(typedef.getPath());
457 unionGenTOBuilder.setModuleName(module.getName());
458 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
459 addCodegenInformation(unionGenTOBuilder, typedef);
460 generatedTOBuilders.add(unionGenTOBuilder);
462 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
463 // also negation information and hence guarantees uniqueness.
464 final Map<String, String> expressions = new HashMap<>();
465 for (TypeDefinition<?> unionType : unionTypes) {
466 final String unionTypeName = unionType.getQName().getLocalName();
468 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
469 // do not follow type encapsulation -- we use the general case for that.
470 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
471 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
472 } else if (unionType instanceof UnionTypeDefinition) {
473 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
474 (UnionTypeDefinition) unionType, parentNode));
475 } else if (unionType instanceof EnumTypeDefinition) {
476 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
477 unionTypeName, unionGenTOBuilder);
478 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
480 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
481 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
484 addStringRegExAsConstant(unionGenTOBuilder, expressions);
486 storeGenTO(typedef, unionGenTOBuilder, parentNode);
488 return generatedTOBuilders;
492 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
495 * In this case the new generated TO is created for union subtype (recursive call of method
496 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
497 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
498 * created property which type is equal to new generated TO.
500 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
501 * @param basePackageName string with the name of the module package
502 * @param unionSubtype type definition which represents union subtype
503 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
504 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
506 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
507 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
508 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
509 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
510 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
511 newTOBuilderName, unionSubtype, parentNode);
513 final GeneratedPropertyBuilder propertyBuilder;
514 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
515 newTOBuilderName.simpleName()));
516 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
517 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
518 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
520 return subUnionGenTOBUilders;
524 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
525 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
526 * the base type is used for the property creation.
528 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
529 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
530 * @param expressions list of strings with the regular expressions
531 * @param parentNode parent Schema Node for Extended Subtype
533 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
534 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
535 final String unionTypeName = unionSubtype.getQName().getLocalName();
536 final Type genTO = findGenTO(unionTypeName, unionSubtype);
538 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
542 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
543 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
544 final Type javaType = baseJavaTypeForSchema(baseType, parentNode,
545 BindingGeneratorUtil.getRestrictions(unionSubtype));
546 if (javaType != null) {
547 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
549 } else if (baseType instanceof LeafrefTypeDefinition) {
550 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
551 boolean typeExist = false;
552 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
553 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
554 if (origType != null && javaType != null && javaType == origType) {
559 if (!typeExist && javaType != null) {
560 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
561 BindingMapping.getUnionLeafrefMemberName(parentUnionGenTOBuilder.getName(), javaType.getName()));
564 if (baseType instanceof StringTypeDefinition) {
565 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
569 private static Type baseJavaTypeForSchema(final TypeDefinition<?> type, final SchemaNode parentNode,
570 final Restrictions restrictions) {
571 final String typeName = type.getQName().getLocalName();
572 final Type mapped = BaseYangTypes.javaTypeForYangType(typeName);
573 return mapped == null || restrictions == null ? mapped : Types.restrictedType(mapped, restrictions);
577 * Searches for generated TO for <code>searchedTypeDef</code> type definition
578 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
580 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
581 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
583 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
584 final Module typeModule = findParentModule(schemaContext, parentNode);
585 if (typeModule != null && typeModule.getName() != null) {
586 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
587 typeModule.getName());
588 final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
589 if (genTOs != null) {
590 return genTOs.get(searchedTypeName);
597 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
598 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
600 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
601 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
603 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
604 final SchemaNode parentNode) {
605 if (!(newTypeDef instanceof UnionTypeDefinition)) {
606 final Module parentModule = findParentModule(schemaContext, parentNode);
607 if (parentModule != null && parentModule.getName() != null) {
608 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
609 parentModule.getName());
610 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
611 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
617 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
618 * to <code>unonGenTransObject</code>.
620 * @param unionGenTransObject generated TO to which should be property added
621 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
622 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
624 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
625 final String propertyName) {
626 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
627 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
628 .addProperty(BindingMapping.getPropertyName(propertyName));
629 propBuilder.setReturnType(type);
631 unionGenTransObject.addEqualsIdentity(propBuilder);
632 unionGenTransObject.addHashIdentity(propBuilder);
633 unionGenTransObject.addToStringProperty(propBuilder);
638 * Converts <code>typedef</code> to the generated TO builder.
640 * @param basePackageName string with name of package to which the module belongs
641 * @param typedef type definition from which is the generated TO builder created
642 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
644 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
645 final TypeDefinition<?> typedef, final String moduleName) {
646 final JavaTypeName name = JavaTypeName.create(
647 packageNameForGeneratedType(basePackageName, typedef.getPath()),
648 BindingMapping.getClassName(typedef.getQName().getLocalName()));
650 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
651 newType.setSchemaPath(typedef.getPath());
652 newType.setModuleName(moduleName);
653 addCodegenInformation(newType, typedef);
658 * Creates package name from specified <code>basePackageName</code> (package name for module)
659 * and <code>schemaPath</code>. Resulting package name is concatenation of <code>basePackageName</code>
660 * and all local names of YANG nodes which are parents of some node for which <code>schemaPath</code> is specified.
662 * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
663 * return an invalid string.
664 * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
665 * @return string with valid JAVA package name
666 * @throws NullPointerException if any of the arguments are null
668 private static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath) {
669 final int size = Iterables.size(schemaPath.getPathTowardsRoot()) - 1;
671 return basePackageName;
674 return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
677 private static String generateNormalizedPackageName(final String base, final Iterable<QName> path, final int size) {
678 final StringBuilder builder = new StringBuilder(base);
679 final Iterator<QName> iterator = path.iterator();
680 for (int i = 0; i < size; ++i) {
682 final String nodeLocalName = iterator.next().getLocalName();
683 // FIXME: Collon ":" is invalid in node local name as per RFC6020, identifier statement.
684 builder.append(DASH_COLON_MATCHER.replaceFrom(nodeLocalName, '.'));
686 return BindingMapping.normalizePackageName(builder.toString());
690 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
691 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
694 * @param typeName new type identifier
695 * @param typeDef type definition from which is the generated TO builder created
696 * @return generated TO builder which represents <code>typeDef</code>
697 * @throws IllegalArgumentException
699 * <li>if <code>typeDef</code> equals null</li>
700 * <li>if <code>basePackageName</code> equals null</li>
703 private GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
704 final BitsTypeDefinition typeDef, final String moduleName) {
705 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
706 genTOBuilder.setSchemaPath(typeDef.getPath());
707 genTOBuilder.setModuleName(moduleName);
708 genTOBuilder.setBaseType(typeDef);
709 genTOBuilder.addImplementsType(TYPE_OBJECT);
710 addCodegenInformation(genTOBuilder, typeDef);
712 for (Bit bit : typeDef.getBits()) {
713 final String name = bit.getName();
714 GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
715 BindingMapping.getPropertyName(name));
716 genPropertyBuilder.setReadOnly(true);
717 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
719 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
720 genTOBuilder.addHashIdentity(genPropertyBuilder);
721 genTOBuilder.addToStringProperty(genPropertyBuilder);
728 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
729 * the <code>regularExpressions</code>.
731 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
732 * @param expressions list of string which represent regular expressions
734 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
735 final Map<String, String> expressions) {
736 if (!expressions.isEmpty()) {
737 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
738 ImmutableMap.copyOf(expressions));
743 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
744 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
747 * It is assumed that <code>innerExtendedType</code> is already present in
748 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
749 * for the returning generated TO.
751 * @param typedef Type Definition
752 * @param innerExtendedType extended type which is part of some other extended type
753 * @param basePackageName string with the package name of the module
754 * @param moduleName Module Name
755 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
756 * @throws IllegalArgumentException
758 * <li>if <code>extendedType</code> equals null</li>
759 * <li>if <code>basePackageName</code> equals null</li>
760 * <li>if <code>typedefName</code> equals null</li>
763 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
764 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
765 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
766 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
768 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
769 BindingMapping.getClassName(typedef.getQName())));
770 genTOBuilder.setSchemaPath(typedef.getPath());
771 genTOBuilder.setModuleName(moduleName);
772 genTOBuilder.setTypedef(true);
773 addCodegenInformation(genTOBuilder, typedef);
775 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
776 genTOBuilder.setRestrictions(r);
777 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
779 if (typedef.getStatus() == Status.DEPRECATED) {
780 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
783 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
784 genTOBuilder.setIsUnion(true);
787 Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
788 Map<String, GeneratedType> typeMap = null;
789 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
790 if (parentModule != null) {
791 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
792 typeMap = modulesByDate.get(parentModule.getRevision());
795 if (typeMap != null) {
796 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
797 final GeneratedType type = typeMap.get(innerTypeDef);
798 if (type instanceof GeneratedTransferObject) {
799 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
802 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
803 makeSerializable(genTOBuilder);
805 return genTOBuilder.build();
809 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
812 * @param gto transfer object which needs to be made serializable
814 private static void makeSerializable(final GeneratedTOBuilder gto) {
815 gto.addImplementsType(Types.serializableType());
816 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
817 prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
822 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
823 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
824 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
825 * type definitions are in the list behind all type definitions on which depends.
827 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
828 * @return list of type definitions sorted according their each other dependencies (type definitions which are
829 * dependent on other type definitions are in list behind them).
831 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
832 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
833 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
835 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
836 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
837 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
838 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
839 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
840 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
843 // SortedMap guarantees order corresponding to keys in ascending order
844 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
845 sortedTypeDefinition.addAll(v);
848 return sortedTypeDefinition;
852 * Returns how many immersion is necessary to get from the type definition to the base type.
854 * @param typeDefinition type definition for which is depth sought.
855 * @return number of immersions which are necessary to get from the type definition to the base type
857 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
858 // FIXME: rewrite this in a non-recursive manner
859 if (typeDefinition == null) {
862 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
863 if (baseType == null) {
868 if (baseType.getBaseType() != null) {
869 depth = depth + getTypeDefinitionDepth(baseType);
870 } else if (baseType instanceof UnionTypeDefinition) {
871 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
872 int maxChildDepth = 0;
874 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
875 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
876 if (childDepth > maxChildDepth) {
877 maxChildDepth = childDepth;
880 return maxChildDepth;
886 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
887 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
888 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
890 * @param name string with name of augmented node
891 * @return string with the number suffix incremented by one (or 1 is added)
893 private static String provideAvailableNameForGenTOBuilder(final String name) {
894 final int dollar = name.indexOf('$');
899 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
900 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
901 return name.substring(0, dollar + 1) + newSuffix;
904 private static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
905 if (!Strings.isNullOrEmpty(units)) {
906 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
907 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
908 prop.setReturnType(Types.STRING);
909 to.addToStringProperty(prop);
914 * Returns parent Yang Module for specified Schema Context in which Schema
915 * Node is declared. If the Schema Node is not present in Schema Context the
916 * operation will return <code>null</code>.
918 * @param context Schema Context
919 * @param schemaNode Schema Node
920 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
921 * return <code>null</code>
922 * @throws NullPointerException if any of the arguments is null
924 private static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
925 return context.findModule(schemaNode.getQName().getModule()).orElse(null);