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.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
15 import com.google.common.annotations.Beta;
16 import com.google.common.base.Preconditions;
17 import com.google.common.base.Strings;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.Sets;
20 import com.google.common.io.BaseEncoding;
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
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.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
68 import org.opendaylight.yangtools.yang.model.api.Status;
69 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
73 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
81 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
84 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
85 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
86 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
87 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 public abstract class AbstractTypeProvider implements TypeProvider {
93 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
94 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
96 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
97 // the case, as unions are emitted to their correct schema path.
98 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
99 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
102 * Contains the schema data red from YANG files.
104 private final SchemaContext schemaContext;
106 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
109 * The map which maps schema paths to JAVA <code>Type</code>.
111 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
112 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
113 private final Map<SchemaNode, JavaTypeName> renames;
116 * Creates new instance of class <code>TypeProviderImpl</code>.
118 * @param schemaContext contains the schema data red from YANG files
119 * @param renames renaming table
120 * @throws IllegalArgumentException if <code>schemaContext</code> equal null.
122 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
123 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
124 this.schemaContext = schemaContext;
125 this.renames = requireNonNull(renames);
126 resolveTypeDefsFromContext();
130 * Puts <code>refType</code> to map with key <code>refTypePath</code>.
132 * @param refTypePath schema path used as the map key
133 * @param refType type which represents the map value
134 * @throws IllegalArgumentException
136 * <li>if <code>refTypePath</code> equal null</li>
137 * <li>if <code>refType</code> equal null</li>
141 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
142 Preconditions.checkArgument(refTypePath != null,
143 "Path reference of Enumeration Type Definition cannot be NULL!");
144 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
145 referencedTypes.put(refTypePath, refType);
148 public Map<Module, Set<Type>> getAdditionalTypes() {
149 return additionalTypes;
153 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
154 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
158 * Converts schema definition type <code>typeDefinition</code> to JAVA <code>Type</code>.
160 * @param typeDefinition type definition which is converted to JAVA type
161 * @throws IllegalArgumentException
163 * <li>if <code>typeDefinition</code> equal null</li>
164 * <li>if Qname of <code>typeDefinition</code> equal null</li>
165 * <li>if name of <code>typeDefinition</code> equal null</li>
169 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
170 final Restrictions restrictions) {
171 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
172 Preconditions.checkArgument(typeDefinition.getQName() != null,
173 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
174 final String typedefName = typeDefinition.getQName().getLocalName();
175 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
177 // Deal with base types
178 if (typeDefinition.getBaseType() == null) {
179 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
180 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
181 // a base type which holds these constraints.
182 if (typeDefinition instanceof DecimalTypeDefinition) {
183 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
184 parentNode, restrictions);
190 // Deal with leafrefs/identityrefs
191 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
196 // FIXME: it looks as though we could be using the same codepath as above...
197 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
199 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
205 Type returnType = javaTypeForExtendedType(typeDefinition);
206 if (restrictions != null && returnType instanceof GeneratedTransferObject) {
207 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
208 final Module module = findParentModule(schemaContext, parentNode);
209 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
210 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
211 typeDefinition.getPath());
212 final String genTOName = BindingMapping.getClassName(typedefName);
213 final String name = packageName + "." + genTOName;
214 if (!returnType.getFullyQualifiedName().equals(name)) {
215 returnType = shadedTOWithRestrictions(gto, restrictions);
221 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
222 final Restrictions restrictions) {
223 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
224 final GeneratedTransferObject parent = gto.getSuperType();
225 if (parent != null) {
226 gtob.setExtendsType(parent);
228 gtob.setRestrictions(restrictions);
229 for (GeneratedProperty gp : gto.getProperties()) {
230 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
231 gpb.setValue(gp.getValue());
232 gpb.setReadOnly(gp.isReadOnly());
233 gpb.setAccessModifier(gp.getAccessModifier());
234 gpb.setReturnType(gp.getReturnType());
235 gpb.setFinal(gp.isFinal());
236 gpb.setStatic(gp.isStatic());
241 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
242 final SchemaNode leafRefValueNode;
243 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
244 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(
245 GROUPS_PATTERN.matcher(leafRefXPath.toString()).replaceAll(""), leafRefXPath.isAbsolute());
247 ///// skip leafrefs in augments - they're checked once augments are resolved
248 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
249 boolean isAugmenting = false;
250 DataNodeContainer current = null;
251 DataSchemaNode dataChildByName;
253 while (iterator.hasNext() && !isAugmenting) {
254 final QName next = iterator.next();
255 if (current == null) {
256 dataChildByName = schemaContext.getDataChildByName(next);
258 dataChildByName = current.getDataChildByName(next);
260 if (dataChildByName != null) {
261 isAugmenting = dataChildByName.isAugmenting();
265 if (dataChildByName instanceof DataNodeContainer) {
266 current = (DataNodeContainer) dataChildByName;
274 final Module parentModule = getParentModule(parentNode);
275 if (!leafRefStrippedXPath.isAbsolute()) {
276 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
277 parentNode, leafRefStrippedXPath);
279 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
281 return leafRefValueNode != null && leafRefValueNode.equals(parentNode);
285 * Returns JAVA <code>Type</code> for instances of the type <code>LeafrefTypeDefinition</code> or
286 * <code>IdentityrefTypeDefinition</code>.
288 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
289 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
291 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
292 if (typeDefinition instanceof LeafrefTypeDefinition) {
293 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
294 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
295 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
296 return provideTypeForLeafref(leafref, parentNode);
297 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
298 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
305 * Returns JAVA <code>Type</code> for instances of the type <code>ExtendedType</code>.
307 * @param typeDefinition type definition which is converted to JAVA <code>Type</code>
308 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
310 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
311 final String typedefName = typeDefinition.getQName().getLocalName();
312 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
313 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
314 if (returnType == null) {
315 if (baseTypeDef instanceof EnumTypeDefinition) {
316 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
317 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
319 final Module module = findParentModule(schemaContext, typeDefinition);
320 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
321 if (module != null) {
322 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
324 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
325 if (genTOs != null) {
326 returnType = genTOs.get(typedefName);
328 if (returnType == null) {
329 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
330 baseTypeDef, typeDefinition, r);
339 * Seeks for identity reference <code>idref</code> the JAVA <code>type</code>.
343 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
344 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
346 * @param idref identityref type definition for which JAVA <code>Type</code> is sought
347 * @return JAVA <code>Type</code> of the identity which is referenced through <code>idref</code>
349 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
350 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
351 if (identities.size() > 1) {
352 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
355 final QName baseIdQName = identities.iterator().next().getQName();
356 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
357 IdentitySchemaNode identity = null;
358 for (IdentitySchemaNode id : module.getIdentities()) {
359 if (id.getQName().equals(baseIdQName)) {
363 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
365 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
366 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(
367 basePackageName, identity.getPath()), BindingMapping.getClassName(identity.getQName()));
368 return Types.classType(Types.wildcardTypeFor(identifier));
372 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
374 * @param typeDefinition
375 * type definition which should be converted to JAVA
377 * @return JAVA <code>Type</code> which represents
378 * <code>typeDefinition</code>
379 * @throws IllegalArgumentException
381 * <li>if <code>typeDefinition</code> equal null</li>
382 * <li>if Q name of <code>typeDefinition</code></li>
383 * <li>if name of <code>typeDefinition</code></li>
386 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition,
387 final SchemaNode parentNode) {
388 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
389 if (typeDefinition.getQName() == null) {
390 throw new IllegalArgumentException("Type Definition cannot have unspecified QName (QName cannot be NULL!)");
392 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
393 "Type Definitions Local Name cannot be NULL!");
395 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
396 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
398 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
399 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
412 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
413 * dicey when we throw in:
427 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
428 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
431 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
432 * an encapsulation for identityref typedefs.
434 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
435 * option, as it would look as though it is the product of a different construct:
441 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
442 * sub-identities of iden.
444 * The story behind leafrefs is probably similar, but that needs to be ascertained.
449 final Module module = findParentModule(schemaContext, parentNode);
450 if (module != null) {
451 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
453 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
454 if (genTOs != null) {
455 return genTOs.get(typeDefinition.getQName().getLocalName());
462 * Gets base type definition for <code>extendTypeDef</code>. The method is
463 * recursively called until non <code>ExtendedType</code> type is found.
465 * @param extendTypeDef
466 * type definition for which is the base type definition sought
467 * @return type definition which is base type for <code>extendTypeDef</code>
468 * @throws IllegalArgumentException
469 * if <code>extendTypeDef</code> equal null
471 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
472 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
474 TypeDefinition<?> ret = extendTypeDef;
475 while (ret.getBaseType() != null) {
476 ret = ret.getBaseType();
483 * Converts <code>leafrefType</code> to JAVA <code>Type</code>. The path of <code>leafrefType</code> is followed
484 * to find referenced node and its <code>Type</code> is returned.
486 * @param leafrefType leafref type definition for which is the type sought
487 * @return JAVA <code>Type</code> of data schema node which is referenced in <code>leafrefType</code>
488 * @throws IllegalArgumentException
490 * <li>if <code>leafrefType</code> equal null</li>
491 * <li>if path statement of <code>leafrefType</code> equal null</li>
495 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
496 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
497 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
498 "The Path Statement for Leafref Type Definition cannot be NULL!");
500 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
501 final String strXPath = xpath.toString();
502 Type returnType = null;
504 if (strXPath != null) {
505 if (strXPath.indexOf('[') == -1) {
506 final Module module = findParentModule(schemaContext, parentNode);
507 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
509 final SchemaNode dataNode;
510 if (xpath.isAbsolute()) {
511 dataNode = findDataSchemaNode(schemaContext, module, xpath);
513 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
515 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
516 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
518 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
519 if (leafContainsEnumDefinition(dataNode)) {
520 returnType = referencedTypes.get(dataNode.getPath());
521 } else if (leafListContainsEnumDefinition(dataNode)) {
522 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
524 if (returnType == null) {
525 returnType = resolveTypeFromDataSchemaNode(dataNode);
528 returnType = Types.objectType();
531 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
532 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
537 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it so then checks if it is of type
538 * <code>EnumTypeDefinition</code>.
540 * @param dataNode data schema node for which is checked if it is leaf and if it is of enum type
541 * @return boolean value
543 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
544 * <li>false - other cases</li>
547 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
548 if (dataNode instanceof LeafSchemaNode) {
549 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
550 return CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition;
556 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
557 * <code>EnumTypeDefinition</code>.
559 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
560 * @return boolean value
562 * <li>true - if <code>dataNode</code> is leaflist of type
564 * <li>false - other cases</li>
567 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
568 if (dataNode instanceof LeafListSchemaNode) {
569 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
570 return leafList.getType() instanceof EnumTypeDefinition;
576 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
578 * @param enumTypeDef enumeration type definition which is converted to enumeration
579 * @param enumName string with name which is used as the enumeration name
580 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
581 * @throws IllegalArgumentException
583 * <li>if <code>enumTypeDef</code> equals null</li>
584 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
585 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
586 * <li>if name of <code>enumTypeDef</code> equal null</li>
589 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
590 final SchemaNode parentNode) {
591 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
592 Preconditions.checkArgument(enumTypeDef.getValues() != null,
593 "EnumTypeDefinition MUST contain at least ONE value definition!");
594 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
595 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
596 "Local Name in EnumTypeDefinition QName cannot be NULL!");
598 final Module module = findParentModule(schemaContext, parentNode);
599 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
600 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
601 addEnumDescription(enumBuilder, enumTypeDef);
602 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
603 enumBuilder.setModuleName(module.getName());
604 enumBuilder.setSchemaPath(enumTypeDef.getPath());
605 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
606 return enumBuilder.toInstance(null);
610 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
612 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
613 * @param enumName string with the name of enumeration
614 * @param typeBuilder generated type builder to which is enumeration added
615 * @return enumeration type which contains enumeration data form <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>
622 * <li>if name of <code>typeBuilder</code> equal null</li>
626 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
627 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
628 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
629 Preconditions.checkArgument(enumTypeDef.getValues() != null,
630 "EnumTypeDefinition MUST contain at least ONE value definition!");
631 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
632 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
633 "Local Name in EnumTypeDefinition QName cannot be NULL!");
634 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
636 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
638 addEnumDescription(enumBuilder, enumTypeDef);
639 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
640 return enumBuilder.toInstance(enumBuilder);
643 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
645 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
647 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
649 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
652 * Converts the pattern constraints to the list of the strings which represents these constraints.
654 * @param patternConstraints list of pattern constraints
655 * @return list of strings which represents the constraint patterns
657 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
659 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
662 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
665 * @param typedef extended type in which are the pattern constraints sought
666 * @return list of strings which represents the constraint patterns
667 * @throws IllegalArgumentException if <code>typedef</code> equals null
670 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
671 if (!(typedef instanceof StringTypeDefinition)) {
672 return ImmutableMap.of();
675 // TODO: run diff against base ?
676 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
680 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
682 * @param dataNode contains information about YANG type
683 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
685 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
686 Type returnType = null;
687 if (dataNode != null) {
688 if (dataNode instanceof LeafSchemaNode) {
689 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
690 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
691 returnType = javaTypeForSchemaDefinitionType(type, leaf);
692 } else if (dataNode instanceof LeafListSchemaNode) {
693 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
694 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
701 * Passes through all modules and through all its type definitions and convert it to generated types.
704 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
705 * of a module are at the beginning sorted so that type definition with less amount of references to other type
706 * definition are processed first.<br>
707 * For each module is created mapping record in the map
708 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
709 * which map current module name to the map which maps type names to returned types (generated types).
711 private void resolveTypeDefsFromContext() {
712 final Set<Module> modules = schemaContext.getModules();
713 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
714 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
716 for (Module module : modulesSortedByDependency) {
717 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
718 module.getName(), key -> new HashMap<>());
719 dateTypeMap.put(module.getRevision(), Collections.emptyMap());
720 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
723 for (Module module : modulesSortedByDependency) {
724 if (module != null) {
725 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
726 if (basePackageName != null) {
727 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
728 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
729 typedefToGeneratedType(basePackageName, module, typedef);
737 * Create Type for specified type definition.
739 * @param basePackageName string with name of package to which the module belongs
740 * @param module string with the name of the module for to which the <code>typedef</code> belongs
741 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
742 * (usually generated TO)
743 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
744 * <code>null</code> value if <code>basePackageName</code> or
745 * <code>modulName</code> or <code>typedef</code> or Q name of
746 * <code>typedef</code> equals <code>null</code>
748 private Type typedefToGeneratedType(final String basePackageName, final Module module,
749 final TypeDefinition<?> typedef) {
750 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
752 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
753 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
757 final String typedefName = typedef.getQName().getLocalName();
759 final Type returnType;
760 if (baseTypedef.getBaseType() != null) {
761 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
763 } else if (baseTypedef instanceof UnionTypeDefinition) {
764 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
765 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
766 (UnionTypeDefinition) baseTypedef, typedef);
767 genTOBuilder.setTypedef(true);
768 genTOBuilder.setIsUnion(true);
769 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
770 makeSerializable(genTOBuilder);
771 returnType = genTOBuilder.build();
773 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
774 // so we are placing the builder alongside the union.
775 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
776 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
777 unionBuilder.setIsUnionBuilder(true);
778 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
779 method.setReturnType(returnType);
780 method.addParameter(Types.STRING, "defaultValue");
781 method.setAccessModifier(AccessModifier.PUBLIC);
782 method.setStatic(true);
783 Set<Type> types = additionalTypes.get(module);
785 types = Sets.newHashSet(unionBuilder.build());
786 additionalTypes.put(module, types);
788 types.add(unionBuilder.build());
790 } else if (baseTypedef instanceof EnumTypeDefinition) {
791 // enums are automatically Serializable
792 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
793 // TODO units for typedef enum
794 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
795 } else if (baseTypedef instanceof BitsTypeDefinition) {
796 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
797 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
798 (BitsTypeDefinition) baseTypedef, module.getName());
799 genTOBuilder.setTypedef(true);
800 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
801 makeSerializable(genTOBuilder);
802 returnType = genTOBuilder.build();
804 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
805 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
807 if (returnType != null) {
808 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
809 genTypeDefsContextMap.get(module.getName());
810 final Optional<Revision> moduleRevision = module.getRevision();
811 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
812 if (typeMap != null) {
813 if (typeMap.isEmpty()) {
814 typeMap = new HashMap<>(4);
815 modulesByDate.put(moduleRevision, typeMap);
817 typeMap.put(typedefName, returnType);
825 * Wraps base YANG type to generated TO.
827 * @param basePackageName string with name of package to which the module belongs
828 * @param typedef type definition which is converted to the TO
829 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
830 * @return generated transfer object which represent<code>javaType</code>
832 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
833 final Type javaType, final String moduleName) {
834 requireNonNull(javaType, "javaType cannot be null");
836 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
837 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
838 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
839 genPropBuilder.setReturnType(javaType);
840 genTOBuilder.addEqualsIdentity(genPropBuilder);
841 genTOBuilder.addHashIdentity(genPropBuilder);
842 genTOBuilder.addToStringProperty(genPropBuilder);
843 if (typedef.getStatus() == Status.DEPRECATED) {
844 genTOBuilder.addAnnotation("java.lang", "Deprecated");
846 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
847 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
849 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
850 genTOBuilder.setTypedef(true);
851 makeSerializable(genTOBuilder);
852 return genTOBuilder.build();
856 * Converts output list of generated TO builders to one TO builder (first
857 * from list) which contains the remaining builders as its enclosing TO.
859 * @param typeName new type identifier
860 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
861 * @return generated TO builder with the list of enclosed generated TO builders
863 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
864 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
865 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
867 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
869 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
870 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
871 return resultTOBuilder;
875 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
876 * <code>typedef</code> is added to generated TO builder as property.
878 * @param typeName new type identifier
879 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
880 * @return generated TO builder which represents <code>typedef</code>
881 * @throws NullPointerException
883 * <li>if <code>basePackageName</code> is null</li>
884 * <li>if <code>typedef</code> is null</li>
885 * <li>if Qname of <code>typedef</code> is null</li>
888 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
889 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
890 requireNonNull(typedef, "Type Definition cannot be NULL!");
891 requireNonNull(typedef.getQName(), "Type definition QName cannot be NULL!");
893 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
894 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
895 final Module module = findParentModule(schemaContext, parentNode);
897 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
898 unionGenTOBuilder.setIsUnion(true);
899 unionGenTOBuilder.setSchemaPath(typedef.getPath());
900 unionGenTOBuilder.setModuleName(module.getName());
901 addCodegenInformation(unionGenTOBuilder, typedef);
902 generatedTOBuilders.add(unionGenTOBuilder);
904 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
905 // also negation information and hence guarantees uniqueness.
906 final Map<String, String> expressions = new HashMap<>();
907 for (TypeDefinition<?> unionType : unionTypes) {
908 final String unionTypeName = unionType.getQName().getLocalName();
910 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
911 // do not follow type encapsulation -- we use the general case for that.
912 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
913 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
914 } else if (unionType instanceof UnionTypeDefinition) {
915 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
916 (UnionTypeDefinition) unionType, parentNode));
917 } else if (unionType instanceof EnumTypeDefinition) {
918 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
919 unionTypeName, unionGenTOBuilder);
920 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
922 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
923 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
926 addStringRegExAsConstant(unionGenTOBuilder, expressions);
928 storeGenTO(typedef, unionGenTOBuilder, parentNode);
930 return generatedTOBuilders;
934 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
937 * In this case the new generated TO is created for union subtype (recursive call of method
938 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
939 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
940 * created property which type is equal to new generated TO.
942 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
943 * @param basePackageName string with the name of the module package
944 * @param unionSubtype type definition which represents union subtype
945 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
946 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
948 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
949 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
950 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
951 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
952 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
953 newTOBuilderName, unionSubtype, parentNode);
955 final GeneratedPropertyBuilder propertyBuilder;
956 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
957 newTOBuilderName.simpleName()));
958 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
959 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
960 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
962 return subUnionGenTOBUilders;
966 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
967 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
968 * the base type is used for the property creation.
970 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
971 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
972 * @param expressions list of strings with the regular expressions
973 * @param parentNode parent Schema Node for Extended Subtype
975 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
976 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
977 final String unionTypeName = unionSubtype.getQName().getLocalName();
978 final Type genTO = findGenTO(unionTypeName, unionSubtype);
980 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
984 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
985 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
986 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
987 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
988 if (javaType != null) {
989 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
991 } else if (baseType instanceof LeafrefTypeDefinition) {
992 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
993 boolean typeExist = false;
994 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
995 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
996 if (origType != null && javaType != null && javaType == origType) {
1001 if (!typeExist && javaType != null) {
1002 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1003 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1006 if (baseType instanceof StringTypeDefinition) {
1007 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1012 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1013 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1015 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1016 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1018 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1019 final Module typeModule = findParentModule(schemaContext, parentNode);
1020 if (typeModule != null && typeModule.getName() != null) {
1021 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1022 typeModule.getName());
1023 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1024 if (genTOs != null) {
1025 return genTOs.get(searchedTypeName);
1032 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1033 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1035 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1036 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1038 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1039 final SchemaNode parentNode) {
1040 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1041 final Module parentModule = findParentModule(schemaContext, parentNode);
1042 if (parentModule != null && parentModule.getName() != null) {
1043 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1044 parentModule.getName());
1045 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1046 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1052 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1053 * to <code>unonGenTransObject</code>.
1055 * @param unionGenTransObject generated TO to which should be property added
1056 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1057 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1059 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1060 final String propertyName) {
1061 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1062 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1063 .addProperty(BindingMapping.getPropertyName(propertyName));
1064 propBuilder.setReturnType(type);
1066 unionGenTransObject.addEqualsIdentity(propBuilder);
1067 unionGenTransObject.addHashIdentity(propBuilder);
1068 unionGenTransObject.addToStringProperty(propBuilder);
1073 * Converts <code>typedef</code> to the generated TO builder.
1075 * @param basePackageName string with name of package to which the module belongs
1076 * @param typedef type definition from which is the generated TO builder created
1077 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1079 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1080 final TypeDefinition<?> typedef, final String moduleName) {
1081 JavaTypeName name = renames.get(typedef);
1083 name = JavaTypeName.create(
1084 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1085 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1088 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1089 newType.setSchemaPath(typedef.getPath());
1090 newType.setModuleName(moduleName);
1091 addCodegenInformation(newType, typedef);
1096 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1097 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1100 * @param typeName new type identifier
1101 * @param typeDef type definition from which is the generated TO builder created
1102 * @return generated TO builder which represents <code>typeDef</code>
1103 * @throws IllegalArgumentException
1105 * <li>if <code>typeDef</code> equals null</li>
1106 * <li>if <code>basePackageName</code> equals null</li>
1109 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1110 final BitsTypeDefinition typeDef, final String moduleName) {
1111 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1112 genTOBuilder.setSchemaPath(typeDef.getPath());
1113 genTOBuilder.setModuleName(moduleName);
1114 genTOBuilder.setBaseType(typeDef);
1115 addCodegenInformation(genTOBuilder, typeDef);
1117 final List<Bit> bitList = typeDef.getBits();
1118 GeneratedPropertyBuilder genPropertyBuilder;
1119 for (Bit bit : bitList) {
1120 final String name = bit.getName();
1121 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1122 genPropertyBuilder.setReadOnly(true);
1123 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1125 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1126 genTOBuilder.addHashIdentity(genPropertyBuilder);
1127 genTOBuilder.addToStringProperty(genPropertyBuilder);
1130 return genTOBuilder;
1134 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1135 * the <code>regularExpressions</code>.
1137 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1138 * @param expressions list of string which represent regular expressions
1140 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1141 final Map<String, String> expressions) {
1142 if (!expressions.isEmpty()) {
1143 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1144 ImmutableMap.copyOf(expressions));
1149 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1150 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1153 * It is assumed that <code>innerExtendedType</code> is already present in
1154 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1155 * for the returning generated TO.
1157 * @param typedef Type Definition
1158 * @param innerExtendedType extended type which is part of some other extended type
1159 * @param basePackageName string with the package name of the module
1160 * @param moduleName Module Name
1161 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1162 * @throws IllegalArgumentException
1164 * <li>if <code>extendedType</code> equals null</li>
1165 * <li>if <code>basePackageName</code> equals null</li>
1166 * <li>if <code>typedefName</code> equals null</li>
1169 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1170 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1171 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1172 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1174 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1175 BindingMapping.getClassName(typedef.getQName())));
1176 genTOBuilder.setSchemaPath(typedef.getPath());
1177 genTOBuilder.setModuleName(moduleName);
1178 genTOBuilder.setTypedef(true);
1179 addCodegenInformation(genTOBuilder, typedef);
1181 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1182 genTOBuilder.setRestrictions(r);
1183 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1185 if (typedef.getStatus() == Status.DEPRECATED) {
1186 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1189 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1190 genTOBuilder.setIsUnion(true);
1193 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1194 Map<String, Type> typeMap = null;
1195 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1196 if (parentModule != null) {
1197 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1198 typeMap = modulesByDate.get(parentModule.getRevision());
1201 if (typeMap != null) {
1202 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1203 final Type type = typeMap.get(innerTypeDef);
1204 if (type instanceof GeneratedTransferObject) {
1205 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1208 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1209 makeSerializable(genTOBuilder);
1211 return genTOBuilder.build();
1215 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1218 * @param gto transfer object which needs to be made serializable
1220 private static void makeSerializable(final GeneratedTOBuilder gto) {
1221 gto.addImplementsType(Types.serializableType());
1222 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1223 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1228 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1229 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1230 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1231 * type definitions are in the list behind all type definitions on which depends.
1233 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1234 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1235 * dependent on other type definitions are in list behind them).
1237 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1238 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1239 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1241 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1242 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1243 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1244 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1245 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1246 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1249 // SortedMap guarantees order corresponding to keys in ascending order
1250 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1251 sortedTypeDefinition.addAll(v);
1254 return sortedTypeDefinition;
1258 * Returns how many immersion is necessary to get from the type definition to the base type.
1260 * @param typeDefinition type definition for which is depth sought.
1261 * @return number of immersions which are necessary to get from the type definition to the base type
1263 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1264 // FIXME: rewrite this in a non-recursive manner
1265 if (typeDefinition == null) {
1268 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1269 if (baseType == null) {
1274 if (baseType.getBaseType() != null) {
1275 depth = depth + getTypeDefinitionDepth(baseType);
1276 } else if (baseType instanceof UnionTypeDefinition) {
1277 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1278 int maxChildDepth = 0;
1280 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1281 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1282 if (childDepth > maxChildDepth) {
1283 maxChildDepth = childDepth;
1286 return maxChildDepth;
1292 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1293 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1294 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1296 * @param name string with name of augmented node
1297 * @return string with the number suffix incremented by one (or 1 is added)
1299 private static String provideAvailableNameForGenTOBuilder(final String name) {
1300 final int dollar = name.indexOf('$');
1305 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1306 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1307 return name.substring(0, dollar + 1) + newSuffix;
1310 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1311 if (!Strings.isNullOrEmpty(units)) {
1312 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1313 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1314 prop.setReturnType(Types.STRING);
1315 to.addToStringProperty(prop);
1320 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1321 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1324 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1325 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1326 final QName typeQName = type.getQName();
1327 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1328 requireNonNull(type, () -> "Cannot provide default construction for null type of " + node);
1329 requireNonNull(defaultValue, () -> "Cannot provide default construction for null default statement of "
1332 final StringBuilder sb = new StringBuilder();
1333 String result = null;
1334 if (base instanceof BinaryTypeDefinition) {
1335 result = binaryToDef(defaultValue);
1336 } else if (base instanceof BitsTypeDefinition) {
1339 final Module parent = getParentModule(node);
1340 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1342 if (!path.hasNext()) {
1343 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1344 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1345 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1347 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1348 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1350 parentName = BindingMapping.getClassName(parent.getName());
1351 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1353 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1354 } else if (base instanceof BooleanTypeDefinition) {
1355 result = typeToBooleanDef(defaultValue);
1356 } else if (base instanceof DecimalTypeDefinition) {
1357 result = typeToDef(BigDecimal.class, defaultValue);
1358 } else if (base instanceof EmptyTypeDefinition) {
1359 result = typeToBooleanDef(defaultValue);
1360 } else if (base instanceof EnumTypeDefinition) {
1361 final char[] defValArray = defaultValue.toCharArray();
1362 final char first = Character.toUpperCase(defaultValue.charAt(0));
1363 defValArray[0] = first;
1364 final String newDefVal = new String(defValArray);
1366 if (type.getBaseType() != null) {
1367 final Module m = getParentModule(type);
1368 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1369 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1371 className = packageName + "." + BindingMapping.getClassName(typeQName);
1373 final Module parentModule = getParentModule(node);
1374 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1375 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1377 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1379 result = className + "." + newDefVal;
1380 } else if (base instanceof IdentityrefTypeDefinition) {
1381 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1382 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1383 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1384 } else if (BaseTypes.isInt8(base)) {
1385 result = typeToValueOfDef(Byte.class, defaultValue);
1386 } else if (BaseTypes.isInt16(base)) {
1387 result = typeToValueOfDef(Short.class, defaultValue);
1388 } else if (BaseTypes.isInt32(base)) {
1389 result = typeToValueOfDef(Integer.class, defaultValue);
1390 } else if (BaseTypes.isInt64(base)) {
1391 result = typeToValueOfDef(Long.class, defaultValue);
1392 } else if (base instanceof LeafrefTypeDefinition) {
1393 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1394 } else if (base instanceof StringTypeDefinition) {
1395 result = "\"" + defaultValue + "\"";
1396 } else if (BaseTypes.isUint8(base)) {
1397 result = typeToValueOfDef(Short.class, defaultValue);
1398 } else if (BaseTypes.isUint16(base)) {
1399 result = typeToValueOfDef(Integer.class, defaultValue);
1400 } else if (BaseTypes.isUint32(base)) {
1401 result = typeToValueOfDef(Long.class, defaultValue);
1402 } else if (BaseTypes.isUint64(base)) {
1403 switch (defaultValue) {
1405 result = "java.math.BigInteger.ZERO";
1408 result = "java.math.BigInteger.ONE";
1411 result = "java.math.BigInteger.TEN";
1414 result = typeToDef(BigInteger.class, defaultValue);
1416 } else if (base instanceof UnionTypeDefinition) {
1417 result = unionToDef(node);
1423 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1424 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1425 final Module m = getParentModule(type);
1426 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1427 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1429 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1430 sb.insert(0, "new " + className + "(");
1431 sb.insert(sb.length(), ')');
1434 return sb.toString();
1437 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1438 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1441 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1442 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1445 private static String typeToBooleanDef(final String defaultValue) {
1446 switch (defaultValue) {
1448 return "java.lang.Boolean.FALSE";
1450 return "java.lang.Boolean.TRUE";
1452 return typeToValueOfDef(Boolean.class, defaultValue);
1456 private static String binaryToDef(final String defaultValue) {
1457 final StringBuilder sb = new StringBuilder();
1458 final BaseEncoding en = BaseEncoding.base64();
1459 final byte[] encoded = en.decode(defaultValue);
1460 sb.append("new byte[] {");
1461 for (int i = 0; i < encoded.length; i++) {
1462 sb.append(encoded[i]);
1463 if (i != encoded.length - 1) {
1468 return sb.toString();
1471 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1473 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1474 final boolean isExt) {
1475 final List<Bit> bits = new ArrayList<>(type.getBits());
1476 bits.sort(BIT_NAME_COMPARATOR);
1477 final StringBuilder sb = new StringBuilder();
1480 sb.append(className);
1483 for (int i = 0; i < bits.size(); i++) {
1484 if (bits.get(i).getName().equals(defaultValue)) {
1489 if (i != bits.size() - 1) {
1496 return sb.toString();
1499 private Module getParentModule(final SchemaNode node) {
1500 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1501 return schemaContext.findModule(qname.getModule()).orElse(null);
1504 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1505 final String defaultValue) {
1506 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1507 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1508 "The Path Statement for Leafref Type Definition cannot be NULL!");
1510 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1511 final String strXPath = xpath.toString();
1513 if (strXPath != null) {
1514 if (strXPath.indexOf('[') == -1) {
1515 final Module module = findParentModule(schemaContext, parentNode);
1516 if (module != null) {
1517 final SchemaNode dataNode;
1518 if (xpath.isAbsolute()) {
1519 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1521 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1523 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1527 return "new java.lang.Object()";
1534 private String unionToDef(final LeafSchemaNode node) {
1535 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1539 if (type.getBaseType() != null) {
1540 final QName typeQName = type.getQName();
1541 Module module = null;
1542 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1543 if (modules.size() > 1) {
1544 for (Module m : modules) {
1545 if (m.getRevision().equals(typeQName.getRevision())) {
1550 if (module == null) {
1551 final List<Module> modulesList = new ArrayList<>(modules);
1552 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1553 module = modulesList.get(0);
1556 module = modules.iterator().next();
1559 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1560 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1562 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1563 final QName first = path.next();
1564 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1565 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1566 if (!path.hasNext()) {
1567 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1568 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1570 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1572 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1575 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1578 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1579 final StringBuilder sb = new StringBuilder();
1581 sb.append(className);
1583 sb.append(defaultValue);
1584 sb.append("\".toCharArray())");
1585 return sb.toString();
1589 public String getConstructorPropertyName(final SchemaNode node) {
1590 return node instanceof TypeDefinition<?> ? "value" : "";
1594 public String getParamNameFromType(final TypeDefinition<?> type) {
1595 return BindingMapping.getPropertyName(type.getQName().getLocalName());