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.GeneratedTypeBuilder;
48 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
49 import org.opendaylight.mdsal.binding.model.api.type.builder.MethodSignatureBuilder;
50 import org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil;
51 import org.opendaylight.mdsal.binding.model.util.TypeConstants;
52 import org.opendaylight.mdsal.binding.model.util.Types;
53 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.AbstractEnumerationBuilder;
54 import org.opendaylight.mdsal.binding.model.util.generated.type.builder.GeneratedPropertyBuilderImpl;
55 import org.opendaylight.yangtools.yang.binding.BindingMapping;
56 import org.opendaylight.yangtools.yang.common.QName;
57 import org.opendaylight.yangtools.yang.common.Revision;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
65 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
66 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
68 import org.opendaylight.yangtools.yang.model.api.Status;
69 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
70 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
73 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
81 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
82 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.util.ModuleDependencySort;
84 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
85 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
86 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
87 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
88 import org.slf4j.Logger;
89 import org.slf4j.LoggerFactory;
92 public abstract class AbstractTypeProvider implements TypeProvider {
93 private static final Logger LOG = LoggerFactory.getLogger(AbstractTypeProvider.class);
94 private static final Pattern GROUPS_PATTERN = Pattern.compile("\\[(.*?)\\]");
95 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
97 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
98 // the case, as unions are emitted to their correct schema path.
99 private static final SchemaPath UNION_PATH = SchemaPath.create(true,
100 org.opendaylight.yangtools.yang.model.util.BaseTypes.UNION_QNAME);
103 * Contains the schema data red from YANG files.
105 private final SchemaContext schemaContext;
108 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
110 private final Map<String, Map<Optional<Revision>, Map<String, Type>>> genTypeDefsContextMap = new HashMap<>();
113 * The map which maps schema paths to JAVA <code>Type</code>.
115 private final Map<SchemaPath, Type> referencedTypes = new HashMap<>();
116 private final Map<Module, Set<Type>> additionalTypes = new HashMap<>();
119 * Creates new instance of class <code>TypeProviderImpl</code>.
121 * @param schemaContext
122 * contains the schema data red from YANG files
123 * @throws IllegalArgumentException
124 * if <code>schemaContext</code> equal null.
126 AbstractTypeProvider(final SchemaContext schemaContext) {
127 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
129 this.schemaContext = schemaContext;
130 resolveTypeDefsFromContext();
134 * Puts <code>refType</code> to map with key <code>refTypePath</code>
137 * schema path used as the map key
139 * type which represents the map value
140 * @throws IllegalArgumentException
142 * <li>if <code>refTypePath</code> equal null</li>
143 * <li>if <code>refType</code> equal null</li>
147 public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
148 Preconditions.checkArgument(refTypePath != null,
149 "Path reference of Enumeration Type Definition cannot be NULL!");
150 Preconditions.checkArgument(refType != null, "Reference to Enumeration Type cannot be NULL!");
151 referencedTypes.put(refTypePath, refType);
154 public Map<Module, Set<Type>> getAdditionalTypes() {
155 return additionalTypes;
160 * Converts basic YANG type <code>type</code> to JAVA <code>Type</code>.
163 * string with YANG name of type
164 * @return JAVA <code>Type</code> for YANG type <code>type</code>
165 * @see TypeProvider#javaTypeForYangType(String)
169 public Type javaTypeForYangType(final String type) {
170 return BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
174 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
175 return javaTypeForSchemaDefinitionType(typeDefinition, parentNode, null);
179 * Converts schema definition type <code>typeDefinition</code> to JAVA
182 * @param typeDefinition
183 * type definition which is converted to JAVA type
184 * @throws IllegalArgumentException
186 * <li>if <code>typeDefinition</code> equal null</li>
187 * <li>if Qname of <code>typeDefinition</code> equal null</li>
188 * <li>if name of <code>typeDefinition</code> equal null</li>
192 public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode,
193 final Restrictions r) {
194 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
195 Preconditions.checkArgument(typeDefinition.getQName() != null,
196 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
197 final String typedefName = typeDefinition.getQName().getLocalName();
198 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
200 // Deal with base types
201 if (typeDefinition.getBaseType() == null) {
202 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
203 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
204 // a base type which holds these constraints.
205 if (typeDefinition instanceof DecimalTypeDefinition) {
206 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition,
213 // Deal with leafrefs/identityrefs
214 Type ret = javaTypeForLeafrefOrIdentityRef(typeDefinition, parentNode);
219 // FIXME: it looks as though we could be using the same codepath as above...
220 ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(typeDefinition.getQName().getLocalName());
222 LOG.debug("Failed to resolve Java type for {}", typeDefinition);
228 Type returnType = javaTypeForExtendedType(typeDefinition);
229 if (r != null && returnType instanceof GeneratedTransferObject) {
230 final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
231 final Module module = findParentModule(schemaContext, parentNode);
232 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
233 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
234 typeDefinition.getPath());
235 final String genTOName = BindingMapping.getClassName(typedefName);
236 final String name = packageName + "." + genTOName;
237 if (!returnType.getFullyQualifiedName().equals(name)) {
238 returnType = shadedTOWithRestrictions(gto, r);
244 private GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
245 final GeneratedTOBuilder gtob = newGeneratedTOBuilder(gto.getPackageName(), gto.getName());
246 final GeneratedTransferObject parent = gto.getSuperType();
247 if (parent != null) {
248 gtob.setExtendsType(parent);
250 gtob.setRestrictions(r);
251 for (GeneratedProperty gp : gto.getProperties()) {
252 final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
253 gpb.setValue(gp.getValue());
254 gpb.setReadOnly(gp.isReadOnly());
255 gpb.setAccessModifier(gp.getAccessModifier());
256 gpb.setReturnType(gp.getReturnType());
257 gpb.setFinal(gp.isFinal());
258 gpb.setStatic(gp.isStatic());
263 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
264 final SchemaNode leafRefValueNode;
265 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
266 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(
267 GROUPS_PATTERN.matcher(leafRefXPath.toString()).replaceAll(""), leafRefXPath.isAbsolute());
269 ///// skip leafrefs in augments - they're checked once augments are resolved
270 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
271 boolean isAugmenting = false;
272 DataNodeContainer current = null;
273 DataSchemaNode dataChildByName;
275 while (iterator.hasNext() && !isAugmenting) {
276 final QName next = iterator.next();
277 if (current == null) {
278 dataChildByName = schemaContext.getDataChildByName(next);
280 dataChildByName = current.getDataChildByName(next);
282 if (dataChildByName != null) {
283 isAugmenting = dataChildByName.isAugmenting();
287 if (dataChildByName instanceof DataNodeContainer) {
288 current = (DataNodeContainer) dataChildByName;
296 final Module parentModule = getParentModule(parentNode);
297 if (!leafRefStrippedXPath.isAbsolute()) {
298 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
299 parentNode, leafRefStrippedXPath);
301 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
303 return leafRefValueNode != null ? leafRefValueNode.equals(parentNode) : false;
307 * Returns JAVA <code>Type</code> for instances of the type
308 * <code>LeafrefTypeDefinition</code> or
309 * <code>IdentityrefTypeDefinition</code>.
311 * @param typeDefinition
312 * type definition which is converted to JAVA <code>Type</code>
313 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
315 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
316 if (typeDefinition instanceof LeafrefTypeDefinition) {
317 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
318 Preconditions.checkArgument(!isLeafRefSelfReference(leafref, parentNode),
319 "Leafref %s is referencing itself, incoming StackOverFlowError detected.", leafref);
320 return provideTypeForLeafref(leafref, parentNode);
321 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
322 return provideTypeForIdentityref((IdentityrefTypeDefinition) typeDefinition);
329 * Returns JAVA <code>Type</code> for instances of the type
330 * <code>ExtendedType</code>.
332 * @param typeDefinition
333 * type definition which is converted to JAVA <code>Type</code>
334 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
336 private Type javaTypeForExtendedType(final TypeDefinition<?> typeDefinition) {
337 final String typedefName = typeDefinition.getQName().getLocalName();
338 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
339 Type returnType = javaTypeForLeafrefOrIdentityRef(baseTypeDef, typeDefinition);
340 if (returnType == null) {
341 if (baseTypeDef instanceof EnumTypeDefinition) {
342 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
343 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
345 final Module module = findParentModule(schemaContext, typeDefinition);
346 final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
347 if (module != null) {
348 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
350 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
351 if (genTOs != null) {
352 returnType = genTOs.get(typedefName);
354 if (returnType == null) {
355 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
356 baseTypeDef, typeDefinition, r);
365 * Seeks for identity reference <code>idref</code> the JAVA
366 * <code>type</code>.<br />
370 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
371 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
374 * identityref type definition for which JAVA <code>Type</code>
376 * @return JAVA <code>Type</code> of the identity which is referenced through
379 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
380 final Collection<IdentitySchemaNode> identities = idref.getIdentities();
381 if (identities.size() > 1) {
382 LOG.warn("Identity reference {} has multiple identities, using only the first one", idref);
385 final QName baseIdQName = identities.iterator().next().getQName();
386 final Module module = schemaContext.findModule(baseIdQName.getModule()).orElse(null);
387 IdentitySchemaNode identity = null;
388 for (IdentitySchemaNode id : module.getIdentities()) {
389 if (id.getQName().equals(baseIdQName)) {
393 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
395 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
396 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName,
398 final String genTypeName = BindingMapping.getClassName(identity.getQName());
400 final Type baseType = Types.typeForClass(Class.class);
401 final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
402 return Types.parameterizedTypeFor(baseType, paramType);
406 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
408 * @param typeDefinition
409 * type definition which should be converted to JAVA
411 * @return JAVA <code>Type</code> which represents
412 * <code>typeDefinition</code>
413 * @throws IllegalArgumentException
415 * <li>if <code>typeDefinition</code> equal null</li>
416 * <li>if Q name of <code>typeDefinition</code></li>
417 * <li>if name of <code>typeDefinition</code></li>
420 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
421 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
422 if (typeDefinition.getQName() == null) {
423 throw new IllegalArgumentException(
424 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
426 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
427 "Type Definitions Local Name cannot be NULL!");
429 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
430 if (baseTypeDef instanceof LeafrefTypeDefinition || baseTypeDef instanceof IdentityrefTypeDefinition) {
432 * This is backwards compatibility baggage from way back when. The problem at hand is inconsistency between
433 * the fact that identity is mapped to a Class, which is also returned from leaves which specify it like
446 * This results in getFoo() returning Class<? extends Iden>, which looks fine on the surface, but gets more
447 * dicey when we throw in:
461 * Now we have competing requirements: typedef would like us to use encapsulation to capture the defined
462 * type, while getBar() wants us to retain shape with getFoo(), as it should not matter how the identityref
465 * In this particular case getFoo() won just after the Binding Spec was frozen, hence we do not generate
466 * an encapsulation for identityref typedefs.
468 * In case you are thinking we could get by having foo-ref map to a subclass of Iden, that is not a good
469 * option, as it would look as though it is the product of a different construct:
475 * Leading to a rather nice namespace clash and also slight incompatibility with unknown third-party
476 * sub-identities of iden.
478 * The story behind leafrefs is probably similar, but that needs to be ascertained.
483 final Module module = findParentModule(schemaContext, parentNode);
484 if (module != null) {
485 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(
487 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
488 if (genTOs != null) {
489 return genTOs.get(typeDefinition.getQName().getLocalName());
496 * Gets base type definition for <code>extendTypeDef</code>. The method is
497 * recursively called until non <code>ExtendedType</code> type is found.
499 * @param extendTypeDef
500 * type definition for which is the base type definition sought
501 * @return type definition which is base type for <code>extendTypeDef</code>
502 * @throws IllegalArgumentException
503 * if <code>extendTypeDef</code> equal null
505 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
506 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
508 TypeDefinition<?> ret = extendTypeDef;
509 while (ret.getBaseType() != null) {
510 ret = ret.getBaseType();
517 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
519 * The path of <code>leafrefType</code> is followed to find referenced node
520 * and its <code>Type</code> is returned.
523 * leafref type definition for which is the type sought
524 * @return JAVA <code>Type</code> of data schema node which is referenced in
525 * <code>leafrefType</code>
526 * @throws IllegalArgumentException
528 * <li>if <code>leafrefType</code> equal null</li>
529 * <li>if path statement of <code>leafrefType</code> equal null</li>
533 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
534 Type returnType = null;
535 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
537 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
538 "The Path Statement for Leafref Type Definition cannot be NULL!");
540 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
541 final String strXPath = xpath.toString();
543 if (strXPath != null) {
544 if (strXPath.indexOf('[') == -1) {
545 final Module module = findParentModule(schemaContext, parentNode);
546 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
548 final SchemaNode dataNode;
549 if (xpath.isAbsolute()) {
550 dataNode = findDataSchemaNode(schemaContext, module, xpath);
552 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
554 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
555 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
557 if (leafContainsEnumDefinition(dataNode)) {
558 returnType = referencedTypes.get(dataNode.getPath());
559 } else if (leafListContainsEnumDefinition(dataNode)) {
560 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
562 returnType = resolveTypeFromDataSchemaNode(dataNode);
565 returnType = Types.typeForClass(Object.class);
568 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
569 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
574 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
575 * so then checks if it is of type <code>EnumTypeDefinition</code>.
578 * data schema node for which is checked if it is leaf and if it
580 * @return boolean value
582 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
583 * <li>false - other cases</li>
586 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
587 if (dataNode instanceof LeafSchemaNode) {
588 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
589 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
597 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
598 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
601 * data schema node for which is checked if it is leaflist and if
603 * @return boolean value
605 * <li>true - if <code>dataNode</code> is leaflist of type
607 * <li>false - other cases</li>
610 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
611 if (dataNode instanceof LeafListSchemaNode) {
612 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
613 if (leafList.getType() instanceof EnumTypeDefinition) {
621 * Converts <code>enumTypeDef</code> to
626 * enumeration type definition which is converted to enumeration
628 * string with name which is used as the enumeration name
629 * @return enumeration type which is built with data (name, enum values)
630 * from <code>enumTypeDef</code>
631 * @throws IllegalArgumentException
633 * <li>if <code>enumTypeDef</code> equals null</li>
634 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
635 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
636 * <li>if name of <code>enumTypeDef</code> equal null</li>
639 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName,
640 final SchemaNode parentNode) {
641 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
642 Preconditions.checkArgument(enumTypeDef.getValues() != null,
643 "EnumTypeDefinition MUST contain at least ONE value definition!");
644 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
645 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
646 "Local Name in EnumTypeDefinition QName cannot be NULL!");
648 final String enumerationName = BindingMapping.getClassName(enumName);
650 final Module module = findParentModule(schemaContext, parentNode);
651 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
653 final AbstractEnumerationBuilder enumBuilder = newEnumerationBuilder(basePackageName, enumerationName);
654 addEnumDescription(enumBuilder, enumTypeDef);
655 enumTypeDef.getReference().ifPresent(enumBuilder::setReference);
656 enumBuilder.setModuleName(module.getName());
657 enumBuilder.setSchemaPath(enumTypeDef.getPath());
658 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
659 return enumBuilder.toInstance(null);
663 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
664 * taken from <code>enumTypeDef</code>.
667 * enumeration type definition is source of enumeration data for
668 * <code>typeBuilder</code>
670 * string with the name of enumeration
672 * generated type builder to which is enumeration added
673 * @return enumeration type which contains enumeration data form
674 * <code>enumTypeDef</code>
675 * @throws IllegalArgumentException
677 * <li>if <code>enumTypeDef</code> equals null</li>
678 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
679 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
680 * <li>if name of <code>enumTypeDef</code> equal null</li>
681 * <li>if name of <code>typeBuilder</code> equal null</li>
685 private Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef,
686 final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
687 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
688 Preconditions.checkArgument(enumTypeDef.getValues() != null,
689 "EnumTypeDefinition MUST contain at least ONE value definition!");
690 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
691 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
692 "Local Name in EnumTypeDefinition QName cannot be NULL!");
693 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
695 final String enumerationName = BindingMapping.getClassName(enumName);
697 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
699 addEnumDescription(enumBuilder, enumTypeDef);
700 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
701 return enumBuilder.toInstance(enumBuilder);
704 public abstract void addEnumDescription(EnumBuilder enumBuilder, EnumTypeDefinition enumTypeDef);
706 public abstract AbstractEnumerationBuilder newEnumerationBuilder(String packageName, String name);
708 public abstract GeneratedTOBuilder newGeneratedTOBuilder(String packageName, String name);
710 public abstract GeneratedTypeBuilder newGeneratedTypeBuilder(String packageName, String name);
713 * Converts the pattern constraints to the list of the strings which represents these constraints.
715 * @param patternConstraints list of pattern constraints
716 * @return list of strings which represents the constraint patterns
718 public abstract Map<String, String> resolveRegExpressions(List<PatternConstraint> patternConstraints);
720 abstract void addCodegenInformation(GeneratedTypeBuilderBase<?> genTOBuilder, TypeDefinition<?> typeDef);
723 * Converts the pattern constraints from <code>typedef</code> to the list of
724 * the strings which represents these constraints.
727 * extended type in which are the pattern constraints sought
728 * @return list of strings which represents the constraint patterns
729 * @throws IllegalArgumentException
730 * if <code>typedef</code> equals null
733 private Map<String, String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
734 if (!(typedef instanceof StringTypeDefinition)) {
735 return ImmutableMap.of();
738 // TODO: run diff against base ?
739 return resolveRegExpressions(((StringTypeDefinition) typedef).getPatternConstraints());
743 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
746 * contains information about YANG type
747 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
749 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
750 Type returnType = null;
751 if (dataNode != null) {
752 if (dataNode instanceof LeafSchemaNode) {
753 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
754 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
755 returnType = javaTypeForSchemaDefinitionType(type, leaf);
756 } else if (dataNode instanceof LeafListSchemaNode) {
757 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
758 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
765 * Passes through all modules and through all its type definitions and
766 * convert it to generated types.
768 * The modules are firstly sorted by mutual dependencies. The modules are
769 * sequentially passed. All type definitions of a module are at the
770 * beginning sorted so that type definition with less amount of references
771 * to other type definition are processed first.<br />
772 * For each module is created mapping record in the map
773 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap}
774 * which map current module name to the map which maps type names to
775 * returned types (generated types).
778 private void resolveTypeDefsFromContext() {
779 final Set<Module> modules = schemaContext.getModules();
780 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
781 final List<Module> modulesSortedByDependency = ModuleDependencySort.sort(modules);
783 for (Module module : modulesSortedByDependency) {
784 Map<Optional<Revision>, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
785 if (dateTypeMap == null) {
786 dateTypeMap = new HashMap<>();
788 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
789 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
792 for (Module module : modulesSortedByDependency) {
793 if (module != null) {
794 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
795 if (basePackageName != null) {
796 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
797 for (TypeDefinition<?> typedef : sortTypeDefinitionAccordingDepth(typeDefinitions)) {
798 typedefToGeneratedType(basePackageName, module, typedef);
807 * @param basePackageName
808 * string with name of package to which the module belongs
810 * string with the name of the module for to which the
811 * <code>typedef</code> belongs
813 * type definition of the node for which should be creted JAVA
814 * <code>Type</code> (usually generated TO)
815 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
816 * <code>null</code> value if <code>basePackageName</code> or
817 * <code>modulName</code> or <code>typedef</code> or Q name of
818 * <code>typedef</code> equals <code>null</code>
820 private Type typedefToGeneratedType(final String basePackageName, final Module module,
821 final TypeDefinition<?> typedef) {
822 final String moduleName = module.getName();
823 final Optional<Revision> moduleRevision = module.getRevision();
824 if (basePackageName != null && moduleName != null && typedef != null && typedef.getQName() != null) {
825 final String typedefName = typedef.getQName().getLocalName();
826 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
827 // See generatedTypeForExtendedDefinitionType() above for rationale behind this special case.
828 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
829 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
830 Type returnType = null;
831 if (innerTypeDefinition.getBaseType() != null) {
832 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName,
834 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
835 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
836 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
837 genTOBuilder.setTypedef(true);
838 genTOBuilder.setIsUnion(true);
839 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
840 makeSerializable(genTOBuilder);
841 returnType = genTOBuilder.build();
843 final GeneratedTOBuilder unionBuilder = newGeneratedTOBuilder(genTOBuilder.getPackageName(),
844 genTOBuilder.getName() + "Builder");
845 unionBuilder.setIsUnionBuilder(true);
846 final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
847 method.setReturnType(returnType);
848 method.addParameter(Types.STRING, "defaultValue");
849 method.setAccessModifier(AccessModifier.PUBLIC);
850 method.setStatic(true);
851 Set<Type> types = additionalTypes.get(module);
853 types = Sets.<Type> newHashSet(unionBuilder.build());
854 additionalTypes.put(module, types);
856 types.add(unionBuilder.build());
858 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
859 // enums are automatically Serializable
860 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
861 // TODO units for typedef enum
862 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
863 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
864 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
865 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
866 basePackageName, bitsTypeDefinition, typedefName, module.getName());
867 genTOBuilder.setTypedef(true);
868 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
869 makeSerializable(genTOBuilder);
870 returnType = genTOBuilder.build();
872 final Type javaType = javaTypeForSchemaDefinitionType(innerTypeDefinition, typedef);
873 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
875 if (returnType != null) {
876 final Map<Optional<Revision>, Map<String, Type>> modulesByDate =
877 genTypeDefsContextMap.get(moduleName);
878 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
879 if (typeMap != null) {
880 if (typeMap.isEmpty()) {
881 typeMap = new HashMap<>(4);
882 modulesByDate.put(moduleRevision, typeMap);
884 typeMap.put(typedefName, returnType);
894 * Wraps base YANG type to generated TO.
896 * @param basePackageName
897 * string with name of package to which the module belongs
899 * type definition which is converted to the TO
901 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
902 * @return generated transfer object which represent<code>javaType</code>
904 private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
905 final Type javaType, final String moduleName) {
906 Preconditions.checkNotNull(javaType, "javaType cannot be null");
907 final String propertyName = "value";
909 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
910 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
911 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
912 genPropBuilder.setReturnType(javaType);
913 genTOBuilder.addEqualsIdentity(genPropBuilder);
914 genTOBuilder.addHashIdentity(genPropBuilder);
915 genTOBuilder.addToStringProperty(genPropBuilder);
916 if (typedef.getStatus() == Status.DEPRECATED) {
917 genTOBuilder.addAnnotation("", "Deprecated");
919 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
920 addStringRegExAsConstant(genTOBuilder, resolveRegExpressionsFromTypedef(typedef));
922 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
923 genTOBuilder.setTypedef(true);
924 makeSerializable(genTOBuilder);
925 return genTOBuilder.build();
929 * Converts output list of generated TO builders to one TO builder (first
930 * from list) which contains the remaining builders as its enclosing TO.
932 * @param basePackageName
933 * string with name of package to which the module belongs
935 * type definition which should be of type
936 * <code>UnionTypeDefinition</code>
938 * string with name for generated TO
939 * @return generated TO builder with the list of enclosed generated TO
942 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName,
943 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
944 final List<GeneratedTOBuilder> builders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
945 typedef, typeDefName, parentNode);
946 Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
948 final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
949 builders.forEach(resultTOBuilder::addEnclosingTransferObject);
951 resultTOBuilder.addProperty("value").setReturnType(Types.CHAR_ARRAY);
952 return resultTOBuilder;
956 * Converts <code>typedef</code> to generated TO with
957 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
958 * added to generated TO builder as property.
960 * @param basePackageName
961 * string with name of package to which the module belongs
963 * type definition which should be of type
964 * <code>UnionTypeDefinition</code>
966 * string with name for generated TO
967 * @return generated TO builder which represents <code>typedef</code>
968 * @throws NullPointerException
970 * <li>if <code>basePackageName</code> is null</li>
971 * <li>if <code>typedef</code> is null</li>
972 * <li>if Qname of <code>typedef</code> is null</li>
975 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName,
976 final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
977 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
978 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
979 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
981 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
982 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
983 final Module module = findParentModule(schemaContext, parentNode);
985 final GeneratedTOBuilder unionGenTOBuilder;
986 if (typeDefName != null && !typeDefName.isEmpty()) {
987 final String typeName = BindingMapping.getClassName(typeDefName);
988 unionGenTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
989 unionGenTOBuilder.setSchemaPath(typedef.getPath());
990 unionGenTOBuilder.setModuleName(module.getName());
991 addCodegenInformation(unionGenTOBuilder, typedef);
993 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
996 generatedTOBuilders.add(unionGenTOBuilder);
997 unionGenTOBuilder.setIsUnion(true);
999 // Pattern string is the key, XSD regex is the value. The reason for this choice is that the pattern carries
1000 // also negation information and hence guarantees uniqueness.
1001 final Map<String, String> expressions = new HashMap<>();
1002 for (TypeDefinition<?> unionType : unionTypes) {
1003 final String unionTypeName = unionType.getQName().getLocalName();
1005 // If we have a base type we should follow the type definition backwards, except for identityrefs, as those
1006 // do not follow type encapsulation -- we use the general case for that.
1007 if (unionType.getBaseType() != null && !(unionType instanceof IdentityrefTypeDefinition)) {
1008 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, expressions, parentNode);
1009 } else if (unionType instanceof UnionTypeDefinition) {
1010 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder,
1011 (UnionTypeDefinition) unionType, basePackageName, parentNode));
1012 } else if (unionType instanceof EnumTypeDefinition) {
1013 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
1014 unionTypeName, unionGenTOBuilder);
1015 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
1017 final Type javaType = javaTypeForSchemaDefinitionType(unionType, parentNode);
1018 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
1021 addStringRegExAsConstant(unionGenTOBuilder, expressions);
1023 storeGenTO(typedef, unionGenTOBuilder, parentNode);
1025 return generatedTOBuilders;
1029 * Wraps code which handle case when union subtype is also of the type
1030 * <code>UnionType</code>.
1032 * In this case the new generated TO is created for union subtype (recursive
1034 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
1035 * String, SchemaNode)}
1036 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
1037 * <code>parentUnionGenTOBuilder</code> is created property which type is
1038 * equal to new generated TO.
1040 * @param parentUnionGenTOBuilder
1041 * generated TO builder to which is the property with the child
1042 * union subtype added
1043 * @param basePackageName
1044 * string with the name of the module package
1045 * @param unionSubtype
1046 * type definition which represents union subtype
1047 * @return list of generated TO builders. The number of the builders can be
1048 * bigger one due to recursive call of
1049 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
1051 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1052 final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
1053 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
1054 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
1055 basePackageName, unionSubtype, newTOBuilderName, parentNode);
1057 final GeneratedPropertyBuilder propertyBuilder;
1058 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
1059 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
1060 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
1061 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
1063 return subUnionGenTOBUilders;
1067 * Wraps code which handle case when union subtype is of the type
1068 * <code>ExtendedType</code>.
1070 * If TO for this type already exists it is used for the creation of the
1071 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
1072 * type is used for the property creation.
1074 * @param parentUnionGenTOBuilder
1075 * generated TO builder in which new property is created
1076 * @param unionSubtype
1077 * type definition of the <code>ExtendedType</code> type which
1078 * represents union subtype
1079 * @param expressions
1080 * list of strings with the regular expressions
1082 * parent Schema Node for Extended Subtype
1085 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder,
1086 final TypeDefinition<?> unionSubtype, final Map<String, String> expressions, final SchemaNode parentNode) {
1087 final String unionTypeName = unionSubtype.getQName().getLocalName();
1088 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1089 if (genTO != null) {
1090 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1094 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1095 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1096 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1098 if (javaType != null) {
1099 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1101 } else if (baseType instanceof LeafrefTypeDefinition) {
1102 final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
1103 boolean typeExist = false;
1104 for (GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder.getProperties()) {
1105 final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
1106 if (origType != null && javaType != null && javaType == origType) {
1111 if (!typeExist && javaType != null) {
1112 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType,
1113 javaType.getName() + parentUnionGenTOBuilder.getName() + "Value");
1116 if (baseType instanceof StringTypeDefinition) {
1117 expressions.putAll(resolveRegExpressionsFromTypedef(unionSubtype));
1122 * Searches for generated TO for <code>searchedTypeDef</code> type
1123 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1125 * @param searchedTypeName
1126 * string with name of <code>searchedTypeDef</code>
1127 * @return generated TO for <code>searchedTypeDef</code> or
1128 * <code>null</code> it it doesn't exist
1130 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1131 final Module typeModule = findParentModule(schemaContext, parentNode);
1132 if (typeModule != null && typeModule.getName() != null) {
1133 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1134 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1135 if (genTOs != null) {
1136 return genTOs.get(searchedTypeName);
1143 * Stores generated TO created from <code>genTOBuilder</code> for
1144 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1145 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1148 * type definition for which is <code>genTOBuilder</code> created
1149 * @param genTOBuilder
1150 * generated TO builder which is converted to generated TO and
1153 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1154 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1155 final Module parentModule = findParentModule(schemaContext, parentNode);
1156 if (parentModule != null && parentModule.getName() != null) {
1157 final Map<Optional<Revision>, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1158 final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1159 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.build());
1165 * Adds a new property with the name <code>propertyName</code> and with type
1166 * <code>type</code> to <code>unonGenTransObject</code>.
1168 * @param unionGenTransObject
1169 * generated TO to which should be property added
1171 * JAVA <code>type</code> of the property which should be added
1172 * to <code>unionGentransObject</code>
1173 * @param propertyName
1174 * string with name of property which should be added to
1175 * <code>unionGentransObject</code>
1177 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1178 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1179 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1180 .addProperty(BindingMapping.getPropertyName(propertyName));
1181 propBuilder.setReturnType(type);
1183 unionGenTransObject.addEqualsIdentity(propBuilder);
1184 unionGenTransObject.addHashIdentity(propBuilder);
1185 unionGenTransObject.addToStringProperty(propBuilder);
1190 * Converts <code>typedef</code> to the generated TO builder.
1192 * @param basePackageName
1193 * string with name of package to which the module belongs
1195 * type definition from which is the generated TO builder created
1196 * @return generated TO builder which contains data from
1197 * <code>typedef</code> and <code>basePackageName</code>
1199 private GeneratedTOBuilder typedefToTransferObject(final String basePackageName,
1200 final TypeDefinition<?> typedef, final String moduleName) {
1202 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1203 final String typeDefTOName = typedef.getQName().getLocalName();
1205 if (packageName != null && typeDefTOName != null) {
1206 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1207 final GeneratedTOBuilder newType = newGeneratedTOBuilder(packageName, genTOName);
1208 newType.setSchemaPath(typedef.getPath());
1209 newType.setModuleName(moduleName);
1210 addCodegenInformation(newType, typedef);
1217 * Converts <code>typeDef</code> which should be of the type
1218 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1220 * All the bits of the typeDef are added to returning generated TO as
1223 * @param basePackageName
1224 * string with name of package to which the module belongs
1226 * type definition from which is the generated TO builder created
1227 * @param typeDefName
1228 * string with the name for generated TO builder
1229 * @return generated TO builder which represents <code>typeDef</code>
1230 * @throws IllegalArgumentException
1232 * <li>if <code>typeDef</code> equals null</li>
1233 * <li>if <code>basePackageName</code> equals null</li>
1236 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName,
1237 final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1239 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1240 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1242 if (typeDef instanceof BitsTypeDefinition) {
1243 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1245 final String typeName = BindingMapping.getClassName(typeDefName);
1246 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, typeName);
1247 genTOBuilder.setSchemaPath(typeDef.getPath());
1248 genTOBuilder.setModuleName(moduleName);
1249 genTOBuilder.setBaseType(typeDef);
1250 addCodegenInformation(genTOBuilder, typeDef);
1252 final List<Bit> bitList = bitsTypeDefinition.getBits();
1253 GeneratedPropertyBuilder genPropertyBuilder;
1254 for (Bit bit : bitList) {
1255 final String name = bit.getName();
1256 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1257 genPropertyBuilder.setReadOnly(true);
1258 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1260 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1261 genTOBuilder.addHashIdentity(genPropertyBuilder);
1262 genTOBuilder.addToStringProperty(genPropertyBuilder);
1265 return genTOBuilder;
1272 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1273 * expressions from the <code>regularExpressions</code>
1275 * @param genTOBuilder
1276 * generated TO builder to which are
1277 * <code>regular expressions</code> added
1278 * @param expressions
1279 * list of string which represent regular expressions
1281 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder,
1282 final Map<String, String> expressions) {
1283 if (!expressions.isEmpty()) {
1284 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1285 ImmutableMap.copyOf(expressions));
1290 * Creates generated TO with data about inner extended type
1291 * <code>innerExtendedType</code>, about the package name
1292 * <code>typedefName</code> and about the generated TO name
1293 * <code>typedefName</code>.
1295 * It is supposed that <code>innerExtendedType</code> is already present in
1296 * {@link AbstractTypeProvider#genTypeDefsContextMap genTypeDefsContextMap} to
1297 * be possible set it as extended type for the returning generated TO.
1301 * @param innerExtendedType
1302 * extended type which is part of some other extended type
1303 * @param basePackageName
1304 * string with the package name of the module
1307 * @return generated TO which extends generated TO for
1308 * <code>innerExtendedType</code>
1309 * @throws IllegalArgumentException
1311 * <li>if <code>extendedType</code> equals null</li>
1312 * <li>if <code>basePackageName</code> equals null</li>
1313 * <li>if <code>typedefName</code> equals null</li>
1316 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef,
1317 final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1318 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1319 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1321 final String typedefName = typedef.getQName().getLocalName();
1322 final String classTypedefName = BindingMapping.getClassName(typedefName);
1323 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1324 final GeneratedTOBuilder genTOBuilder = newGeneratedTOBuilder(basePackageName, classTypedefName);
1325 genTOBuilder.setSchemaPath(typedef.getPath());
1326 genTOBuilder.setModuleName(moduleName);
1327 genTOBuilder.setTypedef(true);
1328 addCodegenInformation(genTOBuilder, typedef);
1330 final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1331 genTOBuilder.setRestrictions(r);
1332 if (typedef.getStatus() == Status.DEPRECATED) {
1333 genTOBuilder.addAnnotation("", "Deprecated");
1336 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1337 genTOBuilder.setIsUnion(true);
1340 Map<Optional<Revision>, Map<String, Type>> modulesByDate = null;
1341 Map<String, Type> typeMap = null;
1342 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1343 if (parentModule != null) {
1344 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1345 typeMap = modulesByDate.get(parentModule.getRevision());
1348 if (typeMap != null) {
1349 final Type type = typeMap.get(innerTypeDef);
1350 if (type instanceof GeneratedTransferObject) {
1351 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1354 addUnitsToGenTO(genTOBuilder, typedef.getUnits().orElse(null));
1355 makeSerializable(genTOBuilder);
1357 return genTOBuilder.build();
1361 * Add {@link Serializable} to implemented interfaces of this TO. Also
1362 * compute and add serialVersionUID property.
1365 * transfer object which needs to be serializable
1367 private static void makeSerializable(final GeneratedTOBuilder gto) {
1368 gto.addImplementsType(Types.typeForClass(Serializable.class));
1369 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1370 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1375 * Finds out for each type definition how many immersion (depth) is
1376 * necessary to get to the base type. Every type definition is inserted to
1377 * the map which key is depth and value is list of type definitions with
1378 * equal depth. In next step are lists from this map concatenated to one
1379 * list in ascending order according to their depth. All type definitions
1380 * are in the list behind all type definitions on which depends.
1382 * @param unsortedTypeDefinitions
1383 * list of type definitions which should be sorted by depth
1384 * @return list of type definitions sorted according their each other
1385 * dependencies (type definitions which are depend on other type
1386 * definitions are in list behind them).
1388 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1389 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1390 final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1392 final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1393 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1394 final Integer depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1395 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1396 if (typeDefinitionsConcreteDepth == null) {
1397 typeDefinitionsConcreteDepth = new ArrayList<>();
1398 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1400 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1403 // SortedMap guarantees order corresponding to keys in ascending order
1404 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1405 sortedTypeDefinition.addAll(v);
1408 return sortedTypeDefinition;
1412 * Returns how many immersion is necessary to get from the type definition
1415 * @param typeDefinition
1416 * type definition for which is depth sought.
1417 * @return number of immersions which are necessary to get from the type
1418 * definition to the base type
1420 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1421 // FIXME: rewrite this in a non-recursive manner
1422 if (typeDefinition == null) {
1425 final TypeDefinition<?> baseType = typeDefinition.getBaseType();
1426 if (baseType == null) {
1431 if (baseType.getBaseType() != null) {
1432 depth = depth + getTypeDefinitionDepth(baseType);
1433 } else if (baseType instanceof UnionTypeDefinition) {
1434 final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1435 int maxChildDepth = 0;
1437 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1438 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1439 if (childDepth > maxChildDepth) {
1440 maxChildDepth = childDepth;
1443 return maxChildDepth;
1449 * Returns string which contains the same value as <code>name</code> but
1450 * integer suffix is incremented by one. If <code>name</code> contains no
1451 * number suffix then number 1 is added.
1454 * string with name of augmented node
1455 * @return string with the number suffix incremented by one (or 1 is added)
1457 private static String provideAvailableNameForGenTOBuilder(final String name) {
1458 final Matcher mtch = NUMBERS_PATTERN.matcher(name);
1460 final int newSuffix = Integer.parseInt(name.substring(mtch.start())) + 1;
1461 return name.substring(0, mtch.start()) + newSuffix;
1467 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1468 if (!Strings.isNullOrEmpty(units)) {
1469 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1470 final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1471 prop.setReturnType(Types.STRING);
1472 to.addToStringProperty(prop);
1477 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1478 return getTypeDefaultConstruction(node, (String) node.getType().getDefaultValue().orElse(null));
1481 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1482 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1483 final QName typeQName = type.getQName();
1484 final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1485 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1486 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1489 final StringBuilder sb = new StringBuilder();
1490 String result = null;
1491 if (base instanceof BinaryTypeDefinition) {
1492 result = binaryToDef(defaultValue);
1493 } else if (base instanceof BitsTypeDefinition) {
1496 final Module parent = getParentModule(node);
1497 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1499 if (!path.hasNext()) {
1500 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1501 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1502 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1504 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1505 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1506 parentName = BindingMapping.getClassName(parent.getName());
1507 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1509 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1510 } else if (base instanceof BooleanTypeDefinition) {
1511 result = typeToBooleanDef(defaultValue);
1512 } else if (base instanceof DecimalTypeDefinition) {
1513 result = typeToDef(BigDecimal.class, defaultValue);
1514 } else if (base instanceof EmptyTypeDefinition) {
1515 result = typeToBooleanDef(defaultValue);
1516 } else if (base instanceof EnumTypeDefinition) {
1517 final char[] defValArray = defaultValue.toCharArray();
1518 final char first = Character.toUpperCase(defaultValue.charAt(0));
1519 defValArray[0] = first;
1520 final String newDefVal = new String(defValArray);
1522 if (type.getBaseType() != null) {
1523 final Module m = getParentModule(type);
1524 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1525 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1526 className = packageName + "." + BindingMapping.getClassName(typeQName);
1528 final Module parentModule = getParentModule(node);
1529 final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1530 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1531 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1533 result = className + "." + newDefVal;
1534 } else if (base instanceof IdentityrefTypeDefinition) {
1535 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1536 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1537 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1538 } else if (BaseTypes.isInt8(base)) {
1539 result = typeToValueOfDef(Byte.class, defaultValue);
1540 } else if (BaseTypes.isInt16(base)) {
1541 result = typeToValueOfDef(Short.class, defaultValue);
1542 } else if (BaseTypes.isInt32(base)) {
1543 result = typeToValueOfDef(Integer.class, defaultValue);
1544 } else if (BaseTypes.isInt64(base)) {
1545 result = typeToValueOfDef(Long.class, defaultValue);
1546 } else if (base instanceof LeafrefTypeDefinition) {
1547 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1548 } else if (base instanceof StringTypeDefinition) {
1549 result = "\"" + defaultValue + "\"";
1550 } else if (BaseTypes.isUint8(base)) {
1551 result = typeToValueOfDef(Short.class, defaultValue);
1552 } else if (BaseTypes.isUint16(base)) {
1553 result = typeToValueOfDef(Integer.class, defaultValue);
1554 } else if (BaseTypes.isUint32(base)) {
1555 result = typeToValueOfDef(Long.class, defaultValue);
1556 } else if (BaseTypes.isUint64(base)) {
1557 switch (defaultValue) {
1559 result = "java.math.BigInteger.ZERO";
1562 result = "java.math.BigInteger.ONE";
1565 result = "java.math.BigInteger.TEN";
1568 result = typeToDef(BigInteger.class, defaultValue);
1570 } else if (base instanceof UnionTypeDefinition) {
1571 result = unionToDef(node);
1577 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1578 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1579 final Module m = getParentModule(type);
1580 final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1581 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1582 final String className = packageName + "." + BindingMapping.getClassName(typeQName);
1583 sb.insert(0, "new " + className + "(");
1584 sb.insert(sb.length(), ')');
1587 return sb.toString();
1590 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1591 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1594 private static String typeToValueOfDef(final Class<?> clazz, final String defaultValue) {
1595 return clazz.getName() + ".valueOf(\"" + defaultValue + "\")";
1598 private static String typeToBooleanDef(final String defaultValue) {
1599 switch (defaultValue) {
1601 return "java.lang.Boolean.FALSE";
1603 return "java.lang.Boolean.TRUE";
1605 return typeToValueOfDef(Boolean.class, defaultValue);
1609 private static String binaryToDef(final String defaultValue) {
1610 final StringBuilder sb = new StringBuilder();
1611 final BaseEncoding en = BaseEncoding.base64();
1612 final byte[] encoded = en.decode(defaultValue);
1613 sb.append("new byte[] {");
1614 for (int i = 0; i < encoded.length; i++) {
1615 sb.append(encoded[i]);
1616 if (i != encoded.length - 1) {
1621 return sb.toString();
1624 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1626 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1627 final List<Bit> bits = new ArrayList<>(type.getBits());
1628 Collections.sort(bits, BIT_NAME_COMPARATOR);
1629 final StringBuilder sb = new StringBuilder();
1632 sb.append(className);
1635 for (int i = 0; i < bits.size(); i++) {
1636 if (bits.get(i).getName().equals(defaultValue)) {
1641 if (i != bits.size() - 1) {
1648 return sb.toString();
1651 private Module getParentModule(final SchemaNode node) {
1652 final QName qname = node.getPath().getPathFromRoot().iterator().next();
1653 return schemaContext.findModule(qname.getModule()).orElse(null);
1656 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1657 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1658 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1659 "The Path Statement for Leafref Type Definition cannot be NULL!");
1661 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1662 final String strXPath = xpath.toString();
1664 if (strXPath != null) {
1665 if (strXPath.indexOf('[') == -1) {
1666 final Module module = findParentModule(schemaContext, parentNode);
1667 if (module != null) {
1668 final SchemaNode dataNode;
1669 if (xpath.isAbsolute()) {
1670 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1672 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1674 final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1678 return "new java.lang.Object()";
1685 private String unionToDef(final LeafSchemaNode node) {
1686 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1690 if (type.getBaseType() != null) {
1691 final QName typeQName = type.getQName();
1692 Module module = null;
1693 final Set<Module> modules = schemaContext.findModules(typeQName.getNamespace());
1694 if (modules.size() > 1) {
1695 for (Module m : modules) {
1696 if (m.getRevision().equals(typeQName.getRevision())) {
1701 if (module == null) {
1702 final List<Module> modulesList = new ArrayList<>(modules);
1703 Collections.sort(modulesList, (o1, o2) -> Revision.compare(o1.getRevision(), o2.getRevision()));
1704 module = modulesList.get(0);
1707 module = modules.iterator().next();
1710 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1711 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1713 final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1714 final QName first = path.next();
1715 final Module parent = schemaContext.findModule(first.getModule()).orElse(null);
1716 final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1717 if (!path.hasNext()) {
1718 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1719 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1721 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
1722 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1725 return union(className, (String) node.getType().getDefaultValue().orElse(null), node);
1728 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1729 final StringBuilder sb = new StringBuilder();
1731 sb.append(className);
1733 sb.append(defaultValue);
1734 sb.append("\".toCharArray())");
1735 return sb.toString();
1739 public String getConstructorPropertyName(final SchemaNode node) {
1740 return node instanceof TypeDefinition<?> ? "value" : "";
1744 public String getParamNameFromType(final TypeDefinition<?> type) {
1745 return BindingMapping.getPropertyName(type.getQName().getLocalName());