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.io.Serializable;
22 import java.math.BigDecimal;
23 import java.math.BigInteger;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.HashMap;
29 import java.util.Iterator;
30 import java.util.List;
32 import java.util.Optional;
34 import java.util.TreeMap;
35 import java.util.regex.Pattern;
36 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
37 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
38 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
39 import org.opendaylight.mdsal.binding.model.api.Enumeration;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
42 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
43 import org.opendaylight.mdsal.binding.model.api.Restrictions;
44 import org.opendaylight.mdsal.binding.model.api.Type;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
50 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
51 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
52 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
53 import org.opendaylight.mdsal.binding.model.util.Types;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
55 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
56 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.Revision;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.Module;
65 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.opendaylight.yangtools.yang.model.api.Status;
70 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
74 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
82 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
85 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
86 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
87 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
88 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
89 import org.slf4j.Logger;
90 import org.slf4j.LoggerFactory;
93 public abstract class AbstractTypeProvider implements TypeProvider {
94 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
95 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
97 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
98 // the case, as unions are emitted to their correct schema path.
99 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
100 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
103 * Contains the schema data red from YANG files.
105 private final SchemaContext schemaContext;
108 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
110 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
113 * The map which maps schema paths to JAVA <code>Type</code>.
115 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
116 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
117 private final Map<SchemaNode, JavaTypeName> renames;
120 * Creates new instance of class <code>TypeProviderImpl</code>.
122 * @param schemaContext
123 * contains the schema data red from YANG files
125 * @throws IllegalArgumentException
126 * if <code>schemaContext</code> equal null.
128 AbstractTypeProvider(final SchemaContext schemaContext, final Map<SchemaNode, JavaTypeName> renames) {
129 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
131 this.schemaContext = schemaContext;
132 this.renames = requireNonNull(renames);
133 resolveTypeDefsFromContext();
137 * Puts <code>refType</code> to map with key <code>refTypePath</code>
140 * schema path used as the map key
142 * type which represents the map value
143 * @throws IllegalArgumentException
145 * <li>if <code>refTypePath</code> equal null</li>
146 * <li>if <code>refType</code> equal null</li>
150 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
151 Preconditions.checkArgument(refTypePath != null,
152 "Path reference of Enumeration Type Definition cannot be NULL!");
153 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
154 referencedTypes.put(refTypePath, refType);
157 public Map<Module, Set<Type>> getAdditionalTypes() {
158 return additionalTypes;
163 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
166 * string with YANG name of type
167 * @return JAVA <code>Type</code> for YANG type <code>type</code>
168 * @see TypeProvider#javaTypeForYangType(String)
172 public Type javaTypeForYangType(final String type) {
173 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
177 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
178 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
182 * Converts schema definition type <code>typeDefinition</code> to JAVA
185 * @param typeDefinition
186 * type definition which is converted to JAVA type
187 * @throws IllegalArgumentException
189 * <li>if <code>typeDefinition</code> equal null</li>
190 * <li>if Qname of <code>typeDefinition</code> equal null</li>
191 * <li>if name of <code>typeDefinition</code> equal null</li>
195 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
196 final Restrictions r) {
197 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
198 Preconditions.checkArgument(typeDefinition.getQName() != null,
199 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
200 final String typedefName = typeDefinition.getQName().getLocalName();
201 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
203 // Deal with base types
204 if (typeDefinition.getBaseType() == null) {
205 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
206 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
207 // a base type which holds these constraints.
208 if (typeDefinition instanceof DecimalTypeDefinition) {
209 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
216 // Deal with leafrefs/identityrefs
217 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
222 // FIXME: it looks as though we could be using the same codepath as above...
223 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
225 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
231 Type returnType = javaTypeForExtendedType(typeDefinition);
232 if (r != null && returnType instanceof GeneratedTransferObject) {
233 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
234 final Module module = findParentModule(schemaContext, parentNode);
235 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
236 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
237 typeDefinition.getPath());
238 final String genTOName = BindingMapping.getClassName(typedefName);
239 final String name = packageName + "." + genTOName;
240 if (!returnType.getFullyQualifiedName().equals(name)) {
241 returnType = shadedTOWithRestrictions(gto, r);
247 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
248 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getIdentifier());
249 final GeneratedTransferObject parent = gto.getSuperType();
250 if (parent != null) {
251 gtob.setExtendsType(parent);
253 gtob.setRestrictions(r);
254 for (GeneratedProperty gp : gto.getProperties()) {
255 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
256 gpb.setValue(gp.getValue());
257 gpb.setReadOnly(gp.isReadOnly());
258 gpb.setAccessModifier(gp.getAccessModifier());
259 gpb.setReturnType(gp.getReturnType());
260 gpb.setFinal(gp.isFinal());
261 gpb.setStatic(gp.isStatic());
266 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
267 final SchemaNode leafRefValueNode;
268 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
269 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(
270 GROUPS_PATTERN.matcher(leafRefXPath.toString()).replaceAll(""), leafRefXPath.isAbsolute());
272 ///// skip leafrefs in augments - they're checked once augments are resolved
273 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
274 boolean isAugmenting = false;
275 DataNodeContainer current = null;
276 DataSchemaNode dataChildByName;
278 while (iterator.hasNext() && !isAugmenting) {
279 final QName next = iterator.next();
280 if (current == null) {
281 dataChildByName = schemaContext.getDataChildByName(next);
283 dataChildByName = current.getDataChildByName(next);
285 if (dataChildByName != null) {
286 isAugmenting = dataChildByName.isAugmenting();
290 if (dataChildByName instanceof DataNodeContainer) {
291 current = (DataNodeContainer) dataChildByName;
299 final Module parentModule = getParentModule(parentNode);
300 if (!leafRefStrippedXPath.isAbsolute()) {
301 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
302 parentNode, leafRefStrippedXPath);
304 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
306 return leafRefValueNode != null ? leafRefValueNode.equals(parentNode) : false;
310 * Returns JAVA <code>Type</code> for instances of the type
311 * <code>LeafrefTypeDefinition</code> or
312 * <code>IdentityrefTypeDefinition</code>.
314 * @param typeDefinition
315 * type definition which is converted to JAVA <code>Type</code>
316 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
318 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
319 if (typeDefinition instanceof LeafrefTypeDefinition) {
320 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
321 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
322 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
323 return provideTypeForLeafref(leafref, parentNode);
324 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
325 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
332 * Returns JAVA <code>Type</code> for instances of the type
333 * <code>ExtendedType</code>.
335 * @param typeDefinition
336 * type definition which is converted to JAVA <code>Type</code>
337 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
339 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
340 final String typedefName = typeDefinition.getQName().getLocalName();
341 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
342 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
343 if (returnType == null) {
344 if (baseTypeDef instanceof EnumTypeDefinition) {
345 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
346 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
348 final Module module = findParentModule(schemaContext, typeDefinition);
349 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
350 if (module != null) {
351 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
353 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
354 if (genTOs != null) {
355 returnType = genTOs.get(typedefName);
357 if (returnType == null) {
358 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
359 baseTypeDef, typeDefinition, r);
368 * Seeks for identity reference <code>idref</code> the JAVA
369 * <code>type</code>.<br />
373 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
374 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
377 * identityref type definition for which JAVA <code>Type</code>
379 * @return JAVA <code>Type</code> of the identity which is referenced through
382 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
383 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
384 if (identities.size() > 1) {
385 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
388 final QName baseIdQName = identities.iterator().next().getQName();
389 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
390 IdentitySchemaNode identity = null;
391 for (IdentitySchemaNode id : module.getIdentities()) {
392 if (id.getQName().equals(baseIdQName)) {
396 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
398 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
399 final JavaTypeName identifier = JavaTypeName.create(BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
400 identity.getPath()), BindingMapping.getClassName(identity.getQName()));
401 return Types.classType(Types.wildcardTypeFor(identifier));
405 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
407 * @param typeDefinition
408 * type definition which should be converted to JAVA
410 * @return JAVA <code>Type</code> which represents
411 * <code>typeDefinition</code>
412 * @throws IllegalArgumentException
414 * <li>if <code>typeDefinition</code> equal null</li>
415 * <li>if Q name of <code>typeDefinition</code></li>
416 * <li>if name of <code>typeDefinition</code></li>
419 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
420 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
421 if (typeDefinition.getQName() == null) {
422 throw new IllegalArgumentException(
423 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
425 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
426 "Type Definitions Local Name cannot be NULL!");
428 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
429 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
431 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
432 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
445 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
446 * dicey when we throw in:
460 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
461 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
464 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
465 * an encapsulation for identityref typedefs.
467 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
468 * option, as it would look as though it is the product of a different construct:
474 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
475 * sub-identities of iden.
477 * The story behind leafrefs is probably similar, but that needs to be ascertained.
482 final Module module = findParentModule(schemaContext, parentNode);
483 if (module != null) {
484 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
486 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
487 if (genTOs != null) {
488 return genTOs.get(typeDefinition.getQName().getLocalName());
495 * Gets base type definition for <code>extendTypeDef</code>. The method is
496 * recursively called until non <code>ExtendedType</code> type is found.
498 * @param extendTypeDef
499 * type definition for which is the base type definition sought
500 * @return type definition which is base type for <code>extendTypeDef</code>
501 * @throws IllegalArgumentException
502 * if <code>extendTypeDef</code> equal null
504 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
505 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
507 TypeDefinition<?> ret = extendTypeDef;
508 while (ret.getBaseType() != null) {
509 ret = ret.getBaseType();
516 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
518 * The path of <code>leafrefType</code> is followed to find referenced node
519 * and its <code>Type</code> is returned.
522 * leafref type definition for which is the type sought
523 * @return JAVA <code>Type</code> of data schema node which is referenced in
524 * <code>leafrefType</code>
525 * @throws IllegalArgumentException
527 * <li>if <code>leafrefType</code> equal null</li>
528 * <li>if path statement of <code>leafrefType</code> equal null</li>
532 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
533 Type returnType = null;
534 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
536 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
537 "The Path Statement for Leafref Type Definition cannot be NULL!");
539 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
540 final String strXPath = xpath.toString();
542 if (strXPath != null) {
543 if (strXPath.indexOf('[') == -1) {
544 final Module module = findParentModule(schemaContext, parentNode);
545 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
547 final SchemaNode dataNode;
548 if (xpath.isAbsolute()) {
549 dataNode = findDataSchemaNode(schemaContext, module, xpath);
551 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
553 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
554 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
556 // FIXME: this block seems to be some weird magic hack. Analyze and refactor it.
557 if (leafContainsEnumDefinition(dataNode)) {
558 returnType = referencedTypes.get(dataNode.getPath());
559 } else if (leafListContainsEnumDefinition(dataNode)) {
560 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
562 if (returnType == null) {
563 returnType = resolveTypeFromDataSchemaNode(dataNode);
566 returnType = Types.objectType();
569 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
570 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
575 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
576 * so then checks if it is of type <code>EnumTypeDefinition</code>.
579 * data schema node for which is checked if it is leaf and if it
581 * @return boolean value
583 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
584 * <li>false - other cases</li>
587 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
588 if (dataNode instanceof LeafSchemaNode) {
589 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
590 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
598 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
599 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
602 * data schema node for which is checked if it is leaflist and if
604 * @return boolean value
606 * <li>true - if <code>dataNode</code> is leaflist of type
608 * <li>false - other cases</li>
611 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
612 if (dataNode instanceof LeafListSchemaNode) {
613 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
614 if (leafList.getType() instanceof EnumTypeDefinition) {
622 * Converts <code>enumTypeDef</code> to
627 * enumeration type definition which is converted to enumeration
629 * string with name which is used as the enumeration name
630 * @return enumeration type which is built with data (name, enum values)
631 * from <code>enumTypeDef</code>
632 * @throws IllegalArgumentException
634 * <li>if <code>enumTypeDef</code> equals null</li>
635 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
636 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
637 * <li>if name of <code>enumTypeDef</code> equal null</li>
640 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
641 final SchemaNode parentNode) {
642 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
643 Preconditions.checkArgument(enumTypeDef.getValues() != null,
644 "EnumTypeDefinition MUST contain at least ONE value definition!");
645 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
646 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
647 "Local Name in EnumTypeDefinition QName cannot be NULL!");
649 final Module module = findParentModule(schemaContext, parentNode);
650 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(JavaTypeName.create(
651 BindingMapping.getRootPackageName(module.getQNameModule()), BindingMapping.getClassName(enumName)));
652 addEnumDescription(enumBuilder, enumTypeDef);
653 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
654 enumBuilder.setModuleName(module.getName());
655 enumBuilder.setSchemaPath(enumTypeDef.getPath());
656 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
657 return enumBuilder.toInstance(null);
661 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
662 * taken from <code>enumTypeDef</code>.
665 * enumeration type definition is source of enumeration data for
666 * <code>typeBuilder</code>
668 * string with the name of enumeration
670 * generated type builder to which is enumeration added
671 * @return enumeration type which contains enumeration data form
672 * <code>enumTypeDef</code>
673 * @throws IllegalArgumentException
675 * <li>if <code>enumTypeDef</code> equals null</li>
676 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
677 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
678 * <li>if name of <code>enumTypeDef</code> equal null</li>
679 * <li>if name of <code>typeBuilder</code> equal null</li>
683 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
684 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
685 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
686 Preconditions.checkArgument(enumTypeDef.getValues() != null,
687 "EnumTypeDefinition MUST contain at least ONE value definition!");
688 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
689 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
690 "Local Name in EnumTypeDefinition QName cannot be NULL!");
691 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
693 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(BindingMapping.getClassName(enumName));
695 addEnumDescription(enumBuilder, enumTypeDef);
696 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
697 return enumBuilder.toInstance(enumBuilder);
700 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
702 public abstract AbstractEnumerationBuilder newEnumerationBuilder(JavaTypeName identifier);
704 public abstract GeneratedTOBuilder newGeneratedTOBuilder(JavaTypeName identifier);
706 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(JavaTypeName identifier);
709 * Converts the pattern constraints to the list of the strings which represents these constraints.
711 * @param patternConstraints list of pattern constraints
712 * @return list of strings which represents the constraint patterns
714 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
716 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
719 * Converts the pattern constraints from <code>typedef</code> to the list of
720 * the strings which represents these constraints.
723 * extended type in which are the pattern constraints sought
724 * @return list of strings which represents the constraint patterns
725 * @throws IllegalArgumentException
726 * if <code>typedef</code> equals null
729 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
730 if (!(typedef instanceof StringTypeDefinition)) {
731 return ImmutableMap.of();
734 // TODO: run diff against base ?
735 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
739 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
742 * contains information about YANG type
743 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
745 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
746 Type returnType = null;
747 if (dataNode != null) {
748 if (dataNode instanceof LeafSchemaNode) {
749 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
750 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
751 returnType = javaTypeForSchemaDefinitionType(type, leaf);
752 } else if (dataNode instanceof LeafListSchemaNode) {
753 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
754 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
761 * Passes through all modules and through all its type definitions and
762 * convert it to generated types.
764 * The modules are firstly sorted by mutual dependencies. The modules are
765 * sequentially passed. All type definitions of a module are at the
766 * beginning sorted so that type definition with less amount of references
767 * to other type definition are processed first.<br />
768 * For each module is created mapping record in the map
769 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
770 * which map current module name to the map which maps type names to
771 * returned types (generated types).
774 private void resolveTypeDefsFromContext() {
775 final Set<Module> modules = schemaContext.getModules();
776 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
777 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
779 for (Module module : modulesSortedByDependency) {
780 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.computeIfAbsent(
781 module.getName(), key -> new HashMap<>());
782 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
783 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
786 for (Module module : modulesSortedByDependency) {
787 if (module != null) {
788 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
789 if (basePackageName != null) {
790 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
791 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
792 typedefToGeneratedType(basePackageName, module, typedef);
801 * @param basePackageName
802 * string with name of package to which the module belongs
804 * string with the name of the module for to which the
805 * <code>typedef</code> belongs
807 * type definition of the node for which should be created JAVA <code>Type</code> (usually generated TO)
808 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
809 * <code>null</code> value if <code>basePackageName</code> or
810 * <code>modulName</code> or <code>typedef</code> or Q name of
811 * <code>typedef</code> equals <code>null</code>
813 private Type typedefToGeneratedType(final String basePackageName, final Module module,
814 final TypeDefinition<?> typedef) {
815 final TypeDefinition<?> baseTypedef = typedef.getBaseType();
817 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
818 if (baseTypedef instanceof LeafrefTypeDefinition || baseTypedef instanceof IdentityrefTypeDefinition) {
822 final String typedefName = typedef.getQName().getLocalName();
824 final Type returnType;
825 if (baseTypedef.getBaseType() != null) {
826 returnType = provideGeneratedTOFromExtendedType(typedef, baseTypedef, basePackageName,
828 } else if (baseTypedef instanceof UnionTypeDefinition) {
829 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(
830 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
831 (UnionTypeDefinition) baseTypedef, typedef);
832 genTOBuilder.setTypedef(true);
833 genTOBuilder.setIsUnion(true);
834 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
835 makeSerializable(genTOBuilder);
836 returnType = genTOBuilder.build();
838 // Define a corresponding union builder. Typedefs are always anchored at a Java package root,
839 // so we are placing the builder alongside the union.
840 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(
841 JavaTypeName.create(genTOBuilder.getPackageName(), genTOBuilder.getName() + "Builder"));
842 unionBuilder.setIsUnionBuilder(true);
843 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
844 method.setReturnType(returnType);
845 method.addParameter(Types.STRING, "defaultValue");
846 method.setAccessModifier(AccessModifier.PUBLIC);
847 method.setStatic(true);
848 Set<Type> types = additionalTypes.get(module);
850 types = Sets.<Type> newHashSet(unionBuilder.build());
851 additionalTypes.put(module, types);
853 types.add(unionBuilder.build());
855 } else if (baseTypedef instanceof EnumTypeDefinition) {
856 // enums are automatically Serializable
857 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypedef;
858 // TODO units for typedef enum
859 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
860 } else if (baseTypedef instanceof BitsTypeDefinition) {
861 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
862 JavaTypeName.create(basePackageName, BindingMapping.getClassName(typedef.getQName())),
863 (BitsTypeDefinition) baseTypedef, module.getName());
864 genTOBuilder.setTypedef(true);
865 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
866 makeSerializable(genTOBuilder);
867 returnType = genTOBuilder.build();
869 final Type javaType = javaTypeForSchemaDefinitionType(baseTypedef, typedef);
870 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
872 if (returnType != null) {
873 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
874 genTypeDefsContextMap.get(module.getName());
875 final Optional<Revision> moduleRevision = module.getRevision();
876 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
877 if (typeMap != null) {
878 if (typeMap.isEmpty()) {
879 typeMap = new HashMap<>(4);
880 modulesByDate.put(moduleRevision, typeMap);
882 typeMap.put(typedefName, returnType);
890 * Wraps base YANG type to generated TO.
892 * @param basePackageName
893 * string with name of package to which the module belongs
895 * type definition which is converted to the TO
897 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
898 * @return generated transfer object which represent<code>javaType</code>
900 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
901 final Type javaType, final String moduleName) {
902 Preconditions.checkNotNull(javaType, "javaType cannot be null");
904 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
905 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
906 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty("value");
907 genPropBuilder.setReturnType(javaType);
908 genTOBuilder.addEqualsIdentity(genPropBuilder);
909 genTOBuilder.addHashIdentity(genPropBuilder);
910 genTOBuilder.addToStringProperty(genPropBuilder);
911 if (typedef.getStatus() == Status.DEPRECATED) {
912 genTOBuilder.addAnnotation("java.lang", "Deprecated");
914 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
915 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
917 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
918 genTOBuilder.setTypedef(true);
919 makeSerializable(genTOBuilder);
920 return genTOBuilder.build();
924 * Converts output list of generated TO builders to one TO builder (first
925 * from list) which contains the remaining builders as its enclosing TO.
927 * @param typeName new type identifier
928 * @param typedef type definition which should be of type {@link UnionTypeDefinition}
929 * @return generated TO builder with the list of enclosed generated TO builders
931 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final JavaTypeName typeName,
932 final UnionTypeDefinition typedef, final TypeDefinition<?> parentNode) {
933 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(typeName, typedef,
935 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
937 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
938 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
939 return resultTOBuilder;
943 * Converts <code>typedef</code> to generated TO with
944 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
945 * added to generated TO builder as property.
947 * @param typeName new type identifier
949 * type definition which should be of type
950 * <code>UnionTypeDefinition</code>
951 * @return generated TO builder which represents <code>typedef</code>
952 * @throws NullPointerException
954 * <li>if <code>basePackageName</code> is null</li>
955 * <li>if <code>typedef</code> is null</li>
956 * <li>if Qname of <code>typedef</code> is null</li>
959 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final JavaTypeName typeName,
960 final UnionTypeDefinition typedef, final SchemaNode parentNode) {
961 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
962 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
964 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
965 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
966 final Module module = findParentModule(schemaContext, parentNode);
968 final GeneratedTOBuilder unionGenTOBuilder = newGeneratedTOBuilder(typeName);
969 unionGenTOBuilder.setIsUnion(true);
970 unionGenTOBuilder.setSchemaPath(typedef.getPath());
971 unionGenTOBuilder.setModuleName(module.getName());
972 addCodegenInformation(unionGenTOBuilder, typedef);
973 generatedTOBuilders.add(unionGenTOBuilder);
975 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
976 // also negation information and hence guarantees uniqueness.
977 final Map<String, String> expressions = new HashMap<>();
978 for (TypeDefinition<?> unionType : unionTypes) {
979 final String unionTypeName = unionType.getQName().getLocalName();
981 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
982 // do not follow type encapsulation -- we use the general case for that.
983 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
984 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
985 } else if (unionType instanceof UnionTypeDefinition) {
986 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
987 (UnionTypeDefinition) unionType, parentNode));
988 } else if (unionType instanceof EnumTypeDefinition) {
989 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
990 unionTypeName, unionGenTOBuilder);
991 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
993 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
994 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
997 addStringRegExAsConstant(unionGenTOBuilder, expressions);
999 storeGenTO(typedef, unionGenTOBuilder, parentNode);
1001 return generatedTOBuilders;
1005 * Wraps code which handles the case when union subtype is also of the type <code>UnionType</code>.
1007 * In this case the new generated TO is created for union subtype (recursive call of method
1008 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition, String, SchemaNode)}
1009 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder <code>parentUnionGenTOBuilder</code> is
1010 * created property which type is equal to new generated TO.
1012 * @param parentUnionGenTOBuilder
1013 * generated TO builder to which is the property with the child
1014 * union subtype added
1015 * @param basePackageName
1016 * string with the name of the module package
1017 * @param unionSubtype
1018 * type definition which represents union subtype
1019 * @return list of generated TO builders. The number of the builders can be
1020 * bigger one due to recursive call of
1021 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
1023 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1024 final UnionTypeDefinition unionSubtype, final SchemaNode parentNode) {
1025 final JavaTypeName newTOBuilderName = parentUnionGenTOBuilder.getIdentifier().createSibling(
1026 provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName()));
1027 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1028 newTOBuilderName, unionSubtype, parentNode);
1030 final GeneratedPropertyBuilder propertyBuilder;
1031 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(
1032 newTOBuilderName.simpleName()));
1033 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0).build());
1034 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1035 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1037 return subUnionGenTOBUilders;
1041 * Wraps code which handle case when union subtype is of the type
1042 * <code>ExtendedType</code>.
1044 * If TO for this type already exists it is used for the creation of the
1045 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1046 * type is used for the property creation.
1048 * @param parentUnionGenTOBuilder
1049 * generated TO builder in which new property is created
1050 * @param unionSubtype
1051 * type definition of the <code>ExtendedType</code> type which
1052 * represents union subtype
1053 * @param expressions
1054 * list of strings with the regular expressions
1056 * parent Schema Node for Extended Subtype
1059 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1060 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1061 final String unionTypeName = unionSubtype.getQName().getLocalName();
1062 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1063 if (genTO != null) {
1064 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1068 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1069 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1070 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1071 parentNode, BindingGeneratorUtil.getRestrictions(unionSubtype));
1072 if (javaType != null) {
1073 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1075 } else if (baseType instanceof LeafrefTypeDefinition) {
1076 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1077 boolean typeExist = false;
1078 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1079 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1080 if (origType != null && javaType != null && javaType == origType) {
1085 if (!typeExist && javaType != null) {
1086 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1087 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1090 if (baseType instanceof StringTypeDefinition) {
1091 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1096 * Searches for generated TO for <code>searchedTypeDef</code> type
1097 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1099 * @param searchedTypeName
1100 * string with name of <code>searchedTypeDef</code>
1101 * @return generated TO for <code>searchedTypeDef</code> or
1102 * <code>null</code> it it doesn't exist
1104 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1105 final Module typeModule = findParentModule(schemaContext, parentNode);
1106 if (typeModule != null && typeModule.getName() != null) {
1107 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1108 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1109 if (genTOs != null) {
1110 return genTOs.get(searchedTypeName);
1117 * Stores generated TO created from <code>genTOBuilder</code> for
1118 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1119 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1122 * type definition for which is <code>genTOBuilder</code> created
1123 * @param genTOBuilder
1124 * generated TO builder which is converted to generated TO and
1127 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1128 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1129 final Module parentModule = findParentModule(schemaContext, parentNode);
1130 if (parentModule != null && parentModule.getName() != null) {
1131 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1132 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1133 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1139 * Adds a new property with the name <code>propertyName</code> and with type
1140 * <code>type</code> to <code>unonGenTransObject</code>.
1142 * @param unionGenTransObject
1143 * generated TO to which should be property added
1145 * JAVA <code>type</code> of the property which should be added
1146 * to <code>unionGentransObject</code>
1147 * @param propertyName
1148 * string with name of property which should be added to
1149 * <code>unionGentransObject</code>
1151 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1152 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1153 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1154 .addProperty(BindingMapping.getPropertyName(propertyName));
1155 propBuilder.setReturnType(type);
1157 unionGenTransObject.addEqualsIdentity(propBuilder);
1158 unionGenTransObject.addHashIdentity(propBuilder);
1159 unionGenTransObject.addToStringProperty(propBuilder);
1164 * Converts <code>typedef</code> to the generated TO builder.
1166 * @param basePackageName
1167 * string with name of package to which the module belongs
1169 * type definition from which is the generated TO builder created
1170 * @return generated TO builder which contains data from
1171 * <code>typedef</code> and <code>basePackageName</code>
1173 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1174 final TypeDefinition<?> typedef, final String moduleName) {
1175 JavaTypeName name = renames.get(typedef);
1177 name = JavaTypeName.create(
1178 BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath()),
1179 BindingMapping.getClassName(typedef.getQName().getLocalName()));
1182 final GeneratedTOBuilder newType = newGeneratedTOBuilder(name);
1183 newType.setSchemaPath(typedef.getPath());
1184 newType.setModuleName(moduleName);
1185 addCodegenInformation(newType, typedef);
1190 * Converts <code>typeDef</code> which should be of the type
1191 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1193 * All the bits of the typeDef are added to returning generated TO as
1196 * @param typeName new type identifier
1198 * type definition from which is the generated TO builder created
1199 * @return generated TO builder which represents <code>typeDef</code>
1200 * @throws IllegalArgumentException
1202 * <li>if <code>typeDef</code> equals null</li>
1203 * <li>if <code>basePackageName</code> equals null</li>
1206 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final JavaTypeName typeName,
1207 final BitsTypeDefinition typeDef, final String moduleName) {
1208 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(typeName);
1209 genTOBuilder.setSchemaPath(typeDef.getPath());
1210 genTOBuilder.setModuleName(moduleName);
1211 genTOBuilder.setBaseType(typeDef);
1212 addCodegenInformation(genTOBuilder, typeDef);
1214 final List<Bit> bitList = typeDef.getBits();
1215 GeneratedPropertyBuilder genPropertyBuilder;
1216 for (Bit bit : bitList) {
1217 final String name = bit.getName();
1218 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1219 genPropertyBuilder.setReadOnly(true);
1220 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1222 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1223 genTOBuilder.addHashIdentity(genPropertyBuilder);
1224 genTOBuilder.addToStringProperty(genPropertyBuilder);
1227 return genTOBuilder;
1232 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1233 * expressions from the <code>regularExpressions</code>
1235 * @param genTOBuilder
1236 * generated TO builder to which are
1237 * <code>regular expressions</code> added
1238 * @param expressions
1239 * list of string which represent regular expressions
1241 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1242 final Map<String, String> expressions) {
1243 if (!expressions.isEmpty()) {
1244 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1245 ImmutableMap.copyOf(expressions));
1250 * Creates generated TO with data about inner extended type
1251 * <code>innerExtendedType</code>, about the package name
1252 * <code>typedefName</code> and about the generated TO name
1253 * <code>typedefName</code>.
1255 * It is supposed that <code>innerExtendedType</code> is already present in
1256 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1257 * be possible set it as extended type for the returning generated TO.
1261 * @param innerExtendedType
1262 * extended type which is part of some other extended type
1263 * @param basePackageName
1264 * string with the package name of the module
1267 * @return generated TO which extends generated TO for
1268 * <code>innerExtendedType</code>
1269 * @throws IllegalArgumentException
1271 * <li>if <code>extendedType</code> equals null</li>
1272 * <li>if <code>basePackageName</code> equals null</li>
1273 * <li>if <code>typedefName</code> equals null</li>
1276 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1277 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1278 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1279 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1281 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(JavaTypeName.create(basePackageName,
1282 BindingMapping.getClassName(typedef.getQName())));
1283 genTOBuilder.setSchemaPath(typedef.getPath());
1284 genTOBuilder.setModuleName(moduleName);
1285 genTOBuilder.setTypedef(true);
1286 addCodegenInformation(genTOBuilder, typedef);
1288 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1289 genTOBuilder.setRestrictions(r);
1290 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
1292 if (typedef.getStatus() == Status.DEPRECATED) {
1293 genTOBuilder.addAnnotation("java.lang", "Deprecated");
1296 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1297 genTOBuilder.setIsUnion(true);
1300 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1301 Map<String, Type> typeMap = null;
1302 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1303 if (parentModule != null) {
1304 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1305 typeMap = modulesByDate.get(parentModule.getRevision());
1308 if (typeMap != null) {
1309 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1310 final Type type = typeMap.get(innerTypeDef);
1311 if (type instanceof GeneratedTransferObject) {
1312 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1315 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1316 makeSerializable(genTOBuilder);
1318 return genTOBuilder.build();
1322 * Add {@link Serializable} to implemented interfaces of this TO. Also
1323 * compute and add serialVersionUID property.
1326 * transfer object which needs to be serializable
1328 private static void makeSerializable(final GeneratedTOBuilder gto) {
1329 gto.addImplementsType(Types.serializableType());
1330 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1331 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1336 * Finds out for each type definition how many immersion (depth) is
1337 * necessary to get to the base type. Every type definition is inserted to
1338 * the map which key is depth and value is list of type definitions with
1339 * equal depth. In next step are lists from this map concatenated to one
1340 * list in ascending order according to their depth. All type definitions
1341 * are in the list behind all type definitions on which depends.
1343 * @param unsortedTypeDefinitions
1344 * list of type definitions which should be sorted by depth
1345 * @return list of type definitions sorted according their each other
1346 * dependencies (type definitions which are depend on other type
1347 * definitions are in list behind them).
1349 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1350 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1351 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1353 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1354 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1355 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1356 List<TypeDefinition<?>> typeDefinitionsConcreteDepth =
1357 typeDefinitionsDepths.computeIfAbsent(depth, k -> new ArrayList<>());
1358 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1361 // SortedMap guarantees order corresponding to keys in ascending order
1362 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1363 sortedTypeDefinition.addAll(v);
1366 return sortedTypeDefinition;
1370 * Returns how many immersion is necessary to get from the type definition
1373 * @param typeDefinition
1374 * type definition for which is depth sought.
1375 * @return number of immersions which are necessary to get from the type
1376 * definition to the base type
1378 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1379 // FIXME: rewrite this in a non-recursive manner
1380 if (typeDefinition == null) {
1383 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1384 if (baseType == null) {
1389 if (baseType.getBaseType() != null) {
1390 depth = depth + getTypeDefinitionDepth(baseType);
1391 } else if (baseType instanceof UnionTypeDefinition) {
1392 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1393 int maxChildDepth = 0;
1395 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1396 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1397 if (childDepth > maxChildDepth) {
1398 maxChildDepth = childDepth;
1401 return maxChildDepth;
1407 * Returns string which contains the same value as <code>name</code> but integer suffix is incremented by one. If
1408 * <code>name</code> contains no number suffix, a new suffix initialized at 1 is added. A suffix is actually
1409 * composed of a '$' marker, which is safe, as no YANG identifier can contain '$', and a unsigned decimal integer.
1411 * @param name string with name of augmented node
1412 * @return string with the number suffix incremented by one (or 1 is added)
1414 private static String provideAvailableNameForGenTOBuilder(final String name) {
1415 final int dollar = name.indexOf('$');
1420 final int newSuffix = Integer.parseUnsignedInt(name.substring(dollar + 1)) + 1;
1421 Preconditions.checkState(newSuffix > 0, "Suffix counter overflow");
1422 return name.substring(0, dollar + 1) + newSuffix;
1425 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1426 if (!Strings.isNullOrEmpty(units)) {
1427 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1428 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1429 prop.setReturnType(Types.STRING);
1430 to.addToStringProperty(prop);
1435 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1436 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1439 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1440 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1441 final QName typeQName = type.getQName();
1442 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1443 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1444 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1447 final StringBuilder sb = new StringBuilder();
1448 String result = null;
1449 if (base instanceof BinaryTypeDefinition) {
1450 result = binaryToDef(defaultValue);
1451 } else if (base instanceof BitsTypeDefinition) {
1454 final Module parent = getParentModule(node);
1455 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1457 if (!path.hasNext()) {
1458 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1459 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1460 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1462 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1463 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1464 parentName = BindingMapping.getClassName(parent.getName());
1465 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1467 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1468 } else if (base instanceof BooleanTypeDefinition) {
1469 result = typeToBooleanDef(defaultValue);
1470 } else if (base instanceof DecimalTypeDefinition) {
1471 result = typeToDef(BigDecimal.class, defaultValue);
1472 } else if (base instanceof EmptyTypeDefinition) {
1473 result = typeToBooleanDef(defaultValue);
1474 } else if (base instanceof EnumTypeDefinition) {
1475 final char[] defValArray = defaultValue.toCharArray();
1476 final char first = Character.toUpperCase(defaultValue.charAt(0));
1477 defValArray[0] = first;
1478 final String newDefVal = new String(defValArray);
1480 if (type.getBaseType() != null) {
1481 final Module m = getParentModule(type);
1482 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1483 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1484 className = packageName + "." + BindingMapping.getClassName(typeQName);
1486 final Module parentModule = getParentModule(node);
1487 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1488 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1489 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1491 result = className + "." + newDefVal;
1492 } else if (base instanceof IdentityrefTypeDefinition) {
1493 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1494 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1495 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1496 } else if (BaseTypes.isInt8(base)) {
1497 result = typeToValueOfDef(Byte.class, defaultValue);
1498 } else if (BaseTypes.isInt16(base)) {
1499 result = typeToValueOfDef(Short.class, defaultValue);
1500 } else if (BaseTypes.isInt32(base)) {
1501 result = typeToValueOfDef(Integer.class, defaultValue);
1502 } else if (BaseTypes.isInt64(base)) {
1503 result = typeToValueOfDef(Long.class, defaultValue);
1504 } else if (base instanceof LeafrefTypeDefinition) {
1505 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1506 } else if (base instanceof StringTypeDefinition) {
1507 result = "\"" + defaultValue + "\"";
1508 } else if (BaseTypes.isUint8(base)) {
1509 result = typeToValueOfDef(Short.class, defaultValue);
1510 } else if (BaseTypes.isUint16(base)) {
1511 result = typeToValueOfDef(Integer.class, defaultValue);
1512 } else if (BaseTypes.isUint32(base)) {
1513 result = typeToValueOfDef(Long.class, defaultValue);
1514 } else if (BaseTypes.isUint64(base)) {
1515 switch (defaultValue) {
1517 result = "java.math.BigInteger.ZERO";
1520 result = "java.math.BigInteger.ONE";
1523 result = "java.math.BigInteger.TEN";
1526 result = typeToDef(BigInteger.class, defaultValue);
1528 } else if (base instanceof UnionTypeDefinition) {
1529 result = unionToDef(node);
1535 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1536 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1537 final Module m = getParentModule(type);
1538 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1539 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1540 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1541 sb.insert(0, "new " + className + "(");
1542 sb.insert(sb.length(), ')');
1545 return sb.toString();
1548 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1549 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1552 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1553 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1556 private static String typeToBooleanDef(final String defaultValue) {
1557 switch (defaultValue) {
1559 return "java.lang.Boolean.FALSE";
1561 return "java.lang.Boolean.TRUE";
1563 return typeToValueOfDef(Boolean.class, defaultValue);
1567 private static String binaryToDef(final String defaultValue) {
1568 final StringBuilder sb = new StringBuilder();
1569 final BaseEncoding en = BaseEncoding.base64();
1570 final byte[] encoded = en.decode(defaultValue);
1571 sb.append("new byte[] {");
1572 for (int i = 0; i < encoded.length; i++) {
1573 sb.append(encoded[i]);
1574 if (i != encoded.length - 1) {
1579 return sb.toString();
1582 private static final Comparator<Bit> BIT_NAME_COMPARATOR = Comparator.comparing(Bit::getName);
1584 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1585 final List<Bit> bits = new ArrayList<>(type.getBits());
1586 bits.sort(BIT_NAME_COMPARATOR);
1587 final StringBuilder sb = new StringBuilder();
1590 sb.append(className);
1593 for (int i = 0; i < bits.size(); i++) {
1594 if (bits.get(i).getName().equals(defaultValue)) {
1599 if (i != bits.size() - 1) {
1606 return sb.toString();
1609 private Module getParentModule(final SchemaNode node) {
1610 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1611 return schemaContext.findModule(qname.getModule()).orElse(null);
1614 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1615 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1616 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1617 "The Path Statement for Leafref Type Definition cannot be NULL!");
1619 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1620 final String strXPath = xpath.toString();
1622 if (strXPath != null) {
1623 if (strXPath.indexOf('[') == -1) {
1624 final Module module = findParentModule(schemaContext, parentNode);
1625 if (module != null) {
1626 final SchemaNode dataNode;
1627 if (xpath.isAbsolute()) {
1628 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1630 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1632 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1636 return "new java.lang.Object()";
1643 private String unionToDef(final LeafSchemaNode node) {
1644 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1648 if (type.getBaseType() != null) {
1649 final QName typeQName = type.getQName();
1650 Module module = null;
1651 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1652 if (modules.size() > 1) {
1653 for (Module m : modules) {
1654 if (m.getRevision().equals(typeQName.getRevision())) {
1659 if (module == null) {
1660 final List<Module> modulesList = new ArrayList<>(modules);
1661 modulesList.sort((o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1662 module = modulesList.get(0);
1665 module = modules.iterator().next();
1668 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1669 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1671 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1672 final QName first = path.next();
1673 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1674 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1675 if (!path.hasNext()) {
1676 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1677 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1679 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1680 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1683 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1686 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1687 final StringBuilder sb = new StringBuilder();
1689 sb.append(className);
1691 sb.append(defaultValue);
1692 sb.append("\".toCharArray())");
1693 return sb.toString();
1697 public String getConstructorPropertyName(final SchemaNode node) {
1698 return node instanceof TypeDefinition<?> ? "value" : "";
1702 public String getParamNameFromType(final TypeDefinition<?> type) {
1703 return BindingMapping.getPropertyName(type.getQName().getLocalName());