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.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataTreeSchemaNode;
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 Module parentModule = getParentModule(parentNode);
270 final SchemaNode leafRefValueNode;
271 if (leafRefXPath.isAbsolute()) {
272 leafRefValueNode = SchemaContextUtil.findDataTreeSchemaNode(schemaContext, parentModule.getQNameModule(),
275 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
276 parentNode, new PathExpressionImpl(
277 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), false));
280 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
284 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
285 * <code>IdentityrefTypeDefinition</code>.
287 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
288 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
290 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
291 final boolean inGrouping) {
292 if (typeDefinition instanceof LeafrefTypeDefinition) {
293 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
294 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
295 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
296 return provideTypeForLeafref(leafref, parentNode, inGrouping);
297 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
298 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
305 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
307 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
308 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
310 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
311 final String typedefName = typeDefinition.getQName().getLocalName();
312 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
313 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
314 if (returnType == null) {
315 if (baseTypeDef instanceof EnumTypeDefinition) {
316 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
317 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
319 final Module module = findParentModule(schemaContext, typeDefinition);
320 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
321 if (module != null) {
322 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
324 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
325 if (genTOs != null) {
326 returnType = genTOs.get(typedefName);
328 if (returnType == null) {
329 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
330 baseTypeDef, typeDefinition, r, lenient);
339 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
343 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
344 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
346 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
347 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
349 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
350 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
351 if (identities.size() > 1) {
352 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
355 final QName baseIdQName = identities.iterator().next().getQName();
356 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
357 IdentitySchemaNode identity = null;
358 for (IdentitySchemaNode id : module.getIdentities()) {
359 if (id.getQName().equals(baseIdQName)) {
363 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
365 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
366 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
367 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
368 return Types.classType(Types.wildcardTypeFor(identifier));
372 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
374 * @param typeDefinition
375 * type definition which should be converted to JAVA
377 * @return JAVA <code>Type</code> which represents
378 * <code>typeDefinition</code>
379 * @throws IllegalArgumentException
381 * <li>if <code>typeDefinition</code> equal null</li>
382 * <li>if Q name of <code>typeDefinition</code></li>
383 * <li>if name of <code>typeDefinition</code></li>
386 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
387 final SchemaNode parentNode) {
388 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
389 if (typeDefinition.getQName() == null) {
390 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
392 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
393 "Type Definitions Local Name cannot be NULL!");
395 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
396 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
398 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
399 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
412 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
413 * dicey when we throw in:
427 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
428 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
431 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
432 * an encapsulation for identityref typedefs.
434 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
435 * option, as it would look as though it is the product of a different construct:
441 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
442 * sub-identities of iden.
444 * The story behind leafrefs is probably similar, but that needs to be ascertained.
449 final Module module = findParentModule(schemaContext, parentNode);
450 if (module != null) {
451 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
453 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
454 if (genTOs != null) {
455 return genTOs.get(typeDefinition.getQName().getLocalName());
462 * Gets base type definition for <code>extendTypeDef</code>. The method is
463 * recursively called until non <code>ExtendedType</code> type is found.
465 * @param extendTypeDef
466 * type definition for which is the base type definition sought
467 * @return type definition which is base type for <code>extendTypeDef</code>
468 * @throws IllegalArgumentException
469 * if <code>extendTypeDef</code> equal null
471 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
472 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
474 TypeDefinition<?> ret = extendTypeDef;
475 while (ret.getBaseType() != null) {
476 ret = ret.getBaseType();
483 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
484 * to find referenced node and its <code>Type</code> is returned.
486 * @param leafrefType leafref type definition for which is the type sought
487 * @param parentNode parent node of the leaf being resolved
488 * @param inGrouping true if we are resolving the type within a grouping.
489 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
490 * @throws IllegalArgumentException
492 * <li>if <code>leafrefType</code> equal null</li>
493 * <li>if path statement of <code>leafrefType</code> equal null</li>
496 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
497 final boolean inGrouping) {
498 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
500 final PathExpression xpath = leafrefType.getPathStatement();
501 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
503 final String strXPath = xpath.getOriginalString();
504 if (strXPath.indexOf('[') != -1) {
505 // XXX: why are we special-casing this?
506 return Types.objectType();
509 final Module module = findParentModule(schemaContext, parentNode);
510 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
512 final SchemaNode dataNode;
513 if (xpath.isAbsolute()) {
514 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
516 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
517 if (dataNode == null && inGrouping) {
518 // Relative path within a grouping may end up being unresolvable because it may refer outside
519 // the grouping, in which case it is polymorphic based on instantiation, for example:
542 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
544 return Types.objectType();
547 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
548 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
550 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
551 Type returnType = null;
552 if (leafContainsEnumDefinition(dataNode)) {
553 returnType = referencedTypes.get(dataNode.getPath());
554 } else if (leafListContainsEnumDefinition(dataNode)) {
555 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
557 if (returnType == null) {
558 returnType = resolveTypeFromDataSchemaNode(dataNode);
560 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
561 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
566 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
567 * <code>EnumTypeDefinition</code>.
569 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
570 * @return boolean value
572 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
573 * <li>false - other cases</li>
576 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
577 if (dataNode instanceof LeafSchemaNode) {
578 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
579 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
585 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
586 * <code>EnumTypeDefinition</code>.
588 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
589 * @return boolean value
591 * <li>true - if <code>dataNode</code> is leaflist of type
593 * <li>false - other cases</li>
596 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
597 if (dataNode instanceof LeafListSchemaNode) {
598 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
599 return leafList.getType() instanceof EnumTypeDefinition;
605 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
607 * @param enumTypeDef enumeration type definition which is converted to enumeration
608 * @param enumName string with name which is used as the enumeration name
609 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
610 * @throws IllegalArgumentException
612 * <li>if <code>enumTypeDef</code> equals null</li>
613 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
614 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
615 * <li>if name of <code>enumTypeDef</code> equal null</li>
618 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
619 final SchemaNode parentNode) {
620 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
621 Preconditions.checkArgument(enumTypeDef.getValues() != null,
622 "EnumTypeDefinition MUST contain at least ONE value definition!");
623 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
624 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
625 "Local Name in EnumTypeDefinition QName cannot be NULL!");
627 final Module module = findParentModule(schemaContext, parentNode);
628 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
629 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
630 addEnumDescription(enumBuilder, enumTypeDef);
631 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
632 enumBuilder.setModuleName(module.getName());
633 enumBuilder.setSchemaPath(enumTypeDef.getPath());
634 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
635 return enumBuilder.toInstance(null);
639 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
641 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
642 * @param enumName string with the name of enumeration
643 * @param typeBuilder generated type builder to which is enumeration added
644 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
645 * @throws IllegalArgumentException
647 * <li>if <code>enumTypeDef</code> equals null</li>
648 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
649 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
650 * <li>if name of <code>enumTypeDef</code> equal null</li>
651 * <li>if name of <code>typeBuilder</code> equal null</li>
655 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
656 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
657 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
658 Preconditions.checkArgument(enumTypeDef.getValues() != null,
659 "EnumTypeDefinition MUST contain at least ONE value definition!");
660 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
661 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
662 "Local Name in EnumTypeDefinition QName cannot be NULL!");
663 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
665 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
667 addEnumDescription(enumBuilder, enumTypeDef);
668 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
669 return enumBuilder.toInstance(enumBuilder);
672 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
674 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
676 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
678 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
681 * Converts the pattern constraints to the list of the strings which represents these constraints.
683 * @param patternConstraints list of pattern constraints
684 * @return list of strings which represents the constraint patterns
686 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
688 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
691 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
694 * @param typedef extended type in which are the pattern constraints sought
695 * @return list of strings which represents the constraint patterns
696 * @throws IllegalArgumentException if <code>typedef</code> equals null
699 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
700 if (!(typedef instanceof StringTypeDefinition)) {
701 return ImmutableMap.of();
704 // TODO: run diff against base ?
705 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
709 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
711 * @param dataNode contains information about YANG type
712 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
714 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
715 Type returnType = null;
716 if (dataNode != null) {
717 if (dataNode instanceof LeafSchemaNode) {
718 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
719 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
720 returnType = javaTypeForSchemaDefinitionType(type, leaf);
721 } else if (dataNode instanceof LeafListSchemaNode) {
722 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
723 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
730 * Passes through all modules and through all its type definitions and convert it to generated types.
733 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
734 * of a module are at the beginning sorted so that type definition with less amount of references to other type
735 * definition are processed first.<br>
736 * For each module is created mapping record in the map
737 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
738 * which map current module name to the map which maps type names to returned types (generated types).
740 private void resolveTypeDefsFromContext() {
741 final Set<Module> modules = schemaContext.getModules();
742 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
743 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
745 for (Module module : modulesSortedByDependency) {
746 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
747 module.getName(), key -> new HashMap<>());
748 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
749 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
752 for (Module module : modulesSortedByDependency) {
753 if (module != null) {
754 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
755 if (basePackageName != null) {
756 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
757 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
758 typedefToGeneratedType(basePackageName, module, typedef);
766 * Create Type for specified type definition.
768 * @param basePackageName string with name of package to which the module belongs
769 * @param module string with the name of the module for to which the <code>typedef</code> belongs
770 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
771 * (usually generated TO)
772 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
773 * <code>null</code> value if <code>basePackageName</code> or
774 * <code>modulName</code> or <code>typedef</code> or Q name of
775 * <code>typedef</code> equals <code>null</code>
777 private Type typedefToGeneratedType(final String basePackageName, final Module module,
778 final TypeDefinition<?> typedef) {
779 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
781 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
782 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
786 final String typedefName = typedef.getQName().getLocalName();
788 final Type returnType;
789 if (baseTypedef.getBaseType() != null) {
790 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
792 } else if (baseTypedef instanceof UnionTypeDefinition) {
793 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
794 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
795 (UnionTypeDefinition) baseTypedef, typedef);
796 genTOBuilder.setTypedef(true);
797 genTOBuilder.setIsUnion(true);
798 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
799 makeSerializable(genTOBuilder);
800 returnType = genTOBuilder.build();
802 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
803 // so we are placing the builder alongside the union.
804 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
805 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
806 unionBuilder.setIsUnionBuilder(true);
807 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
808 method.setReturnType(returnType);
809 method.addParameter(Types.STRING, "defaultValue");
810 method.setAccessModifier(AccessModifier.PUBLIC);
811 method.setStatic(true);
812 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
813 } else if (baseTypedef instanceof EnumTypeDefinition) {
814 // enums are automatically Serializable
815 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
816 // TODO units for typedef enum
817 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
818 } else if (baseTypedef instanceof BitsTypeDefinition) {
819 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
820 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
821 (BitsTypeDefinition) baseTypedef, module.getName());
822 genTOBuilder.setTypedef(true);
823 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
824 makeSerializable(genTOBuilder);
825 returnType = genTOBuilder.build();
827 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
828 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
830 if (returnType != null) {
831 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
832 genTypeDefsContextMap.get(module.getName());
833 final Optional<Revision> moduleRevision = module.getRevision();
834 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
835 if (typeMap != null) {
836 if (typeMap.isEmpty()) {
837 typeMap = new HashMap<>(4);
838 modulesByDate.put(moduleRevision, typeMap);
840 typeMap.put(typedefName, returnType);
848 * Wraps base YANG type to generated TO.
850 * @param basePackageName string with name of package to which the module belongs
851 * @param typedef type definition which is converted to the TO
852 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
853 * @return generated transfer object which represent<code>javaType</code>
855 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
856 final Type javaType, final String moduleName) {
857 requireNonNull(javaType, "javaType cannot be null");
859 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
860 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
861 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
862 genPropBuilder.setReturnType(javaType);
863 genTOBuilder.addEqualsIdentity(genPropBuilder);
864 genTOBuilder.addHashIdentity(genPropBuilder);
865 genTOBuilder.addToStringProperty(genPropBuilder);
866 genTOBuilder.addImplementsType(TYPE_OBJECT);
867 if (typedef.getStatus() == Status.DEPRECATED) {
868 genTOBuilder.addAnnotation("java.lang", "Deprecated");
870 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
871 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
873 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
874 genTOBuilder.setTypedef(true);
875 makeSerializable(genTOBuilder);
876 return genTOBuilder.build();
880 * Converts output list of generated TO builders to one TO builder (first
881 * from list) which contains the remaining builders as its enclosing TO.
883 * @param typeName new type identifier
884 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
885 * @return generated TO builder with the list of enclosed generated TO builders
887 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
888 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
889 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
891 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
893 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
894 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
895 return resultTOBuilder;
899 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
900 * <code>typedef</code> is added to generated TO builder as property.
902 * @param typeName new type identifier
903 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
904 * @return generated TO builder which represents <code>typedef</code>
905 * @throws NullPointerException
907 * <li>if <code>basePackageName</code> is null</li>
908 * <li>if <code>typedef</code> is null</li>
909 * <li>if Qname of <code>typedef</code> is null</li>
912 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
913 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
914 requireNonNull(typedef, "Type Definition cannot be NULL!");
915 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
917 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
918 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
919 final Module module = findParentModule(schemaContext, parentNode);
921 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
922 unionGenTOBuilder.setIsUnion(true);
923 unionGenTOBuilder.setSchemaPath(typedef.getPath());
924 unionGenTOBuilder.setModuleName(module.getName());
925 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
926 addCodegenInformation(unionGenTOBuilder, typedef);
927 generatedTOBuilders.add(unionGenTOBuilder);
929 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
930 // also negation information and hence guarantees uniqueness.
931 final Map<String, String> expressions = new HashMap<>();
932 for (TypeDefinition<?> unionType : unionTypes) {
933 final String unionTypeName = unionType.getQName().getLocalName();
935 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
936 // do not follow type encapsulation -- we use the general case for that.
937 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
938 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
939 } else if (unionType instanceof UnionTypeDefinition) {
940 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
941 (UnionTypeDefinition) unionType, parentNode));
942 } else if (unionType instanceof EnumTypeDefinition) {
943 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
944 unionTypeName, unionGenTOBuilder);
945 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
947 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
948 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
951 addStringRegExAsConstant(unionGenTOBuilder, expressions);
953 storeGenTO(typedef, unionGenTOBuilder, parentNode);
955 return generatedTOBuilders;
959 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
962 * In this case the new generated TO is created for union subtype (recursive call of method
963 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
964 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
965 * created property which type is equal to new generated TO.
967 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
968 * @param basePackageName string with the name of the module package
969 * @param unionSubtype type definition which represents union subtype
970 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
971 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
973 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
974 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
975 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
976 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
977 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
978 newTOBuilderName, unionSubtype, parentNode);
980 final GeneratedPropertyBuilder propertyBuilder;
981 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
982 newTOBuilderName.simpleName()));
983 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
984 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
985 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
987 return subUnionGenTOBUilders;
991 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
992 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
993 * the base type is used for the property creation.
995 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
996 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
997 * @param expressions list of strings with the regular expressions
998 * @param parentNode parent Schema Node for Extended Subtype
1000 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1001 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1002 final String unionTypeName = unionSubtype.getQName().getLocalName();
1003 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1004 if (genTO != null) {
1005 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1009 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1010 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1011 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1012 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1013 if (javaType != null) {
1014 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1016 } else if (baseType instanceof LeafrefTypeDefinition) {
1017 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1018 boolean typeExist = false;
1019 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1020 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1021 if (origType != null && javaType != null && javaType == origType) {
1026 if (!typeExist && javaType != null) {
1027 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1028 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1031 if (baseType instanceof StringTypeDefinition) {
1032 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1037 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1038 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1040 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1041 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1043 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1044 final Module typeModule = findParentModule(schemaContext, parentNode);
1045 if (typeModule != null && typeModule.getName() != null) {
1046 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1047 typeModule.getName());
1048 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1049 if (genTOs != null) {
1050 return genTOs.get(searchedTypeName);
1057 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1058 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1060 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1061 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1063 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1064 final SchemaNode parentNode) {
1065 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1066 final Module parentModule = findParentModule(schemaContext, parentNode);
1067 if (parentModule != null && parentModule.getName() != null) {
1068 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1069 parentModule.getName());
1070 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1071 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1077 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1078 * to <code>unonGenTransObject</code>.
1080 * @param unionGenTransObject generated TO to which should be property added
1081 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1082 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1084 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1085 final String propertyName) {
1086 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1087 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1088 .addProperty(BindingMapping.getPropertyName(propertyName));
1089 propBuilder.setReturnType(type);
1091 unionGenTransObject.addEqualsIdentity(propBuilder);
1092 unionGenTransObject.addHashIdentity(propBuilder);
1093 unionGenTransObject.addToStringProperty(propBuilder);
1098 * Converts <code>typedef</code> to the generated TO builder.
1100 * @param basePackageName string with name of package to which the module belongs
1101 * @param typedef type definition from which is the generated TO builder created
1102 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1104 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1105 final TypeDefinition<?> typedef, final String moduleName) {
1106 JavaTypeName name = renames.get(typedef);
1108 name = JavaTypeName.create(
1109 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1110 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1113 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1114 newType.setSchemaPath(typedef.getPath());
1115 newType.setModuleName(moduleName);
1116 addCodegenInformation(newType, typedef);
1121 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1122 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1125 * @param typeName new type identifier
1126 * @param typeDef type definition from which is the generated TO builder created
1127 * @return generated TO builder which represents <code>typeDef</code>
1128 * @throws IllegalArgumentException
1130 * <li>if <code>typeDef</code> equals null</li>
1131 * <li>if <code>basePackageName</code> equals null</li>
1134 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1135 final BitsTypeDefinition typeDef, final String moduleName) {
1136 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1137 genTOBuilder.setSchemaPath(typeDef.getPath());
1138 genTOBuilder.setModuleName(moduleName);
1139 genTOBuilder.setBaseType(typeDef);
1140 genTOBuilder.addImplementsType(TYPE_OBJECT);
1141 addCodegenInformation(genTOBuilder, typeDef);
1143 final List<Bit> bitList = typeDef.getBits();
1144 GeneratedPropertyBuilder genPropertyBuilder;
1145 for (Bit bit : bitList) {
1146 final String name = bit.getName();
1147 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1148 genPropertyBuilder.setReadOnly(true);
1149 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1151 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1152 genTOBuilder.addHashIdentity(genPropertyBuilder);
1153 genTOBuilder.addToStringProperty(genPropertyBuilder);
1156 return genTOBuilder;
1160 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1161 * the <code>regularExpressions</code>.
1163 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1164 * @param expressions list of string which represent regular expressions
1166 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1167 final Map<String, String> expressions) {
1168 if (!expressions.isEmpty()) {
1169 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1170 ImmutableMap.copyOf(expressions));
1175 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1176 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1179 * It is assumed that <code>innerExtendedType</code> is already present in
1180 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1181 * for the returning generated TO.
1183 * @param typedef Type Definition
1184 * @param innerExtendedType extended type which is part of some other extended type
1185 * @param basePackageName string with the package name of the module
1186 * @param moduleName Module Name
1187 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1188 * @throws IllegalArgumentException
1190 * <li>if <code>extendedType</code> equals null</li>
1191 * <li>if <code>basePackageName</code> equals null</li>
1192 * <li>if <code>typedefName</code> equals null</li>
1195 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1196 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1197 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1198 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1200 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1201 BindingMapping.getClassName(typedef.getQName())));
1202 genTOBuilder.setSchemaPath(typedef.getPath());
1203 genTOBuilder.setModuleName(moduleName);
1204 genTOBuilder.setTypedef(true);
1205 addCodegenInformation(genTOBuilder, typedef);
1207 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1208 genTOBuilder.setRestrictions(r);
1209 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1211 if (typedef.getStatus() == Status.DEPRECATED) {
1212 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1215 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1216 genTOBuilder.setIsUnion(true);
1219 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1220 Map<String, Type> typeMap = null;
1221 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1222 if (parentModule != null) {
1223 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1224 typeMap = modulesByDate.get(parentModule.getRevision());
1227 if (typeMap != null) {
1228 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1229 final Type type = typeMap.get(innerTypeDef);
1230 if (type instanceof GeneratedTransferObject) {
1231 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1234 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1235 makeSerializable(genTOBuilder);
1237 return genTOBuilder.build();
1241 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1244 * @param gto transfer object which needs to be made serializable
1246 private static void makeSerializable(final GeneratedTOBuilder gto) {
1247 gto.addImplementsType(Types.serializableType());
1248 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1249 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1254 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1255 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1256 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1257 * type definitions are in the list behind all type definitions on which depends.
1259 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1260 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1261 * dependent on other type definitions are in list behind them).
1263 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1264 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1265 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1267 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1268 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1269 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1270 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1271 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1272 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1275 // SortedMap guarantees order corresponding to keys in ascending order
1276 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1277 sortedTypeDefinition.addAll(v);
1280 return sortedTypeDefinition;
1284 * Returns how many immersion is necessary to get from the type definition to the base type.
1286 * @param typeDefinition type definition for which is depth sought.
1287 * @return number of immersions which are necessary to get from the type definition to the base type
1289 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1290 // FIXME: rewrite this in a non-recursive manner
1291 if (typeDefinition == null) {
1294 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1295 if (baseType == null) {
1300 if (baseType.getBaseType() != null) {
1301 depth = depth + getTypeDefinitionDepth(baseType);
1302 } else if (baseType instanceof UnionTypeDefinition) {
1303 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1304 int maxChildDepth = 0;
1306 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1307 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1308 if (childDepth > maxChildDepth) {
1309 maxChildDepth = childDepth;
1312 return maxChildDepth;
1318 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1319 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1320 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1322 * @param name string with name of augmented node
1323 * @return string with the number suffix incremented by one (or 1 is added)
1325 private static String provideAvailableNameForGenTOBuilder(final String name) {
1326 final int dollar = name.indexOf('$');
1331 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1332 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1333 return name.substring(0, dollar + 1) + newSuffix;
1336 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1337 if (!Strings.isNullOrEmpty(units)) {
1338 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1339 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1340 prop.setReturnType(Types.STRING);
1341 to.addToStringProperty(prop);
1346 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1347 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1350 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1351 final TypeDefinition<?> type = CompatUtils.compatType(node);
1352 final QName typeQName = type.getQName();
1353 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1354 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1355 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1358 final StringBuilder sb = new StringBuilder();
1359 String result = null;
1360 if (base instanceof BinaryTypeDefinition) {
1361 result = binaryToDef(defaultValue);
1362 } else if (base instanceof BitsTypeDefinition) {
1365 final Module parent = getParentModule(node);
1366 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1368 if (!path.hasNext()) {
1369 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1370 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1371 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1373 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1374 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1376 parentName = BindingMapping.getClassName(parent.getName());
1377 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1379 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1380 } else if (base instanceof BooleanTypeDefinition) {
1381 result = typeToBooleanDef(defaultValue);
1382 } else if (base instanceof DecimalTypeDefinition) {
1383 result = typeToDef(BigDecimal.class, defaultValue);
1384 } else if (base instanceof EmptyTypeDefinition) {
1385 result = typeToBooleanDef(defaultValue);
1386 } else if (base instanceof EnumTypeDefinition) {
1387 final char[] defValArray = defaultValue.toCharArray();
1388 final char first = Character.toUpperCase(defaultValue.charAt(0));
1389 defValArray[0] = first;
1390 final String newDefVal = new String(defValArray);
1392 if (type.getBaseType() != null) {
1393 final Module m = getParentModule(type);
1394 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1395 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1397 className = packageName + "." + BindingMapping.getClassName(typeQName);
1399 final Module parentModule = getParentModule(node);
1400 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1401 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1403 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1405 result = className + "." + newDefVal;
1406 } else if (base instanceof IdentityrefTypeDefinition) {
1407 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1408 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1409 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1410 } else if (BaseTypes.isInt8(base)) {
1411 result = typeToValueOfDef(Byte.class, defaultValue);
1412 } else if (BaseTypes.isInt16(base)) {
1413 result = typeToValueOfDef(Short.class, defaultValue);
1414 } else if (BaseTypes.isInt32(base)) {
1415 result = typeToValueOfDef(Integer.class, defaultValue);
1416 } else if (BaseTypes.isInt64(base)) {
1417 result = typeToValueOfDef(Long.class, defaultValue);
1418 } else if (base instanceof LeafrefTypeDefinition) {
1419 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1420 } else if (base instanceof StringTypeDefinition) {
1421 result = "\"" + defaultValue + "\"";
1422 } else if (BaseTypes.isUint8(base)) {
1423 result = typeToValueOfDef(Short.class, defaultValue);
1424 } else if (BaseTypes.isUint16(base)) {
1425 result = typeToValueOfDef(Integer.class, defaultValue);
1426 } else if (BaseTypes.isUint32(base)) {
1427 result = typeToValueOfDef(Long.class, defaultValue);
1428 } else if (BaseTypes.isUint64(base)) {
1429 switch (defaultValue) {
1431 result = "java.math.BigInteger.ZERO";
1434 result = "java.math.BigInteger.ONE";
1437 result = "java.math.BigInteger.TEN";
1440 result = typeToDef(BigInteger.class, defaultValue);
1442 } else if (base instanceof UnionTypeDefinition) {
1443 result = unionToDef(node);
1449 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1450 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1451 final Module m = getParentModule(type);
1452 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1453 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1455 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1456 sb.insert(0, "new " + className + "(");
1457 sb.insert(sb.length(), ')');
1460 return sb.toString();
1463 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1464 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1467 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1468 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1471 private static String typeToBooleanDef(final String defaultValue) {
1472 switch (defaultValue) {
1474 return "java.lang.Boolean.FALSE";
1476 return "java.lang.Boolean.TRUE";
1478 return typeToValueOfDef(Boolean.class, defaultValue);
1482 private static String binaryToDef(final String defaultValue) {
1483 final StringBuilder sb = new StringBuilder();
1484 final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1485 sb.append("new byte[] {");
1486 for (int i = 0; i < encoded.length; i++) {
1487 sb.append(encoded[i]);
1488 if (i != encoded.length - 1) {
1493 return sb.toString();
1496 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1498 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1499 final boolean isExt) {
1500 final List<Bit> bits = new ArrayList<>(type.getBits());
1501 bits.sort(BIT_NAME_COMPARATOR);
1502 final StringBuilder sb = new StringBuilder();
1505 sb.append(className);
1508 for (int i = 0; i < bits.size(); i++) {
1509 if (bits.get(i).getName().equals(defaultValue)) {
1514 if (i != bits.size() - 1) {
1521 return sb.toString();
1524 private Module getParentModule(final SchemaNode node) {
1525 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1526 return schemaContext.findModule(qname.getModule()).orElse(null);
1529 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1530 final String defaultValue) {
1531 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1532 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1533 "The Path Statement for Leafref Type Definition cannot be NULL!");
1535 final PathExpression xpath = leafrefType.getPathStatement();
1536 final String strXPath = xpath.getOriginalString();
1538 if (strXPath != null) {
1539 if (strXPath.indexOf('[') == -1) {
1540 final Module module = findParentModule(schemaContext, parentNode);
1541 if (module != null) {
1542 final SchemaNode dataNode;
1543 if (xpath.isAbsolute()) {
1544 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
1546 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1548 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1552 return "new java.lang.Object()";
1559 private String unionToDef(final LeafSchemaNode node) {
1560 final TypeDefinition<?> type = CompatUtils.compatType(node);
1564 if (type.getBaseType() != null) {
1565 final QName typeQName = type.getQName();
1566 Module module = null;
1567 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1568 if (modules.size() > 1) {
1569 for (Module m : modules) {
1570 if (m.getRevision().equals(typeQName.getRevision())) {
1575 if (module == null) {
1576 final List<Module> modulesList = new ArrayList<>(modules);
1577 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1578 module = modulesList.get(0);
1581 module = modules.iterator().next();
1584 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1585 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1587 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1588 final QName first = path.next();
1589 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1590 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1591 if (!path.hasNext()) {
1592 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1593 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1595 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1597 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1600 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1603 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1604 final StringBuilder sb = new StringBuilder();
1606 sb.append(className);
1608 sb.append(defaultValue);
1609 sb.append("\".toCharArray())");
1610 return sb.toString();
1614 public String getConstructorPropertyName(final SchemaNode node) {
1615 return node instanceof TypeDefinition<?> ? "value" : "";
1619 public String getParamNameFromType(final TypeDefinition<?> type) {
1620 return BindingMapping.getPropertyName(type.getQName().getLocalName());