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.Sets;
19 import com.google.common.io.BaseEncoding;
20 import java.io.Serializable;
21 import java.math.BigDecimal;
22 import java.math.BigInteger;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.Collections;
26 import java.util.Comparator;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
31 import java.util.Optional;
33 import java.util.TreeMap;
34 import java.util.regex.Matcher;
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.Restrictions;
43 import org.opendaylight.mdsal.binding.model.api.Type;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.EnumBuilder;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedPropertyBuilder;
46 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTOBuilder;
47 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
49 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
50 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
51 import org.opendaylight.mdsal.binding.model.util.Types;
52 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.EnumerationBuilderImpl;
53 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
54 import org.opendaylight.yangtools.yang.binding.BindingMapping;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.Revision;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.Module;
63 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
65 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
67 import org.opendaylight.yangtools.yang.model.api.Status;
68 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
69 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
72 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
82 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
83 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
84 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
85 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
86 import org.slf4j.Logger;
87 import org.slf4j.LoggerFactory;
90 public abstract class AbstractTypeProvider implements TypeProvider {
91 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
92 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
93 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
95 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
96 // the case, as unions are emitted to their correct schema path.
97 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
98 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
101 * Contains the schema data red from YANG files.
103 private final SchemaContext schemaContext;
106 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
108 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
111 * The map which maps schema paths to JAVA <code>Type</code>.
113 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
114 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
117 * Creates new instance of class <code>TypeProviderImpl</code>.
119 * @param schemaContext
120 * contains the schema data red from YANG files
121 * @throws IllegalArgumentException
122 * if <code>schemaContext</code> equal null.
124 AbstractTypeProvider(final SchemaContext schemaContext) {
125 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
127 this.schemaContext = schemaContext;
128 resolveTypeDefsFromContext();
132 * Puts <code>refType</code> to map with key <code>refTypePath</code>
135 * schema path used as the map key
137 * type which represents the map value
138 * @throws IllegalArgumentException
140 * <li>if <code>refTypePath</code> equal null</li>
141 * <li>if <code>refType</code> equal null</li>
145 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
146 Preconditions.checkArgument(refTypePath != null,
147 "Path reference of Enumeration Type Definition cannot be NULL!");
148 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
149 referencedTypes.put(refTypePath, refType);
152 public Map<Module, Set<Type>> getAdditionalTypes() {
153 return additionalTypes;
158 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
161 * string with YANG name of type
162 * @return JAVA <code>Type</code> for YANG type <code>type</code>
163 * @see TypeProvider#javaTypeForYangType(String)
167 public Type javaTypeForYangType(final String type) {
168 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
172 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
173 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
177 * Converts schema definition type <code>typeDefinition</code> to JAVA
180 * @param typeDefinition
181 * type definition which is converted to JAVA type
182 * @throws IllegalArgumentException
184 * <li>if <code>typeDefinition</code> equal null</li>
185 * <li>if Qname of <code>typeDefinition</code> equal null</li>
186 * <li>if name of <code>typeDefinition</code> equal null</li>
190 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
191 final Restrictions r) {
192 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
193 Preconditions.checkArgument(typeDefinition.getQName() != null,
194 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
195 final String typedefName = typeDefinition.getQName().getLocalName();
196 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
198 // Deal with base types
199 if (typeDefinition.getBaseType() == null) {
200 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
201 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
202 // a base type which holds these constraints.
203 if (typeDefinition instanceof DecimalTypeDefinition) {
204 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
211 // Deal with leafrefs/identityrefs
212 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
217 // FIXME: it looks as though we could be using the same codepath as above...
218 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
220 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
226 Type returnType = javaTypeForExtendedType(typeDefinition);
227 if (r != null && returnType instanceof GeneratedTransferObject) {
228 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
229 final Module module = findParentModule(schemaContext, parentNode);
230 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
231 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
232 typeDefinition.getPath());
233 final String genTOName = BindingMapping.getClassName(typedefName);
234 final String name = packageName + "." + genTOName;
235 if (!returnType.getFullyQualifiedName().equals(name)) {
236 returnType = shadedTOWithRestrictions(gto, r);
242 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
243 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getPackageName(), gto.getName());
244 final GeneratedTransferObject parent = gto.getSuperType();
245 if (parent != null) {
246 gtob.setExtendsType(parent);
248 gtob.setRestrictions(r);
249 for (GeneratedProperty gp : gto.getProperties()) {
250 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
251 gpb.setValue(gp.getValue());
252 gpb.setReadOnly(gp.isReadOnly());
253 gpb.setAccessModifier(gp.getAccessModifier());
254 gpb.setReturnType(gp.getReturnType());
255 gpb.setFinal(gp.isFinal());
256 gpb.setStatic(gp.isStatic());
258 return gtob.toInstance();
261 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
262 final SchemaNode leafRefValueNode;
263 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
264 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(
265 GROUPS_PATTERN.matcher(leafRefXPath.toString()).replaceAll(""), leafRefXPath.isAbsolute());
267 ///// skip leafrefs in augments - they're checked once augments are resolved
268 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
269 boolean isAugmenting = false;
270 DataNodeContainer current = null;
271 DataSchemaNode dataChildByName;
273 while (iterator.hasNext() && !isAugmenting) {
274 final QName next = iterator.next();
275 if (current == null) {
276 dataChildByName = schemaContext.getDataChildByName(next);
278 dataChildByName = current.getDataChildByName(next);
280 if (dataChildByName != null) {
281 isAugmenting = dataChildByName.isAugmenting();
285 if (dataChildByName instanceof DataNodeContainer) {
286 current = (DataNodeContainer) dataChildByName;
294 final Module parentModule = getParentModule(parentNode);
295 if (!leafRefStrippedXPath.isAbsolute()) {
296 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
297 parentNode, leafRefStrippedXPath);
299 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
301 return leafRefValueNode != null ? leafRefValueNode.equals(parentNode) : false;
305 * Returns JAVA <code>Type</code> for instances of the type
306 * <code>LeafrefTypeDefinition</code> or
307 * <code>IdentityrefTypeDefinition</code>.
309 * @param typeDefinition
310 * type definition which is converted to JAVA <code>Type</code>
311 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
313 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
314 if (typeDefinition instanceof LeafrefTypeDefinition) {
315 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
316 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
317 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
318 return provideTypeForLeafref(leafref, parentNode);
319 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
320 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
327 * Returns JAVA <code>Type</code> for instances of the type
328 * <code>ExtendedType</code>.
330 * @param typeDefinition
331 * type definition which is converted to JAVA <code>Type</code>
332 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
334 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
335 final String typedefName = typeDefinition.getQName().getLocalName();
336 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
337 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
338 if (returnType == null) {
339 if (baseTypeDef instanceof EnumTypeDefinition) {
340 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
341 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
343 final Module module = findParentModule(schemaContext, typeDefinition);
344 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
345 if (module != null) {
346 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
348 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
349 if (genTOs != null) {
350 returnType = genTOs.get(typedefName);
352 if (returnType == null) {
353 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
354 baseTypeDef, typeDefinition, r);
363 * Seeks for identity reference <code>idref</code> the JAVA
364 * <code>type</code>.<br />
368 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
369 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
372 * identityref type definition for which JAVA <code>Type</code>
374 * @return JAVA <code>Type</code> of the identity which is referenced through
377 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
378 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
379 if (identities.size() > 1) {
380 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
383 final QName baseIdQName = identities.iterator().next().getQName();
384 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
385 IdentitySchemaNode identity = null;
386 for (IdentitySchemaNode id : module.getIdentities()) {
387 if (id.getQName().equals(baseIdQName)) {
391 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
393 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
394 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
396 final String genTypeName = BindingMapping.getClassName(identity.getQName());
398 final Type baseType = Types.typeForClass(Class.class);
399 final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
400 return Types.parameterizedTypeFor(baseType, paramType);
404 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
406 * @param typeDefinition
407 * type definition which should be converted to JAVA
409 * @return JAVA <code>Type</code> which represents
410 * <code>typeDefinition</code>
411 * @throws IllegalArgumentException
413 * <li>if <code>typeDefinition</code> equal null</li>
414 * <li>if Q name of <code>typeDefinition</code></li>
415 * <li>if name of <code>typeDefinition</code></li>
418 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
419 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
420 if (typeDefinition.getQName() == null) {
421 throw new IllegalArgumentException(
422 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
424 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
425 "Type Definitions Local Name cannot be NULL!");
427 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
428 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
430 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
431 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
444 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
445 * dicey when we throw in:
459 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
460 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
463 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
464 * an encapsulation for identityref typedefs.
466 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
467 * option, as it would look as though it is the product of a different construct:
473 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
474 * sub-identities of iden.
476 * The story behind leafrefs is probably similar, but that needs to be ascertained.
481 final Module module = findParentModule(schemaContext, parentNode);
482 if (module != null) {
483 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
485 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
486 if (genTOs != null) {
487 return genTOs.get(typeDefinition.getQName().getLocalName());
494 * Gets base type definition for <code>extendTypeDef</code>. The method is
495 * recursively called until non <code>ExtendedType</code> type is found.
497 * @param extendTypeDef
498 * type definition for which is the base type definition sought
499 * @return type definition which is base type for <code>extendTypeDef</code>
500 * @throws IllegalArgumentException
501 * if <code>extendTypeDef</code> equal null
503 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
504 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
506 TypeDefinition<?> ret = extendTypeDef;
507 while (ret.getBaseType() != null) {
508 ret = ret.getBaseType();
515 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
517 * The path of <code>leafrefType</code> is followed to find referenced node
518 * and its <code>Type</code> is returned.
521 * leafref type definition for which is the type sought
522 * @return JAVA <code>Type</code> of data schema node which is referenced in
523 * <code>leafrefType</code>
524 * @throws IllegalArgumentException
526 * <li>if <code>leafrefType</code> equal null</li>
527 * <li>if path statement of <code>leafrefType</code> equal null</li>
531 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
532 Type returnType = null;
533 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
535 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
536 "The Path Statement for Leafref Type Definition cannot be NULL!");
538 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
539 final String strXPath = xpath.toString();
541 if (strXPath != null) {
542 if (strXPath.indexOf('[') == -1) {
543 final Module module = findParentModule(schemaContext, parentNode);
544 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
546 final SchemaNode dataNode;
547 if (xpath.isAbsolute()) {
548 dataNode = findDataSchemaNode(schemaContext, module, xpath);
550 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
552 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
553 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
555 if (leafContainsEnumDefinition(dataNode)) {
556 returnType = referencedTypes.get(dataNode.getPath());
557 } else if (leafListContainsEnumDefinition(dataNode)) {
558 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
560 returnType = resolveTypeFromDataSchemaNode(dataNode);
563 returnType = Types.typeForClass(Object.class);
566 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
567 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
572 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
573 * so then checks if it is of type <code>EnumTypeDefinition</code>.
576 * data schema node for which is checked if it is leaf and if it
578 * @return boolean value
580 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
581 * <li>false - other cases</li>
584 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
585 if (dataNode instanceof LeafSchemaNode) {
586 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
587 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
595 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
596 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
599 * data schema node for which is checked if it is leaflist and if
601 * @return boolean value
603 * <li>true - if <code>dataNode</code> is leaflist of type
605 * <li>false - other cases</li>
608 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
609 if (dataNode instanceof LeafListSchemaNode) {
610 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
611 if (leafList.getType() instanceof EnumTypeDefinition) {
619 * Converts <code>enumTypeDef</code> to
624 * enumeration type definition which is converted to enumeration
626 * string with name which is used as the enumeration name
627 * @return enumeration type which is built with data (name, enum values)
628 * from <code>enumTypeDef</code>
629 * @throws IllegalArgumentException
631 * <li>if <code>enumTypeDef</code> equals null</li>
632 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
633 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
634 * <li>if name of <code>enumTypeDef</code> equal null</li>
637 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
638 final SchemaNode parentNode) {
639 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
640 Preconditions.checkArgument(enumTypeDef.getValues() != null,
641 "EnumTypeDefinition MUST contain at least ONE value definition!");
642 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
643 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
644 "Local Name in EnumTypeDefinition QName cannot be NULL!");
646 final String enumerationName = BindingMapping.getClassName(enumName);
648 final Module module = findParentModule(schemaContext, parentNode);
649 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
651 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
652 addEnumDescription(enumBuilder, enumTypeDef);
653 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
654 enumBuilder.setModuleName(module.getName());
655 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
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 String enumerationName = BindingMapping.getClassName(enumName);
695 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
697 addEnumDescription(enumBuilder, enumTypeDef);
698 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
699 return enumBuilder.toInstance(enumBuilder);
702 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
704 public abstract GeneratedTOBuilder newGeneratedTOBuilder(String packageName, String name);
706 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
709 * Converts the pattern constraints from <code>typedef</code> to the list of
710 * the strings which represents these constraints.
713 * extended type in which are the pattern constraints sought
714 * @return list of strings which represents the constraint patterns
715 * @throws IllegalArgumentException
716 * if <code>typedef</code> equals null
719 abstract Map<String, String> resolveRegExpressionsFromTypedef(TypeDefinition<?> typedef);
722 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
725 * contains information about YANG type
726 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
728 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
729 Type returnType = null;
730 if (dataNode != null) {
731 if (dataNode instanceof LeafSchemaNode) {
732 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
733 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
734 returnType = javaTypeForSchemaDefinitionType(type, leaf);
735 } else if (dataNode instanceof LeafListSchemaNode) {
736 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
737 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
744 * Passes through all modules and through all its type definitions and
745 * convert it to generated types.
747 * The modules are firstly sorted by mutual dependencies. The modules are
748 * sequentially passed. All type definitions of a module are at the
749 * beginning sorted so that type definition with less amount of references
750 * to other type definition are processed first.<br />
751 * For each module is created mapping record in the map
752 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
753 * which map current module name to the map which maps type names to
754 * returned types (generated types).
757 private void resolveTypeDefsFromContext() {
758 final Set<Module> modules = schemaContext.getModules();
759 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
760 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
762 for (Module module : modulesSortedByDependency) {
763 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
764 if (dateTypeMap == null) {
765 dateTypeMap = new HashMap<>();
767 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
768 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
771 for (Module module : modulesSortedByDependency) {
772 if (module != null) {
773 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
774 if (basePackageName != null) {
775 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
776 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
777 typedefToGeneratedType(basePackageName, module, typedef);
786 * @param basePackageName
787 * string with name of package to which the module belongs
789 * string with the name of the module for to which the
790 * <code>typedef</code> belongs
792 * type definition of the node for which should be creted JAVA
793 * <code>Type</code> (usually generated TO)
794 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
795 * <code>null</code> value if <code>basePackageName</code> or
796 * <code>modulName</code> or <code>typedef</code> or Q name of
797 * <code>typedef</code> equals <code>null</code>
799 private Type typedefToGeneratedType(final String basePackageName, final Module module,
800 final TypeDefinition<?> typedef) {
801 final String moduleName = module.getName();
802 final Optional<Revision> moduleRevision = module.getRevision();
803 if (basePackageName != null && moduleName != null && typedef != null && typedef.getQName() != null) {
804 final String typedefName = typedef.getQName().getLocalName();
805 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
806 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
807 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
808 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
809 Type returnType = null;
810 if (innerTypeDefinition.getBaseType() != null) {
811 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
813 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
814 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
815 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
816 genTOBuilder.setTypedef(true);
817 genTOBuilder.setIsUnion(true);
818 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
819 makeSerializable(genTOBuilder);
820 returnType = genTOBuilder.toInstance();
822 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(genTOBuilder.getPackageName(),
823 genTOBuilder.getName() + "Builder");
824 unionBuilder.setIsUnionBuilder(true);
825 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
826 method.setReturnType(returnType);
827 method.addParameter(Types.STRING, "defaultValue");
828 method.setAccessModifier(AccessModifier.PUBLIC);
829 method.setStatic(true);
830 Set<Type> types = additionalTypes.get(module);
832 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
833 additionalTypes.put(module, types);
835 types.add(unionBuilder.toInstance());
837 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
838 // enums are automatically Serializable
839 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
840 // TODO units for typedef enum
841 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
842 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
843 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
844 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
845 basePackageName, bitsTypeDefinition, typedefName, module.getName());
846 genTOBuilder.setTypedef(true);
847 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
848 makeSerializable(genTOBuilder);
849 returnType = genTOBuilder.toInstance();
851 final Type javaType = javaTypeForSchemaDefinitionType(innerTypeDefinition, typedef);
852 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
854 if (returnType != null) {
855 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
856 genTypeDefsContextMap.get(moduleName);
857 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
858 if (typeMap != null) {
859 if (typeMap.isEmpty()) {
860 typeMap = new HashMap<>(4);
861 modulesByDate.put(moduleRevision, typeMap);
863 typeMap.put(typedefName, returnType);
873 * Wraps base YANG type to generated TO.
875 * @param basePackageName
876 * string with name of package to which the module belongs
878 * type definition which is converted to the TO
880 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
881 * @return generated transfer object which represent<code>javaType</code>
883 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
884 final Type javaType, final String moduleName) {
885 Preconditions.checkNotNull(javaType, "javaType cannot be null");
886 final String propertyName = "value";
888 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
889 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
890 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
891 genPropBuilder.setReturnType(javaType);
892 genTOBuilder.addEqualsIdentity(genPropBuilder);
893 genTOBuilder.addHashIdentity(genPropBuilder);
894 genTOBuilder.addToStringProperty(genPropBuilder);
895 if (typedef.getStatus() == Status.DEPRECATED) {
896 genTOBuilder.addAnnotation("", "Deprecated");
898 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
899 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
901 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
902 genTOBuilder.setTypedef(true);
903 makeSerializable(genTOBuilder);
904 return genTOBuilder.toInstance();
908 * Converts output list of generated TO builders to one TO builder (first
909 * from list) which contains the remaining builders as its enclosing TO.
911 * @param basePackageName
912 * string with name of package to which the module belongs
914 * type definition which should be of type
915 * <code>UnionTypeDefinition</code>
917 * string with name for generated TO
918 * @return generated TO builder with the list of enclosed generated TO
921 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
922 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
923 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
924 typedef, typeDefName, parentNode);
925 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
927 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
928 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
930 resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
931 return resultTOBuilder;
935 * Converts <code>typedef</code> to generated TO with
936 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
937 * added to generated TO builder as property.
939 * @param basePackageName
940 * string with name of package to which the module belongs
942 * type definition which should be of type
943 * <code>UnionTypeDefinition</code>
945 * string with name for generated TO
946 * @return generated TO builder which represents <code>typedef</code>
947 * @throws NullPointerException
949 * <li>if <code>basePackageName</code> is null</li>
950 * <li>if <code>typedef</code> is null</li>
951 * <li>if Qname of <code>typedef</code> is null</li>
954 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
955 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
956 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
957 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
958 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
960 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
961 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
962 final Module module = findParentModule(schemaContext, parentNode);
964 final GeneratedTOBuilder unionGenTOBuilder;
965 if (typeDefName != null && !typeDefName.isEmpty()) {
966 final String typeName = BindingMapping.getClassName(typeDefName);
967 unionGenTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
968 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
969 unionGenTOBuilder.setModuleName(module.getName());
970 addCodegenInformation(unionGenTOBuilder, typedef);
972 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
975 generatedTOBuilders.add(unionGenTOBuilder);
976 unionGenTOBuilder.setIsUnion(true);
978 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
979 // also negation information and hence guarantees uniqueness.
980 final Map<String, String> expressions = new HashMap<>();
981 for (TypeDefinition<?> unionType : unionTypes) {
982 final String unionTypeName = unionType.getQName().getLocalName();
984 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
985 // do not follow type encapsulation -- we use the general case for that.
986 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
987 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
988 } else if (unionType instanceof UnionTypeDefinition) {
989 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
990 (UnionTypeDefinition) unionType, basePackageName, parentNode));
991 } else if (unionType instanceof EnumTypeDefinition) {
992 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
993 unionTypeName, unionGenTOBuilder);
994 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
996 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
997 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
1000 addStringRegExAsConstant(unionGenTOBuilder, expressions);
1002 storeGenTO(typedef, unionGenTOBuilder, parentNode);
1004 return generatedTOBuilders;
1008 * Wraps code which handle case when union subtype is also of the type
1009 * <code>UnionType</code>.
1011 * In this case the new generated TO is created for union subtype (recursive
1013 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
1014 * String, SchemaNode)}
1015 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
1016 * <code>parentUnionGenTOBuilder</code> is created property which type is
1017 * equal to new generated TO.
1019 * @param parentUnionGenTOBuilder
1020 * generated TO builder to which is the property with the child
1021 * union subtype added
1022 * @param basePackageName
1023 * string with the name of the module package
1024 * @param unionSubtype
1025 * type definition which represents union subtype
1026 * @return list of generated TO builders. The number of the builders can be
1027 * bigger one due to recursive call of
1028 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
1030 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1031 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
1032 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
1033 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1034 basePackageName, unionSubtype, newTOBuilderName, parentNode);
1036 final GeneratedPropertyBuilder propertyBuilder;
1037 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
1038 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
1039 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1040 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1042 return subUnionGenTOBUilders;
1046 * Wraps code which handle case when union subtype is of the type
1047 * <code>ExtendedType</code>.
1049 * If TO for this type already exists it is used for the creation of the
1050 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1051 * type is used for the property creation.
1053 * @param parentUnionGenTOBuilder
1054 * generated TO builder in which new property is created
1055 * @param unionSubtype
1056 * type definition of the <code>ExtendedType</code> type which
1057 * represents union subtype
1058 * @param expressions
1059 * list of strings with the regular expressions
1061 * parent Schema Node for Extended Subtype
1064 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1065 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1066 final String unionTypeName = unionSubtype.getQName().getLocalName();
1067 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1068 if (genTO != null) {
1069 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1073 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1074 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1075 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1077 if (javaType != null) {
1078 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1080 } else if (baseType instanceof LeafrefTypeDefinition) {
1081 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1082 boolean typeExist = false;
1083 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1084 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1085 if (origType != null && javaType != null && javaType == origType) {
1090 if (!typeExist && javaType != null) {
1091 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1092 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1095 if (baseType instanceof StringTypeDefinition) {
1096 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1101 * Searches for generated TO for <code>searchedTypeDef</code> type
1102 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1104 * @param searchedTypeName
1105 * string with name of <code>searchedTypeDef</code>
1106 * @return generated TO for <code>searchedTypeDef</code> or
1107 * <code>null</code> it it doesn't exist
1109 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1110 final Module typeModule = findParentModule(schemaContext, parentNode);
1111 if (typeModule != null && typeModule.getName() != null) {
1112 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1113 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1114 if (genTOs != null) {
1115 return genTOs.get(searchedTypeName);
1122 * Stores generated TO created from <code>genTOBuilder</code> for
1123 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1124 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1127 * type definition for which is <code>genTOBuilder</code> created
1128 * @param genTOBuilder
1129 * generated TO builder which is converted to generated TO and
1132 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1133 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1134 final Module parentModule = findParentModule(schemaContext, parentNode);
1135 if (parentModule != null && parentModule.getName() != null) {
1136 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1137 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1138 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1144 * Adds a new property with the name <code>propertyName</code> and with type
1145 * <code>type</code> to <code>unonGenTransObject</code>.
1147 * @param unionGenTransObject
1148 * generated TO to which should be property added
1150 * JAVA <code>type</code> of the property which should be added
1151 * to <code>unionGentransObject</code>
1152 * @param propertyName
1153 * string with name of property which should be added to
1154 * <code>unionGentransObject</code>
1156 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1157 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1158 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1159 .addProperty(BindingMapping.getPropertyName(propertyName));
1160 propBuilder.setReturnType(type);
1162 unionGenTransObject.addEqualsIdentity(propBuilder);
1163 unionGenTransObject.addHashIdentity(propBuilder);
1164 unionGenTransObject.addToStringProperty(propBuilder);
1169 * Converts <code>typedef</code> to the generated TO builder.
1171 * @param basePackageName
1172 * string with name of package to which the module belongs
1174 * type definition from which is the generated TO builder created
1175 * @return generated TO builder which contains data from
1176 * <code>typedef</code> and <code>basePackageName</code>
1178 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1179 final TypeDefinition<?> typedef, final String moduleName) {
1181 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1182 final String typeDefTOName = typedef.getQName().getLocalName();
1184 if (packageName != null && typeDefTOName != null) {
1185 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1186 final GeneratedTOBuilder newType = newGeneratedTOBuilder(packageName, genTOName);
1187 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1188 newType.setModuleName(moduleName);
1189 addCodegenInformation(newType, typedef);
1196 * Converts <code>typeDef</code> which should be of the type
1197 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1199 * All the bits of the typeDef are added to returning generated TO as
1202 * @param basePackageName
1203 * string with name of package to which the module belongs
1205 * type definition from which is the generated TO builder created
1206 * @param typeDefName
1207 * string with the name for generated TO builder
1208 * @return generated TO builder which represents <code>typeDef</code>
1209 * @throws IllegalArgumentException
1211 * <li>if <code>typeDef</code> equals null</li>
1212 * <li>if <code>basePackageName</code> equals null</li>
1215 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1216 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1218 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1219 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1221 if (typeDef instanceof BitsTypeDefinition) {
1222 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1224 final String typeName = BindingMapping.getClassName(typeDefName);
1225 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
1226 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1227 genTOBuilder.setModuleName(moduleName);
1228 genTOBuilder.setBaseType(typeDef);
1229 addCodegenInformation(genTOBuilder, typeDef);
1231 final List<Bit> bitList = bitsTypeDefinition.getBits();
1232 GeneratedPropertyBuilder genPropertyBuilder;
1233 for (Bit bit : bitList) {
1234 final String name = bit.getName();
1235 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1236 genPropertyBuilder.setReadOnly(true);
1237 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1239 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1240 genTOBuilder.addHashIdentity(genPropertyBuilder);
1241 genTOBuilder.addToStringProperty(genPropertyBuilder);
1244 return genTOBuilder;
1251 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1252 * expressions from the <code>regularExpressions</code>
1254 * @param genTOBuilder
1255 * generated TO builder to which are
1256 * <code>regular expressions</code> added
1257 * @param expressions
1258 * list of string which represent regular expressions
1260 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1261 final Map<String, String> expressions) {
1262 if (!expressions.isEmpty()) {
1263 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1264 ImmutableMap.copyOf(expressions));
1269 * Creates generated TO with data about inner extended type
1270 * <code>innerExtendedType</code>, about the package name
1271 * <code>typedefName</code> and about the generated TO name
1272 * <code>typedefName</code>.
1274 * It is supposed that <code>innerExtendedType</code> is already present in
1275 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1276 * be possible set it as extended type for the returning generated TO.
1280 * @param innerExtendedType
1281 * extended type which is part of some other extended type
1282 * @param basePackageName
1283 * string with the package name of the module
1286 * @return generated TO which extends generated TO for
1287 * <code>innerExtendedType</code>
1288 * @throws IllegalArgumentException
1290 * <li>if <code>extendedType</code> equals null</li>
1291 * <li>if <code>basePackageName</code> equals null</li>
1292 * <li>if <code>typedefName</code> equals null</li>
1295 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1296 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1297 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1298 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1300 final String typedefName = typedef.getQName().getLocalName();
1301 final String classTypedefName = BindingMapping.getClassName(typedefName);
1302 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1303 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, classTypedefName);
1304 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1305 genTOBuilder.setModuleName(moduleName);
1306 genTOBuilder.setTypedef(true);
1307 addCodegenInformation(genTOBuilder, typedef);
1309 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1310 genTOBuilder.setRestrictions(r);
1311 if (typedef.getStatus() == Status.DEPRECATED) {
1312 genTOBuilder.addAnnotation("", "Deprecated");
1315 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1316 genTOBuilder.setIsUnion(true);
1319 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1320 Map<String, Type> typeMap = null;
1321 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1322 if (parentModule != null) {
1323 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1324 typeMap = modulesByDate.get(parentModule.getRevision());
1327 if (typeMap != null) {
1328 final Type type = typeMap.get(innerTypeDef);
1329 if (type instanceof GeneratedTransferObject) {
1330 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1333 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1334 makeSerializable(genTOBuilder);
1336 return genTOBuilder.toInstance();
1340 * Add {@link Serializable} to implemented interfaces of this TO. Also
1341 * compute and add serialVersionUID property.
1344 * transfer object which needs to be serializable
1346 private static void makeSerializable(final GeneratedTOBuilder gto) {
1347 gto.addImplementsType(Types.typeForClass(Serializable.class));
1348 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1349 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1354 * Finds out for each type definition how many immersion (depth) is
1355 * necessary to get to the base type. Every type definition is inserted to
1356 * the map which key is depth and value is list of type definitions with
1357 * equal depth. In next step are lists from this map concatenated to one
1358 * list in ascending order according to their depth. All type definitions
1359 * are in the list behind all type definitions on which depends.
1361 * @param unsortedTypeDefinitions
1362 * list of type definitions which should be sorted by depth
1363 * @return list of type definitions sorted according their each other
1364 * dependencies (type definitions which are depend on other type
1365 * definitions are in list behind them).
1367 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1368 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1369 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1371 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1372 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1373 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1374 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1375 if (typeDefinitionsConcreteDepth == null) {
1376 typeDefinitionsConcreteDepth = new ArrayList<>();
1377 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1379 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1382 // SortedMap guarantees order corresponding to keys in ascending order
1383 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1384 sortedTypeDefinition.addAll(v);
1387 return sortedTypeDefinition;
1391 * Returns how many immersion is necessary to get from the type definition
1394 * @param typeDefinition
1395 * type definition for which is depth sought.
1396 * @return number of immersions which are necessary to get from the type
1397 * definition to the base type
1399 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1400 // FIXME: rewrite this in a non-recursive manner
1401 if (typeDefinition == null) {
1404 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1405 if (baseType == null) {
1410 if (baseType.getBaseType() != null) {
1411 depth = depth + getTypeDefinitionDepth(baseType);
1412 } else if (baseType instanceof UnionTypeDefinition) {
1413 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1414 int maxChildDepth = 0;
1416 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1417 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1418 if (childDepth > maxChildDepth) {
1419 maxChildDepth = childDepth;
1422 return maxChildDepth;
1428 * Returns string which contains the same value as <code>name</code> but
1429 * integer suffix is incremented by one. If <code>name</code> contains no
1430 * number suffix then number 1 is added.
1433 * string with name of augmented node
1434 * @return string with the number suffix incremented by one (or 1 is added)
1436 private static String provideAvailableNameForGenTOBuilder(final String name) {
1437 final Matcher mtch = NUMBERS_PATTERN.matcher(name);
1439 final int newSuffix = Integer.parseInt(name.substring(mtch.start())) + 1;
1440 return name.substring(0, mtch.start()) + newSuffix;
1446 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1447 if (!Strings.isNullOrEmpty(units)) {
1448 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1449 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1450 prop.setReturnType(Types.STRING);
1451 to.addToStringProperty(prop);
1456 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1457 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1460 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1461 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1462 final QName typeQName = type.getQName();
1463 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1464 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1465 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1468 final StringBuilder sb = new StringBuilder();
1469 String result = null;
1470 if (base instanceof BinaryTypeDefinition) {
1471 result = binaryToDef(defaultValue);
1472 } else if (base instanceof BitsTypeDefinition) {
1475 final Module parent = getParentModule(node);
1476 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1478 if (!path.hasNext()) {
1479 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1480 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1481 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1483 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1484 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1485 parentName = BindingMapping.getClassName(parent.getName());
1486 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1488 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1489 } else if (base instanceof BooleanTypeDefinition) {
1490 result = typeToBooleanDef(defaultValue);
1491 } else if (base instanceof DecimalTypeDefinition) {
1492 result = typeToDef(BigDecimal.class, defaultValue);
1493 } else if (base instanceof EmptyTypeDefinition) {
1494 result = typeToBooleanDef(defaultValue);
1495 } else if (base instanceof EnumTypeDefinition) {
1496 final char[] defValArray = defaultValue.toCharArray();
1497 final char first = Character.toUpperCase(defaultValue.charAt(0));
1498 defValArray[0] = first;
1499 final String newDefVal = new String(defValArray);
1501 if (type.getBaseType() != null) {
1502 final Module m = getParentModule(type);
1503 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1504 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1505 className = packageName + "." + BindingMapping.getClassName(typeQName);
1507 final Module parentModule = getParentModule(node);
1508 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1509 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1510 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1512 result = className + "." + newDefVal;
1513 } else if (base instanceof IdentityrefTypeDefinition) {
1514 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1515 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1516 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1517 } else if (BaseTypes.isInt8(base)) {
1518 result = typeToValueOfDef(Byte.class, defaultValue);
1519 } else if (BaseTypes.isInt16(base)) {
1520 result = typeToValueOfDef(Short.class, defaultValue);
1521 } else if (BaseTypes.isInt32(base)) {
1522 result = typeToValueOfDef(Integer.class, defaultValue);
1523 } else if (BaseTypes.isInt64(base)) {
1524 result = typeToValueOfDef(Long.class, defaultValue);
1525 } else if (base instanceof LeafrefTypeDefinition) {
1526 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1527 } else if (base instanceof StringTypeDefinition) {
1528 result = "\"" + defaultValue + "\"";
1529 } else if (BaseTypes.isUint8(base)) {
1530 result = typeToValueOfDef(Short.class, defaultValue);
1531 } else if (BaseTypes.isUint16(base)) {
1532 result = typeToValueOfDef(Integer.class, defaultValue);
1533 } else if (BaseTypes.isUint32(base)) {
1534 result = typeToValueOfDef(Long.class, defaultValue);
1535 } else if (BaseTypes.isUint64(base)) {
1536 switch (defaultValue) {
1538 result = "java.math.BigInteger.ZERO";
1541 result = "java.math.BigInteger.ONE";
1544 result = "java.math.BigInteger.TEN";
1547 result = typeToDef(BigInteger.class, defaultValue);
1549 } else if (base instanceof UnionTypeDefinition) {
1550 result = unionToDef(node);
1556 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1557 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1558 final Module m = getParentModule(type);
1559 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1560 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1561 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1562 sb.insert(0, "new " + className + "(");
1563 sb.insert(sb.length(), ')');
1566 return sb.toString();
1569 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1570 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1573 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1574 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1577 private static String typeToBooleanDef(final String defaultValue) {
1578 switch (defaultValue) {
1580 return "java.lang.Boolean.FALSE";
1582 return "java.lang.Boolean.TRUE";
1584 return typeToValueOfDef(Boolean.class, defaultValue);
1588 private static String binaryToDef(final String defaultValue) {
1589 final StringBuilder sb = new StringBuilder();
1590 final BaseEncoding en = BaseEncoding.base64();
1591 final byte[] encoded = en.decode(defaultValue);
1592 sb.append("new byte[] {");
1593 for (int i = 0; i < encoded.length; i++) {
1594 sb.append(encoded[i]);
1595 if (i != encoded.length - 1) {
1600 return sb.toString();
1603 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1605 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1606 final List<Bit> bits = new ArrayList<>(type.getBits());
1607 Collections.sort(bits, BIT_NAME_COMPARATOR);
1608 final StringBuilder sb = new StringBuilder();
1611 sb.append(className);
1614 for (int i = 0; i < bits.size(); i++) {
1615 if (bits.get(i).getName().equals(defaultValue)) {
1620 if (i != bits.size() - 1) {
1627 return sb.toString();
1630 private Module getParentModule(final SchemaNode node) {
1631 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1632 return schemaContext.findModule(qname.getModule()).orElse(null);
1635 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1636 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1637 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1638 "The Path Statement for Leafref Type Definition cannot be NULL!");
1640 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1641 final String strXPath = xpath.toString();
1643 if (strXPath != null) {
1644 if (strXPath.indexOf('[') == -1) {
1645 final Module module = findParentModule(schemaContext, parentNode);
1646 if (module != null) {
1647 final SchemaNode dataNode;
1648 if (xpath.isAbsolute()) {
1649 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1651 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1653 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1657 return "new java.lang.Object()";
1664 private String unionToDef(final LeafSchemaNode node) {
1665 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1669 if (type.getBaseType() != null) {
1670 final QName typeQName = type.getQName();
1671 Module module = null;
1672 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1673 if (modules.size() > 1) {
1674 for (Module m : modules) {
1675 if (m.getRevision().equals(typeQName.getRevision())) {
1680 if (module == null) {
1681 final List<Module> modulesList = new ArrayList<>(modules);
1682 Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1683 module = modulesList.get(0);
1686 module = modules.iterator().next();
1689 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1690 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1692 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1693 final QName first = path.next();
1694 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1695 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1696 if (!path.hasNext()) {
1697 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1698 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1700 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1701 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1704 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1707 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1708 final StringBuilder sb = new StringBuilder();
1710 sb.append(className);
1712 sb.append(defaultValue);
1713 sb.append("\".toCharArray())");
1714 return sb.toString();
1718 public String getConstructorPropertyName(final SchemaNode node) {
1719 return node instanceof TypeDefinition<?> ? "value" : "";
1723 public String getParamNameFromType(final TypeDefinition<?> type) {
1724 return BindingMapping.getPropertyName(type.getQName().getLocalName());