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.BaseYangTypes;
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.BindingGeneratorUtil;
53 import org.opendaylight.mdsal.binding.model.util.BindingTypes;
54 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
55 import org.opendaylight.mdsal.binding.model.util.Types;
56 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
57 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
58 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.common.Revision;
61 import org.opendaylight.yangtools.yang.common.Uint16;
62 import org.opendaylight.yangtools.yang.common.Uint32;
63 import org.opendaylight.yangtools.yang.common.Uint64;
64 import org.opendaylight.yangtools.yang.common.Uint8;
65 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
66 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.Module;
71 import org.opendaylight.yangtools.yang.model.api.PathExpression;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
74 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
75 import org.opendaylight.yangtools.yang.model.api.Status;
76 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
80 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
87 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
88 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
89 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
90 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
91 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
92 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
93 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
94 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
95 import org.slf4j.Logger;
96 import org.slf4j.LoggerFactory;
99 public abstract class AbstractTypeProvider implements TypeProvider {
100 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
101 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
103 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
104 // the case, as unions are emitted to their correct schema path.
105 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
106 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
109 * Contains the schema data red from YANG files.
111 private final SchemaContext schemaContext;
113 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
116 * The map which maps schema paths to JAVA <code>Type</code>.
118 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
119 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
120 private final Map<SchemaNode, JavaTypeName> renames;
123 * Creates new instance of class <code>TypeProviderImpl</code>.
125 * @param schemaContext contains the schema data red from YANG files
126 * @param renames renaming table
127 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
129 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
130 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
131 this.schemaContext = schemaContext;
132 this.renames = requireNonNull(renames);
133 resolveTypeDefsFromContext();
137 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
139 * @param refTypePath schema path used as the map key
140 * @param refType type which represents the map value
141 * @throws IllegalArgumentException
143 * <li>if <code>refTypePath</code> equal null</li>
144 * <li>if <code>refType</code> equal null</li>
148 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
149 Preconditions.checkArgument(refTypePath != null,
150 "Path reference of Enumeration Type Definition cannot be NULL!");
151 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
152 referencedTypes.put(refTypePath, refType);
155 public Map<Module, Set<Type>> getAdditionalTypes() {
156 return additionalTypes;
160 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
161 final boolean lenientRelativeLeafrefs) {
162 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
166 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
168 * @param typeDefinition type definition which is converted to JAVA type
169 * @throws IllegalArgumentException
171 * <li>if <code>typeDefinition</code> equal null</li>
172 * <li>if Qname of <code>typeDefinition</code> equal null</li>
173 * <li>if name of <code>typeDefinition</code> equal null</li>
177 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
178 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
179 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
180 Preconditions.checkArgument(typeDefinition.getQName() != null,
181 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
182 final String typedefName = typeDefinition.getQName().getLocalName();
183 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
185 // Deal with base types
186 if (typeDefinition.getBaseType() == null) {
187 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
188 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
189 // a base type which holds these constraints.
190 if (typeDefinition instanceof DecimalTypeDefinition) {
191 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
192 parentNode, restrictions, lenientRelativeLeafrefs);
198 // Deal with leafrefs/identityrefs
199 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
204 // FIXME: it looks as though we could be using the same codepath as above...
205 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
207 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
213 Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
214 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
215 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
216 final Module module = findParentModule(schemaContext, parentNode);
217 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
218 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
219 typeDefinition.getPath());
220 final String genTOName = BindingMapping.getClassName(typedefName);
221 final String name = packageName + "." + genTOName;
222 if (!returnType.getFullyQualifiedName().equals(name)) {
223 returnType = shadedTOWithRestrictions(gto, restrictions);
229 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
230 final Restrictions restrictions) {
231 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
232 final GeneratedTransferObject parent = gto.getSuperType();
233 if (parent != null) {
234 gtob.setExtendsType(parent);
236 gtob.setRestrictions(restrictions);
237 for (GeneratedProperty gp : gto.getProperties()) {
238 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
239 gpb.setValue(gp.getValue());
240 gpb.setReadOnly(gp.isReadOnly());
241 gpb.setAccessModifier(gp.getAccessModifier());
242 gpb.setReturnType(gp.getReturnType());
243 gpb.setFinal(gp.isFinal());
244 gpb.setStatic(gp.isStatic());
249 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
251 * First check if the leafref is an augment. If that is the case, skip it as it will be checked once augments
254 DataNodeContainer current = null;
255 DataSchemaNode dataChildByName;
256 for (QName next : parentNode.getPath().getPathFromRoot()) {
257 if (current == null) {
258 dataChildByName = schemaContext.getDataChildByName(next);
260 dataChildByName = current.getDataChildByName(next);
262 if (dataChildByName == null) {
265 if (dataChildByName.isAugmenting()) {
268 if (dataChildByName instanceof DataNodeContainer) {
269 current = (DataNodeContainer) dataChildByName;
273 // Then try to look up the expression.
274 final PathExpression leafRefXPath = leafref.getPathStatement();
275 final Module parentModule = getParentModule(parentNode);
276 final SchemaNode leafRefValueNode;
277 if (leafRefXPath.isAbsolute()) {
278 leafRefValueNode = SchemaContextUtil.findDataTreeSchemaNode(schemaContext, parentModule.getQNameModule(),
281 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
282 parentNode, new PathExpressionImpl(
283 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), false));
286 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
290 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
291 * <code>IdentityrefTypeDefinition</code>.
293 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
294 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
296 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
297 final boolean inGrouping) {
298 if (typeDefinition instanceof LeafrefTypeDefinition) {
299 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
300 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
301 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
302 return provideTypeForLeafref(leafref, parentNode, inGrouping);
303 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
304 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
311 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
313 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
314 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
316 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition, final boolean lenient) {
317 final String typedefName = typeDefinition.getQName().getLocalName();
318 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
319 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition, lenient);
320 if (returnType == null) {
321 if (baseTypeDef instanceof EnumTypeDefinition) {
322 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
323 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
325 final Module module = findParentModule(schemaContext, typeDefinition);
326 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
327 if (module != null) {
328 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
330 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
331 if (genTOs != null) {
332 returnType = genTOs.get(typedefName);
334 if (returnType == null) {
335 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
336 baseTypeDef, typeDefinition, r, lenient);
345 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
349 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
350 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
352 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
353 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
355 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
356 final Collection<? extends IdentitySchemaNode> identities = idref.getIdentities();
357 if (identities.size() > 1) {
358 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
361 final QName baseIdQName = identities.iterator().next().getQName();
362 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
363 IdentitySchemaNode identity = null;
364 for (IdentitySchemaNode id : module.getIdentities()) {
365 if (id.getQName().equals(baseIdQName)) {
369 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exist");
371 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
372 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
373 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
374 return Types.classType(Types.wildcardTypeFor(identifier));
378 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
380 * @param typeDefinition
381 * type definition which should be converted to JAVA
383 * @return JAVA <code>Type</code> which represents
384 * <code>typeDefinition</code>
385 * @throws IllegalArgumentException
387 * <li>if <code>typeDefinition</code> equal null</li>
388 * <li>if Q name of <code>typeDefinition</code></li>
389 * <li>if name of <code>typeDefinition</code></li>
392 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
393 final SchemaNode parentNode) {
394 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
395 if (typeDefinition.getQName() == null) {
396 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
398 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
399 "Type Definitions Local Name cannot be NULL!");
401 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
402 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
404 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
405 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
418 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
419 * dicey when we throw in:
433 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
434 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
437 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
438 * an encapsulation for identityref typedefs.
440 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
441 * option, as it would look as though it is the product of a different construct:
447 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
448 * sub-identities of iden.
450 * The story behind leafrefs is probably similar, but that needs to be ascertained.
455 final Module module = findParentModule(schemaContext, parentNode);
456 if (module != null) {
457 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
459 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
460 if (genTOs != null) {
461 return genTOs.get(typeDefinition.getQName().getLocalName());
468 * Gets base type definition for <code>extendTypeDef</code>. The method is
469 * recursively called until non <code>ExtendedType</code> type is found.
471 * @param extendTypeDef
472 * type definition for which is the base type definition sought
473 * @return type definition which is base type for <code>extendTypeDef</code>
474 * @throws IllegalArgumentException
475 * if <code>extendTypeDef</code> equal null
477 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
478 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
480 TypeDefinition<?> ret = extendTypeDef;
481 while (ret.getBaseType() != null) {
482 ret = ret.getBaseType();
489 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
490 * to find referenced node and its <code>Type</code> is returned.
492 * @param leafrefType leafref type definition for which is the type sought
493 * @param parentNode parent node of the leaf being resolved
494 * @param inGrouping true if we are resolving the type within a grouping.
495 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
496 * @throws IllegalArgumentException
498 * <li>if <code>leafrefType</code> equal null</li>
499 * <li>if path statement of <code>leafrefType</code> equal null</li>
503 Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
504 final boolean inGrouping) {
505 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
507 final PathExpression xpath = leafrefType.getPathStatement();
508 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
510 final String strXPath = xpath.getOriginalString();
511 if (strXPath.indexOf('[') != -1) {
512 // XXX: why are we special-casing this?
513 return Types.objectType();
516 final Module module = findParentModule(schemaContext, parentNode);
517 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
519 final SchemaNode dataNode;
520 if (xpath.isAbsolute()) {
521 dataNode = findDataTreeSchemaNode(schemaContext, module.getQNameModule(), xpath);
523 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
524 if (dataNode == null && inGrouping) {
525 // Relative path within a grouping may end up being unresolvable because it may refer outside
526 // the grouping, in which case it is polymorphic based on instantiation, for example:
549 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
551 return Types.objectType();
554 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
555 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
557 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
558 Type returnType = null;
559 if (leafContainsEnumDefinition(dataNode)) {
560 returnType = referencedTypes.get(dataNode.getPath());
561 } else if (leafListContainsEnumDefinition(dataNode)) {
562 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
564 if (returnType == null) {
565 returnType = resolveTypeFromDataSchemaNode(dataNode, inGrouping);
567 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
568 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
573 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
574 * <code>EnumTypeDefinition</code>.
576 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
577 * @return boolean value
579 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
580 * <li>false - other cases</li>
583 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
584 if (dataNode instanceof LeafSchemaNode) {
585 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
586 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
592 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
593 * <code>EnumTypeDefinition</code>.
595 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
596 * @return boolean value
598 * <li>true - if <code>dataNode</code> is leaflist of type
600 * <li>false - other cases</li>
603 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
604 if (dataNode instanceof LeafListSchemaNode) {
605 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
606 return leafList.getType() instanceof EnumTypeDefinition;
612 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
614 * @param enumTypeDef enumeration type definition which is converted to enumeration
615 * @param enumName string with name which is used as the enumeration name
616 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
617 * @throws IllegalArgumentException
619 * <li>if <code>enumTypeDef</code> equals null</li>
620 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
621 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
622 * <li>if name of <code>enumTypeDef</code> equal null</li>
625 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
626 final SchemaNode parentNode) {
627 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
628 Preconditions.checkArgument(enumTypeDef.getValues() != null,
629 "EnumTypeDefinition MUST contain at least ONE value definition!");
630 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
631 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
632 "Local Name in EnumTypeDefinition QName cannot be NULL!");
634 final Module module = findParentModule(schemaContext, parentNode);
635 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
636 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
637 addEnumDescription(enumBuilder, enumTypeDef);
638 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
639 enumBuilder.setModuleName(module.getName());
640 enumBuilder.setSchemaPath(enumTypeDef.getPath());
641 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
642 return enumBuilder.toInstance(null);
646 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
648 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
649 * @param enumName string with the name of enumeration
650 * @param typeBuilder generated type builder to which is enumeration added
651 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
652 * @throws IllegalArgumentException
654 * <li>if <code>enumTypeDef</code> equals null</li>
655 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
656 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
657 * <li>if name of <code>enumTypeDef</code> equal null</li>
658 * <li>if name of <code>typeBuilder</code> equal null</li>
662 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
663 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
664 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
665 Preconditions.checkArgument(enumTypeDef.getValues() != null,
666 "EnumTypeDefinition MUST contain at least ONE value definition!");
667 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
668 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
669 "Local Name in EnumTypeDefinition QName cannot be NULL!");
670 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
672 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
674 addEnumDescription(enumBuilder, enumTypeDef);
675 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
676 return enumBuilder.toInstance(enumBuilder);
679 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
681 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
683 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
685 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
688 * Converts the pattern constraints to the list of the strings which represents these constraints.
690 * @param patternConstraints list of pattern constraints
691 * @return list of strings which represents the constraint patterns
693 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
695 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
698 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
701 * @param typedef extended type in which are the pattern constraints sought
702 * @return list of strings which represents the constraint patterns
703 * @throws IllegalArgumentException if <code>typedef</code> equals null
706 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
707 if (!(typedef instanceof StringTypeDefinition)) {
708 return ImmutableMap.of();
711 // TODO: run diff against base ?
712 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
716 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
718 * @param dataNode contains information about YANG type
719 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
721 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode, final boolean inGrouping) {
722 Type returnType = null;
723 if (dataNode != null) {
724 if (dataNode instanceof LeafSchemaNode) {
725 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
726 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
727 returnType = javaTypeForSchemaDefinitionType(type, leaf, inGrouping);
728 } else if (dataNode instanceof LeafListSchemaNode) {
729 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
730 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList, inGrouping);
737 * Passes through all modules and through all its type definitions and convert it to generated types.
740 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
741 * of a module are at the beginning sorted so that type definition with less amount of references to other type
742 * definition are processed first.<br>
743 * For each module is created mapping record in the map
744 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
745 * which map current module name to the map which maps type names to returned types (generated types).
747 private void resolveTypeDefsFromContext() {
748 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(schemaContext.getModules());
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(TypeConstants.VALUE_PROP);
867 genPropBuilder.setReturnType(javaType);
869 genTOBuilder.addEqualsIdentity(genPropBuilder);
870 genTOBuilder.addHashIdentity(genPropBuilder);
871 genTOBuilder.addToStringProperty(genPropBuilder);
872 genTOBuilder.addImplementsType(BindingTypes.scalarTypeObject(javaType));
873 if (typedef.getStatus() == Status.DEPRECATED) {
874 genTOBuilder.addAnnotation("java.lang", "Deprecated");
876 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
877 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
879 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
880 genTOBuilder.setTypedef(true);
881 makeSerializable(genTOBuilder);
882 return genTOBuilder.build();
886 * Converts output list of generated TO builders to one TO builder (first
887 * from list) which contains the remaining builders as its enclosing TO.
889 * @param typeName new type identifier
890 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
891 * @return generated TO builder with the list of enclosed generated TO builders
893 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
894 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
895 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
897 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
899 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
900 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
901 return resultTOBuilder;
905 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
906 * <code>typedef</code> is added to generated TO builder as property.
908 * @param typeName new type identifier
909 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
910 * @return generated TO builder which represents <code>typedef</code>
911 * @throws NullPointerException
913 * <li>if <code>basePackageName</code> is null</li>
914 * <li>if <code>typedef</code> is null</li>
915 * <li>if Qname of <code>typedef</code> is null</li>
918 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
919 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
920 requireNonNull(typedef, "Type Definition cannot be NULL!");
921 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
923 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
924 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
925 final Module module = findParentModule(schemaContext, parentNode);
927 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
928 unionGenTOBuilder.setIsUnion(true);
929 unionGenTOBuilder.setSchemaPath(typedef.getPath());
930 unionGenTOBuilder.setModuleName(module.getName());
931 unionGenTOBuilder.addImplementsType(TYPE_OBJECT);
932 addCodegenInformation(unionGenTOBuilder, typedef);
933 generatedTOBuilders.add(unionGenTOBuilder);
935 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
936 // also negation information and hence guarantees uniqueness.
937 final Map<String, String> expressions = new HashMap<>();
938 for (TypeDefinition<?> unionType : unionTypes) {
939 final String unionTypeName = unionType.getQName().getLocalName();
941 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
942 // do not follow type encapsulation -- we use the general case for that.
943 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
944 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
945 } else if (unionType instanceof UnionTypeDefinition) {
946 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
947 (UnionTypeDefinition) unionType, parentNode));
948 } else if (unionType instanceof EnumTypeDefinition) {
949 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
950 unionTypeName, unionGenTOBuilder);
951 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
953 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
954 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
957 addStringRegExAsConstant(unionGenTOBuilder, expressions);
959 storeGenTO(typedef, unionGenTOBuilder, parentNode);
961 return generatedTOBuilders;
965 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
968 * In this case the new generated TO is created for union subtype (recursive call of method
969 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
970 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
971 * created property which type is equal to new generated TO.
973 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
974 * @param basePackageName string with the name of the module package
975 * @param unionSubtype type definition which represents union subtype
976 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
977 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
979 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
980 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
981 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
982 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
983 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
984 newTOBuilderName, unionSubtype, parentNode);
986 final GeneratedPropertyBuilder propertyBuilder;
987 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
988 newTOBuilderName.simpleName()));
989 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
990 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
991 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
993 return subUnionGenTOBUilders;
997 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
998 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
999 * the base type is used for the property creation.
1001 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
1002 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
1003 * @param expressions list of strings with the regular expressions
1004 * @param parentNode parent Schema Node for Extended Subtype
1006 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1007 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1008 final String unionTypeName = unionSubtype.getQName().getLocalName();
1009 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1010 if (genTO != null) {
1011 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1015 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1016 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1017 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1018 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1019 if (javaType != null) {
1020 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1022 } else if (baseType instanceof LeafrefTypeDefinition) {
1023 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1024 boolean typeExist = false;
1025 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1026 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1027 if (origType != null && javaType != null && javaType == origType) {
1032 if (!typeExist && javaType != null) {
1033 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1034 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1037 if (baseType instanceof StringTypeDefinition) {
1038 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1043 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1044 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1046 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1047 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1049 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1050 final Module typeModule = findParentModule(schemaContext, parentNode);
1051 if (typeModule != null && typeModule.getName() != null) {
1052 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1053 typeModule.getName());
1054 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1055 if (genTOs != null) {
1056 return genTOs.get(searchedTypeName);
1063 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1064 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1066 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1067 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1069 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1070 final SchemaNode parentNode) {
1071 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1072 final Module parentModule = findParentModule(schemaContext, parentNode);
1073 if (parentModule != null && parentModule.getName() != null) {
1074 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1075 parentModule.getName());
1076 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1077 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1083 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1084 * to <code>unonGenTransObject</code>.
1086 * @param unionGenTransObject generated TO to which should be property added
1087 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1088 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1090 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1091 final String propertyName) {
1092 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1093 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1094 .addProperty(BindingMapping.getPropertyName(propertyName));
1095 propBuilder.setReturnType(type);
1097 unionGenTransObject.addEqualsIdentity(propBuilder);
1098 unionGenTransObject.addHashIdentity(propBuilder);
1099 unionGenTransObject.addToStringProperty(propBuilder);
1104 * Converts <code>typedef</code> to the generated TO builder.
1106 * @param basePackageName string with name of package to which the module belongs
1107 * @param typedef type definition from which is the generated TO builder created
1108 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1110 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1111 final TypeDefinition<?> typedef, final String moduleName) {
1112 JavaTypeName name = renames.get(typedef);
1114 name = JavaTypeName.create(
1115 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1116 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1119 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1120 newType.setSchemaPath(typedef.getPath());
1121 newType.setModuleName(moduleName);
1122 addCodegenInformation(newType, typedef);
1127 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1128 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1131 * @param typeName new type identifier
1132 * @param typeDef type definition from which is the generated TO builder created
1133 * @return generated TO builder which represents <code>typeDef</code>
1134 * @throws IllegalArgumentException
1136 * <li>if <code>typeDef</code> equals null</li>
1137 * <li>if <code>basePackageName</code> equals null</li>
1140 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1141 final BitsTypeDefinition typeDef, final String moduleName) {
1142 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1143 genTOBuilder.setSchemaPath(typeDef.getPath());
1144 genTOBuilder.setModuleName(moduleName);
1145 genTOBuilder.setBaseType(typeDef);
1146 genTOBuilder.addImplementsType(TYPE_OBJECT);
1147 addCodegenInformation(genTOBuilder, typeDef);
1149 for (Bit bit : typeDef.getBits()) {
1150 final String name = bit.getName();
1151 GeneratedPropertyBuilder genPropertyBuilder = genTOBuilder.addProperty(
1152 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 Collection<? extends 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 return new StringBuilder()
1601 .append(defaultValue)
1602 .append("\".toCharArray())")
1607 public String getConstructorPropertyName(final SchemaNode node) {
1608 return node instanceof TypeDefinition<?> ? TypeConstants.VALUE_PROP : "";
1612 public String getParamNameFromType(final TypeDefinition<?> type) {
1613 return BindingMapping.getPropertyName(type.getQName().getLocalName());