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.BiMap;
19 import com.google.common.collect.HashBiMap;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.Sets;
22 import com.google.common.io.BaseEncoding;
23 import java.io.Serializable;
24 import java.math.BigDecimal;
25 import java.math.BigInteger;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.Comparator;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.Optional;
36 import java.util.TreeMap;
37 import java.util.regex.Pattern;
38 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
39 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
40 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
41 import org.opendaylight.mdsal.binding.model.api.Enumeration;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
43 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
44 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
45 import org.opendaylight.mdsal.binding.model.api.Restrictions;
46 import org.opendaylight.mdsal.binding.model.api.Type;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
51 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
52 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
53 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
54 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
55 import org.opendaylight.mdsal.binding.model.util.Types;
56 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
57 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
58 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
59 import org.opendaylight.yangtools.yang.common.QName;
60 import org.opendaylight.yangtools.yang.common.Revision;
61 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
62 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.Module;
67 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.opendaylight.yangtools.yang.model.api.Status;
72 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
76 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
84 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
86 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
87 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
88 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
89 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
90 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
91 import org.slf4j.Logger;
92 import org.slf4j.LoggerFactory;
95 public abstract class AbstractTypeProvider implements TypeProvider {
96 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
97 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
99 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
100 // the case, as unions are emitted to their correct schema path.
101 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
102 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
105 * Contains the schema data red from YANG files.
107 private final SchemaContext schemaContext;
110 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
112 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
115 * The map which maps schema paths to JAVA <code>Type</code>.
117 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
118 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
119 private final Map<SchemaNode, JavaTypeName> renames;
122 * Creates new instance of class <code>TypeProviderImpl</code>.
124 * @param schemaContext
125 * contains the schema data red from YANG files
127 * @throws IllegalArgumentException
128 * if <code>schemaContext</code> equal null.
130 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
131 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
133 this.schemaContext = schemaContext;
134 this.renames = requireNonNull(renames);
135 resolveTypeDefsFromContext();
139 * Puts <code>refType</code> to map with key <code>refTypePath</code>
142 * schema path used as the map key
144 * type which represents the map value
145 * @throws IllegalArgumentException
147 * <li>if <code>refTypePath</code> equal null</li>
148 * <li>if <code>refType</code> equal null</li>
152 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
153 Preconditions.checkArgument(refTypePath != null,
154 "Path reference of Enumeration Type Definition cannot be NULL!");
155 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
156 referencedTypes.put(refTypePath, refType);
159 public Map<Module, Set<Type>> getAdditionalTypes() {
160 return additionalTypes;
164 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
165 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
169 * Converts schema definition type <code>typeDefinition</code> to JAVA
172 * @param typeDefinition
173 * type definition which is converted to JAVA type
174 * @throws IllegalArgumentException
176 * <li>if <code>typeDefinition</code> equal null</li>
177 * <li>if Qname of <code>typeDefinition</code> equal null</li>
178 * <li>if name of <code>typeDefinition</code> equal null</li>
182 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
183 final Restrictions r) {
184 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
185 Preconditions.checkArgument(typeDefinition.getQName() != null,
186 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
187 final String typedefName = typeDefinition.getQName().getLocalName();
188 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
190 // Deal with base types
191 if (typeDefinition.getBaseType() == null) {
192 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
193 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
194 // a base type which holds these constraints.
195 if (typeDefinition instanceof DecimalTypeDefinition) {
196 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
203 // Deal with leafrefs/identityrefs
204 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
209 // FIXME: it looks as though we could be using the same codepath as above...
210 ret = BaseYangTypes.javaTypeForYangType(typeDefinition.getQName().getLocalName());
212 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
218 Type returnType = javaTypeForExtendedType(typeDefinition);
219 if (r != null && returnType instanceof GeneratedTransferObject) {
220 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
221 final Module module = findParentModule(schemaContext, parentNode);
222 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
223 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
224 typeDefinition.getPath());
225 final String genTOName = BindingMapping.getClassName(typedefName);
226 final String name = packageName + "." + genTOName;
227 if (!returnType.getFullyQualifiedName().equals(name)) {
228 returnType = shadedTOWithRestrictions(gto, r);
234 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
235 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
236 final GeneratedTransferObject parent = gto.getSuperType();
237 if (parent != null) {
238 gtob.setExtendsType(parent);
240 gtob.setRestrictions(r);
241 for (GeneratedProperty gp : gto.getProperties()) {
242 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
243 gpb.setValue(gp.getValue());
244 gpb.setReadOnly(gp.isReadOnly());
245 gpb.setAccessModifier(gp.getAccessModifier());
246 gpb.setReturnType(gp.getReturnType());
247 gpb.setFinal(gp.isFinal());
248 gpb.setStatic(gp.isStatic());
253 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
254 final SchemaNode leafRefValueNode;
255 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
256 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(
257 GROUPS_PATTERN.matcher(leafRefXPath.toString()).replaceAll(""), leafRefXPath.isAbsolute());
259 ///// skip leafrefs in augments - they're checked once augments are resolved
260 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
261 boolean isAugmenting = false;
262 DataNodeContainer current = null;
263 DataSchemaNode dataChildByName;
265 while (iterator.hasNext() && !isAugmenting) {
266 final QName next = iterator.next();
267 if (current == null) {
268 dataChildByName = schemaContext.getDataChildByName(next);
270 dataChildByName = current.getDataChildByName(next);
272 if (dataChildByName != null) {
273 isAugmenting = dataChildByName.isAugmenting();
277 if (dataChildByName instanceof DataNodeContainer) {
278 current = (DataNodeContainer) dataChildByName;
286 final Module parentModule = getParentModule(parentNode);
287 if (!leafRefStrippedXPath.isAbsolute()) {
288 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
289 parentNode, leafRefStrippedXPath);
291 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
293 return leafRefValueNode != null ? leafRefValueNode.equals(parentNode) : false;
297 * Returns JAVA <code>Type</code> for instances of the type
298 * <code>LeafrefTypeDefinition</code> or
299 * <code>IdentityrefTypeDefinition</code>.
301 * @param typeDefinition
302 * type definition which is converted to JAVA <code>Type</code>
303 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
305 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
306 if (typeDefinition instanceof LeafrefTypeDefinition) {
307 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
308 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
309 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
310 return provideTypeForLeafref(leafref, parentNode);
311 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
312 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
319 * Returns JAVA <code>Type</code> for instances of the type
320 * <code>ExtendedType</code>.
322 * @param typeDefinition
323 * type definition which is converted to JAVA <code>Type</code>
324 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
326 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
327 final String typedefName = typeDefinition.getQName().getLocalName();
328 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
329 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
330 if (returnType == null) {
331 if (baseTypeDef instanceof EnumTypeDefinition) {
332 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
333 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
335 final Module module = findParentModule(schemaContext, typeDefinition);
336 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
337 if (module != null) {
338 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
340 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
341 if (genTOs != null) {
342 returnType = genTOs.get(typedefName);
344 if (returnType == null) {
345 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
346 baseTypeDef, typeDefinition, r);
355 * Seeks for identity reference <code>idref</code> the JAVA
356 * <code>type</code>.<br />
360 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
361 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
364 * identityref type definition for which JAVA <code>Type</code>
366 * @return JAVA <code>Type</code> of the identity which is referenced through
369 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
370 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
371 if (identities.size() > 1) {
372 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
375 final QName baseIdQName = identities.iterator().next().getQName();
376 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
377 IdentitySchemaNode identity = null;
378 for (IdentitySchemaNode id : module.getIdentities()) {
379 if (id.getQName().equals(baseIdQName)) {
383 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
385 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
386 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
387 identity.getPath()), BindingMapping.getClassName(identity.getQName()));
388 return Types.classType(Types.wildcardTypeFor(identifier));
392 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
394 * @param typeDefinition
395 * type definition which should be converted to JAVA
397 * @return JAVA <code>Type</code> which represents
398 * <code>typeDefinition</code>
399 * @throws IllegalArgumentException
401 * <li>if <code>typeDefinition</code> equal null</li>
402 * <li>if Q name of <code>typeDefinition</code></li>
403 * <li>if name of <code>typeDefinition</code></li>
406 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
407 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
408 if (typeDefinition.getQName() == null) {
409 throw new IllegalArgumentException(
410 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
412 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
413 "Type Definitions Local Name cannot be NULL!");
415 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
416 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
418 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
419 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
432 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
433 * dicey when we throw in:
447 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
448 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
451 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
452 * an encapsulation for identityref typedefs.
454 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
455 * option, as it would look as though it is the product of a different construct:
461 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
462 * sub-identities of iden.
464 * The story behind leafrefs is probably similar, but that needs to be ascertained.
469 final Module module = findParentModule(schemaContext, parentNode);
470 if (module != null) {
471 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
473 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
474 if (genTOs != null) {
475 return genTOs.get(typeDefinition.getQName().getLocalName());
482 * Gets base type definition for <code>extendTypeDef</code>. The method is
483 * recursively called until non <code>ExtendedType</code> type is found.
485 * @param extendTypeDef
486 * type definition for which is the base type definition sought
487 * @return type definition which is base type for <code>extendTypeDef</code>
488 * @throws IllegalArgumentException
489 * if <code>extendTypeDef</code> equal null
491 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
492 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
494 TypeDefinition<?> ret = extendTypeDef;
495 while (ret.getBaseType() != null) {
496 ret = ret.getBaseType();
503 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
505 * The path of <code>leafrefType</code> is followed to find referenced node
506 * and its <code>Type</code> is returned.
509 * leafref type definition for which is the type sought
510 * @return JAVA <code>Type</code> of data schema node which is referenced in
511 * <code>leafrefType</code>
512 * @throws IllegalArgumentException
514 * <li>if <code>leafrefType</code> equal null</li>
515 * <li>if path statement of <code>leafrefType</code> equal null</li>
519 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
520 Type returnType = null;
521 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
523 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
524 "The Path Statement for Leafref Type Definition cannot be NULL!");
526 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
527 final String strXPath = xpath.toString();
529 if (strXPath != null) {
530 if (strXPath.indexOf('[') == -1) {
531 final Module module = findParentModule(schemaContext, parentNode);
532 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
534 final SchemaNode dataNode;
535 if (xpath.isAbsolute()) {
536 dataNode = findDataSchemaNode(schemaContext, module, xpath);
538 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
540 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
541 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
543 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
544 if (leafContainsEnumDefinition(dataNode)) {
545 returnType = referencedTypes.get(dataNode.getPath());
546 } else if (leafListContainsEnumDefinition(dataNode)) {
547 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
549 if (returnType == null) {
550 returnType = resolveTypeFromDataSchemaNode(dataNode);
553 returnType = Types.objectType();
556 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
557 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
562 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
563 * so then checks if it is of type <code>EnumTypeDefinition</code>.
566 * data schema node for which is checked if it is leaf and if it
568 * @return boolean value
570 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
571 * <li>false - other cases</li>
574 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
575 if (dataNode instanceof LeafSchemaNode) {
576 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
577 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
585 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
586 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
589 * data schema node for which is checked if it is leaflist and if
591 * @return boolean value
593 * <li>true - if <code>dataNode</code> is leaflist of type
595 * <li>false - other cases</li>
598 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
599 if (dataNode instanceof LeafListSchemaNode) {
600 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
601 if (leafList.getType() instanceof EnumTypeDefinition) {
609 * Converts <code>enumTypeDef</code> to
614 * enumeration type definition which is converted to enumeration
616 * string with name which is used as the enumeration name
617 * @return enumeration type which is built with data (name, enum values)
618 * from <code>enumTypeDef</code>
619 * @throws IllegalArgumentException
621 * <li>if <code>enumTypeDef</code> equals null</li>
622 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
623 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
624 * <li>if name of <code>enumTypeDef</code> equal null</li>
627 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
628 final SchemaNode parentNode) {
629 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
630 Preconditions.checkArgument(enumTypeDef.getValues() != null,
631 "EnumTypeDefinition MUST contain at least ONE value definition!");
632 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
633 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
634 "Local Name in EnumTypeDefinition QName cannot be NULL!");
636 final Module module = findParentModule(schemaContext, parentNode);
637 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
638 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
639 addEnumDescription(enumBuilder, enumTypeDef);
640 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
641 enumBuilder.setModuleName(module.getName());
642 enumBuilder.setSchemaPath(enumTypeDef.getPath());
643 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
644 return enumBuilder.toInstance(null);
648 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
649 * taken from <code>enumTypeDef</code>.
652 * enumeration type definition is source of enumeration data for
653 * <code>typeBuilder</code>
655 * string with the name of enumeration
657 * generated type builder to which is enumeration added
658 * @return enumeration type which contains enumeration data form
659 * <code>enumTypeDef</code>
660 * @throws IllegalArgumentException
662 * <li>if <code>enumTypeDef</code> equals null</li>
663 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
664 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
665 * <li>if name of <code>enumTypeDef</code> equal null</li>
666 * <li>if name of <code>typeBuilder</code> equal null</li>
670 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
671 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
672 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
673 Preconditions.checkArgument(enumTypeDef.getValues() != null,
674 "EnumTypeDefinition MUST contain at least ONE value definition!");
675 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
676 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
677 "Local Name in EnumTypeDefinition QName cannot be NULL!");
678 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
680 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
682 addEnumDescription(enumBuilder, enumTypeDef);
683 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
684 return enumBuilder.toInstance(enumBuilder);
687 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
689 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
691 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
693 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
696 * Converts the pattern constraints to the list of the strings which represents these constraints.
698 * @param patternConstraints list of pattern constraints
699 * @return list of strings which represents the constraint patterns
701 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
703 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
706 * Converts the pattern constraints from <code>typedef</code> to the list of
707 * the strings which represents these constraints.
710 * extended type in which are the pattern constraints sought
711 * @return list of strings which represents the constraint patterns
712 * @throws IllegalArgumentException
713 * if <code>typedef</code> equals null
716 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
717 if (!(typedef instanceof StringTypeDefinition)) {
718 return ImmutableMap.of();
721 // TODO: run diff against base ?
722 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
726 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
729 * contains information about YANG type
730 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
732 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
733 Type returnType = null;
734 if (dataNode != null) {
735 if (dataNode instanceof LeafSchemaNode) {
736 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
737 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
738 returnType = javaTypeForSchemaDefinitionType(type, leaf);
739 } else if (dataNode instanceof LeafListSchemaNode) {
740 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
741 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
748 * Passes through all modules and through all its type definitions and
749 * convert it to generated types.
751 * The modules are firstly sorted by mutual dependencies. The modules are
752 * sequentially passed. All type definitions of a module are at the
753 * beginning sorted so that type definition with less amount of references
754 * to other type definition are processed first.<br />
755 * For each module is created mapping record in the map
756 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
757 * which map current module name to the map which maps type names to
758 * returned types (generated types).
761 private void resolveTypeDefsFromContext() {
762 final Set<Module> modules = schemaContext.getModules();
763 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
764 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
766 for (Module module : modulesSortedByDependency) {
767 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
768 module.getName(), key -> new HashMap<>());
769 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
770 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
773 for (Module module : modulesSortedByDependency) {
774 if (module != null) {
775 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
776 if (basePackageName != null) {
777 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
778 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
779 typedefToGeneratedType(basePackageName, module, typedef);
788 * @param basePackageName
789 * string with name of package to which the module belongs
791 * string with the name of the module for to which the
792 * <code>typedef</code> belongs
794 * type definition of the node for which should be created JAVA <code>Type</code> (usually generated TO)
795 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
796 * <code>null</code> value if <code>basePackageName</code> or
797 * <code>modulName</code> or <code>typedef</code> or Q name of
798 * <code>typedef</code> equals <code>null</code>
800 private Type typedefToGeneratedType(final String basePackageName, final Module module,
801 final TypeDefinition<?> typedef) {
802 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
804 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
805 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
809 final String typedefName = typedef.getQName().getLocalName();
811 final Type returnType;
812 if (baseTypedef.getBaseType() != null) {
813 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
815 } else if (baseTypedef instanceof UnionTypeDefinition) {
816 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
817 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
818 (UnionTypeDefinition) baseTypedef, typedef);
819 genTOBuilder.setTypedef(true);
820 genTOBuilder.setIsUnion(true);
821 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
822 makeSerializable(genTOBuilder);
823 returnType = genTOBuilder.build();
825 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
826 // so we are placing the builder alongside the union.
827 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
828 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
829 unionBuilder.setIsUnionBuilder(true);
830 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
831 method.setReturnType(returnType);
832 method.addParameter(Types.STRING, "defaultValue");
833 method.setAccessModifier(AccessModifier.PUBLIC);
834 method.setStatic(true);
835 Set<Type> types = additionalTypes.get(module);
837 types = Sets.<Type> newHashSet(unionBuilder.build());
838 additionalTypes.put(module, types);
840 types.add(unionBuilder.build());
842 } else if (baseTypedef instanceof EnumTypeDefinition) {
843 // enums are automatically Serializable
844 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
845 // TODO units for typedef enum
846 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
847 } else if (baseTypedef instanceof BitsTypeDefinition) {
848 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
849 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
850 (BitsTypeDefinition) baseTypedef, module.getName());
851 genTOBuilder.setTypedef(true);
852 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
853 makeSerializable(genTOBuilder);
854 returnType = genTOBuilder.build();
856 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
857 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
859 if (returnType != null) {
860 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
861 genTypeDefsContextMap.get(module.getName());
862 final Optional<Revision> moduleRevision = module.getRevision();
863 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
864 if (typeMap != null) {
865 if (typeMap.isEmpty()) {
866 typeMap = new HashMap<>(4);
867 modulesByDate.put(moduleRevision, typeMap);
869 typeMap.put(typedefName, returnType);
877 * Wraps base YANG type to generated TO.
879 * @param basePackageName
880 * string with name of package to which the module belongs
882 * type definition which is converted to the TO
884 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
885 * @return generated transfer object which represent<code>javaType</code>
887 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
888 final Type javaType, final String moduleName) {
889 Preconditions.checkNotNull(javaType, "javaType cannot be null");
891 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
892 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
893 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
894 genPropBuilder.setReturnType(javaType);
895 genTOBuilder.addEqualsIdentity(genPropBuilder);
896 genTOBuilder.addHashIdentity(genPropBuilder);
897 genTOBuilder.addToStringProperty(genPropBuilder);
898 if (typedef.getStatus() == Status.DEPRECATED) {
899 genTOBuilder.addAnnotation("java.lang", "Deprecated");
901 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
902 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
904 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
905 genTOBuilder.setTypedef(true);
906 makeSerializable(genTOBuilder);
907 return genTOBuilder.build();
911 * Converts output list of generated TO builders to one TO builder (first
912 * from list) which contains the remaining builders as its enclosing TO.
914 * @param typeName new type identifier
915 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
916 * @return generated TO builder with the list of enclosed generated TO builders
918 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
919 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
920 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
922 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
924 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
925 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
926 return resultTOBuilder;
930 * Converts <code>typedef</code> to generated TO with
931 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
932 * added to generated TO builder as property.
934 * @param typeName new type identifier
936 * type definition which should be of type
937 * <code>UnionTypeDefinition</code>
938 * @return generated TO builder which represents <code>typedef</code>
939 * @throws NullPointerException
941 * <li>if <code>basePackageName</code> is null</li>
942 * <li>if <code>typedef</code> is null</li>
943 * <li>if Qname of <code>typedef</code> is null</li>
946 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
947 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
948 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
949 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
951 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
952 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
953 final Module module = findParentModule(schemaContext, parentNode);
955 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
956 unionGenTOBuilder.setIsUnion(true);
957 unionGenTOBuilder.setSchemaPath(typedef.getPath());
958 unionGenTOBuilder.setModuleName(module.getName());
959 addCodegenInformation(unionGenTOBuilder, typedef);
960 generatedTOBuilders.add(unionGenTOBuilder);
962 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
963 // also negation information and hence guarantees uniqueness.
964 final Map<String, String> expressions = new HashMap<>();
965 final Map<TypeDefinition, String> propertyNames = resolveUnionMemberTypePropertyNames(unionTypes);
966 for (TypeDefinition<?> unionType : unionTypes) {
967 final String propertyName = propertyNames.get(unionType);
969 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
970 // do not follow type encapsulation -- we use the general case for that.
971 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
972 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode,
974 } else if (unionType instanceof UnionTypeDefinition) {
975 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
976 (UnionTypeDefinition) unionType, parentNode));
977 } else if (unionType instanceof EnumTypeDefinition) {
978 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
979 propertyName, unionGenTOBuilder);
980 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, propertyName);
982 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
983 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, propertyName);
986 addStringRegExAsConstant(unionGenTOBuilder, expressions);
988 storeGenTO(typedef, unionGenTOBuilder, parentNode);
990 return generatedTOBuilders;
993 private Map<TypeDefinition, String> resolveUnionMemberTypePropertyNames(final List<TypeDefinition<?>> unionTypes) {
994 final BiMap<String, TypeDefinition> propertyNames = HashBiMap.create();
997 for (TypeDefinition<?> type : unionTypes) {
998 propertyName = type.getQName().getLocalName();
999 if (propertyNames.containsKey(propertyName)) {
1000 propertyName = propertyName + (++suffix);
1003 propertyNames.put(propertyName, type);
1006 return propertyNames.inverse();
1010 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
1012 * In this case the new generated TO is created for union subtype (recursive call of method
1013 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
1014 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
1015 * created property which type is equal to new generated TO.
1017 * @param parentUnionGenTOBuilder
1018 * generated TO builder to which is the property with the child
1019 * union subtype added
1020 * @param basePackageName
1021 * string with the name of the module package
1022 * @param unionSubtype
1023 * type definition which represents union subtype
1024 * @return list of generated TO builders. The number of the builders can be
1025 * bigger one due to recursive call of
1026 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
1028 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1029 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
1030 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
1031 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
1032 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1033 newTOBuilderName, unionSubtype, parentNode);
1035 final GeneratedPropertyBuilder propertyBuilder;
1036 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
1037 newTOBuilderName.simpleName()));
1038 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
1039 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1040 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1042 return subUnionGenTOBUilders;
1046 * Wraps code which handle case when union subtype is of the type
1047 * <code>ExtendedType</code>.
1049 * If TO for this type already exists it is used for the creation of the
1050 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1051 * type is used for the property creation.
1053 * @param parentUnionGenTOBuilder
1054 * generated TO builder in which new property is created
1055 * @param unionSubtype
1056 * type definition of the <code>ExtendedType</code> type which
1057 * represents union subtype
1058 * @param expressions
1059 * list of strings with the regular expressions
1061 * parent Schema Node for Extended Subtype
1064 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1065 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode,
1066 final String propertyName) {
1067 final String unionTypeName = unionSubtype.getQName().getLocalName();
1068 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1069 if (genTO != null) {
1070 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1074 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1075 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1076 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1077 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1078 if (javaType != null) {
1079 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, propertyName);
1081 } else if (baseType instanceof LeafrefTypeDefinition) {
1082 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1083 boolean typeExist = false;
1084 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1085 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1086 if (origType != null && javaType != null && javaType == origType) {
1091 if (!typeExist && javaType != null) {
1092 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1093 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1096 if (baseType instanceof StringTypeDefinition) {
1097 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1102 * Searches for generated TO for <code>searchedTypeDef</code> type
1103 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1105 * @param searchedTypeName
1106 * string with name of <code>searchedTypeDef</code>
1107 * @return generated TO for <code>searchedTypeDef</code> or
1108 * <code>null</code> it it doesn't exist
1110 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1111 final Module typeModule = findParentModule(schemaContext, parentNode);
1112 if (typeModule != null && typeModule.getName() != null) {
1113 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1114 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1115 if (genTOs != null) {
1116 return genTOs.get(searchedTypeName);
1123 * Stores generated TO created from <code>genTOBuilder</code> for
1124 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1125 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1128 * type definition for which is <code>genTOBuilder</code> created
1129 * @param genTOBuilder
1130 * generated TO builder which is converted to generated TO and
1133 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1134 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1135 final Module parentModule = findParentModule(schemaContext, parentNode);
1136 if (parentModule != null && parentModule.getName() != null) {
1137 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1138 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1139 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1145 * Adds a new property with the name <code>propertyName</code> and with type
1146 * <code>type</code> to <code>unonGenTransObject</code>.
1148 * @param unionGenTransObject
1149 * generated TO to which should be property added
1151 * JAVA <code>type</code> of the property which should be added
1152 * to <code>unionGentransObject</code>
1153 * @param propertyName
1154 * string with name of property which should be added to
1155 * <code>unionGentransObject</code>
1157 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1158 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1159 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1160 .addProperty(BindingMapping.getPropertyName(propertyName));
1161 propBuilder.setReturnType(type);
1163 unionGenTransObject.addEqualsIdentity(propBuilder);
1164 unionGenTransObject.addHashIdentity(propBuilder);
1165 unionGenTransObject.addToStringProperty(propBuilder);
1170 * Converts <code>typedef</code> to the generated TO builder.
1172 * @param basePackageName
1173 * string with name of package to which the module belongs
1175 * type definition from which is the generated TO builder created
1176 * @return generated TO builder which contains data from
1177 * <code>typedef</code> and <code>basePackageName</code>
1179 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1180 final TypeDefinition<?> typedef, final String moduleName) {
1181 JavaTypeName name = renames.get(typedef);
1183 name = JavaTypeName.create(
1184 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1185 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1188 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1189 newType.setSchemaPath(typedef.getPath());
1190 newType.setModuleName(moduleName);
1191 addCodegenInformation(newType, typedef);
1196 * Converts <code>typeDef</code> which should be of the type
1197 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1199 * All the bits of the typeDef are added to returning generated TO as
1202 * @param typeName new type identifier
1204 * type definition from which is the generated TO builder created
1205 * @return generated TO builder which represents <code>typeDef</code>
1206 * @throws IllegalArgumentException
1208 * <li>if <code>typeDef</code> equals null</li>
1209 * <li>if <code>basePackageName</code> equals null</li>
1212 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1213 final BitsTypeDefinition typeDef, final String moduleName) {
1214 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1215 genTOBuilder.setSchemaPath(typeDef.getPath());
1216 genTOBuilder.setModuleName(moduleName);
1217 genTOBuilder.setBaseType(typeDef);
1218 addCodegenInformation(genTOBuilder, typeDef);
1220 final List<Bit> bitList = typeDef.getBits();
1221 GeneratedPropertyBuilder genPropertyBuilder;
1222 for (Bit bit : bitList) {
1223 final String name = bit.getName();
1224 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1225 genPropertyBuilder.setReadOnly(true);
1226 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1228 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1229 genTOBuilder.addHashIdentity(genPropertyBuilder);
1230 genTOBuilder.addToStringProperty(genPropertyBuilder);
1233 return genTOBuilder;
1238 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1239 * expressions from the <code>regularExpressions</code>
1241 * @param genTOBuilder
1242 * generated TO builder to which are
1243 * <code>regular expressions</code> added
1244 * @param expressions
1245 * list of string which represent regular expressions
1247 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1248 final Map<String, String> expressions) {
1249 if (!expressions.isEmpty()) {
1250 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1251 ImmutableMap.copyOf(expressions));
1256 * Creates generated TO with data about inner extended type
1257 * <code>innerExtendedType</code>, about the package name
1258 * <code>typedefName</code> and about the generated TO name
1259 * <code>typedefName</code>.
1261 * It is supposed that <code>innerExtendedType</code> is already present in
1262 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1263 * be possible set it as extended type for the returning generated TO.
1267 * @param innerExtendedType
1268 * extended type which is part of some other extended type
1269 * @param basePackageName
1270 * string with the package name of the module
1273 * @return generated TO which extends generated TO for
1274 * <code>innerExtendedType</code>
1275 * @throws IllegalArgumentException
1277 * <li>if <code>extendedType</code> equals null</li>
1278 * <li>if <code>basePackageName</code> equals null</li>
1279 * <li>if <code>typedefName</code> equals null</li>
1282 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1283 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1284 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1285 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1287 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1288 BindingMapping.getClassName(typedef.getQName())));
1289 genTOBuilder.setSchemaPath(typedef.getPath());
1290 genTOBuilder.setModuleName(moduleName);
1291 genTOBuilder.setTypedef(true);
1292 addCodegenInformation(genTOBuilder, typedef);
1294 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1295 genTOBuilder.setRestrictions(r);
1296 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1298 if (typedef.getStatus() == Status.DEPRECATED) {
1299 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1302 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1303 genTOBuilder.setIsUnion(true);
1306 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1307 Map<String, Type> typeMap = null;
1308 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1309 if (parentModule != null) {
1310 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1311 typeMap = modulesByDate.get(parentModule.getRevision());
1314 if (typeMap != null) {
1315 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1316 final Type type = typeMap.get(innerTypeDef);
1317 if (type instanceof GeneratedTransferObject) {
1318 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1321 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1322 makeSerializable(genTOBuilder);
1324 return genTOBuilder.build();
1328 * Add {@link Serializable} to implemented interfaces of this TO. Also
1329 * compute and add serialVersionUID property.
1332 * transfer object which needs to be serializable
1334 private static void makeSerializable(final GeneratedTOBuilder gto) {
1335 gto.addImplementsType(Types.serializableType());
1336 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1337 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1342 * Finds out for each type definition how many immersion (depth) is
1343 * necessary to get to the base type. Every type definition is inserted to
1344 * the map which key is depth and value is list of type definitions with
1345 * equal depth. In next step are lists from this map concatenated to one
1346 * list in ascending order according to their depth. All type definitions
1347 * are in the list behind all type definitions on which depends.
1349 * @param unsortedTypeDefinitions
1350 * list of type definitions which should be sorted by depth
1351 * @return list of type definitions sorted according their each other
1352 * dependencies (type definitions which are depend on other type
1353 * definitions are in list behind them).
1355 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1356 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1357 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1359 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1360 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1361 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1362 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1363 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1364 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1367 // SortedMap guarantees order corresponding to keys in ascending order
1368 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1369 sortedTypeDefinition.addAll(v);
1372 return sortedTypeDefinition;
1376 * Returns how many immersion is necessary to get from the type definition
1379 * @param typeDefinition
1380 * type definition for which is depth sought.
1381 * @return number of immersions which are necessary to get from the type
1382 * definition to the base type
1384 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1385 // FIXME: rewrite this in a non-recursive manner
1386 if (typeDefinition == null) {
1389 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1390 if (baseType == null) {
1395 if (baseType.getBaseType() != null) {
1396 depth = depth + getTypeDefinitionDepth(baseType);
1397 } else if (baseType instanceof UnionTypeDefinition) {
1398 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1399 int maxChildDepth = 0;
1401 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1402 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1403 if (childDepth > maxChildDepth) {
1404 maxChildDepth = childDepth;
1407 return maxChildDepth;
1413 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1414 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1415 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1417 * @param name string with name of augmented node
1418 * @return string with the number suffix incremented by one (or 1 is added)
1420 private static String provideAvailableNameForGenTOBuilder(final String name) {
1421 final int dollar = name.indexOf('$');
1426 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1427 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1428 return name.substring(0, dollar + 1) + newSuffix;
1431 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1432 if (!Strings.isNullOrEmpty(units)) {
1433 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1434 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1435 prop.setReturnType(Types.STRING);
1436 to.addToStringProperty(prop);
1441 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1442 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1445 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1446 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1447 final QName typeQName = type.getQName();
1448 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1449 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1450 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1453 final StringBuilder sb = new StringBuilder();
1454 String result = null;
1455 if (base instanceof BinaryTypeDefinition) {
1456 result = binaryToDef(defaultValue);
1457 } else if (base instanceof BitsTypeDefinition) {
1460 final Module parent = getParentModule(node);
1461 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1463 if (!path.hasNext()) {
1464 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1465 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1466 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1468 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1469 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1470 parentName = BindingMapping.getClassName(parent.getName());
1471 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1473 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1474 } else if (base instanceof BooleanTypeDefinition) {
1475 result = typeToBooleanDef(defaultValue);
1476 } else if (base instanceof DecimalTypeDefinition) {
1477 result = typeToDef(BigDecimal.class, defaultValue);
1478 } else if (base instanceof EmptyTypeDefinition) {
1479 result = typeToBooleanDef(defaultValue);
1480 } else if (base instanceof EnumTypeDefinition) {
1481 final char[] defValArray = defaultValue.toCharArray();
1482 final char first = Character.toUpperCase(defaultValue.charAt(0));
1483 defValArray[0] = first;
1484 final String newDefVal = new String(defValArray);
1486 if (type.getBaseType() != null) {
1487 final Module m = getParentModule(type);
1488 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1489 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1490 className = packageName + "." + BindingMapping.getClassName(typeQName);
1492 final Module parentModule = getParentModule(node);
1493 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1494 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1495 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1497 result = className + "." + newDefVal;
1498 } else if (base instanceof IdentityrefTypeDefinition) {
1499 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1500 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1501 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1502 } else if (BaseTypes.isInt8(base)) {
1503 result = typeToValueOfDef(Byte.class, defaultValue);
1504 } else if (BaseTypes.isInt16(base)) {
1505 result = typeToValueOfDef(Short.class, defaultValue);
1506 } else if (BaseTypes.isInt32(base)) {
1507 result = typeToValueOfDef(Integer.class, defaultValue);
1508 } else if (BaseTypes.isInt64(base)) {
1509 result = typeToValueOfDef(Long.class, defaultValue);
1510 } else if (base instanceof LeafrefTypeDefinition) {
1511 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1512 } else if (base instanceof StringTypeDefinition) {
1513 result = "\"" + defaultValue + "\"";
1514 } else if (BaseTypes.isUint8(base)) {
1515 result = typeToValueOfDef(Short.class, defaultValue);
1516 } else if (BaseTypes.isUint16(base)) {
1517 result = typeToValueOfDef(Integer.class, defaultValue);
1518 } else if (BaseTypes.isUint32(base)) {
1519 result = typeToValueOfDef(Long.class, defaultValue);
1520 } else if (BaseTypes.isUint64(base)) {
1521 switch (defaultValue) {
1523 result = "java.math.BigInteger.ZERO";
1526 result = "java.math.BigInteger.ONE";
1529 result = "java.math.BigInteger.TEN";
1532 result = typeToDef(BigInteger.class, defaultValue);
1534 } else if (base instanceof UnionTypeDefinition) {
1535 result = unionToDef(node);
1541 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1542 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1543 final Module m = getParentModule(type);
1544 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1545 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1546 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1547 sb.insert(0, "new " + className + "(");
1548 sb.insert(sb.length(), ')');
1551 return sb.toString();
1554 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1555 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1558 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1559 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1562 private static String typeToBooleanDef(final String defaultValue) {
1563 switch (defaultValue) {
1565 return "java.lang.Boolean.FALSE";
1567 return "java.lang.Boolean.TRUE";
1569 return typeToValueOfDef(Boolean.class, defaultValue);
1573 private static String binaryToDef(final String defaultValue) {
1574 final StringBuilder sb = new StringBuilder();
1575 final BaseEncoding en = BaseEncoding.base64();
1576 final byte[] encoded = en.decode(defaultValue);
1577 sb.append("new byte[] {");
1578 for (int i = 0; i < encoded.length; i++) {
1579 sb.append(encoded[i]);
1580 if (i != encoded.length - 1) {
1585 return sb.toString();
1588 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1590 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1591 final List<Bit> bits = new ArrayList<>(type.getBits());
1592 bits.sort(BIT_NAME_COMPARATOR);
1593 final StringBuilder sb = new StringBuilder();
1596 sb.append(className);
1599 for (int i = 0; i < bits.size(); i++) {
1600 if (bits.get(i).getName().equals(defaultValue)) {
1605 if (i != bits.size() - 1) {
1612 return sb.toString();
1615 private Module getParentModule(final SchemaNode node) {
1616 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1617 return schemaContext.findModule(qname.getModule()).orElse(null);
1620 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1621 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1622 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1623 "The Path Statement for Leafref Type Definition cannot be NULL!");
1625 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1626 final String strXPath = xpath.toString();
1628 if (strXPath != null) {
1629 if (strXPath.indexOf('[') == -1) {
1630 final Module module = findParentModule(schemaContext, parentNode);
1631 if (module != null) {
1632 final SchemaNode dataNode;
1633 if (xpath.isAbsolute()) {
1634 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1636 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1638 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1642 return "new java.lang.Object()";
1649 private String unionToDef(final LeafSchemaNode node) {
1650 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1654 if (type.getBaseType() != null) {
1655 final QName typeQName = type.getQName();
1656 Module module = null;
1657 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1658 if (modules.size() > 1) {
1659 for (Module m : modules) {
1660 if (m.getRevision().equals(typeQName.getRevision())) {
1665 if (module == null) {
1666 final List<Module> modulesList = new ArrayList<>(modules);
1667 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1668 module = modulesList.get(0);
1671 module = modules.iterator().next();
1674 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1675 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1677 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1678 final QName first = path.next();
1679 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1680 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1681 if (!path.hasNext()) {
1682 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1683 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1685 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1686 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1689 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1692 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1693 final StringBuilder sb = new StringBuilder();
1695 sb.append(className);
1697 sb.append(defaultValue);
1698 sb.append("\".toCharArray())");
1699 return sb.toString();
1703 public String getConstructorPropertyName(final SchemaNode node) {
1704 return node instanceof TypeDefinition<?> ? "value" : "";
1708 public String getParamNameFromType(final TypeDefinition<?> type) {
1709 return BindingMapping.getPropertyName(type.getQName().getLocalName());