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.util.ArrayList;
22 import java.util.Base64;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Optional;
33 import java.util.TreeMap;
34 import java.util.regex.Pattern;
35 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
36 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
37 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
38 import org.opendaylight.mdsal.binding.model.api.Enumeration;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
41 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
42 import org.opendaylight.mdsal.binding.model.api.Restrictions;
43 import org.opendaylight.mdsal.binding.model.api.Type;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
50 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
51 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
52 import org.opendaylight.mdsal.binding.model.util.Types;
53 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
55 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.common.Revision;
58 import org.opendaylight.yangtools.yang.common.Uint16;
59 import org.opendaylight.yangtools.yang.common.Uint32;
60 import org.opendaylight.yangtools.yang.common.Uint64;
61 import org.opendaylight.yangtools.yang.common.Uint8;
62 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
63 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.Module;
68 import org.opendaylight.yangtools.yang.model.api.PathExpression;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
72 import org.opendaylight.yangtools.yang.model.api.Status;
73 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
77 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
85 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
87 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
88 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
89 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
90 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
91 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
96 public abstract class AbstractTypeProvider implements TypeProvider {
97 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
98 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
100 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
101 // the case, as unions are emitted to their correct schema path.
102 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
103 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
106 * Contains the schema data red from YANG files.
108 private final SchemaContext schemaContext;
110 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
113 * The map which maps schema paths to JAVA <code>Type</code>.
115 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
116 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
117 private final Map<SchemaNode, JavaTypeName> renames;
120 * Creates new instance of class <code>TypeProviderImpl</code>.
122 * @param schemaContext contains the schema data red from YANG files
123 * @param renames renaming table
124 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
126 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
127 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
128 this.schemaContext = schemaContext;
129 this.renames = requireNonNull(renames);
130 resolveTypeDefsFromContext();
134 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
136 * @param refTypePath schema path used as the map key
137 * @param refType type which represents the map value
138 * @throws IllegalArgumentException
140 * <li>if <code>refTypePath</code> equal null</li>
141 * <li>if <code>refType</code> equal null</li>
145 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
146 Preconditions.checkArgument(refTypePath != null,
147 "Path reference of Enumeration Type Definition cannot be NULL!");
148 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
149 referencedTypes.put(refTypePath, refType);
152 public Map<Module, Set<Type>> getAdditionalTypes() {
153 return additionalTypes;
157 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
158 final boolean lenientRelativeLeafrefs) {
159 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
163 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
165 * @param typeDefinition type definition which is converted to JAVA type
166 * @throws IllegalArgumentException
168 * <li>if <code>typeDefinition</code> equal null</li>
169 * <li>if Qname of <code>typeDefinition</code> equal null</li>
170 * <li>if name of <code>typeDefinition</code> equal null</li>
174 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
175 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
176 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
177 Preconditions.checkArgument(typeDefinition.getQName() != null,
178 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
179 final String typedefName = typeDefinition.getQName().getLocalName();
180 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
182 // Deal with base types
183 if (typeDefinition.getBaseType() == null) {
184 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
185 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
186 // a base type which holds these constraints.
187 if (typeDefinition instanceof DecimalTypeDefinition) {
188 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
189 parentNode, restrictions, lenientRelativeLeafrefs);
195 // Deal with leafrefs/identityrefs
196 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
201 // FIXME: it looks as though we could be using the same codepath as above...
202 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
204 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
210 Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
211 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
212 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
213 final Module module = findParentModule(schemaContext, parentNode);
214 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
215 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
216 typeDefinition.getPath());
217 final String genTOName = BindingMapping.getClassName(typedefName);
218 final String name = packageName + "." + genTOName;
219 if (!returnType.getFullyQualifiedName().equals(name)) {
220 returnType = shadedTOWithRestrictions(gto, restrictions);
226 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
227 final Restrictions restrictions) {
228 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
229 final GeneratedTransferObject parent = gto.getSuperType();
230 if (parent != null) {
231 gtob.setExtendsType(parent);
233 gtob.setRestrictions(restrictions);
234 for (GeneratedProperty gp : gto.getProperties()) {
235 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
236 gpb.setValue(gp.getValue());
237 gpb.setReadOnly(gp.isReadOnly());
238 gpb.setAccessModifier(gp.getAccessModifier());
239 gpb.setReturnType(gp.getReturnType());
240 gpb.setFinal(gp.isFinal());
241 gpb.setStatic(gp.isStatic());
246 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
248 * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
251 DataNodeContainer current = null;
252 DataSchemaNode dataChildByName;
253 for (QName next : parentNode.getPath().getPathFromRoot()) {
254 if (current == null) {
255 dataChildByName = schemaContext.getDataChildByName(next);
257 dataChildByName = current.getDataChildByName(next);
259 if (dataChildByName == null) {
262 if (dataChildByName.isAugmenting()) {
265 if (dataChildByName instanceof DataNodeContainer) {
266 current = (DataNodeContainer) dataChildByName;
270 // Then try to look up the expression.
271 final PathExpression leafRefXPath = leafref.getPathStatement();
272 final PathExpression leafRefStrippedXPath = new PathExpressionImpl(
273 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), leafRefXPath.isAbsolute());
274 final Module parentModule = getParentModule(parentNode);
275 final SchemaNode leafRefValueNode;
276 if (!leafRefStrippedXPath.isAbsolute()) {
277 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
278 parentNode, leafRefStrippedXPath);
280 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
282 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
286 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
287 * <code>IdentityrefTypeDefinition</code>.
289 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
290 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
292 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
293 final boolean inGrouping) {
294 if (typeDefinition instanceof LeafrefTypeDefinition) {
295 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
296 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
297 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
298 return provideTypeForLeafref(leafref, parentNode, inGrouping);
299 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
300 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
307 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
309 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
310 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
312 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
313 final String typedefName = typeDefinition.getQName().getLocalName();
314 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
315 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
316 if (returnType == null) {
317 if (baseTypeDef instanceof EnumTypeDefinition) {
318 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
319 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
321 final Module module = findParentModule(schemaContext, typeDefinition);
322 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
323 if (module != null) {
324 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
326 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
327 if (genTOs != null) {
328 returnType = genTOs.get(typedefName);
330 if (returnType == null) {
331 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
332 baseTypeDef, typeDefinition, r, lenient);
341 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
345 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
346 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
348 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
349 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
351 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
352 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
353 if (identities.size() > 1) {
354 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
357 final QName baseIdQName = identities.iterator().next().getQName();
358 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
359 IdentitySchemaNode identity = null;
360 for (IdentitySchemaNode id : module.getIdentities()) {
361 if (id.getQName().equals(baseIdQName)) {
365 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
367 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
368 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
369 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
370 return Types.classType(Types.wildcardTypeFor(identifier));
374 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
376 * @param typeDefinition
377 * type definition which should be converted to JAVA
379 * @return JAVA <code>Type</code> which represents
380 * <code>typeDefinition</code>
381 * @throws IllegalArgumentException
383 * <li>if <code>typeDefinition</code> equal null</li>
384 * <li>if Q name of <code>typeDefinition</code></li>
385 * <li>if name of <code>typeDefinition</code></li>
388 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
389 final SchemaNode parentNode) {
390 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
391 if (typeDefinition.getQName() == null) {
392 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
394 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
395 "Type Definitions Local Name cannot be NULL!");
397 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
398 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
400 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
401 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
414 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
415 * dicey when we throw in:
429 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
430 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
433 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
434 * an encapsulation for identityref typedefs.
436 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
437 * option, as it would look as though it is the product of a different construct:
443 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
444 * sub-identities of iden.
446 * The story behind leafrefs is probably similar, but that needs to be ascertained.
451 final Module module = findParentModule(schemaContext, parentNode);
452 if (module != null) {
453 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
455 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
456 if (genTOs != null) {
457 return genTOs.get(typeDefinition.getQName().getLocalName());
464 * Gets base type definition for <code>extendTypeDef</code>. The method is
465 * recursively called until non <code>ExtendedType</code> type is found.
467 * @param extendTypeDef
468 * type definition for which is the base type definition sought
469 * @return type definition which is base type for <code>extendTypeDef</code>
470 * @throws IllegalArgumentException
471 * if <code>extendTypeDef</code> equal null
473 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
474 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
476 TypeDefinition<?> ret = extendTypeDef;
477 while (ret.getBaseType() != null) {
478 ret = ret.getBaseType();
485 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
486 * to find referenced node and its <code>Type</code> is returned.
488 * @param leafrefType leafref type definition for which is the type sought
489 * @param parentNode parent node of the leaf being resolved
490 * @param inGrouping true if we are resolving the type within a grouping.
491 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
492 * @throws IllegalArgumentException
494 * <li>if <code>leafrefType</code> equal null</li>
495 * <li>if path statement of <code>leafrefType</code> equal null</li>
498 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
499 final boolean inGrouping) {
500 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
502 final PathExpression xpath = leafrefType.getPathStatement();
503 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
505 final String strXPath = xpath.getOriginalString();
506 if (strXPath.indexOf('[') != -1) {
507 // XXX: why are we special-casing this?
508 return Types.objectType();
511 final Module module = findParentModule(schemaContext, parentNode);
512 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
514 final SchemaNode dataNode;
515 if (xpath.isAbsolute()) {
516 dataNode = findDataSchemaNode(schemaContext, module, xpath);
518 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
519 if (dataNode == null && inGrouping) {
520 // Relative path within a grouping may end up being unresolvable because it may refer outside
521 // the grouping, in which case it is polymorphic based on instantiation, for example:
544 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
546 return Types.objectType();
549 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
550 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
552 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
553 Type returnType = null;
554 if (leafContainsEnumDefinition(dataNode)) {
555 returnType = referencedTypes.get(dataNode.getPath());
556 } else if (leafListContainsEnumDefinition(dataNode)) {
557 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
559 if (returnType == null) {
560 returnType = resolveTypeFromDataSchemaNode(dataNode);
562 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
563 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
568 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
569 * <code>EnumTypeDefinition</code>.
571 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
572 * @return boolean value
574 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
575 * <li>false - other cases</li>
578 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
579 if (dataNode instanceof LeafSchemaNode) {
580 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
581 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
587 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
588 * <code>EnumTypeDefinition</code>.
590 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
591 * @return boolean value
593 * <li>true - if <code>dataNode</code> is leaflist of type
595 * <li>false - other cases</li>
598 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
599 if (dataNode instanceof LeafListSchemaNode) {
600 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
601 return leafList.getType() instanceof EnumTypeDefinition;
607 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
609 * @param enumTypeDef enumeration type definition which is converted to enumeration
610 * @param enumName string with name which is used as the enumeration name
611 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
612 * @throws IllegalArgumentException
614 * <li>if <code>enumTypeDef</code> equals null</li>
615 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
616 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
617 * <li>if name of <code>enumTypeDef</code> equal null</li>
620 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
621 final SchemaNode parentNode) {
622 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
623 Preconditions.checkArgument(enumTypeDef.getValues() != null,
624 "EnumTypeDefinition MUST contain at least ONE value definition!");
625 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
626 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
627 "Local Name in EnumTypeDefinition QName cannot be NULL!");
629 final Module module = findParentModule(schemaContext, parentNode);
630 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
631 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
632 addEnumDescription(enumBuilder, enumTypeDef);
633 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
634 enumBuilder.setModuleName(module.getName());
635 enumBuilder.setSchemaPath(enumTypeDef.getPath());
636 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
637 return enumBuilder.toInstance(null);
641 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
643 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
644 * @param enumName string with the name of enumeration
645 * @param typeBuilder generated type builder to which is enumeration added
646 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
647 * @throws IllegalArgumentException
649 * <li>if <code>enumTypeDef</code> equals null</li>
650 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
651 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
652 * <li>if name of <code>enumTypeDef</code> equal null</li>
653 * <li>if name of <code>typeBuilder</code> equal null</li>
657 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
658 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
659 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
660 Preconditions.checkArgument(enumTypeDef.getValues() != null,
661 "EnumTypeDefinition MUST contain at least ONE value definition!");
662 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
663 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
664 "Local Name in EnumTypeDefinition QName cannot be NULL!");
665 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
667 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
669 addEnumDescription(enumBuilder, enumTypeDef);
670 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
671 return enumBuilder.toInstance(enumBuilder);
674 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
676 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
678 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
680 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
683 * Converts the pattern constraints to the list of the strings which represents these constraints.
685 * @param patternConstraints list of pattern constraints
686 * @return list of strings which represents the constraint patterns
688 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
690 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
693 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
696 * @param typedef extended type in which are the pattern constraints sought
697 * @return list of strings which represents the constraint patterns
698 * @throws IllegalArgumentException if <code>typedef</code> equals null
701 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
702 if (!(typedef instanceof StringTypeDefinition)) {
703 return ImmutableMap.of();
706 // TODO: run diff against base ?
707 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
711 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
713 * @param dataNode contains information about YANG type
714 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
716 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
717 Type returnType = null;
718 if (dataNode != null) {
719 if (dataNode instanceof LeafSchemaNode) {
720 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
721 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
722 returnType = javaTypeForSchemaDefinitionType(type, leaf);
723 } else if (dataNode instanceof LeafListSchemaNode) {
724 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
725 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
732 * Passes through all modules and through all its type definitions and convert it to generated types.
735 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
736 * of a module are at the beginning sorted so that type definition with less amount of references to other type
737 * definition are processed first.<br>
738 * For each module is created mapping record in the map
739 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
740 * which map current module name to the map which maps type names to returned types (generated types).
742 private void resolveTypeDefsFromContext() {
743 final Set<Module> modules = schemaContext.getModules();
744 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
745 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
747 for (Module module : modulesSortedByDependency) {
748 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
749 module.getName(), key -> new HashMap<>());
750 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
751 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
754 for (Module module : modulesSortedByDependency) {
755 if (module != null) {
756 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
757 if (basePackageName != null) {
758 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
759 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
760 typedefToGeneratedType(basePackageName, module, typedef);
768 * Create Type for specified type definition.
770 * @param basePackageName string with name of package to which the module belongs
771 * @param module string with the name of the module for to which the <code>typedef</code> belongs
772 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
773 * (usually generated TO)
774 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
775 * <code>null</code> value if <code>basePackageName</code> or
776 * <code>modulName</code> or <code>typedef</code> or Q name of
777 * <code>typedef</code> equals <code>null</code>
779 private Type typedefToGeneratedType(final String basePackageName, final Module module,
780 final TypeDefinition<?> typedef) {
781 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
783 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
784 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
788 final String typedefName = typedef.getQName().getLocalName();
790 final Type returnType;
791 if (baseTypedef.getBaseType() != null) {
792 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
794 } else if (baseTypedef instanceof UnionTypeDefinition) {
795 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
796 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
797 (UnionTypeDefinition) baseTypedef, typedef);
798 genTOBuilder.setTypedef(true);
799 genTOBuilder.setIsUnion(true);
800 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
801 makeSerializable(genTOBuilder);
802 returnType = genTOBuilder.build();
804 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
805 // so we are placing the builder alongside the union.
806 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
807 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
808 unionBuilder.setIsUnionBuilder(true);
809 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
810 method.setReturnType(returnType);
811 method.addParameter(Types.STRING, "defaultValue");
812 method.setAccessModifier(AccessModifier.PUBLIC);
813 method.setStatic(true);
814 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
815 } else if (baseTypedef instanceof EnumTypeDefinition) {
816 // enums are automatically Serializable
817 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
818 // TODO units for typedef enum
819 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
820 } else if (baseTypedef instanceof BitsTypeDefinition) {
821 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
822 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
823 (BitsTypeDefinition) baseTypedef, module.getName());
824 genTOBuilder.setTypedef(true);
825 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
826 makeSerializable(genTOBuilder);
827 returnType = genTOBuilder.build();
829 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
830 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
832 if (returnType != null) {
833 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
834 genTypeDefsContextMap.get(module.getName());
835 final Optional<Revision> moduleRevision = module.getRevision();
836 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
837 if (typeMap != null) {
838 if (typeMap.isEmpty()) {
839 typeMap = new HashMap<>(4);
840 modulesByDate.put(moduleRevision, typeMap);
842 typeMap.put(typedefName, returnType);
850 * Wraps base YANG type to generated TO.
852 * @param basePackageName string with name of package to which the module belongs
853 * @param typedef type definition which is converted to the TO
854 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
855 * @return generated transfer object which represent<code>javaType</code>
857 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
858 final Type javaType, final String moduleName) {
859 requireNonNull(javaType, "javaType cannot be null");
861 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
862 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
863 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
864 genPropBuilder.setReturnType(javaType);
865 genTOBuilder.addEqualsIdentity(genPropBuilder);
866 genTOBuilder.addHashIdentity(genPropBuilder);
867 genTOBuilder.addToStringProperty(genPropBuilder);
868 genTOBuilder.addImplementsType(TYPE_OBJECT);
869 if (typedef.getStatus() == Status.DEPRECATED) {
870 genTOBuilder.addAnnotation("java.lang", "Deprecated");
872 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
873 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
875 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
876 genTOBuilder.setTypedef(true);
877 makeSerializable(genTOBuilder);
878 return genTOBuilder.build();
882 * Converts output list of generated TO builders to one TO builder (first
883 * from list) which contains the remaining builders as its enclosing TO.
885 * @param typeName new type identifier
886 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
887 * @return generated TO builder with the list of enclosed generated TO builders
889 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
890 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
891 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
893 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
895 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
896 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
897 return resultTOBuilder;
901 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
902 * <code>typedef</code> is added to generated TO builder as property.
904 * @param typeName new type identifier
905 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
906 * @return generated TO builder which represents <code>typedef</code>
907 * @throws NullPointerException
909 * <li>if <code>basePackageName</code> is null</li>
910 * <li>if <code>typedef</code> is null</li>
911 * <li>if Qname of <code>typedef</code> is null</li>
914 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
915 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
916 requireNonNull(typedef, "Type Definition cannot be NULL!");
917 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
919 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
920 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
921 final Module module = findParentModule(schemaContext, parentNode);
923 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
924 unionGenTOBuilder.setIsUnion(true);
925 unionGenTOBuilder.setSchemaPath(typedef.getPath());
926 unionGenTOBuilder.setModuleName(module.getName());
927 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
928 addCodegenInformation(unionGenTOBuilder, typedef);
929 generatedTOBuilders.add(unionGenTOBuilder);
931 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
932 // also negation information and hence guarantees uniqueness.
933 final Map<String, String> expressions = new HashMap<>();
934 for (TypeDefinition<?> unionType : unionTypes) {
935 final String unionTypeName = unionType.getQName().getLocalName();
937 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
938 // do not follow type encapsulation -- we use the general case for that.
939 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
940 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
941 } else if (unionType instanceof UnionTypeDefinition) {
942 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
943 (UnionTypeDefinition) unionType, parentNode));
944 } else if (unionType instanceof EnumTypeDefinition) {
945 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
946 unionTypeName, unionGenTOBuilder);
947 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
949 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
950 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
953 addStringRegExAsConstant(unionGenTOBuilder, expressions);
955 storeGenTO(typedef, unionGenTOBuilder, parentNode);
957 return generatedTOBuilders;
961 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
964 * In this case the new generated TO is created for union subtype (recursive call of method
965 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
966 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
967 * created property which type is equal to new generated TO.
969 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
970 * @param basePackageName string with the name of the module package
971 * @param unionSubtype type definition which represents union subtype
972 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
973 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
975 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
976 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
977 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
978 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
979 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
980 newTOBuilderName, unionSubtype, parentNode);
982 final GeneratedPropertyBuilder propertyBuilder;
983 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
984 newTOBuilderName.simpleName()));
985 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
986 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
987 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
989 return subUnionGenTOBUilders;
993 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
994 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
995 * the base type is used for the property creation.
997 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
998 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
999 * @param expressions list of strings with the regular expressions
1000 * @param parentNode parent Schema Node for Extended Subtype
1002 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1003 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1004 final String unionTypeName = unionSubtype.getQName().getLocalName();
1005 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1006 if (genTO != null) {
1007 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1011 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1012 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1013 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1014 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1015 if (javaType != null) {
1016 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1018 } else if (baseType instanceof LeafrefTypeDefinition) {
1019 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1020 boolean typeExist = false;
1021 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1022 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1023 if (origType != null && javaType != null && javaType == origType) {
1028 if (!typeExist && javaType != null) {
1029 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1030 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1033 if (baseType instanceof StringTypeDefinition) {
1034 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1039 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1040 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1042 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1043 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1045 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1046 final Module typeModule = findParentModule(schemaContext, parentNode);
1047 if (typeModule != null && typeModule.getName() != null) {
1048 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1049 typeModule.getName());
1050 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1051 if (genTOs != null) {
1052 return genTOs.get(searchedTypeName);
1059 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1060 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1062 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1063 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1065 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1066 final SchemaNode parentNode) {
1067 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1068 final Module parentModule = findParentModule(schemaContext, parentNode);
1069 if (parentModule != null && parentModule.getName() != null) {
1070 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1071 parentModule.getName());
1072 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1073 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1079 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1080 * to <code>unonGenTransObject</code>.
1082 * @param unionGenTransObject generated TO to which should be property added
1083 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1084 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1086 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1087 final String propertyName) {
1088 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1089 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1090 .addProperty(BindingMapping.getPropertyName(propertyName));
1091 propBuilder.setReturnType(type);
1093 unionGenTransObject.addEqualsIdentity(propBuilder);
1094 unionGenTransObject.addHashIdentity(propBuilder);
1095 unionGenTransObject.addToStringProperty(propBuilder);
1100 * Converts <code>typedef</code> to the generated TO builder.
1102 * @param basePackageName string with name of package to which the module belongs
1103 * @param typedef type definition from which is the generated TO builder created
1104 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1106 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1107 final TypeDefinition<?> typedef, final String moduleName) {
1108 JavaTypeName name = renames.get(typedef);
1110 name = JavaTypeName.create(
1111 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1112 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1115 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1116 newType.setSchemaPath(typedef.getPath());
1117 newType.setModuleName(moduleName);
1118 addCodegenInformation(newType, typedef);
1123 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1124 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1127 * @param typeName new type identifier
1128 * @param typeDef type definition from which is the generated TO builder created
1129 * @return generated TO builder which represents <code>typeDef</code>
1130 * @throws IllegalArgumentException
1132 * <li>if <code>typeDef</code> equals null</li>
1133 * <li>if <code>basePackageName</code> equals null</li>
1136 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1137 final BitsTypeDefinition typeDef, final String moduleName) {
1138 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1139 genTOBuilder.setSchemaPath(typeDef.getPath());
1140 genTOBuilder.setModuleName(moduleName);
1141 genTOBuilder.setBaseType(typeDef);
1142 genTOBuilder.addImplementsType(TYPE_OBJECT);
1143 addCodegenInformation(genTOBuilder, typeDef);
1145 final List<Bit> bitList = typeDef.getBits();
1146 GeneratedPropertyBuilder genPropertyBuilder;
1147 for (Bit bit : bitList) {
1148 final String name = bit.getName();
1149 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1150 genPropertyBuilder.setReadOnly(true);
1151 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1153 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1154 genTOBuilder.addHashIdentity(genPropertyBuilder);
1155 genTOBuilder.addToStringProperty(genPropertyBuilder);
1158 return genTOBuilder;
1162 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1163 * the <code>regularExpressions</code>.
1165 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1166 * @param expressions list of string which represent regular expressions
1168 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1169 final Map<String, String> expressions) {
1170 if (!expressions.isEmpty()) {
1171 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1172 ImmutableMap.copyOf(expressions));
1177 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1178 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1181 * It is assumed that <code>innerExtendedType</code> is already present in
1182 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1183 * for the returning generated TO.
1185 * @param typedef Type Definition
1186 * @param innerExtendedType extended type which is part of some other extended type
1187 * @param basePackageName string with the package name of the module
1188 * @param moduleName Module Name
1189 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1190 * @throws IllegalArgumentException
1192 * <li>if <code>extendedType</code> equals null</li>
1193 * <li>if <code>basePackageName</code> equals null</li>
1194 * <li>if <code>typedefName</code> equals null</li>
1197 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1198 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1199 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1200 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1202 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1203 BindingMapping.getClassName(typedef.getQName())));
1204 genTOBuilder.setSchemaPath(typedef.getPath());
1205 genTOBuilder.setModuleName(moduleName);
1206 genTOBuilder.setTypedef(true);
1207 addCodegenInformation(genTOBuilder, typedef);
1209 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1210 genTOBuilder.setRestrictions(r);
1211 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1213 if (typedef.getStatus() == Status.DEPRECATED) {
1214 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1217 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1218 genTOBuilder.setIsUnion(true);
1221 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1222 Map<String, Type> typeMap = null;
1223 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1224 if (parentModule != null) {
1225 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1226 typeMap = modulesByDate.get(parentModule.getRevision());
1229 if (typeMap != null) {
1230 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1231 final Type type = typeMap.get(innerTypeDef);
1232 if (type instanceof GeneratedTransferObject) {
1233 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1236 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1237 makeSerializable(genTOBuilder);
1239 return genTOBuilder.build();
1243 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1246 * @param gto transfer object which needs to be made serializable
1248 private static void makeSerializable(final GeneratedTOBuilder gto) {
1249 gto.addImplementsType(Types.serializableType());
1250 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1251 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1256 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1257 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1258 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1259 * type definitions are in the list behind all type definitions on which depends.
1261 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1262 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1263 * dependent on other type definitions are in list behind them).
1265 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1266 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1267 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1269 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1270 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1271 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1272 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1273 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1274 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1277 // SortedMap guarantees order corresponding to keys in ascending order
1278 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1279 sortedTypeDefinition.addAll(v);
1282 return sortedTypeDefinition;
1286 * Returns how many immersion is necessary to get from the type definition to the base type.
1288 * @param typeDefinition type definition for which is depth sought.
1289 * @return number of immersions which are necessary to get from the type definition to the base type
1291 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1292 // FIXME: rewrite this in a non-recursive manner
1293 if (typeDefinition == null) {
1296 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1297 if (baseType == null) {
1302 if (baseType.getBaseType() != null) {
1303 depth = depth + getTypeDefinitionDepth(baseType);
1304 } else if (baseType instanceof UnionTypeDefinition) {
1305 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1306 int maxChildDepth = 0;
1308 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1309 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1310 if (childDepth > maxChildDepth) {
1311 maxChildDepth = childDepth;
1314 return maxChildDepth;
1320 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1321 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1322 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1324 * @param name string with name of augmented node
1325 * @return string with the number suffix incremented by one (or 1 is added)
1327 private static String provideAvailableNameForGenTOBuilder(final String name) {
1328 final int dollar = name.indexOf('$');
1333 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1334 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1335 return name.substring(0, dollar + 1) + newSuffix;
1338 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1339 if (!Strings.isNullOrEmpty(units)) {
1340 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1341 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1342 prop.setReturnType(Types.STRING);
1343 to.addToStringProperty(prop);
1348 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1349 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1352 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1353 final TypeDefinition<?> type = CompatUtils.compatType(node);
1354 final QName typeQName = type.getQName();
1355 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1356 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1357 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1360 final StringBuilder sb = new StringBuilder();
1361 String result = null;
1362 if (base instanceof BinaryTypeDefinition) {
1363 result = binaryToDef(defaultValue);
1364 } else if (base instanceof BitsTypeDefinition) {
1367 final Module parent = getParentModule(node);
1368 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1370 if (!path.hasNext()) {
1371 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1372 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1373 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1375 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1376 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1378 parentName = BindingMapping.getClassName(parent.getName());
1379 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1381 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1382 } else if (base instanceof BooleanTypeDefinition) {
1383 result = typeToBooleanDef(defaultValue);
1384 } else if (base instanceof DecimalTypeDefinition) {
1385 result = typeToDef(BigDecimal.class, defaultValue);
1386 } else if (base instanceof EmptyTypeDefinition) {
1387 result = typeToBooleanDef(defaultValue);
1388 } else if (base instanceof EnumTypeDefinition) {
1389 final char[] defValArray = defaultValue.toCharArray();
1390 final char first = Character.toUpperCase(defaultValue.charAt(0));
1391 defValArray[0] = first;
1392 final String newDefVal = new String(defValArray);
1394 if (type.getBaseType() != null) {
1395 final Module m = getParentModule(type);
1396 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1397 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1399 className = packageName + "." + BindingMapping.getClassName(typeQName);
1401 final Module parentModule = getParentModule(node);
1402 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1403 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1405 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1407 result = className + "." + newDefVal;
1408 } else if (base instanceof IdentityrefTypeDefinition) {
1409 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1410 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1411 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1412 } else if (BaseTypes.isInt8(base)) {
1413 result = typeToValueOfDef(Byte.class, defaultValue);
1414 } else if (BaseTypes.isInt16(base)) {
1415 result = typeToValueOfDef(Short.class, defaultValue);
1416 } else if (BaseTypes.isInt32(base)) {
1417 result = typeToValueOfDef(Integer.class, defaultValue);
1418 } else if (BaseTypes.isInt64(base)) {
1419 result = typeToValueOfDef(Long.class, defaultValue);
1420 } else if (base instanceof LeafrefTypeDefinition) {
1421 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1422 } else if (base instanceof StringTypeDefinition) {
1423 result = "\"" + defaultValue + "\"";
1424 } else if (BaseTypes.isUint8(base)) {
1425 result = typeToValueOfDef(Uint8.class, defaultValue);
1426 } else if (BaseTypes.isUint16(base)) {
1427 result = typeToValueOfDef(Uint16.class, defaultValue);
1428 } else if (BaseTypes.isUint32(base)) {
1429 result = typeToValueOfDef(Uint32.class, defaultValue);
1430 } else if (BaseTypes.isUint64(base)) {
1431 result = typeToValueOfDef(Uint64.class, defaultValue);
1432 } else if (base instanceof UnionTypeDefinition) {
1433 result = unionToDef(node);
1439 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1440 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1441 final Module m = getParentModule(type);
1442 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1443 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1445 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1446 sb.insert(0, "new " + className + "(");
1447 sb.insert(sb.length(), ')');
1450 return sb.toString();
1453 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1454 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1457 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1458 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1461 private static String typeToBooleanDef(final String defaultValue) {
1462 switch (defaultValue) {
1464 return "java.lang.Boolean.FALSE";
1466 return "java.lang.Boolean.TRUE";
1468 return typeToValueOfDef(Boolean.class, defaultValue);
1472 private static String binaryToDef(final String defaultValue) {
1473 final StringBuilder sb = new StringBuilder();
1474 final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1475 sb.append("new byte[] {");
1476 for (int i = 0; i < encoded.length; i++) {
1477 sb.append(encoded[i]);
1478 if (i != encoded.length - 1) {
1483 return sb.toString();
1486 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1488 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1489 final boolean isExt) {
1490 final List<Bit> bits = new ArrayList<>(type.getBits());
1491 bits.sort(BIT_NAME_COMPARATOR);
1492 final StringBuilder sb = new StringBuilder();
1495 sb.append(className);
1498 for (int i = 0; i < bits.size(); i++) {
1499 if (bits.get(i).getName().equals(defaultValue)) {
1504 if (i != bits.size() - 1) {
1511 return sb.toString();
1514 private Module getParentModule(final SchemaNode node) {
1515 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1516 return schemaContext.findModule(qname.getModule()).orElse(null);
1519 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1520 final String defaultValue) {
1521 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1522 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1523 "The Path Statement for Leafref Type Definition cannot be NULL!");
1525 final PathExpression xpath = leafrefType.getPathStatement();
1526 final String strXPath = xpath.getOriginalString();
1528 if (strXPath != null) {
1529 if (strXPath.indexOf('[') == -1) {
1530 final Module module = findParentModule(schemaContext, parentNode);
1531 if (module != null) {
1532 final SchemaNode dataNode;
1533 if (xpath.isAbsolute()) {
1534 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1536 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1538 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1542 return "new java.lang.Object()";
1549 private String unionToDef(final LeafSchemaNode node) {
1550 final TypeDefinition<?> type = CompatUtils.compatType(node);
1554 if (type.getBaseType() != null) {
1555 final QName typeQName = type.getQName();
1556 Module module = null;
1557 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1558 if (modules.size() > 1) {
1559 for (Module m : modules) {
1560 if (m.getRevision().equals(typeQName.getRevision())) {
1565 if (module == null) {
1566 final List<Module> modulesList = new ArrayList<>(modules);
1567 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1568 module = modulesList.get(0);
1571 module = modules.iterator().next();
1574 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1575 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1577 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1578 final QName first = path.next();
1579 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1580 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1581 if (!path.hasNext()) {
1582 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1583 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1585 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1587 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1590 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1593 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1594 final StringBuilder sb = new StringBuilder();
1596 sb.append(className);
1598 sb.append(defaultValue);
1599 sb.append("\".toCharArray())");
1600 return sb.toString();
1604 public String getConstructorPropertyName(final SchemaNode node) {
1605 return node instanceof TypeDefinition<?> ? "value" : "";
1609 public String getParamNameFromType(final TypeDefinition<?> type) {
1610 return BindingMapping.getPropertyName(type.getQName().getLocalName());