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.annotations.VisibleForTesting;
18 import com.google.common.base.Preconditions;
19 import com.google.common.base.Strings;
20 import com.google.common.collect.ImmutableMap;
21 import java.math.BigDecimal;
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.common.Uint16;
60 import org.opendaylight.yangtools.yang.common.Uint32;
61 import org.opendaylight.yangtools.yang.common.Uint64;
62 import org.opendaylight.yangtools.yang.common.Uint8;
63 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
64 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.PathExpression;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
72 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
73 import org.opendaylight.yangtools.yang.model.api.Status;
74 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
78 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
86 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
87 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
88 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
89 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
90 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
91 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
92 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
93 import org.slf4j.Logger;
94 import org.slf4j.LoggerFactory;
97 public abstract class AbstractTypeProvider implements TypeProvider {
98 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
99 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
101 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
102 // the case, as unions are emitted to their correct schema path.
103 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
104 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
107 * Contains the schema data red from YANG files.
109 private final SchemaContext schemaContext;
111 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
114 * The map which maps schema paths to JAVA <code>Type</code>.
116 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
117 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
118 private final Map<SchemaNode, JavaTypeName> renames;
121 * Creates new instance of class <code>TypeProviderImpl</code>.
123 * @param schemaContext contains the schema data red from YANG files
124 * @param renames renaming table
125 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
127 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
128 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
129 this.schemaContext = schemaContext;
130 this.renames = requireNonNull(renames);
131 resolveTypeDefsFromContext();
135 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
137 * @param refTypePath schema path used as the map key
138 * @param refType type which represents the map value
139 * @throws IllegalArgumentException
141 * <li>if <code>refTypePath</code> equal null</li>
142 * <li>if <code>refType</code> equal null</li>
146 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
147 Preconditions.checkArgument(refTypePath != null,
148 "Path reference of Enumeration Type Definition cannot be NULL!");
149 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
150 referencedTypes.put(refTypePath, refType);
153 public Map<Module, Set<Type>> getAdditionalTypes() {
154 return additionalTypes;
158 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
159 final boolean lenientRelativeLeafrefs) {
160 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
164 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
166 * @param typeDefinition type definition which is converted to JAVA type
167 * @throws IllegalArgumentException
169 * <li>if <code>typeDefinition</code> equal null</li>
170 * <li>if Qname of <code>typeDefinition</code> equal null</li>
171 * <li>if name of <code>typeDefinition</code> equal null</li>
175 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
176 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
177 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
178 Preconditions.checkArgument(typeDefinition.getQName() != null,
179 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
180 final String typedefName = typeDefinition.getQName().getLocalName();
181 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
183 // Deal with base types
184 if (typeDefinition.getBaseType() == null) {
185 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
186 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
187 // a base type which holds these constraints.
188 if (typeDefinition instanceof DecimalTypeDefinition) {
189 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
190 parentNode, restrictions, lenientRelativeLeafrefs);
196 // Deal with leafrefs/identityrefs
197 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
202 // FIXME: it looks as though we could be using the same codepath as above...
203 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
205 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
211 Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
212 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
213 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
214 final Module module = findParentModule(schemaContext, parentNode);
215 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
216 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
217 typeDefinition.getPath());
218 final String genTOName = BindingMapping.getClassName(typedefName);
219 final String name = packageName + "." + genTOName;
220 if (!returnType.getFullyQualifiedName().equals(name)) {
221 returnType = shadedTOWithRestrictions(gto, restrictions);
227 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
228 final Restrictions restrictions) {
229 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
230 final GeneratedTransferObject parent = gto.getSuperType();
231 if (parent != null) {
232 gtob.setExtendsType(parent);
234 gtob.setRestrictions(restrictions);
235 for (GeneratedProperty gp : gto.getProperties()) {
236 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
237 gpb.setValue(gp.getValue());
238 gpb.setReadOnly(gp.isReadOnly());
239 gpb.setAccessModifier(gp.getAccessModifier());
240 gpb.setReturnType(gp.getReturnType());
241 gpb.setFinal(gp.isFinal());
242 gpb.setStatic(gp.isStatic());
247 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
249 * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
252 DataNodeContainer current = null;
253 DataSchemaNode dataChildByName;
254 for (QName next : parentNode.getPath().getPathFromRoot()) {
255 if (current == null) {
256 dataChildByName = schemaContext.getDataChildByName(next);
258 dataChildByName = current.getDataChildByName(next);
260 if (dataChildByName == null) {
263 if (dataChildByName.isAugmenting()) {
266 if (dataChildByName instanceof DataNodeContainer) {
267 current = (DataNodeContainer) dataChildByName;
271 // Then try to look up the expression.
272 final PathExpression leafRefXPath = leafref.getPathStatement();
273 final Module parentModule = getParentModule(parentNode);
274 final SchemaNode leafRefValueNode;
275 if (leafRefXPath.isAbsolute()) {
276 leafRefValueNode = SchemaContextUtil.findDataTreeSchemaNode(schemaContext, parentModule.getQNameModule(),
279 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
280 parentNode, new PathExpressionImpl(
281 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), false));
284 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
288 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
289 * <code>IdentityrefTypeDefinition</code>.
291 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
292 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
294 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
295 final boolean inGrouping) {
296 if (typeDefinition instanceof LeafrefTypeDefinition) {
297 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
298 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
299 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
300 return provideTypeForLeafref(leafref, parentNode, inGrouping);
301 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
302 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
309 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
311 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
312 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
314 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
315 final String typedefName = typeDefinition.getQName().getLocalName();
316 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
317 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
318 if (returnType == null) {
319 if (baseTypeDef instanceof EnumTypeDefinition) {
320 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
321 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
323 final Module module = findParentModule(schemaContext, typeDefinition);
324 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
325 if (module != null) {
326 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
328 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
329 if (genTOs != null) {
330 returnType = genTOs.get(typedefName);
332 if (returnType == null) {
333 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
334 baseTypeDef, typeDefinition, r, lenient);
343 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
347 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
348 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
350 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
351 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
353 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
354 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
355 if (identities.size() > 1) {
356 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
359 final QName baseIdQName = identities.iterator().next().getQName();
360 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
361 IdentitySchemaNode identity = null;
362 for (IdentitySchemaNode id : module.getIdentities()) {
363 if (id.getQName().equals(baseIdQName)) {
367 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
369 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
370 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
371 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
372 return Types.classType(Types.wildcardTypeFor(identifier));
376 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
378 * @param typeDefinition
379 * type definition which should be converted to JAVA
381 * @return JAVA <code>Type</code> which represents
382 * <code>typeDefinition</code>
383 * @throws IllegalArgumentException
385 * <li>if <code>typeDefinition</code> equal null</li>
386 * <li>if Q name of <code>typeDefinition</code></li>
387 * <li>if name of <code>typeDefinition</code></li>
390 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
391 final SchemaNode parentNode) {
392 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
393 if (typeDefinition.getQName() == null) {
394 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
396 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
397 "Type Definitions Local Name cannot be NULL!");
399 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
400 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
402 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
403 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
416 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
417 * dicey when we throw in:
431 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
432 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
435 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
436 * an encapsulation for identityref typedefs.
438 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
439 * option, as it would look as though it is the product of a different construct:
445 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
446 * sub-identities of iden.
448 * The story behind leafrefs is probably similar, but that needs to be ascertained.
453 final Module module = findParentModule(schemaContext, parentNode);
454 if (module != null) {
455 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
457 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
458 if (genTOs != null) {
459 return genTOs.get(typeDefinition.getQName().getLocalName());
466 * Gets base type definition for <code>extendTypeDef</code>. The method is
467 * recursively called until non <code>ExtendedType</code> type is found.
469 * @param extendTypeDef
470 * type definition for which is the base type definition sought
471 * @return type definition which is base type for <code>extendTypeDef</code>
472 * @throws IllegalArgumentException
473 * if <code>extendTypeDef</code> equal null
475 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
476 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
478 TypeDefinition<?> ret = extendTypeDef;
479 while (ret.getBaseType() != null) {
480 ret = ret.getBaseType();
487 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
488 * to find referenced node and its <code>Type</code> is returned.
490 * @param leafrefType leafref type definition for which is the type sought
491 * @param parentNode parent node of the leaf being resolved
492 * @param inGrouping true if we are resolving the type within a grouping.
493 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
494 * @throws IllegalArgumentException
496 * <li>if <code>leafrefType</code> equal null</li>
497 * <li>if path statement of <code>leafrefType</code> equal null</li>
501 Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
502 final boolean inGrouping) {
503 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
505 final PathExpression xpath = leafrefType.getPathStatement();
506 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
508 final String strXPath = xpath.getOriginalString();
509 if (strXPath.indexOf('[') != -1) {
510 // XXX: why are we special-casing this?
511 return Types.objectType();
514 final Module module = findParentModule(schemaContext, parentNode);
515 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
517 final SchemaNode dataNode;
518 if (xpath.isAbsolute()) {
519 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
521 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
522 if (dataNode == null && inGrouping) {
523 // Relative path within a grouping may end up being unresolvable because it may refer outside
524 // the grouping, in which case it is polymorphic based on instantiation, for example:
547 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
549 return Types.objectType();
552 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
553 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
555 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
556 Type returnType = null;
557 if (leafContainsEnumDefinition(dataNode)) {
558 returnType = referencedTypes.get(dataNode.getPath());
559 } else if (leafListContainsEnumDefinition(dataNode)) {
560 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
562 if (returnType == null) {
563 returnType = resolveTypeFromDataSchemaNode(dataNode);
565 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
566 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
571 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
572 * <code>EnumTypeDefinition</code>.
574 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
575 * @return boolean value
577 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
578 * <li>false - other cases</li>
581 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
582 if (dataNode instanceof LeafSchemaNode) {
583 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
584 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
590 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
591 * <code>EnumTypeDefinition</code>.
593 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
594 * @return boolean value
596 * <li>true - if <code>dataNode</code> is leaflist of type
598 * <li>false - other cases</li>
601 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
602 if (dataNode instanceof LeafListSchemaNode) {
603 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
604 return leafList.getType() instanceof EnumTypeDefinition;
610 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
612 * @param enumTypeDef enumeration type definition which is converted to enumeration
613 * @param enumName string with name which is used as the enumeration name
614 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
615 * @throws IllegalArgumentException
617 * <li>if <code>enumTypeDef</code> equals null</li>
618 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
619 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
620 * <li>if name of <code>enumTypeDef</code> equal null</li>
623 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
624 final SchemaNode parentNode) {
625 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
626 Preconditions.checkArgument(enumTypeDef.getValues() != null,
627 "EnumTypeDefinition MUST contain at least ONE value definition!");
628 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
629 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
630 "Local Name in EnumTypeDefinition QName cannot be NULL!");
632 final Module module = findParentModule(schemaContext, parentNode);
633 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
634 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
635 addEnumDescription(enumBuilder, enumTypeDef);
636 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
637 enumBuilder.setModuleName(module.getName());
638 enumBuilder.setSchemaPath(enumTypeDef.getPath());
639 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
640 return enumBuilder.toInstance(null);
644 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
646 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
647 * @param enumName string with the name of enumeration
648 * @param typeBuilder generated type builder to which is enumeration added
649 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
650 * @throws IllegalArgumentException
652 * <li>if <code>enumTypeDef</code> equals null</li>
653 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
654 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
655 * <li>if name of <code>enumTypeDef</code> equal null</li>
656 * <li>if name of <code>typeBuilder</code> equal null</li>
660 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
661 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
662 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
663 Preconditions.checkArgument(enumTypeDef.getValues() != null,
664 "EnumTypeDefinition MUST contain at least ONE value definition!");
665 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
666 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
667 "Local Name in EnumTypeDefinition QName cannot be NULL!");
668 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
670 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
672 addEnumDescription(enumBuilder, enumTypeDef);
673 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
674 return enumBuilder.toInstance(enumBuilder);
677 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
679 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
681 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
683 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
686 * Converts the pattern constraints to the list of the strings which represents these constraints.
688 * @param patternConstraints list of pattern constraints
689 * @return list of strings which represents the constraint patterns
691 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
693 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
696 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
699 * @param typedef extended type in which are the pattern constraints sought
700 * @return list of strings which represents the constraint patterns
701 * @throws IllegalArgumentException if <code>typedef</code> equals null
704 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
705 if (!(typedef instanceof StringTypeDefinition)) {
706 return ImmutableMap.of();
709 // TODO: run diff against base ?
710 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
714 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
716 * @param dataNode contains information about YANG type
717 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
719 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
720 Type returnType = null;
721 if (dataNode != null) {
722 if (dataNode instanceof LeafSchemaNode) {
723 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
724 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
725 returnType = javaTypeForSchemaDefinitionType(type, leaf);
726 } else if (dataNode instanceof LeafListSchemaNode) {
727 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
728 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
735 * Passes through all modules and through all its type definitions and convert it to generated types.
738 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
739 * of a module are at the beginning sorted so that type definition with less amount of references to other type
740 * definition are processed first.<br>
741 * For each module is created mapping record in the map
742 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
743 * which map current module name to the map which maps type names to returned types (generated types).
745 private void resolveTypeDefsFromContext() {
746 final Set<Module> modules = schemaContext.getModules();
747 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
748 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
750 for (Module module : modulesSortedByDependency) {
751 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
752 module.getName(), key -> new HashMap<>());
753 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
754 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
757 for (Module module : modulesSortedByDependency) {
758 if (module != null) {
759 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
760 if (basePackageName != null) {
761 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
762 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
763 typedefToGeneratedType(basePackageName, module, typedef);
771 * Create Type for specified type definition.
773 * @param basePackageName string with name of package to which the module belongs
774 * @param module string with the name of the module for to which the <code>typedef</code> belongs
775 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
776 * (usually generated TO)
777 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
778 * <code>null</code> value if <code>basePackageName</code> or
779 * <code>modulName</code> or <code>typedef</code> or Q name of
780 * <code>typedef</code> equals <code>null</code>
782 private Type typedefToGeneratedType(final String basePackageName, final Module module,
783 final TypeDefinition<?> typedef) {
784 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
786 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
787 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
791 final String typedefName = typedef.getQName().getLocalName();
793 final Type returnType;
794 if (baseTypedef.getBaseType() != null) {
795 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
797 } else if (baseTypedef instanceof UnionTypeDefinition) {
798 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
799 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
800 (UnionTypeDefinition) baseTypedef, typedef);
801 genTOBuilder.setTypedef(true);
802 genTOBuilder.setIsUnion(true);
803 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
804 makeSerializable(genTOBuilder);
805 returnType = genTOBuilder.build();
807 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
808 // so we are placing the builder alongside the union.
809 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
810 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
811 unionBuilder.setIsUnionBuilder(true);
812 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
813 method.setReturnType(returnType);
814 method.addParameter(Types.STRING, "defaultValue");
815 method.setAccessModifier(AccessModifier.PUBLIC);
816 method.setStatic(true);
817 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
818 } else if (baseTypedef instanceof EnumTypeDefinition) {
819 // enums are automatically Serializable
820 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
821 // TODO units for typedef enum
822 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
823 } else if (baseTypedef instanceof BitsTypeDefinition) {
824 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
825 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
826 (BitsTypeDefinition) baseTypedef, module.getName());
827 genTOBuilder.setTypedef(true);
828 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
829 makeSerializable(genTOBuilder);
830 returnType = genTOBuilder.build();
832 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
833 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
835 if (returnType != null) {
836 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
837 genTypeDefsContextMap.get(module.getName());
838 final Optional<Revision> moduleRevision = module.getRevision();
839 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
840 if (typeMap != null) {
841 if (typeMap.isEmpty()) {
842 typeMap = new HashMap<>(4);
843 modulesByDate.put(moduleRevision, typeMap);
845 typeMap.put(typedefName, returnType);
853 * Wraps base YANG type to generated TO.
855 * @param basePackageName string with name of package to which the module belongs
856 * @param typedef type definition which is converted to the TO
857 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
858 * @return generated transfer object which represent<code>javaType</code>
860 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
861 final Type javaType, final String moduleName) {
862 requireNonNull(javaType, "javaType cannot be null");
864 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
865 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
866 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
867 genPropBuilder.setReturnType(javaType);
868 genTOBuilder.addEqualsIdentity(genPropBuilder);
869 genTOBuilder.addHashIdentity(genPropBuilder);
870 genTOBuilder.addToStringProperty(genPropBuilder);
871 genTOBuilder.addImplementsType(TYPE_OBJECT);
872 if (typedef.getStatus() == Status.DEPRECATED) {
873 genTOBuilder.addAnnotation("java.lang", "Deprecated");
875 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
876 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
878 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
879 genTOBuilder.setTypedef(true);
880 makeSerializable(genTOBuilder);
881 return genTOBuilder.build();
885 * Converts output list of generated TO builders to one TO builder (first
886 * from list) which contains the remaining builders as its enclosing TO.
888 * @param typeName new type identifier
889 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
890 * @return generated TO builder with the list of enclosed generated TO builders
892 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
893 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
894 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
896 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
898 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
899 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
900 return resultTOBuilder;
904 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
905 * <code>typedef</code> is added to generated TO builder as property.
907 * @param typeName new type identifier
908 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
909 * @return generated TO builder which represents <code>typedef</code>
910 * @throws NullPointerException
912 * <li>if <code>basePackageName</code> is null</li>
913 * <li>if <code>typedef</code> is null</li>
914 * <li>if Qname of <code>typedef</code> is null</li>
917 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
918 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
919 requireNonNull(typedef, "Type Definition cannot be NULL!");
920 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
922 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
923 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
924 final Module module = findParentModule(schemaContext, parentNode);
926 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
927 unionGenTOBuilder.setIsUnion(true);
928 unionGenTOBuilder.setSchemaPath(typedef.getPath());
929 unionGenTOBuilder.setModuleName(module.getName());
930 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
931 addCodegenInformation(unionGenTOBuilder, typedef);
932 generatedTOBuilders.add(unionGenTOBuilder);
934 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
935 // also negation information and hence guarantees uniqueness.
936 final Map<String, String> expressions = new HashMap<>();
937 for (TypeDefinition<?> unionType : unionTypes) {
938 final String unionTypeName = unionType.getQName().getLocalName();
940 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
941 // do not follow type encapsulation -- we use the general case for that.
942 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
943 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
944 } else if (unionType instanceof UnionTypeDefinition) {
945 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
946 (UnionTypeDefinition) unionType, parentNode));
947 } else if (unionType instanceof EnumTypeDefinition) {
948 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
949 unionTypeName, unionGenTOBuilder);
950 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
952 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
953 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
956 addStringRegExAsConstant(unionGenTOBuilder, expressions);
958 storeGenTO(typedef, unionGenTOBuilder, parentNode);
960 return generatedTOBuilders;
964 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
967 * In this case the new generated TO is created for union subtype (recursive call of method
968 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
969 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
970 * created property which type is equal to new generated TO.
972 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
973 * @param basePackageName string with the name of the module package
974 * @param unionSubtype type definition which represents union subtype
975 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
976 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
978 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
979 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
980 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
981 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
982 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
983 newTOBuilderName, unionSubtype, parentNode);
985 final GeneratedPropertyBuilder propertyBuilder;
986 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
987 newTOBuilderName.simpleName()));
988 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
989 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
990 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
992 return subUnionGenTOBUilders;
996 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
997 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
998 * the base type is used for the property creation.
1000 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
1001 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
1002 * @param expressions list of strings with the regular expressions
1003 * @param parentNode parent Schema Node for Extended Subtype
1005 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1006 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1007 final String unionTypeName = unionSubtype.getQName().getLocalName();
1008 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1009 if (genTO != null) {
1010 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1014 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1015 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1016 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1017 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1018 if (javaType != null) {
1019 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1021 } else if (baseType instanceof LeafrefTypeDefinition) {
1022 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1023 boolean typeExist = false;
1024 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1025 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1026 if (origType != null && javaType != null && javaType == origType) {
1031 if (!typeExist && javaType != null) {
1032 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1033 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1036 if (baseType instanceof StringTypeDefinition) {
1037 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1042 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1043 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1045 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1046 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1048 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1049 final Module typeModule = findParentModule(schemaContext, parentNode);
1050 if (typeModule != null && typeModule.getName() != null) {
1051 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1052 typeModule.getName());
1053 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1054 if (genTOs != null) {
1055 return genTOs.get(searchedTypeName);
1062 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1063 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1065 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1066 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1068 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1069 final SchemaNode parentNode) {
1070 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1071 final Module parentModule = findParentModule(schemaContext, parentNode);
1072 if (parentModule != null && parentModule.getName() != null) {
1073 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1074 parentModule.getName());
1075 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1076 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1082 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1083 * to <code>unonGenTransObject</code>.
1085 * @param unionGenTransObject generated TO to which should be property added
1086 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1087 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1089 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1090 final String propertyName) {
1091 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1092 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1093 .addProperty(BindingMapping.getPropertyName(propertyName));
1094 propBuilder.setReturnType(type);
1096 unionGenTransObject.addEqualsIdentity(propBuilder);
1097 unionGenTransObject.addHashIdentity(propBuilder);
1098 unionGenTransObject.addToStringProperty(propBuilder);
1103 * Converts <code>typedef</code> to the generated TO builder.
1105 * @param basePackageName string with name of package to which the module belongs
1106 * @param typedef type definition from which is the generated TO builder created
1107 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1109 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1110 final TypeDefinition<?> typedef, final String moduleName) {
1111 JavaTypeName name = renames.get(typedef);
1113 name = JavaTypeName.create(
1114 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1115 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1118 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1119 newType.setSchemaPath(typedef.getPath());
1120 newType.setModuleName(moduleName);
1121 addCodegenInformation(newType, typedef);
1126 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1127 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1130 * @param typeName new type identifier
1131 * @param typeDef type definition from which is the generated TO builder created
1132 * @return generated TO builder which represents <code>typeDef</code>
1133 * @throws IllegalArgumentException
1135 * <li>if <code>typeDef</code> equals null</li>
1136 * <li>if <code>basePackageName</code> equals null</li>
1139 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1140 final BitsTypeDefinition typeDef, final String moduleName) {
1141 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1142 genTOBuilder.setSchemaPath(typeDef.getPath());
1143 genTOBuilder.setModuleName(moduleName);
1144 genTOBuilder.setBaseType(typeDef);
1145 genTOBuilder.addImplementsType(TYPE_OBJECT);
1146 addCodegenInformation(genTOBuilder, typeDef);
1148 final List<Bit> bitList = typeDef.getBits();
1149 GeneratedPropertyBuilder genPropertyBuilder;
1150 for (Bit bit : bitList) {
1151 final String name = bit.getName();
1152 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1153 genPropertyBuilder.setReadOnly(true);
1154 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1156 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1157 genTOBuilder.addHashIdentity(genPropertyBuilder);
1158 genTOBuilder.addToStringProperty(genPropertyBuilder);
1161 return genTOBuilder;
1165 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1166 * the <code>regularExpressions</code>.
1168 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1169 * @param expressions list of string which represent regular expressions
1171 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1172 final Map<String, String> expressions) {
1173 if (!expressions.isEmpty()) {
1174 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1175 ImmutableMap.copyOf(expressions));
1180 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1181 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1184 * It is assumed that <code>innerExtendedType</code> is already present in
1185 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1186 * for the returning generated TO.
1188 * @param typedef Type Definition
1189 * @param innerExtendedType extended type which is part of some other extended type
1190 * @param basePackageName string with the package name of the module
1191 * @param moduleName Module Name
1192 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1193 * @throws IllegalArgumentException
1195 * <li>if <code>extendedType</code> equals null</li>
1196 * <li>if <code>basePackageName</code> equals null</li>
1197 * <li>if <code>typedefName</code> equals null</li>
1200 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1201 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1202 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1203 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1205 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1206 BindingMapping.getClassName(typedef.getQName())));
1207 genTOBuilder.setSchemaPath(typedef.getPath());
1208 genTOBuilder.setModuleName(moduleName);
1209 genTOBuilder.setTypedef(true);
1210 addCodegenInformation(genTOBuilder, typedef);
1212 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1213 genTOBuilder.setRestrictions(r);
1214 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1216 if (typedef.getStatus() == Status.DEPRECATED) {
1217 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1220 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1221 genTOBuilder.setIsUnion(true);
1224 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1225 Map<String, Type> typeMap = null;
1226 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1227 if (parentModule != null) {
1228 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1229 typeMap = modulesByDate.get(parentModule.getRevision());
1232 if (typeMap != null) {
1233 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1234 final Type type = typeMap.get(innerTypeDef);
1235 if (type instanceof GeneratedTransferObject) {
1236 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1239 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1240 makeSerializable(genTOBuilder);
1242 return genTOBuilder.build();
1246 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1249 * @param gto transfer object which needs to be made serializable
1251 private static void makeSerializable(final GeneratedTOBuilder gto) {
1252 gto.addImplementsType(Types.serializableType());
1253 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1254 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1259 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1260 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1261 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1262 * type definitions are in the list behind all type definitions on which depends.
1264 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1265 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1266 * dependent on other type definitions are in list behind them).
1268 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1269 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1270 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1272 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1273 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1274 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1275 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1276 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1277 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1280 // SortedMap guarantees order corresponding to keys in ascending order
1281 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1282 sortedTypeDefinition.addAll(v);
1285 return sortedTypeDefinition;
1289 * Returns how many immersion is necessary to get from the type definition to the base type.
1291 * @param typeDefinition type definition for which is depth sought.
1292 * @return number of immersions which are necessary to get from the type definition to the base type
1294 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1295 // FIXME: rewrite this in a non-recursive manner
1296 if (typeDefinition == null) {
1299 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1300 if (baseType == null) {
1305 if (baseType.getBaseType() != null) {
1306 depth = depth + getTypeDefinitionDepth(baseType);
1307 } else if (baseType instanceof UnionTypeDefinition) {
1308 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1309 int maxChildDepth = 0;
1311 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1312 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1313 if (childDepth > maxChildDepth) {
1314 maxChildDepth = childDepth;
1317 return maxChildDepth;
1323 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1324 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1325 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1327 * @param name string with name of augmented node
1328 * @return string with the number suffix incremented by one (or 1 is added)
1330 private static String provideAvailableNameForGenTOBuilder(final String name) {
1331 final int dollar = name.indexOf('$');
1336 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1337 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1338 return name.substring(0, dollar + 1) + newSuffix;
1341 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1342 if (!Strings.isNullOrEmpty(units)) {
1343 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1344 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1345 prop.setReturnType(Types.STRING);
1346 to.addToStringProperty(prop);
1351 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1352 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1355 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1356 final TypeDefinition<?> type = CompatUtils.compatType(node);
1357 final QName typeQName = type.getQName();
1358 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1359 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1360 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1363 final StringBuilder sb = new StringBuilder();
1364 String result = null;
1365 if (base instanceof BinaryTypeDefinition) {
1366 result = binaryToDef(defaultValue);
1367 } else if (base instanceof BitsTypeDefinition) {
1370 final Module parent = getParentModule(node);
1371 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1373 if (!path.hasNext()) {
1374 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1375 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1376 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1378 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1379 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1381 parentName = BindingMapping.getClassName(parent.getName());
1382 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1384 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1385 } else if (base instanceof BooleanTypeDefinition) {
1386 result = typeToBooleanDef(defaultValue);
1387 } else if (base instanceof DecimalTypeDefinition) {
1388 result = typeToDef(BigDecimal.class, defaultValue);
1389 } else if (base instanceof EmptyTypeDefinition) {
1390 result = typeToBooleanDef(defaultValue);
1391 } else if (base instanceof EnumTypeDefinition) {
1392 final char[] defValArray = defaultValue.toCharArray();
1393 final char first = Character.toUpperCase(defaultValue.charAt(0));
1394 defValArray[0] = first;
1395 final String newDefVal = new String(defValArray);
1397 if (type.getBaseType() != null) {
1398 final Module m = getParentModule(type);
1399 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1400 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1402 className = packageName + "." + BindingMapping.getClassName(typeQName);
1404 final Module parentModule = getParentModule(node);
1405 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1406 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1408 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1410 result = className + "." + newDefVal;
1411 } else if (base instanceof IdentityrefTypeDefinition) {
1412 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1413 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1414 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1415 } else if (BaseTypes.isInt8(base)) {
1416 result = typeToValueOfDef(Byte.class, defaultValue);
1417 } else if (BaseTypes.isInt16(base)) {
1418 result = typeToValueOfDef(Short.class, defaultValue);
1419 } else if (BaseTypes.isInt32(base)) {
1420 result = typeToValueOfDef(Integer.class, defaultValue);
1421 } else if (BaseTypes.isInt64(base)) {
1422 result = typeToValueOfDef(Long.class, defaultValue);
1423 } else if (base instanceof LeafrefTypeDefinition) {
1424 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1425 } else if (base instanceof StringTypeDefinition) {
1426 result = "\"" + defaultValue + "\"";
1427 } else if (BaseTypes.isUint8(base)) {
1428 result = typeToValueOfDef(Uint8.class, defaultValue);
1429 } else if (BaseTypes.isUint16(base)) {
1430 result = typeToValueOfDef(Uint16.class, defaultValue);
1431 } else if (BaseTypes.isUint32(base)) {
1432 result = typeToValueOfDef(Uint32.class, defaultValue);
1433 } else if (BaseTypes.isUint64(base)) {
1434 result = typeToValueOfDef(Uint64.class, defaultValue);
1435 } else if (base instanceof UnionTypeDefinition) {
1436 result = unionToDef(node);
1442 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1443 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1444 final Module m = getParentModule(type);
1445 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1446 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1448 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1449 sb.insert(0, "new " + className + "(");
1450 sb.insert(sb.length(), ')');
1453 return sb.toString();
1456 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1457 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1460 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1461 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1464 private static String typeToBooleanDef(final String defaultValue) {
1465 switch (defaultValue) {
1467 return "java.lang.Boolean.FALSE";
1469 return "java.lang.Boolean.TRUE";
1471 return typeToValueOfDef(Boolean.class, defaultValue);
1475 private static String binaryToDef(final String defaultValue) {
1476 final StringBuilder sb = new StringBuilder();
1477 final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1478 sb.append("new byte[] {");
1479 for (int i = 0; i < encoded.length; i++) {
1480 sb.append(encoded[i]);
1481 if (i != encoded.length - 1) {
1486 return sb.toString();
1489 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1491 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1492 final boolean isExt) {
1493 final List<Bit> bits = new ArrayList<>(type.getBits());
1494 bits.sort(BIT_NAME_COMPARATOR);
1495 final StringBuilder sb = new StringBuilder();
1498 sb.append(className);
1501 for (int i = 0; i < bits.size(); i++) {
1502 if (bits.get(i).getName().equals(defaultValue)) {
1507 if (i != bits.size() - 1) {
1514 return sb.toString();
1517 private Module getParentModule(final SchemaNode node) {
1518 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1519 return schemaContext.findModule(qname.getModule()).orElse(null);
1522 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1523 final String defaultValue) {
1524 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1525 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1526 "The Path Statement for Leafref Type Definition cannot be NULL!");
1528 final PathExpression xpath = leafrefType.getPathStatement();
1529 final String strXPath = xpath.getOriginalString();
1531 if (strXPath != null) {
1532 if (strXPath.indexOf('[') == -1) {
1533 final Module module = findParentModule(schemaContext, parentNode);
1534 if (module != null) {
1535 final SchemaNode dataNode;
1536 if (xpath.isAbsolute()) {
1537 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
1539 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1541 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1545 return "new java.lang.Object()";
1552 private String unionToDef(final LeafSchemaNode node) {
1553 final TypeDefinition<?> type = CompatUtils.compatType(node);
1557 if (type.getBaseType() != null) {
1558 final QName typeQName = type.getQName();
1559 Module module = null;
1560 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1561 if (modules.size() > 1) {
1562 for (Module m : modules) {
1563 if (m.getRevision().equals(typeQName.getRevision())) {
1568 if (module == null) {
1569 final List<Module> modulesList = new ArrayList<>(modules);
1570 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1571 module = modulesList.get(0);
1574 module = modules.iterator().next();
1577 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1578 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1580 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1581 final QName first = path.next();
1582 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1583 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1584 if (!path.hasNext()) {
1585 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1586 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1588 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1590 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1593 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1596 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1597 final StringBuilder sb = new StringBuilder();
1599 sb.append(className);
1601 sb.append(defaultValue);
1602 sb.append("\".toCharArray())");
1603 return sb.toString();
1607 public String getConstructorPropertyName(final SchemaNode node) {
1608 return node instanceof TypeDefinition<?> ? "value" : "";
1612 public String getParamNameFromType(final TypeDefinition<?> type) {
1613 return BindingMapping.getPropertyName(type.getQName().getLocalName());