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;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.Preconditions;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.ImmutableMap;
20 import java.math.BigDecimal;
21 import java.math.BigInteger;
22 import java.util.ArrayList;
23 import java.util.Base64;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Optional;
34 import java.util.TreeMap;
35 import java.util.regex.Pattern;
36 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
37 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
38 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
39 import org.opendaylight.mdsal.binding.model.api.Enumeration;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
42 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
43 import org.opendaylight.mdsal.binding.model.api.Restrictions;
44 import org.opendaylight.mdsal.binding.model.api.Type;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
51 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
52 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
53 import org.opendaylight.mdsal.binding.model.util.Types;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
55 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
56 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.Revision;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.Module;
65 import org.opendaylight.yangtools.yang.model.api.PathExpression;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.opendaylight.yangtools.yang.model.api.Status;
70 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
74 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
82 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
85 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
86 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
87 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
88 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 public abstract class AbstractTypeProvider implements TypeProvider {
94 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
95 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
97 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
98 // the case, as unions are emitted to their correct schema path.
99 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
100 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
103 * Contains the schema data red from YANG files.
105 private final SchemaContext schemaContext;
107 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
110 * The map which maps schema paths to JAVA <code>Type</code>.
112 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
113 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
114 private final Map<SchemaNode, JavaTypeName> renames;
117 * Creates new instance of class <code>TypeProviderImpl</code>.
119 * @param schemaContext contains the schema data red from YANG files
120 * @param renames renaming table
121 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
123 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
124 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
125 this.schemaContext = schemaContext;
126 this.renames = requireNonNull(renames);
127 resolveTypeDefsFromContext();
131 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
133 * @param refTypePath schema path used as the map key
134 * @param refType type which represents the map value
135 * @throws IllegalArgumentException
137 * <li>if <code>refTypePath</code> equal null</li>
138 * <li>if <code>refType</code> equal null</li>
142 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
143 Preconditions.checkArgument(refTypePath != null,
144 "Path reference of Enumeration Type Definition cannot be NULL!");
145 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
146 referencedTypes.put(refTypePath, refType);
149 public Map<Module, Set<Type>> getAdditionalTypes() {
150 return additionalTypes;
154 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
155 final boolean lenientRelativeLeafrefs) {
156 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
160 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
162 * @param typeDefinition type definition which is converted to JAVA type
163 * @throws IllegalArgumentException
165 * <li>if <code>typeDefinition</code> equal null</li>
166 * <li>if Qname of <code>typeDefinition</code> equal null</li>
167 * <li>if name of <code>typeDefinition</code> equal null</li>
171 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
172 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
173 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
174 Preconditions.checkArgument(typeDefinition.getQName() != null,
175 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
176 final String typedefName = typeDefinition.getQName().getLocalName();
177 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
179 // Deal with base types
180 if (typeDefinition.getBaseType() == null) {
181 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
182 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
183 // a base type which holds these constraints.
184 if (typeDefinition instanceof DecimalTypeDefinition) {
185 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
186 parentNode, restrictions, lenientRelativeLeafrefs);
192 // Deal with leafrefs/identityrefs
193 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
198 // FIXME: it looks as though we could be using the same codepath as above...
199 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
201 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
207 Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
208 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
209 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
210 final Module module = findParentModule(schemaContext, parentNode);
211 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
212 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
213 typeDefinition.getPath());
214 final String genTOName = BindingMapping.getClassName(typedefName);
215 final String name = packageName + "." + genTOName;
216 if (!returnType.getFullyQualifiedName().equals(name)) {
217 returnType = shadedTOWithRestrictions(gto, restrictions);
223 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
224 final Restrictions restrictions) {
225 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
226 final GeneratedTransferObject parent = gto.getSuperType();
227 if (parent != null) {
228 gtob.setExtendsType(parent);
230 gtob.setRestrictions(restrictions);
231 for (GeneratedProperty gp : gto.getProperties()) {
232 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
233 gpb.setValue(gp.getValue());
234 gpb.setReadOnly(gp.isReadOnly());
235 gpb.setAccessModifier(gp.getAccessModifier());
236 gpb.setReturnType(gp.getReturnType());
237 gpb.setFinal(gp.isFinal());
238 gpb.setStatic(gp.isStatic());
243 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
245 * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
248 DataNodeContainer current = null;
249 DataSchemaNode dataChildByName;
250 for (QName next : parentNode.getPath().getPathFromRoot()) {
251 if (current == null) {
252 dataChildByName = schemaContext.getDataChildByName(next);
254 dataChildByName = current.getDataChildByName(next);
256 if (dataChildByName == null) {
259 if (dataChildByName.isAugmenting()) {
262 if (dataChildByName instanceof DataNodeContainer) {
263 current = (DataNodeContainer) dataChildByName;
267 // Then try to look up the expression.
268 final PathExpression leafRefXPath = leafref.getPathStatement();
269 final PathExpression leafRefStrippedXPath = new PathExpressionImpl(
270 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), leafRefXPath.isAbsolute());
271 final Module parentModule = getParentModule(parentNode);
272 final SchemaNode leafRefValueNode;
273 if (!leafRefStrippedXPath.isAbsolute()) {
274 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
275 parentNode, leafRefStrippedXPath);
277 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
279 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
283 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
284 * <code>IdentityrefTypeDefinition</code>.
286 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
287 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
289 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
290 final boolean inGrouping) {
291 if (typeDefinition instanceof LeafrefTypeDefinition) {
292 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
293 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
294 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
295 return provideTypeForLeafref(leafref, parentNode, inGrouping);
296 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
297 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
304 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
306 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
307 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
309 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
310 final String typedefName = typeDefinition.getQName().getLocalName();
311 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
312 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
313 if (returnType == null) {
314 if (baseTypeDef instanceof EnumTypeDefinition) {
315 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
316 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
318 final Module module = findParentModule(schemaContext, typeDefinition);
319 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
320 if (module != null) {
321 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
323 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
324 if (genTOs != null) {
325 returnType = genTOs.get(typedefName);
327 if (returnType == null) {
328 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
329 baseTypeDef, typeDefinition, r, lenient);
338 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
342 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
343 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
345 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
346 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
348 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
349 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
350 if (identities.size() > 1) {
351 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
354 final QName baseIdQName = identities.iterator().next().getQName();
355 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
356 IdentitySchemaNode identity = null;
357 for (IdentitySchemaNode id : module.getIdentities()) {
358 if (id.getQName().equals(baseIdQName)) {
362 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
364 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
365 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
366 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
367 return Types.classType(Types.wildcardTypeFor(identifier));
371 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
373 * @param typeDefinition
374 * type definition which should be converted to JAVA
376 * @return JAVA <code>Type</code> which represents
377 * <code>typeDefinition</code>
378 * @throws IllegalArgumentException
380 * <li>if <code>typeDefinition</code> equal null</li>
381 * <li>if Q name of <code>typeDefinition</code></li>
382 * <li>if name of <code>typeDefinition</code></li>
385 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
386 final SchemaNode parentNode) {
387 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
388 if (typeDefinition.getQName() == null) {
389 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
391 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
392 "Type Definitions Local Name cannot be NULL!");
394 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
395 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
397 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
398 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
411 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
412 * dicey when we throw in:
426 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
427 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
430 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
431 * an encapsulation for identityref typedefs.
433 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
434 * option, as it would look as though it is the product of a different construct:
440 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
441 * sub-identities of iden.
443 * The story behind leafrefs is probably similar, but that needs to be ascertained.
448 final Module module = findParentModule(schemaContext, parentNode);
449 if (module != null) {
450 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
452 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
453 if (genTOs != null) {
454 return genTOs.get(typeDefinition.getQName().getLocalName());
461 * Gets base type definition for <code>extendTypeDef</code>. The method is
462 * recursively called until non <code>ExtendedType</code> type is found.
464 * @param extendTypeDef
465 * type definition for which is the base type definition sought
466 * @return type definition which is base type for <code>extendTypeDef</code>
467 * @throws IllegalArgumentException
468 * if <code>extendTypeDef</code> equal null
470 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
471 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
473 TypeDefinition<?> ret = extendTypeDef;
474 while (ret.getBaseType() != null) {
475 ret = ret.getBaseType();
482 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
483 * to find referenced node and its <code>Type</code> is returned.
485 * @param leafrefType leafref type definition for which is the type sought
486 * @param parentNode parent node of the leaf being resolved
487 * @param inGrouping true if we are resolving the type within a grouping.
488 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
489 * @throws IllegalArgumentException
491 * <li>if <code>leafrefType</code> equal null</li>
492 * <li>if path statement of <code>leafrefType</code> equal null</li>
495 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
496 final boolean inGrouping) {
497 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
499 final PathExpression xpath = leafrefType.getPathStatement();
500 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
502 final String strXPath = xpath.getOriginalString();
503 if (strXPath.indexOf('[') != -1) {
504 // XXX: why are we special-casing this?
505 return Types.objectType();
508 final Module module = findParentModule(schemaContext, parentNode);
509 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
511 final SchemaNode dataNode;
512 if (xpath.isAbsolute()) {
513 dataNode = findDataSchemaNode(schemaContext, module, xpath);
515 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
516 if (dataNode == null && inGrouping) {
517 // Relative path within a grouping may end up being unresolvable because it may refer outside
518 // the grouping, in which case it is polymorphic based on instantiation, for example:
541 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
543 return Types.objectType();
546 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
547 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
549 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
550 Type returnType = null;
551 if (leafContainsEnumDefinition(dataNode)) {
552 returnType = referencedTypes.get(dataNode.getPath());
553 } else if (leafListContainsEnumDefinition(dataNode)) {
554 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
556 if (returnType == null) {
557 returnType = resolveTypeFromDataSchemaNode(dataNode);
559 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
560 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
565 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
566 * <code>EnumTypeDefinition</code>.
568 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
569 * @return boolean value
571 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
572 * <li>false - other cases</li>
575 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
576 if (dataNode instanceof LeafSchemaNode) {
577 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
578 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
584 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
585 * <code>EnumTypeDefinition</code>.
587 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
588 * @return boolean value
590 * <li>true - if <code>dataNode</code> is leaflist of type
592 * <li>false - other cases</li>
595 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
596 if (dataNode instanceof LeafListSchemaNode) {
597 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
598 return leafList.getType() instanceof EnumTypeDefinition;
604 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
606 * @param enumTypeDef enumeration type definition which is converted to enumeration
607 * @param enumName string with name which is used as the enumeration name
608 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
609 * @throws IllegalArgumentException
611 * <li>if <code>enumTypeDef</code> equals null</li>
612 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
613 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
614 * <li>if name of <code>enumTypeDef</code> equal null</li>
617 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
618 final SchemaNode parentNode) {
619 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
620 Preconditions.checkArgument(enumTypeDef.getValues() != null,
621 "EnumTypeDefinition MUST contain at least ONE value definition!");
622 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
623 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
624 "Local Name in EnumTypeDefinition QName cannot be NULL!");
626 final Module module = findParentModule(schemaContext, parentNode);
627 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
628 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
629 addEnumDescription(enumBuilder, enumTypeDef);
630 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
631 enumBuilder.setModuleName(module.getName());
632 enumBuilder.setSchemaPath(enumTypeDef.getPath());
633 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
634 return enumBuilder.toInstance(null);
638 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
640 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
641 * @param enumName string with the name of enumeration
642 * @param typeBuilder generated type builder to which is enumeration added
643 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
644 * @throws IllegalArgumentException
646 * <li>if <code>enumTypeDef</code> equals null</li>
647 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
648 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
649 * <li>if name of <code>enumTypeDef</code> equal null</li>
650 * <li>if name of <code>typeBuilder</code> equal null</li>
654 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
655 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
656 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
657 Preconditions.checkArgument(enumTypeDef.getValues() != null,
658 "EnumTypeDefinition MUST contain at least ONE value definition!");
659 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
660 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
661 "Local Name in EnumTypeDefinition QName cannot be NULL!");
662 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
664 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
666 addEnumDescription(enumBuilder, enumTypeDef);
667 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
668 return enumBuilder.toInstance(enumBuilder);
671 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
673 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
675 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
677 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
680 * Converts the pattern constraints to the list of the strings which represents these constraints.
682 * @param patternConstraints list of pattern constraints
683 * @return list of strings which represents the constraint patterns
685 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
687 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
690 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
693 * @param typedef extended type in which are the pattern constraints sought
694 * @return list of strings which represents the constraint patterns
695 * @throws IllegalArgumentException if <code>typedef</code> equals null
698 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
699 if (!(typedef instanceof StringTypeDefinition)) {
700 return ImmutableMap.of();
703 // TODO: run diff against base ?
704 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
708 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
710 * @param dataNode contains information about YANG type
711 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
713 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
714 Type returnType = null;
715 if (dataNode != null) {
716 if (dataNode instanceof LeafSchemaNode) {
717 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
718 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
719 returnType = javaTypeForSchemaDefinitionType(type, leaf);
720 } else if (dataNode instanceof LeafListSchemaNode) {
721 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
722 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
729 * Passes through all modules and through all its type definitions and convert it to generated types.
732 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
733 * of a module are at the beginning sorted so that type definition with less amount of references to other type
734 * definition are processed first.<br>
735 * For each module is created mapping record in the map
736 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
737 * which map current module name to the map which maps type names to returned types (generated types).
739 private void resolveTypeDefsFromContext() {
740 final Set<Module> modules = schemaContext.getModules();
741 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
742 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
744 for (Module module : modulesSortedByDependency) {
745 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
746 module.getName(), key -> new HashMap<>());
747 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
748 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
751 for (Module module : modulesSortedByDependency) {
752 if (module != null) {
753 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
754 if (basePackageName != null) {
755 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
756 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
757 typedefToGeneratedType(basePackageName, module, typedef);
765 * Create Type for specified type definition.
767 * @param basePackageName string with name of package to which the module belongs
768 * @param module string with the name of the module for to which the <code>typedef</code> belongs
769 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
770 * (usually generated TO)
771 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
772 * <code>null</code> value if <code>basePackageName</code> or
773 * <code>modulName</code> or <code>typedef</code> or Q name of
774 * <code>typedef</code> equals <code>null</code>
776 private Type typedefToGeneratedType(final String basePackageName, final Module module,
777 final TypeDefinition<?> typedef) {
778 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
780 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
781 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
785 final String typedefName = typedef.getQName().getLocalName();
787 final Type returnType;
788 if (baseTypedef.getBaseType() != null) {
789 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
791 } else if (baseTypedef instanceof UnionTypeDefinition) {
792 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
793 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
794 (UnionTypeDefinition) baseTypedef, typedef);
795 genTOBuilder.setTypedef(true);
796 genTOBuilder.setIsUnion(true);
797 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
798 makeSerializable(genTOBuilder);
799 returnType = genTOBuilder.build();
801 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
802 // so we are placing the builder alongside the union.
803 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
804 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
805 unionBuilder.setIsUnionBuilder(true);
806 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
807 method.setReturnType(returnType);
808 method.addParameter(Types.STRING, "defaultValue");
809 method.setAccessModifier(AccessModifier.PUBLIC);
810 method.setStatic(true);
811 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
812 } else if (baseTypedef instanceof EnumTypeDefinition) {
813 // enums are automatically Serializable
814 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
815 // TODO units for typedef enum
816 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
817 } else if (baseTypedef instanceof BitsTypeDefinition) {
818 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
819 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
820 (BitsTypeDefinition) baseTypedef, module.getName());
821 genTOBuilder.setTypedef(true);
822 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
823 makeSerializable(genTOBuilder);
824 returnType = genTOBuilder.build();
826 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
827 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
829 if (returnType != null) {
830 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
831 genTypeDefsContextMap.get(module.getName());
832 final Optional<Revision> moduleRevision = module.getRevision();
833 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
834 if (typeMap != null) {
835 if (typeMap.isEmpty()) {
836 typeMap = new HashMap<>(4);
837 modulesByDate.put(moduleRevision, typeMap);
839 typeMap.put(typedefName, returnType);
847 * Wraps base YANG type to generated TO.
849 * @param basePackageName string with name of package to which the module belongs
850 * @param typedef type definition which is converted to the TO
851 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
852 * @return generated transfer object which represent<code>javaType</code>
854 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
855 final Type javaType, final String moduleName) {
856 requireNonNull(javaType, "javaType cannot be null");
858 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
859 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
860 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
861 genPropBuilder.setReturnType(javaType);
862 genTOBuilder.addEqualsIdentity(genPropBuilder);
863 genTOBuilder.addHashIdentity(genPropBuilder);
864 genTOBuilder.addToStringProperty(genPropBuilder);
865 genTOBuilder.addImplementsType(TYPE_OBJECT);
866 if (typedef.getStatus() == Status.DEPRECATED) {
867 genTOBuilder.addAnnotation("java.lang", "Deprecated");
869 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
870 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
872 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
873 genTOBuilder.setTypedef(true);
874 makeSerializable(genTOBuilder);
875 return genTOBuilder.build();
879 * Converts output list of generated TO builders to one TO builder (first
880 * from list) which contains the remaining builders as its enclosing TO.
882 * @param typeName new type identifier
883 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
884 * @return generated TO builder with the list of enclosed generated TO builders
886 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
887 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
888 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
890 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
892 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
893 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
894 return resultTOBuilder;
898 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
899 * <code>typedef</code> is added to generated TO builder as property.
901 * @param typeName new type identifier
902 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
903 * @return generated TO builder which represents <code>typedef</code>
904 * @throws NullPointerException
906 * <li>if <code>basePackageName</code> is null</li>
907 * <li>if <code>typedef</code> is null</li>
908 * <li>if Qname of <code>typedef</code> is null</li>
911 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
912 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
913 requireNonNull(typedef, "Type Definition cannot be NULL!");
914 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
916 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
917 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
918 final Module module = findParentModule(schemaContext, parentNode);
920 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
921 unionGenTOBuilder.setIsUnion(true);
922 unionGenTOBuilder.setSchemaPath(typedef.getPath());
923 unionGenTOBuilder.setModuleName(module.getName());
924 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
925 addCodegenInformation(unionGenTOBuilder, typedef);
926 generatedTOBuilders.add(unionGenTOBuilder);
928 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
929 // also negation information and hence guarantees uniqueness.
930 final Map<String, String> expressions = new HashMap<>();
931 for (TypeDefinition<?> unionType : unionTypes) {
932 final String unionTypeName = unionType.getQName().getLocalName();
934 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
935 // do not follow type encapsulation -- we use the general case for that.
936 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
937 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
938 } else if (unionType instanceof UnionTypeDefinition) {
939 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
940 (UnionTypeDefinition) unionType, parentNode));
941 } else if (unionType instanceof EnumTypeDefinition) {
942 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
943 unionTypeName, unionGenTOBuilder);
944 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
946 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
947 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
950 addStringRegExAsConstant(unionGenTOBuilder, expressions);
952 storeGenTO(typedef, unionGenTOBuilder, parentNode);
954 return generatedTOBuilders;
958 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
961 * In this case the new generated TO is created for union subtype (recursive call of method
962 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
963 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
964 * created property which type is equal to new generated TO.
966 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
967 * @param basePackageName string with the name of the module package
968 * @param unionSubtype type definition which represents union subtype
969 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
970 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
972 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
973 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
974 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
975 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
976 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
977 newTOBuilderName, unionSubtype, parentNode);
979 final GeneratedPropertyBuilder propertyBuilder;
980 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
981 newTOBuilderName.simpleName()));
982 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
983 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
984 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
986 return subUnionGenTOBUilders;
990 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
991 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
992 * the base type is used for the property creation.
994 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
995 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
996 * @param expressions list of strings with the regular expressions
997 * @param parentNode parent Schema Node for Extended Subtype
999 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1000 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1001 final String unionTypeName = unionSubtype.getQName().getLocalName();
1002 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1003 if (genTO != null) {
1004 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1008 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1009 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1010 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1011 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1012 if (javaType != null) {
1013 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1015 } else if (baseType instanceof LeafrefTypeDefinition) {
1016 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1017 boolean typeExist = false;
1018 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1019 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1020 if (origType != null && javaType != null && javaType == origType) {
1025 if (!typeExist && javaType != null) {
1026 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1027 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1030 if (baseType instanceof StringTypeDefinition) {
1031 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1036 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1037 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1039 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1040 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1042 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1043 final Module typeModule = findParentModule(schemaContext, parentNode);
1044 if (typeModule != null && typeModule.getName() != null) {
1045 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1046 typeModule.getName());
1047 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1048 if (genTOs != null) {
1049 return genTOs.get(searchedTypeName);
1056 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1057 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1059 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1060 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1062 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1063 final SchemaNode parentNode) {
1064 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1065 final Module parentModule = findParentModule(schemaContext, parentNode);
1066 if (parentModule != null && parentModule.getName() != null) {
1067 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1068 parentModule.getName());
1069 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1070 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1076 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1077 * to <code>unonGenTransObject</code>.
1079 * @param unionGenTransObject generated TO to which should be property added
1080 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1081 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1083 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1084 final String propertyName) {
1085 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1086 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1087 .addProperty(BindingMapping.getPropertyName(propertyName));
1088 propBuilder.setReturnType(type);
1090 unionGenTransObject.addEqualsIdentity(propBuilder);
1091 unionGenTransObject.addHashIdentity(propBuilder);
1092 unionGenTransObject.addToStringProperty(propBuilder);
1097 * Converts <code>typedef</code> to the generated TO builder.
1099 * @param basePackageName string with name of package to which the module belongs
1100 * @param typedef type definition from which is the generated TO builder created
1101 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1103 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1104 final TypeDefinition<?> typedef, final String moduleName) {
1105 JavaTypeName name = renames.get(typedef);
1107 name = JavaTypeName.create(
1108 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1109 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1112 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1113 newType.setSchemaPath(typedef.getPath());
1114 newType.setModuleName(moduleName);
1115 addCodegenInformation(newType, typedef);
1120 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1121 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1124 * @param typeName new type identifier
1125 * @param typeDef type definition from which is the generated TO builder created
1126 * @return generated TO builder which represents <code>typeDef</code>
1127 * @throws IllegalArgumentException
1129 * <li>if <code>typeDef</code> equals null</li>
1130 * <li>if <code>basePackageName</code> equals null</li>
1133 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1134 final BitsTypeDefinition typeDef, final String moduleName) {
1135 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1136 genTOBuilder.setSchemaPath(typeDef.getPath());
1137 genTOBuilder.setModuleName(moduleName);
1138 genTOBuilder.setBaseType(typeDef);
1139 genTOBuilder.addImplementsType(TYPE_OBJECT);
1140 addCodegenInformation(genTOBuilder, typeDef);
1142 final List<Bit> bitList = typeDef.getBits();
1143 GeneratedPropertyBuilder genPropertyBuilder;
1144 for (Bit bit : bitList) {
1145 final String name = bit.getName();
1146 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1147 genPropertyBuilder.setReadOnly(true);
1148 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1150 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1151 genTOBuilder.addHashIdentity(genPropertyBuilder);
1152 genTOBuilder.addToStringProperty(genPropertyBuilder);
1155 return genTOBuilder;
1159 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1160 * the <code>regularExpressions</code>.
1162 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1163 * @param expressions list of string which represent regular expressions
1165 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1166 final Map<String, String> expressions) {
1167 if (!expressions.isEmpty()) {
1168 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1169 ImmutableMap.copyOf(expressions));
1174 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1175 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1178 * It is assumed that <code>innerExtendedType</code> is already present in
1179 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1180 * for the returning generated TO.
1182 * @param typedef Type Definition
1183 * @param innerExtendedType extended type which is part of some other extended type
1184 * @param basePackageName string with the package name of the module
1185 * @param moduleName Module Name
1186 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1187 * @throws IllegalArgumentException
1189 * <li>if <code>extendedType</code> equals null</li>
1190 * <li>if <code>basePackageName</code> equals null</li>
1191 * <li>if <code>typedefName</code> equals null</li>
1194 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1195 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1196 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1197 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1199 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1200 BindingMapping.getClassName(typedef.getQName())));
1201 genTOBuilder.setSchemaPath(typedef.getPath());
1202 genTOBuilder.setModuleName(moduleName);
1203 genTOBuilder.setTypedef(true);
1204 addCodegenInformation(genTOBuilder, typedef);
1206 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1207 genTOBuilder.setRestrictions(r);
1208 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1210 if (typedef.getStatus() == Status.DEPRECATED) {
1211 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1214 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1215 genTOBuilder.setIsUnion(true);
1218 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1219 Map<String, Type> typeMap = null;
1220 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1221 if (parentModule != null) {
1222 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1223 typeMap = modulesByDate.get(parentModule.getRevision());
1226 if (typeMap != null) {
1227 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1228 final Type type = typeMap.get(innerTypeDef);
1229 if (type instanceof GeneratedTransferObject) {
1230 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1233 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1234 makeSerializable(genTOBuilder);
1236 return genTOBuilder.build();
1240 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1243 * @param gto transfer object which needs to be made serializable
1245 private static void makeSerializable(final GeneratedTOBuilder gto) {
1246 gto.addImplementsType(Types.serializableType());
1247 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1248 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1253 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1254 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1255 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1256 * type definitions are in the list behind all type definitions on which depends.
1258 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1259 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1260 * dependent on other type definitions are in list behind them).
1262 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1263 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1264 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1266 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1267 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1268 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1269 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1270 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1271 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1274 // SortedMap guarantees order corresponding to keys in ascending order
1275 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1276 sortedTypeDefinition.addAll(v);
1279 return sortedTypeDefinition;
1283 * Returns how many immersion is necessary to get from the type definition to the base type.
1285 * @param typeDefinition type definition for which is depth sought.
1286 * @return number of immersions which are necessary to get from the type definition to the base type
1288 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1289 // FIXME: rewrite this in a non-recursive manner
1290 if (typeDefinition == null) {
1293 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1294 if (baseType == null) {
1299 if (baseType.getBaseType() != null) {
1300 depth = depth + getTypeDefinitionDepth(baseType);
1301 } else if (baseType instanceof UnionTypeDefinition) {
1302 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1303 int maxChildDepth = 0;
1305 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1306 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1307 if (childDepth > maxChildDepth) {
1308 maxChildDepth = childDepth;
1311 return maxChildDepth;
1317 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1318 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1319 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1321 * @param name string with name of augmented node
1322 * @return string with the number suffix incremented by one (or 1 is added)
1324 private static String provideAvailableNameForGenTOBuilder(final String name) {
1325 final int dollar = name.indexOf('$');
1330 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1331 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1332 return name.substring(0, dollar + 1) + newSuffix;
1335 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1336 if (!Strings.isNullOrEmpty(units)) {
1337 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1338 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1339 prop.setReturnType(Types.STRING);
1340 to.addToStringProperty(prop);
1345 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1346 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1349 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1350 final TypeDefinition<?> type = CompatUtils.compatType(node);
1351 final QName typeQName = type.getQName();
1352 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1353 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1354 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1357 final StringBuilder sb = new StringBuilder();
1358 String result = null;
1359 if (base instanceof BinaryTypeDefinition) {
1360 result = binaryToDef(defaultValue);
1361 } else if (base instanceof BitsTypeDefinition) {
1364 final Module parent = getParentModule(node);
1365 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1367 if (!path.hasNext()) {
1368 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1369 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1370 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1372 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1373 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1375 parentName = BindingMapping.getClassName(parent.getName());
1376 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1378 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1379 } else if (base instanceof BooleanTypeDefinition) {
1380 result = typeToBooleanDef(defaultValue);
1381 } else if (base instanceof DecimalTypeDefinition) {
1382 result = typeToDef(BigDecimal.class, defaultValue);
1383 } else if (base instanceof EmptyTypeDefinition) {
1384 result = typeToBooleanDef(defaultValue);
1385 } else if (base instanceof EnumTypeDefinition) {
1386 final char[] defValArray = defaultValue.toCharArray();
1387 final char first = Character.toUpperCase(defaultValue.charAt(0));
1388 defValArray[0] = first;
1389 final String newDefVal = new String(defValArray);
1391 if (type.getBaseType() != null) {
1392 final Module m = getParentModule(type);
1393 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1394 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1396 className = packageName + "." + BindingMapping.getClassName(typeQName);
1398 final Module parentModule = getParentModule(node);
1399 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1400 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1402 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1404 result = className + "." + newDefVal;
1405 } else if (base instanceof IdentityrefTypeDefinition) {
1406 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1407 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1408 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1409 } else if (BaseTypes.isInt8(base)) {
1410 result = typeToValueOfDef(Byte.class, defaultValue);
1411 } else if (BaseTypes.isInt16(base)) {
1412 result = typeToValueOfDef(Short.class, defaultValue);
1413 } else if (BaseTypes.isInt32(base)) {
1414 result = typeToValueOfDef(Integer.class, defaultValue);
1415 } else if (BaseTypes.isInt64(base)) {
1416 result = typeToValueOfDef(Long.class, defaultValue);
1417 } else if (base instanceof LeafrefTypeDefinition) {
1418 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1419 } else if (base instanceof StringTypeDefinition) {
1420 result = "\"" + defaultValue + "\"";
1421 } else if (BaseTypes.isUint8(base)) {
1422 result = typeToValueOfDef(Short.class, defaultValue);
1423 } else if (BaseTypes.isUint16(base)) {
1424 result = typeToValueOfDef(Integer.class, defaultValue);
1425 } else if (BaseTypes.isUint32(base)) {
1426 result = typeToValueOfDef(Long.class, defaultValue);
1427 } else if (BaseTypes.isUint64(base)) {
1428 switch (defaultValue) {
1430 result = "java.math.BigInteger.ZERO";
1433 result = "java.math.BigInteger.ONE";
1436 result = "java.math.BigInteger.TEN";
1439 result = typeToDef(BigInteger.class, defaultValue);
1441 } else if (base instanceof UnionTypeDefinition) {
1442 result = unionToDef(node);
1448 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1449 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1450 final Module m = getParentModule(type);
1451 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1452 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1454 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1455 sb.insert(0, "new " + className + "(");
1456 sb.insert(sb.length(), ')');
1459 return sb.toString();
1462 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1463 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1466 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1467 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1470 private static String typeToBooleanDef(final String defaultValue) {
1471 switch (defaultValue) {
1473 return "java.lang.Boolean.FALSE";
1475 return "java.lang.Boolean.TRUE";
1477 return typeToValueOfDef(Boolean.class, defaultValue);
1481 private static String binaryToDef(final String defaultValue) {
1482 final StringBuilder sb = new StringBuilder();
1483 final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1484 sb.append("new byte[] {");
1485 for (int i = 0; i < encoded.length; i++) {
1486 sb.append(encoded[i]);
1487 if (i != encoded.length - 1) {
1492 return sb.toString();
1495 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1497 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1498 final boolean isExt) {
1499 final List<Bit> bits = new ArrayList<>(type.getBits());
1500 bits.sort(BIT_NAME_COMPARATOR);
1501 final StringBuilder sb = new StringBuilder();
1504 sb.append(className);
1507 for (int i = 0; i < bits.size(); i++) {
1508 if (bits.get(i).getName().equals(defaultValue)) {
1513 if (i != bits.size() - 1) {
1520 return sb.toString();
1523 private Module getParentModule(final SchemaNode node) {
1524 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1525 return schemaContext.findModule(qname.getModule()).orElse(null);
1528 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1529 final String defaultValue) {
1530 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1531 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1532 "The Path Statement for Leafref Type Definition cannot be NULL!");
1534 final PathExpression xpath = leafrefType.getPathStatement();
1535 final String strXPath = xpath.getOriginalString();
1537 if (strXPath != null) {
1538 if (strXPath.indexOf('[') == -1) {
1539 final Module module = findParentModule(schemaContext, parentNode);
1540 if (module != null) {
1541 final SchemaNode dataNode;
1542 if (xpath.isAbsolute()) {
1543 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1545 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1547 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1551 return "new java.lang.Object()";
1558 private String unionToDef(final LeafSchemaNode node) {
1559 final TypeDefinition<?> type = CompatUtils.compatType(node);
1563 if (type.getBaseType() != null) {
1564 final QName typeQName = type.getQName();
1565 Module module = null;
1566 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1567 if (modules.size() > 1) {
1568 for (Module m : modules) {
1569 if (m.getRevision().equals(typeQName.getRevision())) {
1574 if (module == null) {
1575 final List<Module> modulesList = new ArrayList<>(modules);
1576 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1577 module = modulesList.get(0);
1580 module = modules.iterator().next();
1583 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1584 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1586 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1587 final QName first = path.next();
1588 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1589 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1590 if (!path.hasNext()) {
1591 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1592 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1594 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1596 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1599 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1602 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1603 final StringBuilder sb = new StringBuilder();
1605 sb.append(className);
1607 sb.append(defaultValue);
1608 sb.append("\".toCharArray())");
1609 return sb.toString();
1613 public String getConstructorPropertyName(final SchemaNode node) {
1614 return node instanceof TypeDefinition<?> ? "value" : "";
1618 public String getParamNameFromType(final TypeDefinition<?> type) {
1619 return BindingMapping.getPropertyName(type.getQName().getLocalName());