2 * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.mdsal.binding.yang.types;
10 import static java.util.Objects.requireNonNull;
11 import static org.opendaylight.mdsal.binding.model.util.BindingTypes.TYPE_OBJECT;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
14 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
16 import com.google.common.annotations.Beta;
17 import com.google.common.base.Preconditions;
18 import com.google.common.base.Strings;
19 import com.google.common.collect.ImmutableMap;
20 import java.math.BigDecimal;
21 import java.util.ArrayList;
22 import java.util.Base64;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.Comparator;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Optional;
33 import java.util.TreeMap;
34 import java.util.regex.Pattern;
35 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
36 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
37 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
38 import org.opendaylight.mdsal.binding.model.api.Enumeration;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
41 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
42 import org.opendaylight.mdsal.binding.model.api.Restrictions;
43 import org.opendaylight.mdsal.binding.model.api.Type;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
50 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
51 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
52 import org.opendaylight.mdsal.binding.model.util.Types;
53 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
55 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.common.Revision;
58 import org.opendaylight.yangtools.yang.common.Uint16;
59 import org.opendaylight.yangtools.yang.common.Uint32;
60 import org.opendaylight.yangtools.yang.common.Uint64;
61 import org.opendaylight.yangtools.yang.common.Uint8;
62 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
63 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.Module;
68 import org.opendaylight.yangtools.yang.model.api.PathExpression;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
72 import org.opendaylight.yangtools.yang.model.api.Status;
73 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
77 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
85 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
86 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
87 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
88 import org.opendaylight.yangtools.yang.model.util.PathExpressionImpl;
89 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
90 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
91 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
96 public abstract class AbstractTypeProvider implements TypeProvider {
97 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
98 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
100 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
101 // the case, as unions are emitted to their correct schema path.
102 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
103 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
106 * Contains the schema data red from YANG files.
108 private final SchemaContext schemaContext;
110 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
113 * The map which maps schema paths to JAVA <code>Type</code>.
115 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
116 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
117 private final Map<SchemaNode, JavaTypeName> renames;
120 * Creates new instance of class <code>TypeProviderImpl</code>.
122 * @param schemaContext contains the schema data red from YANG files
123 * @param renames renaming table
124 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
126 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
127 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
128 this.schemaContext = schemaContext;
129 this.renames = requireNonNull(renames);
130 resolveTypeDefsFromContext();
134 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
136 * @param refTypePath schema path used as the map key
137 * @param refType type which represents the map value
138 * @throws IllegalArgumentException
140 * <li>if <code>refTypePath</code> equal null</li>
141 * <li>if <code>refType</code> equal null</li>
145 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
146 Preconditions.checkArgument(refTypePath != null,
147 "Path reference of Enumeration Type Definition cannot be NULL!");
148 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
149 referencedTypes.put(refTypePath, refType);
152 public Map<Module, Set<Type>> getAdditionalTypes() {
153 return additionalTypes;
157 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
158 final boolean lenientRelativeLeafrefs) {
159 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null, lenientRelativeLeafrefs);
163 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
165 * @param typeDefinition type definition which is converted to JAVA type
166 * @throws IllegalArgumentException
168 * <li>if <code>typeDefinition</code> equal null</li>
169 * <li>if Qname of <code>typeDefinition</code> equal null</li>
170 * <li>if name of <code>typeDefinition</code> equal null</li>
174 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
175 final Restrictions restrictions, final boolean lenientRelativeLeafrefs) {
176 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
177 Preconditions.checkArgument(typeDefinition.getQName() != null,
178 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
179 final String typedefName = typeDefinition.getQName().getLocalName();
180 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
182 // Deal with base types
183 if (typeDefinition.getBaseType() == null) {
184 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
185 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
186 // a base type which holds these constraints.
187 if (typeDefinition instanceof DecimalTypeDefinition) {
188 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
189 parentNode, restrictions, lenientRelativeLeafrefs);
195 // Deal with leafrefs/identityrefs
196 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode, lenientRelativeLeafrefs);
201 // FIXME: it looks as though we could be using the same codepath as above...
202 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
204 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
210 Type returnType = javaTypeForExtendedType(typeDefinition, lenientRelativeLeafrefs);
211 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
212 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
213 final Module module = findParentModule(schemaContext, parentNode);
214 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
215 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
216 typeDefinition.getPath());
217 final String genTOName = BindingMapping.getClassName(typedefName);
218 final String name = packageName + "." + genTOName;
219 if (!returnType.getFullyQualifiedName().equals(name)) {
220 returnType = shadedTOWithRestrictions(gto, restrictions);
226 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
227 final Restrictions restrictions) {
228 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
229 final GeneratedTransferObject parent = gto.getSuperType();
230 if (parent != null) {
231 gtob.setExtendsType(parent);
233 gtob.setRestrictions(restrictions);
234 for (GeneratedProperty gp : gto.getProperties()) {
235 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
236 gpb.setValue(gp.getValue());
237 gpb.setReadOnly(gp.isReadOnly());
238 gpb.setAccessModifier(gp.getAccessModifier());
239 gpb.setReturnType(gp.getReturnType());
240 gpb.setFinal(gp.isFinal());
241 gpb.setStatic(gp.isStatic());
246 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
247 final SchemaNode leafRefValueNode;
248 final PathExpression leafRefXPath = leafref.getPathStatement();
249 final PathExpression leafRefStrippedXPath = new PathExpressionImpl(
250 GROUPS_PATTERN.matcher(leafRefXPath.getOriginalString()).replaceAll(""), leafRefXPath.isAbsolute());
252 ///// skip leafrefs in augments - they're checked once augments are resolved
253 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
254 boolean isAugmenting = false;
255 DataNodeContainer current = null;
256 DataSchemaNode dataChildByName;
258 while (iterator.hasNext() && !isAugmenting) {
259 final QName next = iterator.next();
260 if (current == null) {
261 dataChildByName = schemaContext.getDataChildByName(next);
263 dataChildByName = current.getDataChildByName(next);
265 if (dataChildByName != null) {
266 isAugmenting = dataChildByName.isAugmenting();
270 if (dataChildByName instanceof DataNodeContainer) {
271 current = (DataNodeContainer) dataChildByName;
279 final Module parentModule = getParentModule(parentNode);
280 if (!leafRefStrippedXPath.isAbsolute()) {
281 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
282 parentNode, leafRefStrippedXPath);
284 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
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<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 exists");
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>
502 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode,
503 final boolean inGrouping) {
504 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
506 final PathExpression xpath = leafrefType.getPathStatement();
507 Preconditions.checkArgument(xpath != null, "The Path Statement for Leafref Type Definition cannot be NULL!");
509 final String strXPath = xpath.getOriginalString();
510 if (strXPath.indexOf('[') != -1) {
511 // XXX: why are we special-casing this?
512 return Types.objectType();
515 final Module module = findParentModule(schemaContext, parentNode);
516 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
518 final SchemaNode dataNode;
519 if (xpath.isAbsolute()) {
520 dataNode = findDataSchemaNode(schemaContext, module, xpath);
522 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
523 if (dataNode == null && inGrouping) {
524 // Relative path within a grouping may end up being unresolvable because it may refer outside
525 // the grouping, in which case it is polymorphic based on instantiation, for example:
548 LOG.debug("Leafref type {} not found in parent {}, assuming polymorphic object", leafrefType,
550 return Types.objectType();
553 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
554 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
556 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
557 Type returnType = null;
558 if (leafContainsEnumDefinition(dataNode)) {
559 returnType = referencedTypes.get(dataNode.getPath());
560 } else if (leafListContainsEnumDefinition(dataNode)) {
561 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
563 if (returnType == null) {
564 returnType = resolveTypeFromDataSchemaNode(dataNode);
566 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
567 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
572 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
573 * <code>EnumTypeDefinition</code>.
575 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
576 * @return boolean value
578 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
579 * <li>false - other cases</li>
582 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
583 if (dataNode instanceof LeafSchemaNode) {
584 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
585 return CompatUtils.compatType(leaf) instanceof EnumTypeDefinition;
591 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
592 * <code>EnumTypeDefinition</code>.
594 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
595 * @return boolean value
597 * <li>true - if <code>dataNode</code> is leaflist of type
599 * <li>false - other cases</li>
602 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
603 if (dataNode instanceof LeafListSchemaNode) {
604 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
605 return leafList.getType() instanceof EnumTypeDefinition;
611 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
613 * @param enumTypeDef enumeration type definition which is converted to enumeration
614 * @param enumName string with name which is used as the enumeration name
615 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
616 * @throws IllegalArgumentException
618 * <li>if <code>enumTypeDef</code> equals null</li>
619 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
620 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
621 * <li>if name of <code>enumTypeDef</code> equal null</li>
624 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
625 final SchemaNode parentNode) {
626 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
627 Preconditions.checkArgument(enumTypeDef.getValues() != null,
628 "EnumTypeDefinition MUST contain at least ONE value definition!");
629 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
630 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
631 "Local Name in EnumTypeDefinition QName cannot be NULL!");
633 final Module module = findParentModule(schemaContext, parentNode);
634 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
635 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
636 addEnumDescription(enumBuilder, enumTypeDef);
637 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
638 enumBuilder.setModuleName(module.getName());
639 enumBuilder.setSchemaPath(enumTypeDef.getPath());
640 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
641 return enumBuilder.toInstance(null);
645 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
647 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
648 * @param enumName string with the name of enumeration
649 * @param typeBuilder generated type builder to which is enumeration added
650 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
651 * @throws IllegalArgumentException
653 * <li>if <code>enumTypeDef</code> equals null</li>
654 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
655 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
656 * <li>if name of <code>enumTypeDef</code> equal null</li>
657 * <li>if name of <code>typeBuilder</code> equal null</li>
661 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
662 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
663 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
664 Preconditions.checkArgument(enumTypeDef.getValues() != null,
665 "EnumTypeDefinition MUST contain at least ONE value definition!");
666 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
667 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
668 "Local Name in EnumTypeDefinition QName cannot be NULL!");
669 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
671 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
673 addEnumDescription(enumBuilder, enumTypeDef);
674 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
675 return enumBuilder.toInstance(enumBuilder);
678 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
680 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
682 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
684 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
687 * Converts the pattern constraints to the list of the strings which represents these constraints.
689 * @param patternConstraints list of pattern constraints
690 * @return list of strings which represents the constraint patterns
692 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
694 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
697 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
700 * @param typedef extended type in which are the pattern constraints sought
701 * @return list of strings which represents the constraint patterns
702 * @throws IllegalArgumentException if <code>typedef</code> equals null
705 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
706 if (!(typedef instanceof StringTypeDefinition)) {
707 return ImmutableMap.of();
710 // TODO: run diff against base ?
711 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
715 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
717 * @param dataNode contains information about YANG type
718 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
720 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
721 Type returnType = null;
722 if (dataNode != null) {
723 if (dataNode instanceof LeafSchemaNode) {
724 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
725 final TypeDefinition<?> type = CompatUtils.compatType(leaf);
726 returnType = javaTypeForSchemaDefinitionType(type, leaf);
727 } else if (dataNode instanceof LeafListSchemaNode) {
728 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
729 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
736 * Passes through all modules and through all its type definitions and convert it to generated types.
739 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
740 * of a module are at the beginning sorted so that type definition with less amount of references to other type
741 * definition are processed first.<br>
742 * For each module is created mapping record in the map
743 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
744 * which map current module name to the map which maps type names to returned types (generated types).
746 private void resolveTypeDefsFromContext() {
747 final Set<Module> modules = schemaContext.getModules();
748 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
749 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
751 for (Module module : modulesSortedByDependency) {
752 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
753 module.getName(), key -> new HashMap<>());
754 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
755 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
758 for (Module module : modulesSortedByDependency) {
759 if (module != null) {
760 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
761 if (basePackageName != null) {
762 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
763 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
764 typedefToGeneratedType(basePackageName, module, typedef);
772 * Create Type for specified type definition.
774 * @param basePackageName string with name of package to which the module belongs
775 * @param module string with the name of the module for to which the <code>typedef</code> belongs
776 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
777 * (usually generated TO)
778 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
779 * <code>null</code> value if <code>basePackageName</code> or
780 * <code>modulName</code> or <code>typedef</code> or Q name of
781 * <code>typedef</code> equals <code>null</code>
783 private Type typedefToGeneratedType(final String basePackageName, final Module module,
784 final TypeDefinition<?> typedef) {
785 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
787 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
788 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
792 final String typedefName = typedef.getQName().getLocalName();
794 final Type returnType;
795 if (baseTypedef.getBaseType() != null) {
796 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
798 } else if (baseTypedef instanceof UnionTypeDefinition) {
799 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
800 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
801 (UnionTypeDefinition) baseTypedef, typedef);
802 genTOBuilder.setTypedef(true);
803 genTOBuilder.setIsUnion(true);
804 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
805 makeSerializable(genTOBuilder);
806 returnType = genTOBuilder.build();
808 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
809 // so we are placing the builder alongside the union.
810 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
811 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
812 unionBuilder.setIsUnionBuilder(true);
813 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
814 method.setReturnType(returnType);
815 method.addParameter(Types.STRING, "defaultValue");
816 method.setAccessModifier(AccessModifier.PUBLIC);
817 method.setStatic(true);
818 additionalTypes.computeIfAbsent(module, key -> new HashSet<>()).add(unionBuilder.build());
819 } else if (baseTypedef instanceof EnumTypeDefinition) {
820 // enums are automatically Serializable
821 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
822 // TODO units for typedef enum
823 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
824 } else if (baseTypedef instanceof BitsTypeDefinition) {
825 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
826 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
827 (BitsTypeDefinition) baseTypedef, module.getName());
828 genTOBuilder.setTypedef(true);
829 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
830 makeSerializable(genTOBuilder);
831 returnType = genTOBuilder.build();
833 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
834 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
836 if (returnType != null) {
837 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
838 genTypeDefsContextMap.get(module.getName());
839 final Optional<Revision> moduleRevision = module.getRevision();
840 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
841 if (typeMap != null) {
842 if (typeMap.isEmpty()) {
843 typeMap = new HashMap<>(4);
844 modulesByDate.put(moduleRevision, typeMap);
846 typeMap.put(typedefName, returnType);
854 * Wraps base YANG type to generated TO.
856 * @param basePackageName string with name of package to which the module belongs
857 * @param typedef type definition which is converted to the TO
858 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
859 * @return generated transfer object which represent<code>javaType</code>
861 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
862 final Type javaType, final String moduleName) {
863 requireNonNull(javaType, "javaType cannot be null");
865 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
866 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
867 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
868 genPropBuilder.setReturnType(javaType);
869 genTOBuilder.addEqualsIdentity(genPropBuilder);
870 genTOBuilder.addHashIdentity(genPropBuilder);
871 genTOBuilder.addToStringProperty(genPropBuilder);
872 genTOBuilder.addImplementsType(TYPE_OBJECT);
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 final List<Bit> bitList = typeDef.getBits();
1150 GeneratedPropertyBuilder genPropertyBuilder;
1151 for (Bit bit : bitList) {
1152 final String name = bit.getName();
1153 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1154 genPropertyBuilder.setReadOnly(true);
1155 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1157 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1158 genTOBuilder.addHashIdentity(genPropertyBuilder);
1159 genTOBuilder.addToStringProperty(genPropertyBuilder);
1162 return genTOBuilder;
1166 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1167 * the <code>regularExpressions</code>.
1169 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1170 * @param expressions list of string which represent regular expressions
1172 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1173 final Map<String, String> expressions) {
1174 if (!expressions.isEmpty()) {
1175 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1176 ImmutableMap.copyOf(expressions));
1181 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1182 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1185 * It is assumed that <code>innerExtendedType</code> is already present in
1186 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1187 * for the returning generated TO.
1189 * @param typedef Type Definition
1190 * @param innerExtendedType extended type which is part of some other extended type
1191 * @param basePackageName string with the package name of the module
1192 * @param moduleName Module Name
1193 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1194 * @throws IllegalArgumentException
1196 * <li>if <code>extendedType</code> equals null</li>
1197 * <li>if <code>basePackageName</code> equals null</li>
1198 * <li>if <code>typedefName</code> equals null</li>
1201 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1202 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1203 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1204 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1206 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1207 BindingMapping.getClassName(typedef.getQName())));
1208 genTOBuilder.setSchemaPath(typedef.getPath());
1209 genTOBuilder.setModuleName(moduleName);
1210 genTOBuilder.setTypedef(true);
1211 addCodegenInformation(genTOBuilder, typedef);
1213 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1214 genTOBuilder.setRestrictions(r);
1215 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1217 if (typedef.getStatus() == Status.DEPRECATED) {
1218 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1221 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1222 genTOBuilder.setIsUnion(true);
1225 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1226 Map<String, Type> typeMap = null;
1227 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1228 if (parentModule != null) {
1229 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1230 typeMap = modulesByDate.get(parentModule.getRevision());
1233 if (typeMap != null) {
1234 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1235 final Type type = typeMap.get(innerTypeDef);
1236 if (type instanceof GeneratedTransferObject) {
1237 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1240 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1241 makeSerializable(genTOBuilder);
1243 return genTOBuilder.build();
1247 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1250 * @param gto transfer object which needs to be made serializable
1252 private static void makeSerializable(final GeneratedTOBuilder gto) {
1253 gto.addImplementsType(Types.serializableType());
1254 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1255 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1260 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1261 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1262 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1263 * type definitions are in the list behind all type definitions on which depends.
1265 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1266 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1267 * dependent on other type definitions are in list behind them).
1269 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1270 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1271 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1273 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1274 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1275 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1276 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1277 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1278 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1281 // SortedMap guarantees order corresponding to keys in ascending order
1282 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1283 sortedTypeDefinition.addAll(v);
1286 return sortedTypeDefinition;
1290 * Returns how many immersion is necessary to get from the type definition to the base type.
1292 * @param typeDefinition type definition for which is depth sought.
1293 * @return number of immersions which are necessary to get from the type definition to the base type
1295 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1296 // FIXME: rewrite this in a non-recursive manner
1297 if (typeDefinition == null) {
1300 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1301 if (baseType == null) {
1306 if (baseType.getBaseType() != null) {
1307 depth = depth + getTypeDefinitionDepth(baseType);
1308 } else if (baseType instanceof UnionTypeDefinition) {
1309 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1310 int maxChildDepth = 0;
1312 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1313 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1314 if (childDepth > maxChildDepth) {
1315 maxChildDepth = childDepth;
1318 return maxChildDepth;
1324 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1325 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1326 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1328 * @param name string with name of augmented node
1329 * @return string with the number suffix incremented by one (or 1 is added)
1331 private static String provideAvailableNameForGenTOBuilder(final String name) {
1332 final int dollar = name.indexOf('$');
1337 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1338 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1339 return name.substring(0, dollar + 1) + newSuffix;
1342 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1343 if (!Strings.isNullOrEmpty(units)) {
1344 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1345 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1346 prop.setReturnType(Types.STRING);
1347 to.addToStringProperty(prop);
1352 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1353 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1356 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1357 final TypeDefinition<?> type = CompatUtils.compatType(node);
1358 final QName typeQName = type.getQName();
1359 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1360 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1361 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1364 final StringBuilder sb = new StringBuilder();
1365 String result = null;
1366 if (base instanceof BinaryTypeDefinition) {
1367 result = binaryToDef(defaultValue);
1368 } else if (base instanceof BitsTypeDefinition) {
1371 final Module parent = getParentModule(node);
1372 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1374 if (!path.hasNext()) {
1375 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1376 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1377 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1379 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1380 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1382 parentName = BindingMapping.getClassName(parent.getName());
1383 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1385 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1386 } else if (base instanceof BooleanTypeDefinition) {
1387 result = typeToBooleanDef(defaultValue);
1388 } else if (base instanceof DecimalTypeDefinition) {
1389 result = typeToDef(BigDecimal.class, defaultValue);
1390 } else if (base instanceof EmptyTypeDefinition) {
1391 result = typeToBooleanDef(defaultValue);
1392 } else if (base instanceof EnumTypeDefinition) {
1393 final char[] defValArray = defaultValue.toCharArray();
1394 final char first = Character.toUpperCase(defaultValue.charAt(0));
1395 defValArray[0] = first;
1396 final String newDefVal = new String(defValArray);
1398 if (type.getBaseType() != null) {
1399 final Module m = getParentModule(type);
1400 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1401 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1403 className = packageName + "." + BindingMapping.getClassName(typeQName);
1405 final Module parentModule = getParentModule(node);
1406 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1407 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1409 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1411 result = className + "." + newDefVal;
1412 } else if (base instanceof IdentityrefTypeDefinition) {
1413 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1414 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1415 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1416 } else if (BaseTypes.isInt8(base)) {
1417 result = typeToValueOfDef(Byte.class, defaultValue);
1418 } else if (BaseTypes.isInt16(base)) {
1419 result = typeToValueOfDef(Short.class, defaultValue);
1420 } else if (BaseTypes.isInt32(base)) {
1421 result = typeToValueOfDef(Integer.class, defaultValue);
1422 } else if (BaseTypes.isInt64(base)) {
1423 result = typeToValueOfDef(Long.class, defaultValue);
1424 } else if (base instanceof LeafrefTypeDefinition) {
1425 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1426 } else if (base instanceof StringTypeDefinition) {
1427 result = "\"" + defaultValue + "\"";
1428 } else if (BaseTypes.isUint8(base)) {
1429 result = typeToValueOfDef(Uint8.class, defaultValue);
1430 } else if (BaseTypes.isUint16(base)) {
1431 result = typeToValueOfDef(Uint16.class, defaultValue);
1432 } else if (BaseTypes.isUint32(base)) {
1433 result = typeToValueOfDef(Uint32.class, defaultValue);
1434 } else if (BaseTypes.isUint64(base)) {
1435 result = typeToValueOfDef(Uint64.class, defaultValue);
1436 } else if (base instanceof UnionTypeDefinition) {
1437 result = unionToDef(node);
1443 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1444 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1445 final Module m = getParentModule(type);
1446 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1447 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1449 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1450 sb.insert(0, "new " + className + "(");
1451 sb.insert(sb.length(), ')');
1454 return sb.toString();
1457 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1458 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1461 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1462 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1465 private static String typeToBooleanDef(final String defaultValue) {
1466 switch (defaultValue) {
1468 return "java.lang.Boolean.FALSE";
1470 return "java.lang.Boolean.TRUE";
1472 return typeToValueOfDef(Boolean.class, defaultValue);
1476 private static String binaryToDef(final String defaultValue) {
1477 final StringBuilder sb = new StringBuilder();
1478 final byte[] encoded = Base64.getDecoder().decode(defaultValue);
1479 sb.append("new byte[] {");
1480 for (int i = 0; i < encoded.length; i++) {
1481 sb.append(encoded[i]);
1482 if (i != encoded.length - 1) {
1487 return sb.toString();
1490 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1492 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1493 final boolean isExt) {
1494 final List<Bit> bits = new ArrayList<>(type.getBits());
1495 bits.sort(BIT_NAME_COMPARATOR);
1496 final StringBuilder sb = new StringBuilder();
1499 sb.append(className);
1502 for (int i = 0; i < bits.size(); i++) {
1503 if (bits.get(i).getName().equals(defaultValue)) {
1508 if (i != bits.size() - 1) {
1515 return sb.toString();
1518 private Module getParentModule(final SchemaNode node) {
1519 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1520 return schemaContext.findModule(qname.getModule()).orElse(null);
1523 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1524 final String defaultValue) {
1525 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1526 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1527 "The Path Statement for Leafref Type Definition cannot be NULL!");
1529 final PathExpression xpath = leafrefType.getPathStatement();
1530 final String strXPath = xpath.getOriginalString();
1532 if (strXPath != null) {
1533 if (strXPath.indexOf('[') == -1) {
1534 final Module module = findParentModule(schemaContext, parentNode);
1535 if (module != null) {
1536 final SchemaNode dataNode;
1537 if (xpath.isAbsolute()) {
1538 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1540 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1542 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1546 return "new java.lang.Object()";
1553 private String unionToDef(final LeafSchemaNode node) {
1554 final TypeDefinition<?> type = CompatUtils.compatType(node);
1558 if (type.getBaseType() != null) {
1559 final QName typeQName = type.getQName();
1560 Module module = null;
1561 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1562 if (modules.size() > 1) {
1563 for (Module m : modules) {
1564 if (m.getRevision().equals(typeQName.getRevision())) {
1569 if (module == null) {
1570 final List<Module> modulesList = new ArrayList<>(modules);
1571 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1572 module = modulesList.get(0);
1575 module = modules.iterator().next();
1578 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1579 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1581 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1582 final QName first = path.next();
1583 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1584 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1585 if (!path.hasNext()) {
1586 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1587 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1589 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1591 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1594 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1597 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1598 final StringBuilder sb = new StringBuilder();
1600 sb.append(className);
1602 sb.append(defaultValue);
1603 sb.append("\".toCharArray())");
1604 return sb.toString();
1608 public String getConstructorPropertyName(final SchemaNode node) {
1609 return node instanceof TypeDefinition<?> ? "value" : "";
1613 public String getParamNameFromType(final TypeDefinition<?> type) {
1614 return BindingMapping.getPropertyName(type.getQName().getLocalName());