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.GeneratedTypeBuilder;
43 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
45 import org.opendaylight.mdsal.binding.model.ri.BaseYangTypes;
46 import org.opendaylight.mdsal.binding.model.ri.BindingTypes;
47 import org.opendaylight.mdsal.binding.model.ri.TypeConstants;
48 import org.opendaylight.mdsal.binding.model.ri.Types;
49 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.AbstractEnumerationBuilder;
50 import org.opendaylight.mdsal.binding.model.ri.generated.type.builder.GeneratedPropertyBuilderImpl;
51 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
52 import org.opendaylight.yangtools.yang.common.QName;
53 import org.opendaylight.yangtools.yang.common.Revision;
54 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
55 import org.opendaylight.yangtools.yang.model.api.Module;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
59 import org.opendaylight.yangtools.yang.model.api.Status;
60 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
63 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
67 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
68 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
69 import org.opendaylight.yangtools.yang.model.spi.ModuleDependencySort;
71 // FIXME: remove this class
72 @Deprecated(forRemoval = true)
73 abstract class AbstractTypeProvider implements TypeProvider {
74 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
75 private static final CharMatcher DASH_COLON_MATCHER = CharMatcher.anyOf("-:");
78 * Contains the schema data red from YANG files.
80 private final SchemaContext schemaContext;
82 private final Map<String, Map<Optional<Revision>, Map<String, GeneratedType>>> genTypeDefsContextMap =
86 * The map which maps schema paths to JAVA <code>Type</code>.
88 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
89 private final Map<Module, Set<GeneratedType>> additionalTypes = new HashMap<>();
92 * Creates new instance of class <code>TypeProviderImpl</code>.
94 * @param schemaContext contains the schema data red from YANG files
95 * @param renames renaming table
96 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
98 AbstractTypeProvider(final EffectiveModelContext schemaContext) {
99 this.schemaContext = requireNonNull(schemaContext);
101 resolveTypeDefsFromContext();
105 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
107 * @param refTypePath schema path used as the map key
108 * @param refType type which represents the map value
109 * @throws IllegalArgumentException
111 * <li>if <code>refTypePath</code> equal null</li>
112 * <li>if <code>refType</code> equal null</li>
116 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
117 Preconditions.checkArgument(refTypePath != null,
118 "Path reference of Enumeration Type Definition cannot be NULL!");
119 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
120 referencedTypes.put(refTypePath, refType);
123 public Map<Module, Set<GeneratedType>> getAdditionalTypes() {
124 return additionalTypes;
128 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
129 final boolean lenientRelativeLeafrefs) {
130 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
134 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
136 * @param typeDefinition type definition which is converted to JAVA type
137 * @throws IllegalArgumentException
139 * <li>if <code>typeDefinition</code> equal null</li>
140 * <li>if Qname of <code>typeDefinition</code> equal null</li>
141 * <li>if name of <code>typeDefinition</code> equal null</li>
145 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
146 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
147 throw new UnsupportedOperationException();
151 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
153 * @param typeDefinition
154 * type definition which should be converted to JAVA
156 * @return JAVA <code>Type</code> which represents
157 * <code>typeDefinition</code>
158 * @throws IllegalArgumentException
160 * <li>if <code>typeDefinition</code> equal null</li>
161 * <li>if Q name of <code>typeDefinition</code></li>
162 * <li>if name of <code>typeDefinition</code></li>
165 public GeneratedType generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
166 final SchemaNode parentNode) {
167 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
168 if (typeDefinition.getQName() == null) {
169 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
171 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
172 "Type Definitions Local Name cannot be NULL!");
174 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
175 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
177 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
178 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
191 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
192 * dicey when we throw in:
206 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
207 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
210 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
211 * an encapsulation for identityref typedefs.
213 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
214 * option, as it would look as though it is the product of a different construct:
220 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
221 * sub-identities of iden.
223 * The story behind leafrefs is probably similar, but that needs to be ascertained.
228 final Module module = findParentModule(schemaContext, parentNode);
229 if (module != null) {
230 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
232 final Map<String, GeneratedType> genTOs = modulesByDate.get(module.getRevision());
233 if (genTOs != null) {
234 return genTOs.get(typeDefinition.getQName().getLocalName());
241 * Gets base type definition for <code>extendTypeDef</code>. The method is
242 * recursively called until non <code>ExtendedType</code> type is found.
244 * @param extendTypeDef
245 * type definition for which is the base type definition sought
246 * @return type definition which is base type for <code>extendTypeDef</code>
247 * @throws IllegalArgumentException
248 * if <code>extendTypeDef</code> equal null
250 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
251 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
253 TypeDefinition<?> ret = extendTypeDef;
254 while (ret.getBaseType() != null) {
255 ret = ret.getBaseType();
262 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
264 * @param enumTypeDef enumeration type definition which is converted to enumeration
265 * @param enumName string with name which is used as the enumeration name
266 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
267 * @throws IllegalArgumentException
269 * <li>if <code>enumTypeDef</code> equals null</li>
270 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
271 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
272 * <li>if name of <code>enumTypeDef</code> equal null</li>
275 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
276 final SchemaNode parentNode) {
277 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
278 Preconditions.checkArgument(enumTypeDef.getValues() != null,
279 "EnumTypeDefinition MUST contain at least ONE value definition!");
280 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
281 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
282 "Local Name in EnumTypeDefinition QName cannot be NULL!");
284 final Module module = findParentModule(schemaContext, parentNode);
285 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
286 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
287 addEnumDescription(enumBuilder, enumTypeDef);
288 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
289 enumBuilder.setModuleName(module.getName());
290 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
291 return enumBuilder.toInstance();
295 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
297 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
298 * @param enumName string with the name of enumeration
299 * @param typeBuilder generated type builder to which is enumeration added
300 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
301 * @throws IllegalArgumentException
303 * <li>if <code>enumTypeDef</code> equals null</li>
304 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
305 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
306 * <li>if name of <code>enumTypeDef</code> equal null</li>
307 * <li>if name of <code>typeBuilder</code> equal null</li>
311 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
312 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
313 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
314 Preconditions.checkArgument(enumTypeDef.getValues() != null,
315 "EnumTypeDefinition MUST contain at least ONE value definition!");
316 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
317 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
318 "Local Name in EnumTypeDefinition QName cannot be NULL!");
319 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
321 final EnumBuilder enumBuilder = newEnumerationBuilder(
322 typeBuilder.getIdentifier().createEnclosed(BindingMapping.getClassName(enumName), "$"));
323 addEnumDescription(enumBuilder, enumTypeDef);
324 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
325 final Enumeration ret = enumBuilder.toInstance();
326 typeBuilder.addEnumeration(ret);
331 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
333 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
335 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
337 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
340 * Converts the pattern constraints to the list of the strings which represents these constraints.
342 * @param patternConstraints list of pattern constraints
343 * @return list of strings which represents the constraint patterns
345 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
347 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
350 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
353 * @param typedef extended type in which are the pattern constraints sought
354 * @return list of strings which represents the constraint patterns
355 * @throws IllegalArgumentException if <code>typedef</code> equals null
358 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
359 if (!(typedef instanceof StringTypeDefinition)) {
360 return ImmutableMap.of();
363 // TODO: run diff against base ?
364 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
368 * Passes through all modules and through all its type definitions and convert it to generated types.
371 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
372 * of a module are at the beginning sorted so that type definition with less amount of references to other type
373 * definition are processed first.<br>
374 * For each module is created mapping record in the map
375 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
376 * which map current module name to the map which maps type names to returned types (generated types).
378 private void resolveTypeDefsFromContext() {
379 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
381 for (Module module : modulesSortedByDependency) {
382 Map<Optional<Revision>, Map<String, GeneratedType>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
383 module.getName(), key -> new HashMap<>());
384 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
385 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
388 for (Module module : modulesSortedByDependency) {
389 if (module != null) {
390 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
391 if (basePackageName != null) {
392 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
393 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
394 typedefToGeneratedType(basePackageName, module, typedef);
402 * Create Type for specified type definition.
404 * @param basePackageName string with name of package to which the module belongs
405 * @param module string with the name of the module for to which the <code>typedef</code> belongs
406 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
407 * (usually generated TO)
408 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
409 * <code>null</code> value if <code>basePackageName</code> or
410 * <code>modulName</code> or <code>typedef</code> or Q name of
411 * <code>typedef</code> equals <code>null</code>
413 private Type typedefToGeneratedType(final String basePackageName, final Module module,
414 final TypeDefinition<?> typedef) {
415 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
417 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
418 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
422 final String typedefName = typedef.getQName().getLocalName();
424 final GeneratedType returnType;
425 if (baseTypedef.getBaseType() != null) {
426 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
428 } else if (baseTypedef instanceof UnionTypeDefinition) {
429 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
430 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
431 (UnionTypeDefinition) baseTypedef, typedef);
432 genTOBuilder.setTypedef(true);
433 genTOBuilder.setIsUnion(true);
434 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
435 makeSerializable(genTOBuilder);
436 returnType = genTOBuilder.build();
438 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
439 // so we are placing the builder alongside the union.
440 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
441 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
442 unionBuilder.setIsUnionBuilder(true);
443 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
444 method.setReturnType(returnType);
445 method.addParameter(Types.STRING, "defaultValue");
446 method.setAccessModifier(AccessModifier.PUBLIC);
447 method.setStatic(true);
448 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
449 } else if (baseTypedef instanceof EnumTypeDefinition) {
450 // enums are automatically Serializable
451 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
452 // TODO units for typedef enum
453 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
454 } else if (baseTypedef instanceof BitsTypeDefinition) {
455 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
456 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
457 (BitsTypeDefinition) baseTypedef, module.getName());
458 genTOBuilder.setTypedef(true);
459 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
460 makeSerializable(genTOBuilder);
461 returnType = genTOBuilder.build();
463 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
464 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
466 if (returnType != null) {
467 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate =
468 genTypeDefsContextMap.get(module.getName());
469 final Optional<Revision> moduleRevision = module.getRevision();
470 Map<String, GeneratedType> typeMap = modulesByDate.get(moduleRevision);
471 if (typeMap != null) {
472 if (typeMap.isEmpty()) {
473 typeMap = new HashMap<>(4);
474 modulesByDate.put(moduleRevision, typeMap);
476 typeMap.put(typedefName, returnType);
484 * Wraps base YANG type to generated TO.
486 * @param basePackageName string with name of package to which the module belongs
487 * @param typedef type definition which is converted to the TO
488 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
489 * @return generated transfer object which represent<code>javaType</code>
491 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
492 final Type javaType, final String moduleName) {
493 requireNonNull(javaType, "javaType cannot be null");
495 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
496 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
497 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
498 genPropBuilder.setReturnType(javaType);
500 genTOBuilder.addEqualsIdentity(genPropBuilder);
501 genTOBuilder.addHashIdentity(genPropBuilder);
502 genTOBuilder.addToStringProperty(genPropBuilder);
503 genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
504 if (typedef.getStatus() == Status.DEPRECATED) {
505 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
507 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
508 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
510 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
511 genTOBuilder.setTypedef(true);
512 makeSerializable(genTOBuilder);
513 return genTOBuilder.build();
517 * Converts output list of generated TO builders to one TO builder (first
518 * from list) which contains the remaining builders as its enclosing TO.
520 * @param typeName new type identifier
521 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
522 * @return generated TO builder with the list of enclosed generated TO builders
524 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
525 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
526 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
528 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
530 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
531 builders.forEach(builder -> resultTOBuilder.addEnclosingTransferObject(builder.build()));
532 return resultTOBuilder;
536 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
537 * <code>typedef</code> is added to generated TO builder as property.
539 * @param typeName new type identifier
540 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
541 * @return generated TO builder which represents <code>typedef</code>
542 * @throws NullPointerException
544 * <li>if <code>basePackageName</code> is null</li>
545 * <li>if <code>typedef</code> is null</li>
546 * <li>if Qname of <code>typedef</code> is null</li>
549 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
550 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
551 requireNonNull(typedef, "Type Definition cannot be NULL!");
552 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
554 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
555 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
556 final Module module = findParentModule(schemaContext, parentNode);
558 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
559 unionGenTOBuilder.setIsUnion(true);
560 unionGenTOBuilder.setSchemaPath(typedef.getPath());
561 unionGenTOBuilder.setModuleName(module.getName());
562 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
563 addCodegenInformation(unionGenTOBuilder, typedef);
564 generatedTOBuilders.add(unionGenTOBuilder);
566 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
567 // also negation information and hence guarantees uniqueness.
568 final Map<String, String> expressions = new HashMap<>();
569 for (TypeDefinition<?> unionType : unionTypes) {
570 final String unionTypeName = unionType.getQName().getLocalName();
572 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
573 // do not follow type encapsulation -- we use the general case for that.
574 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
575 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
576 } else if (unionType instanceof UnionTypeDefinition) {
577 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
578 (UnionTypeDefinition) unionType, parentNode));
579 } else if (unionType instanceof EnumTypeDefinition) {
580 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
581 unionTypeName, unionGenTOBuilder);
582 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
584 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
585 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
588 addStringRegExAsConstant(unionGenTOBuilder, expressions);
590 storeGenTO(typedef, unionGenTOBuilder, parentNode);
592 return generatedTOBuilders;
596 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
599 * In this case the new generated TO is created for union subtype (recursive call of method
600 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
601 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
602 * created property which type is equal to new generated TO.
604 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
605 * @param basePackageName string with the name of the module package
606 * @param unionSubtype type definition which represents union subtype
607 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
608 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
610 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
611 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
612 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
613 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
614 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
615 newTOBuilderName, unionSubtype, parentNode);
617 final GeneratedPropertyBuilder propertyBuilder;
618 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
619 newTOBuilderName.simpleName()));
620 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
621 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
622 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
624 return subUnionGenTOBUilders;
628 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
629 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
630 * the base type is used for the property creation.
632 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
633 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
634 * @param expressions list of strings with the regular expressions
635 * @param parentNode parent Schema Node for Extended Subtype
637 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
638 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
639 final String unionTypeName = unionSubtype.getQName().getLocalName();
640 final Type genTO = findGenTO(unionTypeName, unionSubtype);
642 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
646 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
647 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
648 final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
649 BindingGeneratorUtil.getRestrictions(unionSubtype));
650 if (javaType != null) {
651 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
653 } else if (baseType instanceof LeafrefTypeDefinition) {
654 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
655 boolean typeExist = false;
656 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
657 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
658 if (origType != null && javaType != null && javaType == origType) {
663 if (!typeExist && javaType != null) {
664 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
665 BindingMapping.getUnionLeafrefMemberName(parentUnionGenTOBuilder.getName(), javaType.getName()));
668 if (baseType instanceof StringTypeDefinition) {
669 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
674 * Searches for generated TO for <code>searchedTypeDef</code> type definition
675 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
677 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
678 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
680 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
681 final Module typeModule = findParentModule(schemaContext, parentNode);
682 if (typeModule != null && typeModule.getName() != null) {
683 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
684 typeModule.getName());
685 final Map<String, GeneratedType> genTOs = modulesByDate.get(typeModule.getRevision());
686 if (genTOs != null) {
687 return genTOs.get(searchedTypeName);
694 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
695 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
697 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
698 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
700 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
701 final SchemaNode parentNode) {
702 if (!(newTypeDef instanceof UnionTypeDefinition)) {
703 final Module parentModule = findParentModule(schemaContext, parentNode);
704 if (parentModule != null && parentModule.getName() != null) {
705 final Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = genTypeDefsContextMap.get(
706 parentModule.getName());
707 final Map<String, GeneratedType> genTOsMap = modulesByDate.get(parentModule.getRevision());
708 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
714 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
715 * to <code>unonGenTransObject</code>.
717 * @param unionGenTransObject generated TO to which should be property added
718 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
719 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
721 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
722 final String propertyName) {
723 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
724 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
725 .addProperty(BindingMapping.getPropertyName(propertyName));
726 propBuilder.setReturnType(type);
728 unionGenTransObject.addEqualsIdentity(propBuilder);
729 unionGenTransObject.addHashIdentity(propBuilder);
730 unionGenTransObject.addToStringProperty(propBuilder);
735 * Converts <code>typedef</code> to the generated TO builder.
737 * @param basePackageName string with name of package to which the module belongs
738 * @param typedef type definition from which is the generated TO builder created
739 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
741 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
742 final TypeDefinition<?> typedef, final String moduleName) {
743 final JavaTypeName name = JavaTypeName.create(
744 packageNameForGeneratedType(basePackageName, typedef.getPath()),
745 BindingMapping.getClassName(typedef.getQName().getLocalName()));
747 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
748 newType.setSchemaPath(typedef.getPath());
749 newType.setModuleName(moduleName);
750 addCodegenInformation(newType, typedef);
755 * Creates package name from specified <code>basePackageName</code> (package name for module)
756 * and <code>schemaPath</code>. Resulting package name is concatenation of <code>basePackageName</code>
757 * and all local names of YANG nodes which are parents of some node for which <code>schemaPath</code> is specified.
759 * @param basePackageName string with package name of the module, MUST be normalized, otherwise this method may
760 * return an invalid string.
761 * @param schemaPath list of names of YANG nodes which are parents of some node + name of this node
762 * @return string with valid JAVA package name
763 * @throws NullPointerException if any of the arguments are null
765 private static String packageNameForGeneratedType(final String basePackageName, final SchemaPath schemaPath) {
766 final int size = Iterables.size(schemaPath.getPathTowardsRoot()) - 1;
768 return basePackageName;
771 return generateNormalizedPackageName(basePackageName, schemaPath.getPathFromRoot(), size);
774 private static String generateNormalizedPackageName(final String base, final Iterable<QName> path, final int size) {
775 final StringBuilder builder = new StringBuilder(base);
776 final Iterator<QName> iterator = path.iterator();
777 for (int i = 0; i < size; ++i) {
779 final String nodeLocalName = iterator.next().getLocalName();
780 // FIXME: Collon ":" is invalid in node local name as per RFC6020, identifier statement.
781 builder.append(DASH_COLON_MATCHER.replaceFrom(nodeLocalName, '.'));
783 return BindingMapping.normalizePackageName(builder.toString());
788 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
789 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
792 * @param typeName new type identifier
793 * @param typeDef type definition from which is the generated TO builder created
794 * @return generated TO builder which represents <code>typeDef</code>
795 * @throws IllegalArgumentException
797 * <li>if <code>typeDef</code> equals null</li>
798 * <li>if <code>basePackageName</code> equals null</li>
801 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
802 final BitsTypeDefinition typeDef, final String moduleName) {
803 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
804 genTOBuilder.setSchemaPath(typeDef.getPath());
805 genTOBuilder.setModuleName(moduleName);
806 genTOBuilder.setBaseType(typeDef);
807 genTOBuilder.addImplementsType(TYPE_OBJECT);
808 addCodegenInformation(genTOBuilder, typeDef);
810 for (Bit bit : typeDef.getBits()) {
811 final String name = bit.getName();
812 GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
813 BindingMapping.getPropertyName(name));
814 genPropertyBuilder.setReadOnly(true);
815 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
817 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
818 genTOBuilder.addHashIdentity(genPropertyBuilder);
819 genTOBuilder.addToStringProperty(genPropertyBuilder);
826 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
827 * the <code>regularExpressions</code>.
829 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
830 * @param expressions list of string which represent regular expressions
832 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
833 final Map<String, String> expressions) {
834 if (!expressions.isEmpty()) {
835 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
836 ImmutableMap.copyOf(expressions));
841 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
842 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
845 * It is assumed that <code>innerExtendedType</code> is already present in
846 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
847 * for the returning generated TO.
849 * @param typedef Type Definition
850 * @param innerExtendedType extended type which is part of some other extended type
851 * @param basePackageName string with the package name of the module
852 * @param moduleName Module Name
853 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
854 * @throws IllegalArgumentException
856 * <li>if <code>extendedType</code> equals null</li>
857 * <li>if <code>basePackageName</code> equals null</li>
858 * <li>if <code>typedefName</code> equals null</li>
861 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
862 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
863 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
864 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
866 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
867 BindingMapping.getClassName(typedef.getQName())));
868 genTOBuilder.setSchemaPath(typedef.getPath());
869 genTOBuilder.setModuleName(moduleName);
870 genTOBuilder.setTypedef(true);
871 addCodegenInformation(genTOBuilder, typedef);
873 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
874 genTOBuilder.setRestrictions(r);
875 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
877 if (typedef.getStatus() == Status.DEPRECATED) {
878 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
881 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
882 genTOBuilder.setIsUnion(true);
885 Map<Optional<Revision>, Map<String, GeneratedType>> modulesByDate = null;
886 Map<String, GeneratedType> typeMap = null;
887 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
888 if (parentModule != null) {
889 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
890 typeMap = modulesByDate.get(parentModule.getRevision());
893 if (typeMap != null) {
894 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
895 final GeneratedType type = typeMap.get(innerTypeDef);
896 if (type instanceof GeneratedTransferObject) {
897 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
900 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
901 makeSerializable(genTOBuilder);
903 return genTOBuilder.build();
907 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
910 * @param gto transfer object which needs to be made serializable
912 private static void makeSerializable(final GeneratedTOBuilder gto) {
913 gto.addImplementsType(Types.serializableType());
914 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
915 prop.setValue(Long.toString(SerialVersionHelper.computeDefaultSUID(gto)));
920 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
921 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
922 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
923 * type definitions are in the list behind all type definitions on which depends.
925 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
926 * @return list of type definitions sorted according their each other dependencies (type definitions which are
927 * dependent on other type definitions are in list behind them).
929 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
930 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
931 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
933 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
934 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
935 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
936 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
937 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
938 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
941 // SortedMap guarantees order corresponding to keys in ascending order
942 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
943 sortedTypeDefinition.addAll(v);
946 return sortedTypeDefinition;
950 * Returns how many immersion is necessary to get from the type definition to the base type.
952 * @param typeDefinition type definition for which is depth sought.
953 * @return number of immersions which are necessary to get from the type definition to the base type
955 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
956 // FIXME: rewrite this in a non-recursive manner
957 if (typeDefinition == null) {
960 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
961 if (baseType == null) {
966 if (baseType.getBaseType() != null) {
967 depth = depth + getTypeDefinitionDepth(baseType);
968 } else if (baseType instanceof UnionTypeDefinition) {
969 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
970 int maxChildDepth = 0;
972 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
973 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
974 if (childDepth > maxChildDepth) {
975 maxChildDepth = childDepth;
978 return maxChildDepth;
984 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
985 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
986 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
988 * @param name string with name of augmented node
989 * @return string with the number suffix incremented by one (or 1 is added)
991 private static String provideAvailableNameForGenTOBuilder(final String name) {
992 final int dollar = name.indexOf('$');
997 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
998 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
999 return name.substring(0, dollar + 1) + newSuffix;
1002 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1003 if (!Strings.isNullOrEmpty(units)) {
1004 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1005 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1006 prop.setReturnType(Types.STRING);
1007 to.addToStringProperty(prop);
1012 * Returns parent Yang Module for specified Schema Context in which Schema
1013 * Node is declared. If the Schema Node is not present in Schema Context the
1014 * operation will return <code>null</code>.
1016 * @param context Schema Context
1017 * @param schemaNode Schema Node
1018 * @return Yang Module for specified Schema Context and Schema Node, if Schema Node is NOT present, the method will
1019 * return <code>null</code>
1020 * @throws NullPointerException if any of the arguments is null
1022 private static Module findParentModule(final SchemaContext context, final SchemaNode schemaNode) {
1023 return context.findModule(schemaNode.getQName().getModule()).orElse(null);