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.generator.util.BaseYangTypesProvider;
38 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
39 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
40 import org.opendaylight.mdsal.binding.model.api.Enumeration;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
43 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
44 import org.opendaylight.mdsal.binding.model.api.Restrictions;
45 import org.opendaylight.mdsal.binding.model.api.Type;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
52 import org.opendaylight.mdsal.binding.model.util.BaseYangTypes;
53 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
54 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
55 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
56 import org.opendaylight.mdsal.binding.model.util.Types;
57 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
58 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
59 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.common.Revision;
62 import org.opendaylight.yangtools.yang.common.Uint16;
63 import org.opendaylight.yangtools.yang.common.Uint32;
64 import org.opendaylight.yangtools.yang.common.Uint64;
65 import org.opendaylight.yangtools.yang.common.Uint8;
66 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
67 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.Module;
72 import org.opendaylight.yangtools.yang.model.api.PathExpression;
73 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
74 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
75 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
76 import org.opendaylight.yangtools.yang.model.api.Status;
77 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
81 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
87 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
88 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
89 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
90 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
91 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
92 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
93 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
94 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
95 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
96 import org.slf4j.Logger;
97 import org.slf4j.LoggerFactory;
100 public abstract class AbstractTypeProvider implements TypeProvider {
101 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
102 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
103 private static final JavaTypeName DEPRECATED_ANNOTATION = JavaTypeName.create(Deprecated.class);
105 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
106 // the case, as unions are emitted to their correct schema path.
107 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
108 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
111 * Contains the schema data red from YANG files.
113 private final SchemaContext schemaContext;
115 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
118 * The map which maps schema paths to JAVA <code>Type</code>.
120 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
121 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
122 private final Map<SchemaNode, JavaTypeName> renames;
125 * Creates new instance of class <code>TypeProviderImpl</code>.
127 * @param schemaContext contains the schema data red from YANG files
128 * @param renames renaming table
129 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
131 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
132 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
133 this.schemaContext = schemaContext;
134 this.renames = requireNonNull(renames);
135 resolveTypeDefsFromContext();
139 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
141 * @param refTypePath schema path used as the map key
142 * @param refType type which represents the map value
143 * @throws IllegalArgumentException
145 * <li>if <code>refTypePath</code> equal null</li>
146 * <li>if <code>refType</code> equal null</li>
150 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
151 Preconditions.checkArgument(refTypePath != null,
152 "Path reference of Enumeration Type Definition cannot be NULL!");
153 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
154 referencedTypes.put(refTypePath, refType);
157 public Map<Module, Set<Type>> getAdditionalTypes() {
158 return additionalTypes;
162 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
163 final boolean lenientRelativeLeafrefs) {
164 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
168 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
170 * @param typeDefinition type definition which is converted to JAVA type
171 * @throws IllegalArgumentException
173 * <li>if <code>typeDefinition</code> equal null</li>
174 * <li>if Qname of <code>typeDefinition</code> equal null</li>
175 * <li>if name of <code>typeDefinition</code> equal null</li>
179 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
180 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
181 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
182 Preconditions.checkArgument(typeDefinition.getQName() != null,
183 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
184 final String typedefName = typeDefinition.getQName().getLocalName();
185 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
187 // Deal with base types
188 if (typeDefinition.getBaseType() == null) {
189 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
190 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
191 // a base type which holds these constraints.
192 if (typeDefinition instanceof DecimalTypeDefinition) {
193 final Type ret = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(typeDefinition,
194 parentNode, restrictions, lenientRelativeLeafrefs);
200 // Deal with leafrefs/identityrefs
201 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
206 // FIXME: it looks as though we could be using the same codepath as above...
207 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
209 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
215 Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
216 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
217 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
218 final Module module = findParentModule(schemaContext, parentNode);
219 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
220 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
221 typeDefinition.getPath());
222 final String genTOName = BindingMapping.getClassName(typedefName);
223 final String name = packageName + "." + genTOName;
224 if (!returnType.getFullyQualifiedName().equals(name)) {
225 returnType = shadedTOWithRestrictions(gto, restrictions);
231 public SchemaNode getTargetForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
232 final PathExpression xpath = leafrefType.getPathStatement();
233 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
235 final Module module = findParentModule(schemaContext, parentNode);
236 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
238 return xpath.isAbsolute() ? findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath)
239 : findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
242 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
243 final Restrictions restrictions) {
244 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
245 final GeneratedTransferObject parent = gto.getSuperType();
246 if (parent != null) {
247 gtob.setExtendsType(parent);
249 gtob.setRestrictions(restrictions);
250 for (GeneratedProperty gp : gto.getProperties()) {
251 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
252 gpb.setValue(gp.getValue());
253 gpb.setReadOnly(gp.isReadOnly());
254 gpb.setAccessModifier(gp.getAccessModifier());
255 gpb.setReturnType(gp.getReturnType());
256 gpb.setFinal(gp.isFinal());
257 gpb.setStatic(gp.isStatic());
262 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
264 * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
267 DataNodeContainer current = null;
268 DataSchemaNode dataChildByName;
269 for (QName next : parentNode.getPath().getPathFromRoot()) {
270 if (current == null) {
271 dataChildByName = schemaContext.getDataChildByName(next);
273 dataChildByName = current.getDataChildByName(next);
275 if (dataChildByName == null) {
278 if (dataChildByName.isAugmenting()) {
281 if (dataChildByName instanceof DataNodeContainer) {
282 current = (DataNodeContainer) dataChildByName;
286 // Then try to look up the expression.
287 final PathExpression leafRefXPath = leafref.getPathStatement();
288 final Module parentModule = getParentModule(parentNode);
289 final SchemaNode leafRefValueNode;
290 if (leafRefXPath.isAbsolute()) {
291 leafRefValueNode = SchemaContextUtil.findDataTreeSchemaNode(schemaContext, parentModule.getQNameModule(),
294 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
295 parentNode, new PathExpressionImpl(
296 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), false));
299 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
303 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
304 * <code>IdentityrefTypeDefinition</code>.
306 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
307 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
309 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
310 final boolean inGrouping) {
311 if (typeDefinition instanceof LeafrefTypeDefinition) {
312 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
313 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
314 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
315 return provideTypeForLeafref(leafref, parentNode, inGrouping);
316 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
317 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
324 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
326 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
327 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
329 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
330 final String typedefName = typeDefinition.getQName().getLocalName();
331 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
332 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
333 if (returnType == null) {
334 if (baseTypeDef instanceof EnumTypeDefinition) {
335 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
336 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
338 final Module module = findParentModule(schemaContext, typeDefinition);
339 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
340 if (module != null) {
341 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
343 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
344 if (genTOs != null) {
345 returnType = genTOs.get(typedefName);
347 if (returnType == null) {
348 returnType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseTypeDef,
349 typeDefinition, r, lenient);
358 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
362 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
363 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
365 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
366 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
368 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
369 final Collection<? extends IdentitySchemaNode> identities = idref.getIdentities();
370 if (identities.size() > 1) {
371 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
374 final QName baseIdQName = identities.iterator().next().getQName();
375 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
376 IdentitySchemaNode identity = null;
377 for (IdentitySchemaNode id : module.getIdentities()) {
378 if (id.getQName().equals(baseIdQName)) {
382 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exist");
384 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
385 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
386 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
387 return Types.classType(Types.wildcardTypeFor(identifier));
391 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
393 * @param typeDefinition
394 * type definition which should be converted to JAVA
396 * @return JAVA <code>Type</code> which represents
397 * <code>typeDefinition</code>
398 * @throws IllegalArgumentException
400 * <li>if <code>typeDefinition</code> equal null</li>
401 * <li>if Q name of <code>typeDefinition</code></li>
402 * <li>if name of <code>typeDefinition</code></li>
405 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
406 final SchemaNode parentNode) {
407 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
408 if (typeDefinition.getQName() == null) {
409 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
411 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
412 "Type Definitions Local Name cannot be NULL!");
414 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
415 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
417 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
418 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
431 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
432 * dicey when we throw in:
446 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
447 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
450 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
451 * an encapsulation for identityref typedefs.
453 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
454 * option, as it would look as though it is the product of a different construct:
460 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
461 * sub-identities of iden.
463 * The story behind leafrefs is probably similar, but that needs to be ascertained.
468 final Module module = findParentModule(schemaContext, parentNode);
469 if (module != null) {
470 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
472 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
473 if (genTOs != null) {
474 return genTOs.get(typeDefinition.getQName().getLocalName());
481 * Gets base type definition for <code>extendTypeDef</code>. The method is
482 * recursively called until non <code>ExtendedType</code> type is found.
484 * @param extendTypeDef
485 * type definition for which is the base type definition sought
486 * @return type definition which is base type for <code>extendTypeDef</code>
487 * @throws IllegalArgumentException
488 * if <code>extendTypeDef</code> equal null
490 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
491 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
493 TypeDefinition<?> ret = extendTypeDef;
494 while (ret.getBaseType() != null) {
495 ret = ret.getBaseType();
502 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
503 * to find referenced node and its <code>Type</code> is returned.
505 * @param leafrefType leafref type definition for which is the type sought
506 * @param parentNode parent node of the leaf being resolved
507 * @param inGrouping true if we are resolving the type within a grouping.
508 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
509 * @throws IllegalArgumentException
511 * <li>if <code>leafrefType</code> equal null</li>
512 * <li>if path statement of <code>leafrefType</code> equal null</li>
516 Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
517 final boolean inGrouping) {
518 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
520 final PathExpression xpath = leafrefType.getPathStatement();
521 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
523 final String strXPath = xpath.getOriginalString();
524 if (strXPath.indexOf('[') != -1) {
525 // XXX: why are we special-casing this?
526 return Types.objectType();
529 final Module module = findParentModule(schemaContext, parentNode);
530 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
532 final SchemaNode dataNode;
533 if (xpath.isAbsolute()) {
534 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
536 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
537 if (dataNode == null && inGrouping) {
538 // Relative path within a grouping may end up being unresolvable because it may refer outside
539 // the grouping, in which case it is polymorphic based on instantiation, for example:
562 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
564 return Types.objectType();
567 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
568 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
570 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
571 Type returnType = null;
572 if (leafContainsEnumDefinition(dataNode)) {
573 returnType = referencedTypes.get(dataNode.getPath());
574 } else if (leafListContainsEnumDefinition(dataNode)) {
575 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
577 if (returnType == null) {
578 returnType = resolveTypeFromDataSchemaNode(dataNode, inGrouping);
580 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
581 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
586 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
587 * <code>EnumTypeDefinition</code>.
589 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
590 * @return boolean value
592 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
593 * <li>false - other cases</li>
596 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
597 if (dataNode instanceof LeafSchemaNode) {
598 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
599 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
605 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
606 * <code>EnumTypeDefinition</code>.
608 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
609 * @return boolean value
611 * <li>true - if <code>dataNode</code> is leaflist of type
613 * <li>false - other cases</li>
616 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
617 if (dataNode instanceof LeafListSchemaNode) {
618 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
619 return leafList.getType() instanceof EnumTypeDefinition;
625 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
627 * @param enumTypeDef enumeration type definition which is converted to enumeration
628 * @param enumName string with name which is used as the enumeration name
629 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
630 * @throws IllegalArgumentException
632 * <li>if <code>enumTypeDef</code> equals null</li>
633 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
634 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
635 * <li>if name of <code>enumTypeDef</code> equal null</li>
638 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
639 final SchemaNode parentNode) {
640 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
641 Preconditions.checkArgument(enumTypeDef.getValues() != null,
642 "EnumTypeDefinition MUST contain at least ONE value definition!");
643 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
644 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
645 "Local Name in EnumTypeDefinition QName cannot be NULL!");
647 final Module module = findParentModule(schemaContext, parentNode);
648 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
649 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
650 addEnumDescription(enumBuilder, enumTypeDef);
651 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
652 enumBuilder.setModuleName(module.getName());
653 enumBuilder.setSchemaPath(enumTypeDef.getPath());
654 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
655 return enumBuilder.toInstance(null);
659 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
661 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
662 * @param enumName string with the name of enumeration
663 * @param typeBuilder generated type builder to which is enumeration added
664 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
665 * @throws IllegalArgumentException
667 * <li>if <code>enumTypeDef</code> equals null</li>
668 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
669 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
670 * <li>if name of <code>enumTypeDef</code> equal null</li>
671 * <li>if name of <code>typeBuilder</code> equal null</li>
675 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
676 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
677 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
678 Preconditions.checkArgument(enumTypeDef.getValues() != null,
679 "EnumTypeDefinition MUST contain at least ONE value definition!");
680 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
681 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
682 "Local Name in EnumTypeDefinition QName cannot be NULL!");
683 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
685 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
687 addEnumDescription(enumBuilder, enumTypeDef);
688 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
689 return enumBuilder.toInstance(enumBuilder);
692 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
694 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
696 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
698 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
701 * Converts the pattern constraints to the list of the strings which represents these constraints.
703 * @param patternConstraints list of pattern constraints
704 * @return list of strings which represents the constraint patterns
706 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
708 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
711 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
714 * @param typedef extended type in which are the pattern constraints sought
715 * @return list of strings which represents the constraint patterns
716 * @throws IllegalArgumentException if <code>typedef</code> equals null
719 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
720 if (!(typedef instanceof StringTypeDefinition)) {
721 return ImmutableMap.of();
724 // TODO: run diff against base ?
725 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
729 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
731 * @param dataNode contains information about YANG type
732 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
734 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final boolean inGrouping) {
735 Type returnType = null;
736 if (dataNode != null) {
737 if (dataNode instanceof LeafSchemaNode) {
738 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
739 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
740 returnType = javaTypeForSchemaDefinitionType(type, leaf, inGrouping);
741 } else if (dataNode instanceof LeafListSchemaNode) {
742 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
743 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList, inGrouping);
750 * Passes through all modules and through all its type definitions and convert it to generated types.
753 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
754 * of a module are at the beginning sorted so that type definition with less amount of references to other type
755 * definition are processed first.<br>
756 * For each module is created mapping record in the map
757 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
758 * which map current module name to the map which maps type names to returned types (generated types).
760 private void resolveTypeDefsFromContext() {
761 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
763 for (Module module : modulesSortedByDependency) {
764 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
765 module.getName(), key -> new HashMap<>());
766 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
767 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
770 for (Module module : modulesSortedByDependency) {
771 if (module != null) {
772 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
773 if (basePackageName != null) {
774 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
775 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
776 typedefToGeneratedType(basePackageName, module, typedef);
784 * Create Type for specified type definition.
786 * @param basePackageName string with name of package to which the module belongs
787 * @param module string with the name of the module for to which the <code>typedef</code> belongs
788 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
789 * (usually generated TO)
790 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
791 * <code>null</code> value if <code>basePackageName</code> or
792 * <code>modulName</code> or <code>typedef</code> or Q name of
793 * <code>typedef</code> equals <code>null</code>
795 private Type typedefToGeneratedType(final String basePackageName, final Module module,
796 final TypeDefinition<?> typedef) {
797 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
799 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
800 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
804 final String typedefName = typedef.getQName().getLocalName();
806 final Type returnType;
807 if (baseTypedef.getBaseType() != null) {
808 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
810 } else if (baseTypedef instanceof UnionTypeDefinition) {
811 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
812 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
813 (UnionTypeDefinition) baseTypedef, typedef);
814 genTOBuilder.setTypedef(true);
815 genTOBuilder.setIsUnion(true);
816 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
817 makeSerializable(genTOBuilder);
818 returnType = genTOBuilder.build();
820 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
821 // so we are placing the builder alongside the union.
822 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
823 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
824 unionBuilder.setIsUnionBuilder(true);
825 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
826 method.setReturnType(returnType);
827 method.addParameter(Types.STRING, "defaultValue");
828 method.setAccessModifier(AccessModifier.PUBLIC);
829 method.setStatic(true);
830 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
831 } else if (baseTypedef instanceof EnumTypeDefinition) {
832 // enums are automatically Serializable
833 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
834 // TODO units for typedef enum
835 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
836 } else if (baseTypedef instanceof BitsTypeDefinition) {
837 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
838 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
839 (BitsTypeDefinition) baseTypedef, module.getName());
840 genTOBuilder.setTypedef(true);
841 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
842 makeSerializable(genTOBuilder);
843 returnType = genTOBuilder.build();
845 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
846 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
848 if (returnType != null) {
849 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
850 genTypeDefsContextMap.get(module.getName());
851 final Optional<Revision> moduleRevision = module.getRevision();
852 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
853 if (typeMap != null) {
854 if (typeMap.isEmpty()) {
855 typeMap = new HashMap<>(4);
856 modulesByDate.put(moduleRevision, typeMap);
858 typeMap.put(typedefName, returnType);
866 * Wraps base YANG type to generated TO.
868 * @param basePackageName string with name of package to which the module belongs
869 * @param typedef type definition which is converted to the TO
870 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
871 * @return generated transfer object which represent<code>javaType</code>
873 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
874 final Type javaType, final String moduleName) {
875 requireNonNull(javaType, "javaType cannot be null");
877 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
878 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
879 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(TypeConstants.VALUE_PROP);
880 genPropBuilder.setReturnType(javaType);
882 genTOBuilder.addEqualsIdentity(genPropBuilder);
883 genTOBuilder.addHashIdentity(genPropBuilder);
884 genTOBuilder.addToStringProperty(genPropBuilder);
885 genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
886 if (typedef.getStatus() == Status.DEPRECATED) {
887 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
889 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
890 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
892 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
893 genTOBuilder.setTypedef(true);
894 makeSerializable(genTOBuilder);
895 return genTOBuilder.build();
899 * Converts output list of generated TO builders to one TO builder (first
900 * from list) which contains the remaining builders as its enclosing TO.
902 * @param typeName new type identifier
903 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
904 * @return generated TO builder with the list of enclosed generated TO builders
906 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
907 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
908 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
910 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
912 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
913 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
914 return resultTOBuilder;
918 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
919 * <code>typedef</code> is added to generated TO builder as property.
921 * @param typeName new type identifier
922 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
923 * @return generated TO builder which represents <code>typedef</code>
924 * @throws NullPointerException
926 * <li>if <code>basePackageName</code> is null</li>
927 * <li>if <code>typedef</code> is null</li>
928 * <li>if Qname of <code>typedef</code> is null</li>
931 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
932 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
933 requireNonNull(typedef, "Type Definition cannot be NULL!");
934 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
936 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
937 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
938 final Module module = findParentModule(schemaContext, parentNode);
940 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
941 unionGenTOBuilder.setIsUnion(true);
942 unionGenTOBuilder.setSchemaPath(typedef.getPath());
943 unionGenTOBuilder.setModuleName(module.getName());
944 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
945 addCodegenInformation(unionGenTOBuilder, typedef);
946 generatedTOBuilders.add(unionGenTOBuilder);
948 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
949 // also negation information and hence guarantees uniqueness.
950 final Map<String, String> expressions = new HashMap<>();
951 for (TypeDefinition<?> unionType : unionTypes) {
952 final String unionTypeName = unionType.getQName().getLocalName();
954 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
955 // do not follow type encapsulation -- we use the general case for that.
956 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
957 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
958 } else if (unionType instanceof UnionTypeDefinition) {
959 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
960 (UnionTypeDefinition) unionType, parentNode));
961 } else if (unionType instanceof EnumTypeDefinition) {
962 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
963 unionTypeName, unionGenTOBuilder);
964 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
966 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
967 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
970 addStringRegExAsConstant(unionGenTOBuilder, expressions);
972 storeGenTO(typedef, unionGenTOBuilder, parentNode);
974 return generatedTOBuilders;
978 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
981 * In this case the new generated TO is created for union subtype (recursive call of method
982 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
983 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
984 * created property which type is equal to new generated TO.
986 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
987 * @param basePackageName string with the name of the module package
988 * @param unionSubtype type definition which represents union subtype
989 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
990 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
992 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
993 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
994 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
995 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
996 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
997 newTOBuilderName, unionSubtype, parentNode);
999 final GeneratedPropertyBuilder propertyBuilder;
1000 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
1001 newTOBuilderName.simpleName()));
1002 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
1003 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1004 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1006 return subUnionGenTOBUilders;
1010 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
1011 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
1012 * the base type is used for the property creation.
1014 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
1015 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
1016 * @param expressions list of strings with the regular expressions
1017 * @param parentNode parent Schema Node for Extended Subtype
1019 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1020 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1021 final String unionTypeName = unionSubtype.getQName().getLocalName();
1022 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1023 if (genTO != null) {
1024 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1028 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1029 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1030 final Type javaType = BaseYangTypesProvider.INSTANCE.javaTypeForSchemaDefinitionType(baseType, parentNode,
1031 BindingGeneratorUtil.getRestrictions(unionSubtype));
1032 if (javaType != null) {
1033 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1035 } else if (baseType instanceof LeafrefTypeDefinition) {
1036 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1037 boolean typeExist = false;
1038 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1039 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1040 if (origType != null && javaType != null && javaType == origType) {
1045 if (!typeExist && javaType != null) {
1046 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1047 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1050 if (baseType instanceof StringTypeDefinition) {
1051 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1056 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1057 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1059 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1060 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1062 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1063 final Module typeModule = findParentModule(schemaContext, parentNode);
1064 if (typeModule != null && typeModule.getName() != null) {
1065 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1066 typeModule.getName());
1067 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1068 if (genTOs != null) {
1069 return genTOs.get(searchedTypeName);
1076 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1077 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1079 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1080 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1082 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1083 final SchemaNode parentNode) {
1084 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1085 final Module parentModule = findParentModule(schemaContext, parentNode);
1086 if (parentModule != null && parentModule.getName() != null) {
1087 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1088 parentModule.getName());
1089 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1090 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1096 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1097 * to <code>unonGenTransObject</code>.
1099 * @param unionGenTransObject generated TO to which should be property added
1100 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1101 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1103 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1104 final String propertyName) {
1105 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1106 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1107 .addProperty(BindingMapping.getPropertyName(propertyName));
1108 propBuilder.setReturnType(type);
1110 unionGenTransObject.addEqualsIdentity(propBuilder);
1111 unionGenTransObject.addHashIdentity(propBuilder);
1112 unionGenTransObject.addToStringProperty(propBuilder);
1117 * Converts <code>typedef</code> to the generated TO builder.
1119 * @param basePackageName string with name of package to which the module belongs
1120 * @param typedef type definition from which is the generated TO builder created
1121 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1123 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1124 final TypeDefinition<?> typedef, final String moduleName) {
1125 JavaTypeName name = renames.get(typedef);
1127 name = JavaTypeName.create(
1128 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1129 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1132 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1133 newType.setSchemaPath(typedef.getPath());
1134 newType.setModuleName(moduleName);
1135 addCodegenInformation(newType, typedef);
1140 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1141 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1144 * @param typeName new type identifier
1145 * @param typeDef type definition from which is the generated TO builder created
1146 * @return generated TO builder which represents <code>typeDef</code>
1147 * @throws IllegalArgumentException
1149 * <li>if <code>typeDef</code> equals null</li>
1150 * <li>if <code>basePackageName</code> equals null</li>
1153 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1154 final BitsTypeDefinition typeDef, final String moduleName) {
1155 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1156 genTOBuilder.setSchemaPath(typeDef.getPath());
1157 genTOBuilder.setModuleName(moduleName);
1158 genTOBuilder.setBaseType(typeDef);
1159 genTOBuilder.addImplementsType(TYPE_OBJECT);
1160 addCodegenInformation(genTOBuilder, typeDef);
1162 for (Bit bit : typeDef.getBits()) {
1163 final String name = bit.getName();
1164 GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
1165 BindingMapping.getPropertyName(name));
1166 genPropertyBuilder.setReadOnly(true);
1167 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1169 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1170 genTOBuilder.addHashIdentity(genPropertyBuilder);
1171 genTOBuilder.addToStringProperty(genPropertyBuilder);
1174 return genTOBuilder;
1178 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1179 * the <code>regularExpressions</code>.
1181 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1182 * @param expressions list of string which represent regular expressions
1184 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1185 final Map<String, String> expressions) {
1186 if (!expressions.isEmpty()) {
1187 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1188 ImmutableMap.copyOf(expressions));
1193 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1194 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1197 * It is assumed that <code>innerExtendedType</code> is already present in
1198 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1199 * for the returning generated TO.
1201 * @param typedef Type Definition
1202 * @param innerExtendedType extended type which is part of some other extended type
1203 * @param basePackageName string with the package name of the module
1204 * @param moduleName Module Name
1205 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1206 * @throws IllegalArgumentException
1208 * <li>if <code>extendedType</code> equals null</li>
1209 * <li>if <code>basePackageName</code> equals null</li>
1210 * <li>if <code>typedefName</code> equals null</li>
1213 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1214 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1215 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1216 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1218 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1219 BindingMapping.getClassName(typedef.getQName())));
1220 genTOBuilder.setSchemaPath(typedef.getPath());
1221 genTOBuilder.setModuleName(moduleName);
1222 genTOBuilder.setTypedef(true);
1223 addCodegenInformation(genTOBuilder, typedef);
1225 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1226 genTOBuilder.setRestrictions(r);
1227 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1229 if (typedef.getStatus() == Status.DEPRECATED) {
1230 genTOBuilder.addAnnotation(DEPRECATED_ANNOTATION);
1233 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1234 genTOBuilder.setIsUnion(true);
1237 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1238 Map<String, Type> typeMap = null;
1239 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1240 if (parentModule != null) {
1241 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1242 typeMap = modulesByDate.get(parentModule.getRevision());
1245 if (typeMap != null) {
1246 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1247 final Type type = typeMap.get(innerTypeDef);
1248 if (type instanceof GeneratedTransferObject) {
1249 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1252 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1253 makeSerializable(genTOBuilder);
1255 return genTOBuilder.build();
1259 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1262 * @param gto transfer object which needs to be made serializable
1264 private static void makeSerializable(final GeneratedTOBuilder gto) {
1265 gto.addImplementsType(Types.serializableType());
1266 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1267 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1272 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1273 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1274 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1275 * type definitions are in the list behind all type definitions on which depends.
1277 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1278 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1279 * dependent on other type definitions are in list behind them).
1281 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1282 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1283 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1285 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1286 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1287 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1288 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1289 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1290 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1293 // SortedMap guarantees order corresponding to keys in ascending order
1294 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1295 sortedTypeDefinition.addAll(v);
1298 return sortedTypeDefinition;
1302 * Returns how many immersion is necessary to get from the type definition to the base type.
1304 * @param typeDefinition type definition for which is depth sought.
1305 * @return number of immersions which are necessary to get from the type definition to the base type
1307 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1308 // FIXME: rewrite this in a non-recursive manner
1309 if (typeDefinition == null) {
1312 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1313 if (baseType == null) {
1318 if (baseType.getBaseType() != null) {
1319 depth = depth + getTypeDefinitionDepth(baseType);
1320 } else if (baseType instanceof UnionTypeDefinition) {
1321 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1322 int maxChildDepth = 0;
1324 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1325 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1326 if (childDepth > maxChildDepth) {
1327 maxChildDepth = childDepth;
1330 return maxChildDepth;
1336 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1337 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1338 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1340 * @param name string with name of augmented node
1341 * @return string with the number suffix incremented by one (or 1 is added)
1343 private static String provideAvailableNameForGenTOBuilder(final String name) {
1344 final int dollar = name.indexOf('$');
1349 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1350 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1351 return name.substring(0, dollar + 1) + newSuffix;
1354 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1355 if (!Strings.isNullOrEmpty(units)) {
1356 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1357 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1358 prop.setReturnType(Types.STRING);
1359 to.addToStringProperty(prop);
1364 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1365 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1368 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1369 final TypeDefinition<?> type = CompatUtils.compatType(node);
1370 final QName typeQName = type.getQName();
1371 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1372 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1373 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1376 final StringBuilder sb = new StringBuilder();
1377 String result = null;
1378 if (base instanceof BinaryTypeDefinition) {
1379 result = binaryToDef(defaultValue);
1380 } else if (base instanceof BitsTypeDefinition) {
1383 final Module parent = getParentModule(node);
1384 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1386 if (!path.hasNext()) {
1387 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1388 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1389 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1391 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1392 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1394 parentName = BindingMapping.getClassName(parent.getName());
1395 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1397 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1398 } else if (base instanceof BooleanTypeDefinition) {
1399 result = typeToBooleanDef(defaultValue);
1400 } else if (base instanceof DecimalTypeDefinition) {
1401 result = typeToDef(BigDecimal.class, defaultValue);
1402 } else if (base instanceof EmptyTypeDefinition) {
1403 result = typeToBooleanDef(defaultValue);
1404 } else if (base instanceof EnumTypeDefinition) {
1405 final char[] defValArray = defaultValue.toCharArray();
1406 final char first = Character.toUpperCase(defaultValue.charAt(0));
1407 defValArray[0] = first;
1408 final String newDefVal = new String(defValArray);
1410 if (type.getBaseType() != null) {
1411 final Module m = getParentModule(type);
1412 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1413 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1415 className = packageName + "." + BindingMapping.getClassName(typeQName);
1417 final Module parentModule = getParentModule(node);
1418 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1419 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1421 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1423 result = className + "." + newDefVal;
1424 } else if (base instanceof IdentityrefTypeDefinition) {
1425 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1426 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1427 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1428 } else if (BaseTypes.isInt8(base)) {
1429 result = typeToValueOfDef(Byte.class, defaultValue);
1430 } else if (BaseTypes.isInt16(base)) {
1431 result = typeToValueOfDef(Short.class, defaultValue);
1432 } else if (BaseTypes.isInt32(base)) {
1433 result = typeToValueOfDef(Integer.class, defaultValue);
1434 } else if (BaseTypes.isInt64(base)) {
1435 result = typeToValueOfDef(Long.class, defaultValue);
1436 } else if (base instanceof LeafrefTypeDefinition) {
1437 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1438 } else if (base instanceof StringTypeDefinition) {
1439 result = "\"" + defaultValue + "\"";
1440 } else if (BaseTypes.isUint8(base)) {
1441 result = typeToValueOfDef(Uint8.class, defaultValue);
1442 } else if (BaseTypes.isUint16(base)) {
1443 result = typeToValueOfDef(Uint16.class, defaultValue);
1444 } else if (BaseTypes.isUint32(base)) {
1445 result = typeToValueOfDef(Uint32.class, defaultValue);
1446 } else if (BaseTypes.isUint64(base)) {
1447 result = typeToValueOfDef(Uint64.class, defaultValue);
1448 } else if (base instanceof UnionTypeDefinition) {
1449 result = unionToDef(node);
1455 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1456 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1457 final Module m = getParentModule(type);
1458 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1459 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1461 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1462 sb.insert(0, "new " + className + "(");
1463 sb.insert(sb.length(), ')');
1466 return sb.toString();
1469 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1470 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1473 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1474 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1477 private static String typeToBooleanDef(final String defaultValue) {
1478 switch (defaultValue) {
1480 return "java.lang.Boolean.FALSE";
1482 return "java.lang.Boolean.TRUE";
1484 return typeToValueOfDef(Boolean.class, defaultValue);
1488 private static String binaryToDef(final String defaultValue) {
1489 final StringBuilder sb = new StringBuilder();
1490 final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1491 sb.append("new byte[] {");
1492 for (int i = 0; i < encoded.length; i++) {
1493 sb.append(encoded[i]);
1494 if (i != encoded.length - 1) {
1499 return sb.toString();
1502 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1504 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1505 final boolean isExt) {
1506 final List<Bit> bits = new ArrayList<>(type.getBits());
1507 bits.sort(BIT_NAME_COMPARATOR);
1508 final StringBuilder sb = new StringBuilder();
1511 sb.append(className);
1514 for (int i = 0; i < bits.size(); i++) {
1515 if (bits.get(i).getName().equals(defaultValue)) {
1520 if (i != bits.size() - 1) {
1527 return sb.toString();
1530 private Module getParentModule(final SchemaNode node) {
1531 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1532 return schemaContext.findModule(qname.getModule()).orElse(null);
1535 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1536 final String defaultValue) {
1537 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1538 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1539 "The Path Statement for Leafref Type Definition cannot be NULL!");
1541 final PathExpression xpath = leafrefType.getPathStatement();
1542 final String strXPath = xpath.getOriginalString();
1544 if (strXPath != null) {
1545 if (strXPath.indexOf('[') == -1) {
1546 final Module module = findParentModule(schemaContext, parentNode);
1547 if (module != null) {
1548 final SchemaNode dataNode;
1549 if (xpath.isAbsolute()) {
1550 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
1552 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1554 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1558 return "new java.lang.Object()";
1565 private String unionToDef(final LeafSchemaNode node) {
1566 final TypeDefinition<?> type = CompatUtils.compatType(node);
1570 if (type.getBaseType() != null) {
1571 final QName typeQName = type.getQName();
1572 Module module = null;
1573 final Collection<? extends Module> modules = schemaContext.findModules(typeQName.getNamespace());
1574 if (modules.size() > 1) {
1575 for (Module m : modules) {
1576 if (m.getRevision().equals(typeQName.getRevision())) {
1581 if (module == null) {
1582 final List<Module> modulesList = new ArrayList<>(modules);
1583 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1584 module = modulesList.get(0);
1587 module = modules.iterator().next();
1590 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1591 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1593 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1594 final QName first = path.next();
1595 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1596 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1597 if (!path.hasNext()) {
1598 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1599 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1601 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1603 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1606 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1609 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1610 return new StringBuilder()
1614 .append(defaultValue)
1615 .append("\".toCharArray())")
1620 public String getConstructorPropertyName(final SchemaNode node) {
1621 return node instanceof TypeDefinition<?> ? TypeConstants.VALUE_PROP : "";
1625 public String getParamNameFromType(final TypeDefinition<?> type) {
1626 return BindingMapping.getPropertyName(type.getQName().getLocalName());