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) : false;
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 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
558 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if it so then checks if it is of type
559 * <code>EnumTypeDefinition</code>.
561 * @param dataNode data schema node for which is checked if it is leaflist and if it is of enum type
562 * @return boolean value
564 * <li>true - if <code>dataNode</code> is leaflist of type
566 * <li>false - other cases</li>
569 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
570 if (dataNode instanceof LeafListSchemaNode) {
571 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
572 if (leafList.getType() instanceof EnumTypeDefinition) {
580 * Converts <code>enumTypeDef</code> to {@link Enumeration enumeration}.
582 * @param enumTypeDef enumeration type definition which is converted to enumeration
583 * @param enumName string with name which is used as the enumeration name
584 * @return enumeration type which is built with data (name, enum values) from <code>enumTypeDef</code>
585 * @throws IllegalArgumentException
587 * <li>if <code>enumTypeDef</code> equals null</li>
588 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
589 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
590 * <li>if name of <code>enumTypeDef</code> equal null</li>
593 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
594 final SchemaNode parentNode) {
595 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
596 Preconditions.checkArgument(enumTypeDef.getValues() != null,
597 "EnumTypeDefinition MUST contain at least ONE value definition!");
598 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
599 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
600 "Local Name in EnumTypeDefinition QName cannot be NULL!");
602 final Module module = findParentModule(schemaContext, parentNode);
603 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
604 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
605 addEnumDescription(enumBuilder, enumTypeDef);
606 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
607 enumBuilder.setModuleName(module.getName());
608 enumBuilder.setSchemaPath(enumTypeDef.getPath());
609 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
610 return enumBuilder.toInstance(null);
614 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are taken from <code>enumTypeDef</code>.
616 * @param enumTypeDef enumeration type definition is source of enumeration data for <code>typeBuilder</code>
617 * @param enumName string with the name of enumeration
618 * @param typeBuilder generated type builder to which is enumeration added
619 * @return enumeration type which contains enumeration data form <code>enumTypeDef</code>
620 * @throws IllegalArgumentException
622 * <li>if <code>enumTypeDef</code> equals null</li>
623 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
624 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
625 * <li>if name of <code>enumTypeDef</code> equal null</li>
626 * <li>if name of <code>typeBuilder</code> equal null</li>
630 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
631 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
632 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
633 Preconditions.checkArgument(enumTypeDef.getValues() != null,
634 "EnumTypeDefinition MUST contain at least ONE value definition!");
635 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
636 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
637 "Local Name in EnumTypeDefinition QName cannot be NULL!");
638 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
640 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
642 addEnumDescription(enumBuilder, enumTypeDef);
643 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
644 return enumBuilder.toInstance(enumBuilder);
647 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
649 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
651 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
653 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
656 * Converts the pattern constraints to the list of the strings which represents these constraints.
658 * @param patternConstraints list of pattern constraints
659 * @return list of strings which represents the constraint patterns
661 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
663 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
666 * Converts the pattern constraints from <code>typedef</code> to the list of the strings which represents these
669 * @param typedef extended type in which are the pattern constraints sought
670 * @return list of strings which represents the constraint patterns
671 * @throws IllegalArgumentException if <code>typedef</code> equals null
674 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
675 if (!(typedef instanceof StringTypeDefinition)) {
676 return ImmutableMap.of();
679 // TODO: run diff against base ?
680 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
684 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
686 * @param dataNode contains information about YANG type
687 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
689 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
690 Type returnType = null;
691 if (dataNode != null) {
692 if (dataNode instanceof LeafSchemaNode) {
693 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
694 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
695 returnType = javaTypeForSchemaDefinitionType(type, leaf);
696 } else if (dataNode instanceof LeafListSchemaNode) {
697 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
698 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
705 * Passes through all modules and through all its type definitions and convert it to generated types.
708 * The modules are first sorted by mutual dependencies. The modules are sequentially passed. All type definitions
709 * of a module are at the beginning sorted so that type definition with less amount of references to other type
710 * definition are processed first.<br>
711 * For each module is created mapping record in the map
712 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
713 * which map current module name to the map which maps type names to returned types (generated types).
715 private void resolveTypeDefsFromContext() {
716 final Set<Module> modules = schemaContext.getModules();
717 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
718 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
720 for (Module module : modulesSortedByDependency) {
721 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
722 module.getName(), key -> new HashMap<>());
723 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
724 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
727 for (Module module : modulesSortedByDependency) {
728 if (module != null) {
729 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
730 if (basePackageName != null) {
731 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
732 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
733 typedefToGeneratedType(basePackageName, module, typedef);
741 * Create Type for specified type definition.
743 * @param basePackageName string with name of package to which the module belongs
744 * @param module string with the name of the module for to which the <code>typedef</code> belongs
745 * @param typedef type definition of the node for which should be created JAVA <code>Type</code>
746 * (usually generated TO)
747 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
748 * <code>null</code> value if <code>basePackageName</code> or
749 * <code>modulName</code> or <code>typedef</code> or Q name of
750 * <code>typedef</code> equals <code>null</code>
752 private Type typedefToGeneratedType(final String basePackageName, final Module module,
753 final TypeDefinition<?> typedef) {
754 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
756 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
757 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
761 final String typedefName = typedef.getQName().getLocalName();
763 final Type returnType;
764 if (baseTypedef.getBaseType() != null) {
765 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
767 } else if (baseTypedef instanceof UnionTypeDefinition) {
768 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
769 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
770 (UnionTypeDefinition) baseTypedef, typedef);
771 genTOBuilder.setTypedef(true);
772 genTOBuilder.setIsUnion(true);
773 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
774 makeSerializable(genTOBuilder);
775 returnType = genTOBuilder.build();
777 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
778 // so we are placing the builder alongside the union.
779 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
780 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
781 unionBuilder.setIsUnionBuilder(true);
782 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
783 method.setReturnType(returnType);
784 method.addParameter(Types.STRING, "defaultValue");
785 method.setAccessModifier(AccessModifier.PUBLIC);
786 method.setStatic(true);
787 Set<Type> types = additionalTypes.get(module);
789 types = Sets.newHashSet(unionBuilder.build());
790 additionalTypes.put(module, types);
792 types.add(unionBuilder.build());
794 } else if (baseTypedef instanceof EnumTypeDefinition) {
795 // enums are automatically Serializable
796 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
797 // TODO units for typedef enum
798 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
799 } else if (baseTypedef instanceof BitsTypeDefinition) {
800 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
801 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
802 (BitsTypeDefinition) baseTypedef, module.getName());
803 genTOBuilder.setTypedef(true);
804 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
805 makeSerializable(genTOBuilder);
806 returnType = genTOBuilder.build();
808 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
809 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
811 if (returnType != null) {
812 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
813 genTypeDefsContextMap.get(module.getName());
814 final Optional<Revision> moduleRevision = module.getRevision();
815 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
816 if (typeMap != null) {
817 if (typeMap.isEmpty()) {
818 typeMap = new HashMap<>(4);
819 modulesByDate.put(moduleRevision, typeMap);
821 typeMap.put(typedefName, returnType);
829 * Wraps base YANG type to generated TO.
831 * @param basePackageName string with name of package to which the module belongs
832 * @param typedef type definition which is converted to the TO
833 * @param javaType JAVA <code>Type</code> to which is <code>typedef</code> mapped
834 * @return generated transfer object which represent<code>javaType</code>
836 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
837 final Type javaType, final String moduleName) {
838 Preconditions.checkNotNull(javaType, "javaType cannot be null");
840 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
841 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
842 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
843 genPropBuilder.setReturnType(javaType);
844 genTOBuilder.addEqualsIdentity(genPropBuilder);
845 genTOBuilder.addHashIdentity(genPropBuilder);
846 genTOBuilder.addToStringProperty(genPropBuilder);
847 if (typedef.getStatus() == Status.DEPRECATED) {
848 genTOBuilder.addAnnotation("java.lang", "Deprecated");
850 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
851 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
853 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
854 genTOBuilder.setTypedef(true);
855 makeSerializable(genTOBuilder);
856 return genTOBuilder.build();
860 * Converts output list of generated TO builders to one TO builder (first
861 * from list) which contains the remaining builders as its enclosing TO.
863 * @param typeName new type identifier
864 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
865 * @return generated TO builder with the list of enclosed generated TO builders
867 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
868 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
869 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
871 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
873 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
874 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
875 return resultTOBuilder;
879 * Converts <code>typedef</code> to generated TO with <code>typeDefName</code>. Every union type from
880 * <code>typedef</code> is added to generated TO builder as property.
882 * @param typeName new type identifier
883 * @param typedef type definition which should be of type <code>UnionTypeDefinition</code>
884 * @return generated TO builder which represents <code>typedef</code>
885 * @throws NullPointerException
887 * <li>if <code>basePackageName</code> is null</li>
888 * <li>if <code>typedef</code> is null</li>
889 * <li>if Qname of <code>typedef</code> is null</li>
892 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
893 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
894 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
895 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
897 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
898 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
899 final Module module = findParentModule(schemaContext, parentNode);
901 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
902 unionGenTOBuilder.setIsUnion(true);
903 unionGenTOBuilder.setSchemaPath(typedef.getPath());
904 unionGenTOBuilder.setModuleName(module.getName());
905 addCodegenInformation(unionGenTOBuilder, typedef);
906 generatedTOBuilders.add(unionGenTOBuilder);
908 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
909 // also negation information and hence guarantees uniqueness.
910 final Map<String, String> expressions = new HashMap<>();
911 for (TypeDefinition<?> unionType : unionTypes) {
912 final String unionTypeName = unionType.getQName().getLocalName();
914 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
915 // do not follow type encapsulation -- we use the general case for that.
916 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
917 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
918 } else if (unionType instanceof UnionTypeDefinition) {
919 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
920 (UnionTypeDefinition) unionType, parentNode));
921 } else if (unionType instanceof EnumTypeDefinition) {
922 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
923 unionTypeName, unionGenTOBuilder);
924 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
926 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
927 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
930 addStringRegExAsConstant(unionGenTOBuilder, expressions);
932 storeGenTO(typedef, unionGenTOBuilder, parentNode);
934 return generatedTOBuilders;
938 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
941 * In this case the new generated TO is created for union subtype (recursive call of method
942 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
943 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
944 * created property which type is equal to new generated TO.
946 * @param parentUnionGenTOBuilder generated TO builder to which is the property with the child union subtype added
947 * @param basePackageName string with the name of the module package
948 * @param unionSubtype type definition which represents union subtype
949 * @return list of generated TO builders. The number of the builders can be bigger one due to recursive call of
950 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
952 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
953 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
954 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
955 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
956 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
957 newTOBuilderName, unionSubtype, parentNode);
959 final GeneratedPropertyBuilder propertyBuilder;
960 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
961 newTOBuilderName.simpleName()));
962 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
963 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
964 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
966 return subUnionGenTOBUilders;
970 * Wraps code which handle case when union subtype is of the type <code>ExtendedType</code>. If TO for this type
971 * already exists it is used for the creation of the property in <code>parentUnionGenTOBuilder</code>. Otherwise
972 * the base type is used for the property creation.
974 * @param parentUnionGenTOBuilder generated TO builder in which new property is created
975 * @param unionSubtype type definition of the <code>ExtendedType</code> type which represents union subtype
976 * @param expressions list of strings with the regular expressions
977 * @param parentNode parent Schema Node for Extended Subtype
979 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
980 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
981 final String unionTypeName = unionSubtype.getQName().getLocalName();
982 final Type genTO = findGenTO(unionTypeName, unionSubtype);
984 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
988 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
989 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
990 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
991 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
992 if (javaType != null) {
993 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
995 } else if (baseType instanceof LeafrefTypeDefinition) {
996 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
997 boolean typeExist = false;
998 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
999 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1000 if (origType != null && javaType != null && javaType == origType) {
1005 if (!typeExist && javaType != null) {
1006 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1007 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1010 if (baseType instanceof StringTypeDefinition) {
1011 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1016 * Searches for generated TO for <code>searchedTypeDef</code> type definition
1017 * in {@link #genTypeDefsContextMap genTypeDefsContextMap}.
1019 * @param searchedTypeName string with name of <code>searchedTypeDef</code>
1020 * @return generated TO for <code>searchedTypeDef</code> or <code>null</code> it it doesn't exist
1022 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1023 final Module typeModule = findParentModule(schemaContext, parentNode);
1024 if (typeModule != null && typeModule.getName() != null) {
1025 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1026 typeModule.getName());
1027 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1028 if (genTOs != null) {
1029 return genTOs.get(searchedTypeName);
1036 * Stores generated TO created from <code>genTOBuilder</code> for <code>newTypeDef</code>
1037 * to {@link #genTypeDefsContextMap genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists.
1039 * @param newTypeDef type definition for which is <code>genTOBuilder</code> created
1040 * @param genTOBuilder generated TO builder which is converted to generated TO and stored
1042 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder,
1043 final SchemaNode parentNode) {
1044 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1045 final Module parentModule = findParentModule(schemaContext, parentNode);
1046 if (parentModule != null && parentModule.getName() != null) {
1047 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
1048 parentModule.getName());
1049 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1050 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1056 * Adds a new property with the name <code>propertyName</code> and with type <code>type</code>
1057 * to <code>unonGenTransObject</code>.
1059 * @param unionGenTransObject generated TO to which should be property added
1060 * @param type JAVA <code>type</code> of the property which should be added to <code>unionGentransObject</code>
1061 * @param propertyName string with name of property which should be added to <code>unionGentransObject</code>
1063 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
1064 final String propertyName) {
1065 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1066 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1067 .addProperty(BindingMapping.getPropertyName(propertyName));
1068 propBuilder.setReturnType(type);
1070 unionGenTransObject.addEqualsIdentity(propBuilder);
1071 unionGenTransObject.addHashIdentity(propBuilder);
1072 unionGenTransObject.addToStringProperty(propBuilder);
1077 * Converts <code>typedef</code> to the generated TO builder.
1079 * @param basePackageName string with name of package to which the module belongs
1080 * @param typedef type definition from which is the generated TO builder created
1081 * @return generated TO builder which contains data from <code>typedef</code> and <code>basePackageName</code>
1083 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1084 final TypeDefinition<?> typedef, final String moduleName) {
1085 JavaTypeName name = renames.get(typedef);
1087 name = JavaTypeName.create(
1088 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1089 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1092 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1093 newType.setSchemaPath(typedef.getPath());
1094 newType.setModuleName(moduleName);
1095 addCodegenInformation(newType, typedef);
1100 * Converts <code>typeDef</code> which should be of the type <code>BitsTypeDefinition</code>
1101 * to <code>GeneratedTOBuilder</code>. All the bits of the typeDef are added to returning generated TO as
1104 * @param typeName new type identifier
1105 * @param typeDef type definition from which is the generated TO builder created
1106 * @return generated TO builder which represents <code>typeDef</code>
1107 * @throws IllegalArgumentException
1109 * <li>if <code>typeDef</code> equals null</li>
1110 * <li>if <code>basePackageName</code> equals null</li>
1113 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1114 final BitsTypeDefinition typeDef, final String moduleName) {
1115 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1116 genTOBuilder.setSchemaPath(typeDef.getPath());
1117 genTOBuilder.setModuleName(moduleName);
1118 genTOBuilder.setBaseType(typeDef);
1119 addCodegenInformation(genTOBuilder, typeDef);
1121 final List<Bit> bitList = typeDef.getBits();
1122 GeneratedPropertyBuilder genPropertyBuilder;
1123 for (Bit bit : bitList) {
1124 final String name = bit.getName();
1125 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1126 genPropertyBuilder.setReadOnly(true);
1127 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1129 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1130 genTOBuilder.addHashIdentity(genPropertyBuilder);
1131 genTOBuilder.addToStringProperty(genPropertyBuilder);
1134 return genTOBuilder;
1138 * Adds to the <code>genTOBuilder</code> the constant which contains regular expressions from
1139 * the <code>regularExpressions</code>.
1141 * @param genTOBuilder generated TO builder to which are <code>regular expressions</code> added
1142 * @param expressions list of string which represent regular expressions
1144 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1145 final Map<String, String> expressions) {
1146 if (!expressions.isEmpty()) {
1147 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1148 ImmutableMap.copyOf(expressions));
1153 * Creates generated TO with data about inner extended type <code>innerExtendedType</code>, about the package name
1154 * <code>typedefName</code> and about the generated TO name <code>typedefName</code>.
1157 * It is assumed that <code>innerExtendedType</code> is already present in
1158 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to be possible set it as extended type
1159 * for the returning generated TO.
1161 * @param typedef Type Definition
1162 * @param innerExtendedType extended type which is part of some other extended type
1163 * @param basePackageName string with the package name of the module
1164 * @param moduleName Module Name
1165 * @return generated TO which extends generated TO for <code>innerExtendedType</code>
1166 * @throws IllegalArgumentException
1168 * <li>if <code>extendedType</code> equals null</li>
1169 * <li>if <code>basePackageName</code> equals null</li>
1170 * <li>if <code>typedefName</code> equals null</li>
1173 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1174 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1175 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1176 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1178 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1179 BindingMapping.getClassName(typedef.getQName())));
1180 genTOBuilder.setSchemaPath(typedef.getPath());
1181 genTOBuilder.setModuleName(moduleName);
1182 genTOBuilder.setTypedef(true);
1183 addCodegenInformation(genTOBuilder, typedef);
1185 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1186 genTOBuilder.setRestrictions(r);
1187 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1189 if (typedef.getStatus() == Status.DEPRECATED) {
1190 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1193 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1194 genTOBuilder.setIsUnion(true);
1197 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1198 Map<String, Type> typeMap = null;
1199 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1200 if (parentModule != null) {
1201 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1202 typeMap = modulesByDate.get(parentModule.getRevision());
1205 if (typeMap != null) {
1206 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1207 final Type type = typeMap.get(innerTypeDef);
1208 if (type instanceof GeneratedTransferObject) {
1209 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1212 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1213 makeSerializable(genTOBuilder);
1215 return genTOBuilder.build();
1219 * Add {@link java.io.Serializable} to implemented interfaces of this TO. Also compute and add serialVersionUID
1222 * @param gto transfer object which needs to be made serializable
1224 private static void makeSerializable(final GeneratedTOBuilder gto) {
1225 gto.addImplementsType(Types.serializableType());
1226 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1227 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1232 * Finds out for each type definition how many immersion (depth) is necessary to get to the base type. Every type
1233 * definition is inserted to the map which key is depth and value is list of type definitions with equal depth.
1234 * In next step are lists from this map concatenated to one list in ascending order according to their depth. All
1235 * type definitions are in the list behind all type definitions on which depends.
1237 * @param unsortedTypeDefinitions list of type definitions which should be sorted by depth
1238 * @return list of type definitions sorted according their each other dependencies (type definitions which are
1239 * dependent on other type definitions are in list behind them).
1241 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1242 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1243 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1245 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1246 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1247 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1248 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1249 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1250 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1253 // SortedMap guarantees order corresponding to keys in ascending order
1254 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1255 sortedTypeDefinition.addAll(v);
1258 return sortedTypeDefinition;
1262 * Returns how many immersion is necessary to get from the type definition to the base type.
1264 * @param typeDefinition type definition for which is depth sought.
1265 * @return number of immersions which are necessary to get from the type definition to the base type
1267 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1268 // FIXME: rewrite this in a non-recursive manner
1269 if (typeDefinition == null) {
1272 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1273 if (baseType == null) {
1278 if (baseType.getBaseType() != null) {
1279 depth = depth + getTypeDefinitionDepth(baseType);
1280 } else if (baseType instanceof UnionTypeDefinition) {
1281 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1282 int maxChildDepth = 0;
1284 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1285 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1286 if (childDepth > maxChildDepth) {
1287 maxChildDepth = childDepth;
1290 return maxChildDepth;
1296 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1297 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1298 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1300 * @param name string with name of augmented node
1301 * @return string with the number suffix incremented by one (or 1 is added)
1303 private static String provideAvailableNameForGenTOBuilder(final String name) {
1304 final int dollar = name.indexOf('$');
1309 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1310 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1311 return name.substring(0, dollar + 1) + newSuffix;
1314 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1315 if (!Strings.isNullOrEmpty(units)) {
1316 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1317 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1318 prop.setReturnType(Types.STRING);
1319 to.addToStringProperty(prop);
1324 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1325 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1328 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1329 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1330 final QName typeQName = type.getQName();
1331 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1332 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1333 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1336 final StringBuilder sb = new StringBuilder();
1337 String result = null;
1338 if (base instanceof BinaryTypeDefinition) {
1339 result = binaryToDef(defaultValue);
1340 } else if (base instanceof BitsTypeDefinition) {
1343 final Module parent = getParentModule(node);
1344 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1346 if (!path.hasNext()) {
1347 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1348 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1349 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1351 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1352 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1354 parentName = BindingMapping.getClassName(parent.getName());
1355 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1357 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1358 } else if (base instanceof BooleanTypeDefinition) {
1359 result = typeToBooleanDef(defaultValue);
1360 } else if (base instanceof DecimalTypeDefinition) {
1361 result = typeToDef(BigDecimal.class, defaultValue);
1362 } else if (base instanceof EmptyTypeDefinition) {
1363 result = typeToBooleanDef(defaultValue);
1364 } else if (base instanceof EnumTypeDefinition) {
1365 final char[] defValArray = defaultValue.toCharArray();
1366 final char first = Character.toUpperCase(defaultValue.charAt(0));
1367 defValArray[0] = first;
1368 final String newDefVal = new String(defValArray);
1370 if (type.getBaseType() != null) {
1371 final Module m = getParentModule(type);
1372 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1373 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1375 className = packageName + "." + BindingMapping.getClassName(typeQName);
1377 final Module parentModule = getParentModule(node);
1378 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1379 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1381 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1383 result = className + "." + newDefVal;
1384 } else if (base instanceof IdentityrefTypeDefinition) {
1385 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1386 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1387 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1388 } else if (BaseTypes.isInt8(base)) {
1389 result = typeToValueOfDef(Byte.class, defaultValue);
1390 } else if (BaseTypes.isInt16(base)) {
1391 result = typeToValueOfDef(Short.class, defaultValue);
1392 } else if (BaseTypes.isInt32(base)) {
1393 result = typeToValueOfDef(Integer.class, defaultValue);
1394 } else if (BaseTypes.isInt64(base)) {
1395 result = typeToValueOfDef(Long.class, defaultValue);
1396 } else if (base instanceof LeafrefTypeDefinition) {
1397 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1398 } else if (base instanceof StringTypeDefinition) {
1399 result = "\"" + defaultValue + "\"";
1400 } else if (BaseTypes.isUint8(base)) {
1401 result = typeToValueOfDef(Short.class, defaultValue);
1402 } else if (BaseTypes.isUint16(base)) {
1403 result = typeToValueOfDef(Integer.class, defaultValue);
1404 } else if (BaseTypes.isUint32(base)) {
1405 result = typeToValueOfDef(Long.class, defaultValue);
1406 } else if (BaseTypes.isUint64(base)) {
1407 switch (defaultValue) {
1409 result = "java.math.BigInteger.ZERO";
1412 result = "java.math.BigInteger.ONE";
1415 result = "java.math.BigInteger.TEN";
1418 result = typeToDef(BigInteger.class, defaultValue);
1420 } else if (base instanceof UnionTypeDefinition) {
1421 result = unionToDef(node);
1427 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1428 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1429 final Module m = getParentModule(type);
1430 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1431 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1433 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1434 sb.insert(0, "new " + className + "(");
1435 sb.insert(sb.length(), ')');
1438 return sb.toString();
1441 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1442 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1445 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1446 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1449 private static String typeToBooleanDef(final String defaultValue) {
1450 switch (defaultValue) {
1452 return "java.lang.Boolean.FALSE";
1454 return "java.lang.Boolean.TRUE";
1456 return typeToValueOfDef(Boolean.class, defaultValue);
1460 private static String binaryToDef(final String defaultValue) {
1461 final StringBuilder sb = new StringBuilder();
1462 final BaseEncoding en = BaseEncoding.base64();
1463 final byte[] encoded = en.decode(defaultValue);
1464 sb.append("new byte[] {");
1465 for (int i = 0; i < encoded.length; i++) {
1466 sb.append(encoded[i]);
1467 if (i != encoded.length - 1) {
1472 return sb.toString();
1475 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1477 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue,
1478 final boolean isExt) {
1479 final List<Bit> bits = new ArrayList<>(type.getBits());
1480 bits.sort(BIT_NAME_COMPARATOR);
1481 final StringBuilder sb = new StringBuilder();
1484 sb.append(className);
1487 for (int i = 0; i < bits.size(); i++) {
1488 if (bits.get(i).getName().equals(defaultValue)) {
1493 if (i != bits.size() - 1) {
1500 return sb.toString();
1503 private Module getParentModule(final SchemaNode node) {
1504 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1505 return schemaContext.findModule(qname.getModule()).orElse(null);
1508 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType,
1509 final String defaultValue) {
1510 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1511 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1512 "The Path Statement for Leafref Type Definition cannot be NULL!");
1514 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1515 final String strXPath = xpath.toString();
1517 if (strXPath != null) {
1518 if (strXPath.indexOf('[') == -1) {
1519 final Module module = findParentModule(schemaContext, parentNode);
1520 if (module != null) {
1521 final SchemaNode dataNode;
1522 if (xpath.isAbsolute()) {
1523 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1525 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1527 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1531 return "new java.lang.Object()";
1538 private String unionToDef(final LeafSchemaNode node) {
1539 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1543 if (type.getBaseType() != null) {
1544 final QName typeQName = type.getQName();
1545 Module module = null;
1546 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1547 if (modules.size() > 1) {
1548 for (Module m : modules) {
1549 if (m.getRevision().equals(typeQName.getRevision())) {
1554 if (module == null) {
1555 final List<Module> modulesList = new ArrayList<>(modules);
1556 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1557 module = modulesList.get(0);
1560 module = modules.iterator().next();
1563 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1564 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1566 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1567 final QName first = path.next();
1568 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1569 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1570 if (!path.hasNext()) {
1571 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1572 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1574 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
1576 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1579 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1582 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1583 final StringBuilder sb = new StringBuilder();
1585 sb.append(className);
1587 sb.append(defaultValue);
1588 sb.append("\".toCharArray())");
1589 return sb.toString();
1593 public String getConstructorPropertyName(final SchemaNode node) {
1594 return node instanceof TypeDefinition<?> ? "value" : "";
1598 public String getParamNameFromType(final TypeDefinition<?> type) {
1599 return BindingMapping.getPropertyName(type.getQName().getLocalName());