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 org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
14 import com.google.common.annotations.Beta;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.Maps;
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.Matcher;
36 import java.util.regex.Pattern;
37 import org.opendaylight.mdsal.binding.generator.spi.TypeProvider;
38 import org.opendaylight.mdsal.binding.model.api.AccessModifier;
39 import org.opendaylight.mdsal.binding.model.api.ConcreteType;
40 import org.opendaylight.mdsal.binding.model.api.Enumeration;
41 import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
42 import org.opendaylight.mdsal.binding.model.api.GeneratedTransferObject;
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.GeneratedTypeBuilderBase;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
50 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
51 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
52 import org.opendaylight.mdsal.binding.model.util.Types;
53 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.EnumerationBuilderImpl;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
55 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedTOBuilderImpl;
56 import org.opendaylight.yangtools.yang.binding.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.ModifierKind;
82 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
83 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
85 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
86 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
87 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
88 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
89 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
90 import org.slf4j.Logger;
91 import org.slf4j.LoggerFactory;
94 public abstract class AbstractTypeProvider implements TypeProvider {
95 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
96 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
97 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
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<>();
121 * Creates new instance of class <code>TypeProviderImpl</code>.
123 * @param schemaContext
124 * contains the schema data red from YANG files
125 * @throws IllegalArgumentException
126 * if <code>schemaContext</code> equal null.
128 AbstractTypeProvider(final SchemaContext schemaContext) {
129 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
131 this.schemaContext = schemaContext;
132 resolveTypeDefsFromContext();
136 * Puts <code>refType</code> to map with key <code>refTypePath</code>
139 * schema path used as the map key
141 * type which represents the map value
142 * @throws IllegalArgumentException
144 * <li>if <code>refTypePath</code> equal null</li>
145 * <li>if <code>refType</code> equal null</li>
149 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
150 Preconditions.checkArgument(refTypePath != null,
151 "Path reference of Enumeration Type Definition cannot be NULL!");
152 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
153 referencedTypes.put(refTypePath, refType);
156 public Map<Module, Set<Type>> getAdditionalTypes() {
157 return additionalTypes;
162 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
165 * string with YANG name of type
166 * @return JAVA <code>Type</code> for YANG type <code>type</code>
167 * @see TypeProvider#javaTypeForYangType(String)
171 public Type javaTypeForYangType(final String type) {
172 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
176 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
177 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
181 * Converts schema definition type <code>typeDefinition</code> to JAVA
184 * @param typeDefinition
185 * type definition which is converted to JAVA type
186 * @throws IllegalArgumentException
188 * <li>if <code>typeDefinition</code> equal null</li>
189 * <li>if Qname of <code>typeDefinition</code> equal null</li>
190 * <li>if name of <code>typeDefinition</code> equal null</li>
194 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
195 final Restrictions r) {
196 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
197 Preconditions.checkArgument(typeDefinition.getQName() != null,
198 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
199 final String typedefName = typeDefinition.getQName().getLocalName();
200 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
202 // Deal with base types
203 if (typeDefinition.getBaseType() == null) {
204 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
205 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
206 // a base type which holds these constraints.
207 if (typeDefinition instanceof DecimalTypeDefinition) {
208 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
215 // Deal with leafrefs/identityrefs
216 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
221 // FIXME: it looks as though we could be using the same codepath as above...
222 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
224 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
230 Type returnType = javaTypeForExtendedType(typeDefinition);
231 if (r != null && returnType instanceof GeneratedTransferObject) {
232 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
233 final Module module = findParentModule(schemaContext, parentNode);
234 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
235 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
236 typeDefinition.getPath());
237 final String genTOName = BindingMapping.getClassName(typedefName);
238 final String name = packageName + "." + genTOName;
239 if (!returnType.getFullyQualifiedName().equals(name)) {
240 returnType = shadedTOWithRestrictions(gto, r);
246 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto,
247 final Restrictions r) {
248 final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
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());
263 return gtob.toInstance();
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 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
401 final String genTypeName = BindingMapping.getClassName(identity.getQName());
403 final Type baseType = Types.typeForClass(Class.class);
404 final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
405 return Types.parameterizedTypeFor(baseType, paramType);
409 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
411 * @param typeDefinition
412 * type definition which should be converted to JAVA
414 * @return JAVA <code>Type</code> which represents
415 * <code>typeDefinition</code>
416 * @throws IllegalArgumentException
418 * <li>if <code>typeDefinition</code> equal null</li>
419 * <li>if Q name of <code>typeDefinition</code></li>
420 * <li>if name of <code>typeDefinition</code></li>
423 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
424 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
425 if (typeDefinition.getQName() == null) {
426 throw new IllegalArgumentException(
427 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
429 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
430 "Type Definitions Local Name cannot be NULL!");
432 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
433 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
435 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
436 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
449 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
450 * dicey when we throw in:
464 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
465 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
468 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
469 * an encapsulation for identityref typedefs.
471 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
472 * option, as it would look as though it is the product of a different construct:
478 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
479 * sub-identities of iden.
481 * The story behind leafrefs is probably similar, but that needs to be ascertained.
486 final Module module = findParentModule(schemaContext, parentNode);
487 if (module != null) {
488 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
490 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
491 if (genTOs != null) {
492 return genTOs.get(typeDefinition.getQName().getLocalName());
499 * Gets base type definition for <code>extendTypeDef</code>. The method is
500 * recursively called until non <code>ExtendedType</code> type is found.
502 * @param extendTypeDef
503 * type definition for which is the base type definition sought
504 * @return type definition which is base type for <code>extendTypeDef</code>
505 * @throws IllegalArgumentException
506 * if <code>extendTypeDef</code> equal null
508 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
509 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
511 TypeDefinition<?> ret = extendTypeDef;
512 while (ret.getBaseType() != null) {
513 ret = ret.getBaseType();
520 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
522 * The path of <code>leafrefType</code> is followed to find referenced node
523 * and its <code>Type</code> is returned.
526 * leafref type definition for which is the type sought
527 * @return JAVA <code>Type</code> of data schema node which is referenced in
528 * <code>leafrefType</code>
529 * @throws IllegalArgumentException
531 * <li>if <code>leafrefType</code> equal null</li>
532 * <li>if path statement of <code>leafrefType</code> equal null</li>
536 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
537 Type returnType = null;
538 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
540 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
541 "The Path Statement for Leafref Type Definition cannot be NULL!");
543 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
544 final String strXPath = xpath.toString();
546 if (strXPath != null) {
547 if (strXPath.indexOf('[') == -1) {
548 final Module module = findParentModule(schemaContext, parentNode);
549 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
551 final SchemaNode dataNode;
552 if (xpath.isAbsolute()) {
553 dataNode = findDataSchemaNode(schemaContext, module, xpath);
555 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
557 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
558 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
560 if (leafContainsEnumDefinition(dataNode)) {
561 returnType = referencedTypes.get(dataNode.getPath());
562 } else if (leafListContainsEnumDefinition(dataNode)) {
563 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
565 returnType = resolveTypeFromDataSchemaNode(dataNode);
568 returnType = Types.typeForClass(Object.class);
571 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
572 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
577 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
578 * so then checks if it is of type <code>EnumTypeDefinition</code>.
581 * data schema node for which is checked if it is leaf and if it
583 * @return boolean value
585 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
586 * <li>false - other cases</li>
589 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
590 if (dataNode instanceof LeafSchemaNode) {
591 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
592 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
600 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
601 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
604 * data schema node for which is checked if it is leaflist and if
606 * @return boolean value
608 * <li>true - if <code>dataNode</code> is leaflist of type
610 * <li>false - other cases</li>
613 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
614 if (dataNode instanceof LeafListSchemaNode) {
615 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
616 if (leafList.getType() instanceof EnumTypeDefinition) {
624 * Converts <code>enumTypeDef</code> to
629 * enumeration type definition which is converted to enumeration
631 * string with name which is used as the enumeration name
632 * @return enumeration type which is built with data (name, enum values)
633 * from <code>enumTypeDef</code>
634 * @throws IllegalArgumentException
636 * <li>if <code>enumTypeDef</code> equals null</li>
637 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
638 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
639 * <li>if name of <code>enumTypeDef</code> equal null</li>
642 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
643 final SchemaNode parentNode) {
644 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
645 Preconditions.checkArgument(enumTypeDef.getValues() != null,
646 "EnumTypeDefinition MUST contain at least ONE value definition!");
647 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
648 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
649 "Local Name in EnumTypeDefinition QName cannot be NULL!");
651 final String enumerationName = BindingMapping.getClassName(enumName);
653 final Module module = findParentModule(schemaContext, parentNode);
654 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
656 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
657 addEnumDescription(enumBuilder, enumTypeDef);
658 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
659 enumBuilder.setModuleName(module.getName());
660 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
661 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
662 return enumBuilder.toInstance(null);
666 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
667 * taken from <code>enumTypeDef</code>.
670 * enumeration type definition is source of enumeration data for
671 * <code>typeBuilder</code>
673 * string with the name of enumeration
675 * generated type builder to which is enumeration added
676 * @return enumeration type which contains enumeration data form
677 * <code>enumTypeDef</code>
678 * @throws IllegalArgumentException
680 * <li>if <code>enumTypeDef</code> equals null</li>
681 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
682 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
683 * <li>if name of <code>enumTypeDef</code> equal null</li>
684 * <li>if name of <code>typeBuilder</code> equal null</li>
688 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
689 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
690 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
691 Preconditions.checkArgument(enumTypeDef.getValues() != null,
692 "EnumTypeDefinition MUST contain at least ONE value definition!");
693 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
694 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
695 "Local Name in EnumTypeDefinition QName cannot be NULL!");
696 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
698 final String enumerationName = BindingMapping.getClassName(enumName);
700 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
702 addEnumDescription(enumBuilder, enumTypeDef);
703 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
704 return enumBuilder.toInstance(enumBuilder);
707 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
709 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
712 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
715 * contains information about YANG type
716 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
718 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
719 Type returnType = null;
720 if (dataNode != null) {
721 if (dataNode instanceof LeafSchemaNode) {
722 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
723 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
724 returnType = javaTypeForSchemaDefinitionType(type, leaf);
725 } else if (dataNode instanceof LeafListSchemaNode) {
726 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
727 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
734 * Passes through all modules and through all its type definitions and
735 * convert it to generated types.
737 * The modules are firstly sorted by mutual dependencies. The modules are
738 * sequentially passed. All type definitions of a module are at the
739 * beginning sorted so that type definition with less amount of references
740 * to other type definition are processed first.<br />
741 * For each module is created mapping record in the map
742 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
743 * which map current module name to the map which maps type names to
744 * returned types (generated types).
747 private void resolveTypeDefsFromContext() {
748 final Set<Module> modules = schemaContext.getModules();
749 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
750 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
752 for (Module module : modulesSortedByDependency) {
753 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
754 if (dateTypeMap == null) {
755 dateTypeMap = new HashMap<>();
757 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
758 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
761 for (Module module : modulesSortedByDependency) {
762 if (module != null) {
763 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
764 if (basePackageName != null) {
765 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
766 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
767 typedefToGeneratedType(basePackageName, module, typedef);
776 * @param basePackageName
777 * string with name of package to which the module belongs
779 * string with the name of the module for to which the
780 * <code>typedef</code> belongs
782 * type definition of the node for which should be creted JAVA
783 * <code>Type</code> (usually generated TO)
784 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
785 * <code>null</code> value if <code>basePackageName</code> or
786 * <code>modulName</code> or <code>typedef</code> or Q name of
787 * <code>typedef</code> equals <code>null</code>
789 private Type typedefToGeneratedType(final String basePackageName, final Module module, final TypeDefinition<?> typedef) {
790 final String moduleName = module.getName();
791 final Optional<Revision> moduleRevision = module.getRevision();
792 if (basePackageName != null && moduleName != null && typedef != null && typedef.getQName() != null) {
793 final String typedefName = typedef.getQName().getLocalName();
794 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
795 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
796 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
797 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
798 Type returnType = null;
799 if (innerTypeDefinition.getBaseType() != null) {
800 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName, module.getName());
801 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
802 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
803 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
804 genTOBuilder.setTypedef(true);
805 genTOBuilder.setIsUnion(true);
806 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
807 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
808 returnType = genTOBuilder.toInstance();
810 final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
811 genTOBuilder.getName() + "Builder");
812 unionBuilder.setIsUnionBuilder(true);
813 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
814 method.setReturnType(returnType);
815 method.addParameter(Types.STRING, "defaultValue");
816 method.setAccessModifier(AccessModifier.PUBLIC);
817 method.setStatic(true);
818 Set<Type> types = additionalTypes.get(module);
820 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
821 additionalTypes.put(module, types);
823 types.add(unionBuilder.toInstance());
825 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
826 // enums are automatically Serializable
827 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
828 // TODO units for typedef enum
829 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
830 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
831 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
832 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
833 basePackageName, bitsTypeDefinition, typedefName, module.getName());
834 genTOBuilder.setTypedef(true);
835 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
836 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
837 returnType = genTOBuilder.toInstance();
839 final Type javaType = javaTypeForSchemaDefinitionType(innerTypeDefinition, typedef);
840 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
842 if (returnType != null) {
843 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
844 genTypeDefsContextMap.get(moduleName);
845 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
846 if (typeMap != null) {
847 if (typeMap.isEmpty()) {
848 typeMap = new HashMap<>(4);
849 modulesByDate.put(moduleRevision, typeMap);
851 typeMap.put(typedefName, returnType);
861 * Wraps base YANG type to generated TO.
863 * @param basePackageName
864 * string with name of package to which the module belongs
866 * type definition which is converted to the TO
868 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
869 * @return generated transfer object which represent<code>javaType</code>
871 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
872 final Type javaType, final String moduleName) {
873 Preconditions.checkNotNull(javaType, "javaType cannot be null");
874 final String propertyName = "value";
876 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
877 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
878 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
879 genPropBuilder.setReturnType(javaType);
880 genTOBuilder.addEqualsIdentity(genPropBuilder);
881 genTOBuilder.addHashIdentity(genPropBuilder);
882 genTOBuilder.addToStringProperty(genPropBuilder);
883 if (typedef.getStatus() == Status.DEPRECATED) {
884 genTOBuilder.addAnnotation("", "Deprecated");
886 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
887 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
889 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
890 genTOBuilder.setTypedef(true);
891 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
892 return genTOBuilder.toInstance();
896 * Converts output list of generated TO builders to one TO builder (first
897 * from list) which contains the remaining builders as its enclosing TO.
899 * @param basePackageName
900 * string with name of package to which the module belongs
902 * type definition which should be of type
903 * <code>UnionTypeDefinition</code>
905 * string with name for generated TO
906 * @return generated TO builder with the list of enclosed generated TO
909 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
910 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
911 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
912 typedef, typeDefName, parentNode);
913 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
915 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
916 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
918 resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
919 return resultTOBuilder;
923 * Converts <code>typedef</code> to generated TO with
924 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
925 * added to generated TO builder as property.
927 * @param basePackageName
928 * string with name of package to which the module belongs
930 * type definition which should be of type
931 * <code>UnionTypeDefinition</code>
933 * string with name for generated TO
934 * @return generated TO builder which represents <code>typedef</code>
935 * @throws NullPointerException
937 * <li>if <code>basePackageName</code> is null</li>
938 * <li>if <code>typedef</code> is null</li>
939 * <li>if Qname of <code>typedef</code> is null</li>
942 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
943 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
944 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
945 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
946 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
948 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
949 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
950 final Module module = findParentModule(schemaContext, parentNode);
952 final GeneratedTOBuilderImpl unionGenTOBuilder;
953 if (typeDefName != null && !typeDefName.isEmpty()) {
954 final String typeName = BindingMapping.getClassName(typeDefName);
955 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
956 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
957 unionGenTOBuilder.setModuleName(module.getName());
958 addCodegenInformation(unionGenTOBuilder, typedef);
960 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
963 generatedTOBuilders.add(unionGenTOBuilder);
964 unionGenTOBuilder.setIsUnion(true);
966 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
967 // also negation information and hence guarantees uniqueness.
968 final Map<String, String> expressions = new HashMap<>();
969 for (TypeDefinition<?> unionType : unionTypes) {
970 final String unionTypeName = unionType.getQName().getLocalName();
972 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
973 // do not follow type encapsulation -- we use the general case for that.
974 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
975 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
976 } else if (unionType instanceof UnionTypeDefinition) {
977 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
978 (UnionTypeDefinition) unionType, basePackageName, parentNode));
979 } else if (unionType instanceof EnumTypeDefinition) {
980 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
981 unionTypeName, unionGenTOBuilder);
982 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
984 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
985 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
988 addStringRegExAsConstant(unionGenTOBuilder, expressions);
990 storeGenTO(typedef, unionGenTOBuilder, parentNode);
992 return generatedTOBuilders;
996 * Wraps code which handle case when union subtype is also of the type
997 * <code>UnionType</code>.
999 * In this case the new generated TO is created for union subtype (recursive
1001 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
1002 * String, SchemaNode)}
1003 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
1004 * <code>parentUnionGenTOBuilder</code> is created property which type is
1005 * equal to new generated TO.
1007 * @param parentUnionGenTOBuilder
1008 * generated TO builder to which is the property with the child
1009 * union subtype added
1010 * @param basePackageName
1011 * string with the name of the module package
1012 * @param unionSubtype
1013 * type definition which represents union subtype
1014 * @return list of generated TO builders. The number of the builders can be
1015 * bigger one due to recursive call of
1016 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
1018 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1019 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
1020 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
1021 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1022 basePackageName, unionSubtype, newTOBuilderName, parentNode);
1024 final GeneratedPropertyBuilder propertyBuilder;
1025 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
1026 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
1027 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1028 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1030 return subUnionGenTOBUilders;
1034 * Wraps code which handle case when union subtype is of the type
1035 * <code>ExtendedType</code>.
1037 * If TO for this type already exists it is used for the creation of the
1038 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1039 * type is used for the property creation.
1041 * @param parentUnionGenTOBuilder
1042 * generated TO builder in which new property is created
1043 * @param unionSubtype
1044 * type definition of the <code>ExtendedType</code> type which
1045 * represents union subtype
1046 * @param expressions
1047 * list of strings with the regular expressions
1049 * parent Schema Node for Extended Subtype
1052 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1053 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1054 final String unionTypeName = unionSubtype.getQName().getLocalName();
1055 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1056 if (genTO != null) {
1057 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1061 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1062 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1063 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1065 if (javaType != null) {
1066 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1068 } else if (baseType instanceof LeafrefTypeDefinition) {
1069 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1070 boolean typeExist = false;
1071 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1072 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1073 if (origType != null && javaType != null && javaType == origType) {
1078 if (!typeExist && javaType != null) {
1079 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1080 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1083 if (baseType instanceof StringTypeDefinition) {
1084 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1089 * Searches for generated TO for <code>searchedTypeDef</code> type
1090 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1092 * @param searchedTypeName
1093 * string with name of <code>searchedTypeDef</code>
1094 * @return generated TO for <code>searchedTypeDef</code> or
1095 * <code>null</code> it it doesn't exist
1097 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1098 final Module typeModule = findParentModule(schemaContext, parentNode);
1099 if (typeModule != null && typeModule.getName() != null) {
1100 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1101 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1102 if (genTOs != null) {
1103 return genTOs.get(searchedTypeName);
1110 * Stores generated TO created from <code>genTOBuilder</code> for
1111 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1112 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1115 * type definition for which is <code>genTOBuilder</code> created
1116 * @param genTOBuilder
1117 * generated TO builder which is converted to generated TO and
1120 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1121 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1122 final Module parentModule = findParentModule(schemaContext, parentNode);
1123 if (parentModule != null && parentModule.getName() != null) {
1124 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1125 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1126 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1132 * Adds a new property with the name <code>propertyName</code> and with type
1133 * <code>type</code> to <code>unonGenTransObject</code>.
1135 * @param unionGenTransObject
1136 * generated TO to which should be property added
1138 * JAVA <code>type</code> of the property which should be added
1139 * to <code>unionGentransObject</code>
1140 * @param propertyName
1141 * string with name of property which should be added to
1142 * <code>unionGentransObject</code>
1144 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1145 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1146 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1147 .addProperty(BindingMapping.getPropertyName(propertyName));
1148 propBuilder.setReturnType(type);
1150 unionGenTransObject.addEqualsIdentity(propBuilder);
1151 unionGenTransObject.addHashIdentity(propBuilder);
1152 unionGenTransObject.addToStringProperty(propBuilder);
1157 * Converts <code>typedef</code> to the generated TO builder.
1159 * @param basePackageName
1160 * string with name of package to which the module belongs
1162 * type definition from which is the generated TO builder created
1163 * @return generated TO builder which contains data from
1164 * <code>typedef</code> and <code>basePackageName</code>
1166 private GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName,
1167 final TypeDefinition<?> typedef, final String moduleName) {
1169 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1170 final String typeDefTOName = typedef.getQName().getLocalName();
1172 if (packageName != null && typeDefTOName != null) {
1173 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1174 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1175 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1176 newType.setModuleName(moduleName);
1177 addCodegenInformation(newType, typedef);
1184 * Converts <code>typeDef</code> which should be of the type
1185 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1187 * All the bits of the typeDef are added to returning generated TO as
1190 * @param basePackageName
1191 * string with name of package to which the module belongs
1193 * type definition from which is the generated TO builder created
1194 * @param typeDefName
1195 * string with the name for generated TO builder
1196 * @return generated TO builder which represents <code>typeDef</code>
1197 * @throws IllegalArgumentException
1199 * <li>if <code>typeDef</code> equals null</li>
1200 * <li>if <code>basePackageName</code> equals null</li>
1203 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1204 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1206 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1207 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1209 if (typeDef instanceof BitsTypeDefinition) {
1210 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1212 final String typeName = BindingMapping.getClassName(typeDefName);
1213 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1214 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1215 genTOBuilder.setModuleName(moduleName);
1216 genTOBuilder.setBaseType(typeDef);
1217 addCodegenInformation(genTOBuilder, typeDef);
1219 final List<Bit> bitList = bitsTypeDefinition.getBits();
1220 GeneratedPropertyBuilder genPropertyBuilder;
1221 for (Bit bit : bitList) {
1222 final String name = bit.getName();
1223 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1224 genPropertyBuilder.setReadOnly(true);
1225 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1227 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1228 genTOBuilder.addHashIdentity(genPropertyBuilder);
1229 genTOBuilder.addToStringProperty(genPropertyBuilder);
1232 return genTOBuilder;
1238 * Converts the pattern constraints from <code>typedef</code> to the list of
1239 * the strings which represents these constraints.
1242 * extended type in which are the pattern constraints sought
1243 * @return list of strings which represents the constraint patterns
1244 * @throws IllegalArgumentException
1245 * if <code>typedef</code> equals null
1248 private static Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1249 if (!(typedef instanceof StringTypeDefinition)) {
1250 return ImmutableMap.of();
1253 // TODO: run diff against base ?
1254 final List<PatternConstraint> patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1255 final Map<String, String> regExps = Maps.newHashMapWithExpectedSize(patternConstraints.size());
1256 for (PatternConstraint patternConstraint : patternConstraints) {
1257 String regEx = patternConstraint.getJavaPatternString();
1259 // The pattern can be inverted
1260 final Optional<ModifierKind> optModifier = patternConstraint.getModifier();
1261 if (optModifier.isPresent()) {
1262 regEx = applyModifier(optModifier.get(), regEx);
1265 regExps.put(regEx, patternConstraint.getRegularExpressionString());
1271 private static String applyModifier(final ModifierKind modifier, final String pattern) {
1274 return BindingMapping.negatePatternString(pattern);
1276 LOG.warn("Ignoring unhandled modifier {}", modifier);
1283 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1284 * expressions from the <code>regularExpressions</code>
1286 * @param genTOBuilder
1287 * generated TO builder to which are
1288 * <code>regular expressions</code> added
1289 * @param expressions
1290 * list of string which represent regular expressions
1292 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1293 final Map<String, String> expressions) {
1294 if (!expressions.isEmpty()) {
1295 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1296 ImmutableMap.copyOf(expressions));
1301 * Creates generated TO with data about inner extended type
1302 * <code>innerExtendedType</code>, about the package name
1303 * <code>typedefName</code> and about the generated TO name
1304 * <code>typedefName</code>.
1306 * It is supposed that <code>innerExtendedType</code> is already present in
1307 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1308 * be possible set it as extended type for the returning generated TO.
1312 * @param innerExtendedType
1313 * extended type which is part of some other extended type
1314 * @param basePackageName
1315 * string with the package name of the module
1318 * @return generated TO which extends generated TO for
1319 * <code>innerExtendedType</code>
1320 * @throws IllegalArgumentException
1322 * <li>if <code>extendedType</code> equals null</li>
1323 * <li>if <code>basePackageName</code> equals null</li>
1324 * <li>if <code>typedefName</code> equals null</li>
1327 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1328 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1329 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1331 final String typedefName = typedef.getQName().getLocalName();
1332 final String classTypedefName = BindingMapping.getClassName(typedefName);
1333 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1334 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1335 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1336 genTOBuilder.setModuleName(moduleName);
1337 genTOBuilder.setTypedef(true);
1338 addCodegenInformation(genTOBuilder, typedef);
1340 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1341 genTOBuilder.setRestrictions(r);
1342 if (typedef.getStatus() == Status.DEPRECATED) {
1343 genTOBuilder.addAnnotation("", "Deprecated");
1346 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1347 genTOBuilder.setIsUnion(true);
1350 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1351 Map<String, Type> typeMap = null;
1352 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1353 if (parentModule != null) {
1354 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1355 typeMap = modulesByDate.get(parentModule.getRevision());
1358 if (typeMap != null) {
1359 final Type type = typeMap.get(innerTypeDef);
1360 if (type instanceof GeneratedTransferObject) {
1361 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1364 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1365 makeSerializable(genTOBuilder);
1367 return genTOBuilder.toInstance();
1371 * Add {@link Serializable} to implemented interfaces of this TO. Also
1372 * compute and add serialVersionUID property.
1375 * transfer object which needs to be serializable
1377 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1378 gto.addImplementsType(Types.typeForClass(Serializable.class));
1379 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1380 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1385 * Finds out for each type definition how many immersion (depth) is
1386 * necessary to get to the base type. Every type definition is inserted to
1387 * the map which key is depth and value is list of type definitions with
1388 * equal depth. In next step are lists from this map concatenated to one
1389 * list in ascending order according to their depth. All type definitions
1390 * are in the list behind all type definitions on which depends.
1392 * @param unsortedTypeDefinitions
1393 * list of type definitions which should be sorted by depth
1394 * @return list of type definitions sorted according their each other
1395 * dependencies (type definitions which are depend on other type
1396 * definitions are in list behind them).
1398 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1399 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1400 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1402 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1403 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1404 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1405 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1406 if (typeDefinitionsConcreteDepth == null) {
1407 typeDefinitionsConcreteDepth = new ArrayList<>();
1408 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1410 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1413 // SortedMap guarantees order corresponding to keys in ascending order
1414 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1415 sortedTypeDefinition.addAll(v);
1418 return sortedTypeDefinition;
1422 * Returns how many immersion is necessary to get from the type definition
1425 * @param typeDefinition
1426 * type definition for which is depth sought.
1427 * @return number of immersions which are necessary to get from the type
1428 * definition to the base type
1430 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1431 // FIXME: rewrite this in a non-recursive manner
1432 if (typeDefinition == null) {
1435 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1436 if (baseType == null) {
1441 if (baseType.getBaseType() != null) {
1442 depth = depth + getTypeDefinitionDepth(baseType);
1443 } else if (baseType instanceof UnionTypeDefinition) {
1444 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1445 int maxChildDepth = 0;
1447 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1448 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1449 if (childDepth > maxChildDepth) {
1450 maxChildDepth = childDepth;
1453 return maxChildDepth;
1459 * Returns string which contains the same value as <code>name</code> but
1460 * integer suffix is incremented by one. If <code>name</code> contains no
1461 * number suffix then number 1 is added.
1464 * string with name of augmented node
1465 * @return string with the number suffix incremented by one (or 1 is added)
1467 private static String provideAvailableNameForGenTOBuilder(final String name) {
1468 final Matcher mtch = NUMBERS_PATTERN.matcher(name);
1470 final int newSuffix = Integer.parseInt(name.substring(mtch.start())) + 1;
1471 return name.substring(0, mtch.start()) + newSuffix;
1477 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1478 if (!Strings.isNullOrEmpty(units)) {
1479 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1480 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1481 prop.setReturnType(Types.STRING);
1482 to.addToStringProperty(prop);
1487 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1488 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1491 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1492 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1493 final QName typeQName = type.getQName();
1494 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1495 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1496 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1499 final StringBuilder sb = new StringBuilder();
1500 String result = null;
1501 if (base instanceof BinaryTypeDefinition) {
1502 result = binaryToDef(defaultValue);
1503 } else if (base instanceof BitsTypeDefinition) {
1506 final Module parent = getParentModule(node);
1507 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1509 if (!path.hasNext()) {
1510 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1511 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1512 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1514 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1515 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1516 parentName = BindingMapping.getClassName(parent.getName());
1517 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1519 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1520 } else if (base instanceof BooleanTypeDefinition) {
1521 result = typeToBooleanDef(defaultValue);
1522 } else if (base instanceof DecimalTypeDefinition) {
1523 result = typeToDef(BigDecimal.class, defaultValue);
1524 } else if (base instanceof EmptyTypeDefinition) {
1525 result = typeToBooleanDef(defaultValue);
1526 } else if (base instanceof EnumTypeDefinition) {
1527 final char[] defValArray = defaultValue.toCharArray();
1528 final char first = Character.toUpperCase(defaultValue.charAt(0));
1529 defValArray[0] = first;
1530 final String newDefVal = new String(defValArray);
1532 if (type.getBaseType() != null) {
1533 final Module m = getParentModule(type);
1534 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1535 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1536 className = packageName + "." + BindingMapping.getClassName(typeQName);
1538 final Module parentModule = getParentModule(node);
1539 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1540 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1541 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1543 result = className + "." + newDefVal;
1544 } else if (base instanceof IdentityrefTypeDefinition) {
1545 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1546 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1547 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1548 } else if (BaseTypes.isInt8(base)) {
1549 result = typeToValueOfDef(Byte.class, defaultValue);
1550 } else if (BaseTypes.isInt16(base)) {
1551 result = typeToValueOfDef(Short.class, defaultValue);
1552 } else if (BaseTypes.isInt32(base)) {
1553 result = typeToValueOfDef(Integer.class, defaultValue);
1554 } else if (BaseTypes.isInt64(base)) {
1555 result = typeToValueOfDef(Long.class, defaultValue);
1556 } else if (base instanceof LeafrefTypeDefinition) {
1557 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1558 } else if (base instanceof StringTypeDefinition) {
1559 result = "\"" + defaultValue + "\"";
1560 } else if (BaseTypes.isUint8(base)) {
1561 result = typeToValueOfDef(Short.class, defaultValue);
1562 } else if (BaseTypes.isUint16(base)) {
1563 result = typeToValueOfDef(Integer.class, defaultValue);
1564 } else if (BaseTypes.isUint32(base)) {
1565 result = typeToValueOfDef(Long.class, defaultValue);
1566 } else if (BaseTypes.isUint64(base)) {
1567 switch (defaultValue) {
1569 result = "java.math.BigInteger.ZERO";
1572 result = "java.math.BigInteger.ONE";
1575 result = "java.math.BigInteger.TEN";
1578 result = typeToDef(BigInteger.class, defaultValue);
1580 } else if (base instanceof UnionTypeDefinition) {
1581 result = unionToDef(node);
1587 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1588 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1589 final Module m = getParentModule(type);
1590 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1591 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1592 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1593 sb.insert(0, "new " + className + "(");
1594 sb.insert(sb.length(), ')');
1597 return sb.toString();
1600 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1601 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1604 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1605 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1608 private static String typeToBooleanDef(final String defaultValue) {
1609 switch (defaultValue) {
1611 return "java.lang.Boolean.FALSE";
1613 return "java.lang.Boolean.TRUE";
1615 return typeToValueOfDef(Boolean.class, defaultValue);
1619 private static String binaryToDef(final String defaultValue) {
1620 final StringBuilder sb = new StringBuilder();
1621 final BaseEncoding en = BaseEncoding.base64();
1622 final byte[] encoded = en.decode(defaultValue);
1623 sb.append("new byte[] {");
1624 for (int i = 0; i < encoded.length; i++) {
1625 sb.append(encoded[i]);
1626 if (i != encoded.length - 1) {
1631 return sb.toString();
1634 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1636 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1637 final List<Bit> bits = new ArrayList<>(type.getBits());
1638 Collections.sort(bits, BIT_NAME_COMPARATOR);
1639 final StringBuilder sb = new StringBuilder();
1642 sb.append(className);
1645 for (int i = 0; i < bits.size(); i++) {
1646 if (bits.get(i).getName().equals(defaultValue)) {
1651 if (i != bits.size() - 1) {
1658 return sb.toString();
1661 private Module getParentModule(final SchemaNode node) {
1662 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1663 return schemaContext.findModule(qname.getModule()).orElse(null);
1666 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1667 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1668 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1669 "The Path Statement for Leafref Type Definition cannot be NULL!");
1671 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1672 final String strXPath = xpath.toString();
1674 if (strXPath != null) {
1675 if (strXPath.indexOf('[') == -1) {
1676 final Module module = findParentModule(schemaContext, parentNode);
1677 if (module != null) {
1678 final SchemaNode dataNode;
1679 if (xpath.isAbsolute()) {
1680 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1682 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1684 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1688 return "new java.lang.Object()";
1695 private String unionToDef(final LeafSchemaNode node) {
1696 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1700 if (type.getBaseType() != null) {
1701 final QName typeQName = type.getQName();
1702 Module module = null;
1703 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1704 if (modules.size() > 1) {
1705 for (Module m : modules) {
1706 if (m.getRevision().equals(typeQName.getRevision())) {
1711 if (module == null) {
1712 final List<Module> modulesList = new ArrayList<>(modules);
1713 Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1714 module = modulesList.get(0);
1717 module = modules.iterator().next();
1720 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1721 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1723 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1724 final QName first = path.next();
1725 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1726 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1727 if (!path.hasNext()) {
1728 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1729 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1731 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1732 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1735 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1738 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1739 final StringBuilder sb = new StringBuilder();
1741 sb.append(className);
1743 sb.append(defaultValue);
1744 sb.append("\".toCharArray())");
1745 return sb.toString();
1749 public String getConstructorPropertyName(final SchemaNode node) {
1750 return node instanceof TypeDefinition<?> ? "value" : "";
1754 public String getParamNameFromType(final TypeDefinition<?> type) {
1755 return BindingMapping.getPropertyName(type.getQName().getLocalName());