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.yangtools.sal.binding.yang.types;
10 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.encodeAngleBrackets;
11 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
12 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
13 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
15 import com.google.common.base.Preconditions;
16 import com.google.common.base.Strings;
17 import com.google.common.collect.ImmutableList;
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;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.Collections;
27 import java.util.Comparator;
28 import java.util.Date;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
34 import java.util.TreeMap;
35 import java.util.regex.Matcher;
36 import java.util.regex.Pattern;
37 import org.apache.commons.lang3.StringEscapeUtils;
38 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
39 import org.opendaylight.yangtools.binding.generator.util.TypeConstants;
40 import org.opendaylight.yangtools.binding.generator.util.Types;
41 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.EnumerationBuilderImpl;
42 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedPropertyBuilderImpl;
43 import org.opendaylight.yangtools.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
44 import org.opendaylight.yangtools.sal.binding.generator.spi.TypeProvider;
45 import org.opendaylight.yangtools.sal.binding.model.api.AccessModifier;
46 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
47 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration;
48 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty;
49 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject;
50 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
51 import org.opendaylight.yangtools.sal.binding.model.api.Type;
52 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
53 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
54 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
55 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilderBase;
56 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.MethodSignatureBuilder;
57 import org.opendaylight.yangtools.yang.binding.BindingMapping;
58 import org.opendaylight.yangtools.yang.common.QName;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.Module;
65 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
66 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
67 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
69 import org.opendaylight.yangtools.yang.model.api.Status;
70 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
71 import org.opendaylight.yangtools.yang.model.api.type.BinaryTypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
73 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
74 import org.opendaylight.yangtools.yang.model.api.type.BooleanTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.DecimalTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
77 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
78 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
79 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
80 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
81 import org.opendaylight.yangtools.yang.model.api.type.PatternConstraint;
82 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
83 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
84 import org.opendaylight.yangtools.yang.model.util.Decimal64;
85 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
86 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
87 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
88 import org.opendaylight.yangtools.yang.model.util.UnionType;
89 import org.opendaylight.yangtools.yang.model.util.type.BaseTypes;
90 import org.opendaylight.yangtools.yang.model.util.type.CompatUtils;
91 import org.opendaylight.yangtools.yang.parser.util.YangValidationException;
92 import org.slf4j.Logger;
93 import org.slf4j.LoggerFactory;
95 public final class TypeProviderImpl implements TypeProvider {
96 private static final Logger LOG = LoggerFactory.getLogger(TypeProviderImpl.class);
97 private static final Pattern NUMBERS_PATTERN = Pattern.compile("[0-9]+\\z");
100 * Contains the schema data red from YANG files.
102 private final SchemaContext schemaContext;
105 * Map<moduleName, Map<moduleDate, Map<typeName, type>>>
107 private final Map<String, Map<Date, Map<String, Type>>> genTypeDefsContextMap;
110 * The map which maps schema paths to JAVA <code>Type</code>.
112 private final Map<SchemaPath, Type> referencedTypes;
113 private final Map<Module, Set<Type>> additionalTypes;
116 * Creates new instance of class <code>TypeProviderImpl</code>.
118 * @param schemaContext
119 * contains the schema data red from YANG files
120 * @throws IllegalArgumentException
121 * if <code>schemaContext</code> equal null.
123 public TypeProviderImpl(final SchemaContext schemaContext) {
124 Preconditions.checkArgument(schemaContext != null, "Schema Context cannot be null!");
126 this.schemaContext = schemaContext;
127 this.genTypeDefsContextMap = new HashMap<>();
128 this.referencedTypes = new HashMap<>();
129 this.additionalTypes = new HashMap<>();
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, final Restrictions r) {
193 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
194 Preconditions.checkArgument(typeDefinition.getQName() != null,
195 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
196 String typedefName = typeDefinition.getQName().getLocalName();
197 Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
199 // Deal with base types
200 if (typeDefinition.getBaseType() == null) {
201 // We have to deal with differing handling of decimal64. The old parser used a fixed Decimal64 type
202 // and generated an enclosing ExtendedType to hold any range constraints. The new parser instantiates
203 // a base type which holds these constraints -- and the class is not a Decimal64.
204 if (typeDefinition instanceof DecimalTypeDefinition && !(typeDefinition instanceof Decimal64)) {
205 final Type ret = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition, parentNode, r);
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 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
229 Module module = findParentModule(schemaContext, parentNode);
230 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
231 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
232 String genTOName = BindingMapping.getClassName(typedefName);
233 String name = packageName + "." + genTOName;
234 if (!(returnType.getFullyQualifiedName().equals(name))) {
235 returnType = shadedTOWithRestrictions(gto, r);
241 private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
242 GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
243 GeneratedTransferObject parent = gto.getSuperType();
244 if (parent != null) {
245 gtob.setExtendsType(parent);
247 gtob.setRestrictions(r);
248 for (GeneratedProperty gp : gto.getProperties()) {
249 GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
250 gpb.setValue(gp.getValue());
251 gpb.setReadOnly(gp.isReadOnly());
252 gpb.setAccessModifier(gp.getAccessModifier());
253 gpb.setReturnType(gp.getReturnType());
254 gpb.setFinal(gp.isFinal());
255 gpb.setStatic(gp.isStatic());
257 return gtob.toInstance();
260 private boolean isLeafRefSelfReference(final LeafrefTypeDefinition leafref, final SchemaNode parentNode) {
261 final SchemaNode leafRefValueNode;
262 final RevisionAwareXPath leafRefXPath = leafref.getPathStatement();
263 final RevisionAwareXPath leafRefStrippedXPath = new RevisionAwareXPathImpl(leafRefXPath.toString()
264 .replaceAll("\\[(.*?)\\]", ""), leafRefXPath.isAbsolute());
266 ///// skip leafrefs in augments - they're checked once augments are resolved
267 final Iterator<QName> iterator = parentNode.getPath().getPathFromRoot().iterator();
268 boolean isAugmenting = false;
269 DataNodeContainer current = null;
270 DataSchemaNode dataChildByName;
272 while (iterator.hasNext() && !isAugmenting) {
273 final QName next = iterator.next();
274 if (current == null) {
275 dataChildByName = schemaContext.getDataChildByName(next);
277 dataChildByName = current.getDataChildByName(next);
279 if (dataChildByName != null) {
280 isAugmenting = dataChildByName.isAugmenting();
284 if (dataChildByName instanceof DataNodeContainer) {
285 current = (DataNodeContainer) dataChildByName;
293 Module parentModule = getParentModule(parentNode);
294 if (!leafRefStrippedXPath.isAbsolute()) {
295 leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
296 parentNode, leafRefStrippedXPath);
298 leafRefValueNode = SchemaContextUtil.findDataSchemaNode(schemaContext, parentModule, leafRefStrippedXPath);
300 return (leafRefValueNode != null) ? leafRefValueNode.equals(parentNode) : false;
304 * Returns JAVA <code>Type</code> for instances of the type
305 * <code>LeafrefTypeDefinition</code> or
306 * <code>IdentityrefTypeDefinition</code>.
308 * @param typeDefinition
309 * type definition which is converted to JAVA <code>Type</code>
310 * @return JAVA <code>Type</code> instance for <code>typeDefinition</code>
312 private Type javaTypeForLeafrefOrIdentityRef(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
313 if (typeDefinition instanceof LeafrefTypeDefinition) {
314 final LeafrefTypeDefinition leafref = (LeafrefTypeDefinition) typeDefinition;
315 if (isLeafRefSelfReference(leafref, parentNode)) {
316 throw new YangValidationException("Leafref " + leafref.toString() + " is referencing itself, incoming" +
317 " StackOverFlowError detected.");
319 return provideTypeForLeafref(leafref, parentNode);
320 } else if (typeDefinition instanceof IdentityrefTypeDefinition) {
321 final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
322 return provideTypeForIdentityref(idref);
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 Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
347 if (module != null) {
348 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
349 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
350 if (genTOs != null) {
351 returnType = genTOs.get(typedefName);
353 if (returnType == null) {
354 returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
355 baseTypeDef, typeDefinition, r);
364 * Seeks for identity reference <code>idref</code> the JAVA
365 * <code>type</code>.<br />
369 * If identy which is referenced via <code>idref</code> has name <b>Idn</b>
370 * then returning type is <b>{@code Class<? extends Idn>}</b></i>
373 * identityref type definition for which JAVA <code>Type</code>
375 * @return JAVA <code>Type</code> of the identity which is refrenced through
378 private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
379 QName baseIdQName = idref.getIdentity().getQName();
380 Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
381 baseIdQName.getRevision());
382 IdentitySchemaNode identity = null;
383 for (IdentitySchemaNode id : module.getIdentities()) {
384 if (id.getQName().equals(baseIdQName)) {
388 Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
390 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
391 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
392 final String genTypeName = BindingMapping.getClassName(identity.getQName());
394 Type baseType = Types.typeForClass(Class.class);
395 Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
396 return Types.parameterizedTypeFor(baseType, paramType);
400 * Converts <code>typeDefinition</code> to concrete JAVA <code>Type</code>.
402 * @param typeDefinition
403 * type definition which should be converted to JAVA
405 * @return JAVA <code>Type</code> which represents
406 * <code>typeDefinition</code>
407 * @throws IllegalArgumentException
409 * <li>if <code>typeDefinition</code> equal null</li>
410 * <li>if Q name of <code>typeDefinition</code></li>
411 * <li>if name of <code>typeDefinition</code></li>
414 public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition, final SchemaNode parentNode) {
415 Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
416 if (typeDefinition.getQName() == null) {
417 throw new IllegalArgumentException(
418 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
420 Preconditions.checkArgument(typeDefinition.getQName().getLocalName() != null,
421 "Type Definitions Local Name cannot be NULL!");
423 final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
424 if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
425 final Module module = findParentModule(schemaContext, parentNode);
427 if (module != null) {
428 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
429 final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
430 if (genTOs != null) {
431 return genTOs.get(typeDefinition.getQName().getLocalName());
439 * Gets base type definition for <code>extendTypeDef</code>. The method is
440 * recursively called until non <code>ExtendedType</code> type is found.
442 * @param extendTypeDef
443 * type definition for which is the base type definition sought
444 * @return type definition which is base type for <code>extendTypeDef</code>
445 * @throws IllegalArgumentException
446 * if <code>extendTypeDef</code> equal null
448 private static TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
449 Preconditions.checkArgument(extendTypeDef != null, "Type Definition reference cannot be NULL!");
451 TypeDefinition<?> ret = extendTypeDef;
452 while (ret.getBaseType() != null) {
453 ret = ret.getBaseType();
460 * Converts <code>leafrefType</code> to JAVA <code>Type</code>.
462 * The path of <code>leafrefType</code> is followed to find referenced node
463 * and its <code>Type</code> is returned.
466 * leafref type definition for which is the type sought
467 * @return JAVA <code>Type</code> of data schema node which is referenced in
468 * <code>leafrefType</code>
469 * @throws IllegalArgumentException
471 * <li>if <code>leafrefType</code> equal null</li>
472 * <li>if path statement of <code>leafrefType</code> equal null</li>
476 public Type provideTypeForLeafref(final LeafrefTypeDefinition leafrefType, final SchemaNode parentNode) {
477 Type returnType = null;
478 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
480 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
481 "The Path Statement for Leafref Type Definition cannot be NULL!");
483 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
484 final String strXPath = xpath.toString();
486 if (strXPath != null) {
487 if (strXPath.indexOf('[') == -1) {
488 final Module module = findParentModule(schemaContext, parentNode);
489 Preconditions.checkArgument(module != null, "Failed to find module for parent %s", parentNode);
491 final SchemaNode dataNode;
492 if (xpath.isAbsolute()) {
493 dataNode = findDataSchemaNode(schemaContext, module, xpath);
495 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
497 Preconditions.checkArgument(dataNode != null, "Failed to find leafref target: %s in module %s (%s)",
498 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule());
500 if (leafContainsEnumDefinition(dataNode)) {
501 returnType = referencedTypes.get(dataNode.getPath());
502 } else if (leafListContainsEnumDefinition(dataNode)) {
503 returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
505 returnType = resolveTypeFromDataSchemaNode(dataNode);
508 returnType = Types.typeForClass(Object.class);
511 Preconditions.checkArgument(returnType != null, "Failed to find leafref target: %s in module %s (%s)",
512 strXPath, this.getParentModule(parentNode).getName(), parentNode.getQName().getModule(), this);
517 * Checks if <code>dataNode</code> is <code>LeafSchemaNode</code> and if it
518 * so then checks if it is of type <code>EnumTypeDefinition</code>.
521 * data schema node for which is checked if it is leaf and if it
523 * @return boolean value
525 * <li>true - if <code>dataNode</code> is leaf of type enumeration</li>
526 * <li>false - other cases</li>
529 private static boolean leafContainsEnumDefinition(final SchemaNode dataNode) {
530 if (dataNode instanceof LeafSchemaNode) {
531 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
532 if (CompatUtils.compatLeafType(leaf) instanceof EnumTypeDefinition) {
540 * Checks if <code>dataNode</code> is <code>LeafListSchemaNode</code> and if
541 * it so then checks if it is of type <code>EnumTypeDefinition</code>.
544 * data schema node for which is checked if it is leaflist and if
546 * @return boolean value
548 * <li>true - if <code>dataNode</code> is leaflist of type
550 * <li>false - other cases</li>
553 private static boolean leafListContainsEnumDefinition(final SchemaNode dataNode) {
554 if (dataNode instanceof LeafListSchemaNode) {
555 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
556 if (leafList.getType() instanceof EnumTypeDefinition) {
564 * Converts <code>enumTypeDef</code> to
569 * enumeration type definition which is converted to enumeration
571 * string with name which is used as the enumeration name
572 * @return enumeration type which is built with data (name, enum values)
573 * from <code>enumTypeDef</code>
574 * @throws IllegalArgumentException
576 * <li>if <code>enumTypeDef</code> equals null</li>
577 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
578 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
579 * <li>if name of <code>enumTypeDef</code> equal null</li>
582 private Enumeration provideTypeForEnum(final EnumTypeDefinition enumTypeDef, final String enumName, final SchemaNode parentNode) {
583 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
584 Preconditions.checkArgument(enumTypeDef.getValues() != null,
585 "EnumTypeDefinition MUST contain at least ONE value definition!");
586 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
587 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
588 "Local Name in EnumTypeDefinition QName cannot be NULL!");
590 final String enumerationName = BindingMapping.getClassName(enumName);
592 Module module = findParentModule(schemaContext, parentNode);
593 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
595 final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
596 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
597 enumBuilder.setDescription(enumTypedefDescription);
598 enumBuilder.setReference(enumTypeDef.getReference());
599 enumBuilder.setModuleName(module.getName());
600 enumBuilder.setSchemaPath(enumTypeDef.getPath().getPathFromRoot());
601 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
602 return enumBuilder.toInstance(null);
606 * Adds enumeration to <code>typeBuilder</code>. The enumeration data are
607 * taken from <code>enumTypeDef</code>.
610 * enumeration type definition is source of enumeration data for
611 * <code>typeBuilder</code>
613 * string with the name of enumeration
615 * generated type builder to which is enumeration added
616 * @return enumeration type which contains enumeration data form
617 * <code>enumTypeDef</code>
618 * @throws IllegalArgumentException
620 * <li>if <code>enumTypeDef</code> equals null</li>
621 * <li>if enum values of <code>enumTypeDef</code> equal null</li>
622 * <li>if Q name of <code>enumTypeDef</code> equal null</li>
623 * <li>if name of <code>enumTypeDef</code> equal null</li>
624 * <li>if name of <code>typeBuilder</code> equal null</li>
628 private static Enumeration addInnerEnumerationToTypeBuilder(final EnumTypeDefinition enumTypeDef, final String enumName, final GeneratedTypeBuilderBase<?> typeBuilder) {
629 Preconditions.checkArgument(enumTypeDef != null, "EnumTypeDefinition reference cannot be NULL!");
630 Preconditions.checkArgument(enumTypeDef.getValues() != null,
631 "EnumTypeDefinition MUST contain at least ONE value definition!");
632 Preconditions.checkArgument(enumTypeDef.getQName() != null, "EnumTypeDefinition MUST contain NON-NULL QName!");
633 Preconditions.checkArgument(enumTypeDef.getQName().getLocalName() != null,
634 "Local Name in EnumTypeDefinition QName cannot be NULL!");
635 Preconditions.checkArgument(typeBuilder != null, "Generated Type Builder reference cannot be NULL!");
637 final String enumerationName = BindingMapping.getClassName(enumName);
639 final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
640 final String enumTypedefDescription = encodeAngleBrackets(enumTypeDef.getDescription());
641 enumBuilder.setDescription(enumTypedefDescription);
642 enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
643 return enumBuilder.toInstance(enumBuilder);
647 * Converts <code>dataNode</code> to JAVA <code>Type</code>.
650 * contains information about YANG type
651 * @return JAVA <code>Type</code> representation of <code>dataNode</code>
653 private Type resolveTypeFromDataSchemaNode(final SchemaNode dataNode) {
654 Type returnType = null;
655 if (dataNode != null) {
656 if (dataNode instanceof LeafSchemaNode) {
657 final LeafSchemaNode leaf = (LeafSchemaNode) dataNode;
658 final TypeDefinition<?> type = CompatUtils.compatLeafType(leaf);
659 returnType = javaTypeForSchemaDefinitionType(type, leaf);
660 } else if (dataNode instanceof LeafListSchemaNode) {
661 final LeafListSchemaNode leafList = (LeafListSchemaNode) dataNode;
662 returnType = javaTypeForSchemaDefinitionType(leafList.getType(), leafList);
669 * Passes through all modules and through all its type definitions and
670 * convert it to generated types.
672 * The modules are firstly sorted by mutual dependencies. The modules are
673 * sequentially passed. All type definitions of a module are at the
674 * beginning sorted so that type definition with less amount of references
675 * to other type definition are processed first.<br />
676 * For each module is created mapping record in the map
677 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap}
678 * which map current module name to the map which maps type names to
679 * returned types (generated types).
682 private void resolveTypeDefsFromContext() {
683 final Set<Module> modules = schemaContext.getModules();
684 Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
685 final Module[] modulesArray = new Module[modules.size()];
687 for (Module modul : modules) {
688 modulesArray[i++] = modul;
690 final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
693 for (final Module module : modulesSortedByDependency) {
694 Map<Date, Map<String, Type>> dateTypeMap = genTypeDefsContextMap.get(module.getName());
695 if (dateTypeMap == null) {
696 dateTypeMap = new HashMap<>();
698 dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
699 genTypeDefsContextMap.put(module.getName(), dateTypeMap);
702 for (final Module module : modulesSortedByDependency) {
703 if (module != null) {
704 final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
705 if (basePackageName != null) {
706 final List<TypeDefinition<?>> typeDefinitions = TypedefResolver.getAllTypedefs(module);
707 final List<TypeDefinition<?>> listTypeDefinitions = sortTypeDefinitionAccordingDepth(typeDefinitions);
708 if (listTypeDefinitions != null) {
709 for (final TypeDefinition<?> typedef : listTypeDefinitions) {
710 typedefToGeneratedType(basePackageName, module, typedef);
720 * @param basePackageName
721 * string with name of package to which the module belongs
723 * string with the name of the module for to which the
724 * <code>typedef</code> belongs
726 * type definition of the node for which should be creted JAVA
727 * <code>Type</code> (usually generated TO)
728 * @return JAVA <code>Type</code> representation of <code>typedef</code> or
729 * <code>null</code> value if <code>basePackageName</code> or
730 * <code>modulName</code> or <code>typedef</code> or Q name of
731 * <code>typedef</code> equals <code>null</code>
733 private Type typedefToGeneratedType(final String basePackageName, final Module module, final TypeDefinition<?> typedef) {
734 final String moduleName = module.getName();
735 final Date moduleRevision = module.getRevision();
736 if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
737 final String typedefName = typedef.getQName().getLocalName();
738 final TypeDefinition<?> innerTypeDefinition = typedef.getBaseType();
739 if (!(innerTypeDefinition instanceof LeafrefTypeDefinition)
740 && !(innerTypeDefinition instanceof IdentityrefTypeDefinition)) {
741 Type returnType = null;
742 if (innerTypeDefinition.getBaseType() != null) {
743 returnType = provideGeneratedTOFromExtendedType(typedef, innerTypeDefinition, basePackageName, module.getName());
744 } else if (innerTypeDefinition instanceof UnionTypeDefinition) {
745 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForUnionTypeDef(basePackageName,
746 (UnionTypeDefinition) innerTypeDefinition, typedefName, typedef);
747 genTOBuilder.setTypedef(true);
748 genTOBuilder.setIsUnion(true);
749 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
750 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
751 returnType = genTOBuilder.toInstance();
753 GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
754 genTOBuilder.getName() + "Builder");
755 unionBuilder.setIsUnionBuilder(true);
756 MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
757 method.setReturnType(returnType);
758 method.addParameter(Types.STRING, "defaultValue");
759 method.setAccessModifier(AccessModifier.PUBLIC);
760 method.setStatic(true);
761 Set<Type> types = additionalTypes.get(module);
763 types = Sets.<Type> newHashSet(unionBuilder.toInstance());
764 additionalTypes.put(module, types);
766 types.add(unionBuilder.toInstance());
768 } else if (innerTypeDefinition instanceof EnumTypeDefinition) {
769 // enums are automatically Serializable
770 final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) innerTypeDefinition;
771 // TODO units for typedef enum
772 returnType = provideTypeForEnum(enumTypeDef, typedefName, typedef);
773 } else if (innerTypeDefinition instanceof BitsTypeDefinition) {
774 final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) innerTypeDefinition;
775 final GeneratedTOBuilder genTOBuilder = provideGeneratedTOBuilderForBitsTypeDefinition(
776 basePackageName, bitsTypeDefinition, typedefName, module.getName());
777 genTOBuilder.setTypedef(true);
778 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
779 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
780 returnType = genTOBuilder.toInstance();
782 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(
783 innerTypeDefinition, typedef);
784 returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType, module.getName());
786 if (returnType != null) {
787 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
788 Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
789 if (typeMap != null) {
790 if (typeMap.isEmpty()) {
791 typeMap = new HashMap<>(4);
792 modulesByDate.put(moduleRevision, typeMap);
794 typeMap.put(typedefName, returnType);
804 * Wraps base YANG type to generated TO.
806 * @param basePackageName
807 * string with name of package to which the module belongs
809 * type definition which is converted to the TO
811 * JAVA <code>Type</code> to which is <code>typedef</code> mapped
812 * @return generated transfer object which represent<code>javaType</code>
814 private static GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef, final Type javaType, final String moduleName) {
815 Preconditions.checkNotNull(javaType, "javaType cannot be null");
816 final String propertyName = "value";
818 final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef, moduleName);
819 genTOBuilder.setRestrictions(BindingGeneratorUtil.getRestrictions(typedef));
820 final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
821 genPropBuilder.setReturnType(javaType);
822 genTOBuilder.addEqualsIdentity(genPropBuilder);
823 genTOBuilder.addHashIdentity(genPropBuilder);
824 genTOBuilder.addToStringProperty(genPropBuilder);
825 if (typedef.getStatus() == Status.DEPRECATED) {
826 genTOBuilder.addAnnotation("", "Deprecated");
828 if (javaType instanceof ConcreteType && "String".equals(javaType.getName()) && typedef.getBaseType() != null) {
829 final List<String> regExps = resolveRegExpressionsFromTypedef(typedef);
830 addStringRegExAsConstant(genTOBuilder, regExps);
832 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
833 genTOBuilder.setTypedef(true);
834 makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
835 return genTOBuilder.toInstance();
839 * Converts output list of generated TO builders to one TO builder (first
840 * from list) which contains the remaining builders as its enclosing TO.
842 * @param basePackageName
843 * string with name of package to which the module belongs
845 * type definition which should be of type
846 * <code>UnionTypeDefinition</code>
848 * string with name for generated TO
849 * @return generated TO builder with the list of enclosed generated TO
852 public GeneratedTOBuilder provideGeneratedTOBuilderForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
853 final List<GeneratedTOBuilder> genTOBuilders = provideGeneratedTOBuildersForUnionTypeDef(basePackageName,
854 typedef, typeDefName, parentNode);
855 GeneratedTOBuilder resultTOBuilder = null;
856 if (genTOBuilders.isEmpty()) {
857 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typedef);
860 resultTOBuilder = genTOBuilders.remove(0);
861 for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
862 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
865 final GeneratedPropertyBuilder genPropBuilder = resultTOBuilder.addProperty("value");
866 genPropBuilder.setReturnType(Types.CHAR_ARRAY);
867 resultTOBuilder.addEqualsIdentity(genPropBuilder);
868 resultTOBuilder.addHashIdentity(genPropBuilder);
869 resultTOBuilder.addToStringProperty(genPropBuilder);
871 return resultTOBuilder;
875 * Converts <code>typedef</code> to generated TO with
876 * <code>typeDefName</code>. Every union type from <code>typedef</code> is
877 * added to generated TO builder as property.
879 * @param basePackageName
880 * string with name of package to which the module belongs
882 * type definition which should be of type
883 * <code>UnionTypeDefinition</code>
885 * string with name for generated TO
886 * @return generated TO builder which represents <code>typedef</code>
887 * @throws NullPointerException
889 * <li>if <code>basePackageName</code> is null</li>
890 * <li>if <code>typedef</code> is null</li>
891 * <li>if Qname of <code>typedef</code> is null</li>
894 public List<GeneratedTOBuilder> provideGeneratedTOBuildersForUnionTypeDef(final String basePackageName, final UnionTypeDefinition typedef, final String typeDefName, final SchemaNode parentNode) {
895 Preconditions.checkNotNull(basePackageName, "Base Package Name cannot be NULL!");
896 Preconditions.checkNotNull(typedef, "Type Definition cannot be NULL!");
897 Preconditions.checkNotNull(typedef.getQName(), "Type definition QName cannot be NULL!");
899 final List<GeneratedTOBuilder> generatedTOBuilders = new ArrayList<>();
900 final List<TypeDefinition<?>> unionTypes = typedef.getTypes();
901 final Module module = findParentModule(schemaContext, parentNode);
903 final GeneratedTOBuilderImpl unionGenTOBuilder;
904 if (typeDefName != null && !typeDefName.isEmpty()) {
905 final String typeName = BindingMapping.getClassName(typeDefName);
906 unionGenTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
907 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
908 unionGenTOBuilder.setDescription(typedefDescription);
909 unionGenTOBuilder.setReference(typedef.getReference());
910 unionGenTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
911 unionGenTOBuilder.setModuleName(module.getName());
913 unionGenTOBuilder = typedefToTransferObject(basePackageName, typedef, module.getName());
916 generatedTOBuilders.add(unionGenTOBuilder);
917 unionGenTOBuilder.setIsUnion(true);
918 final List<String> regularExpressions = new ArrayList<String>();
919 for (final TypeDefinition<?> unionType : unionTypes) {
920 final String unionTypeName = unionType.getQName().getLocalName();
921 if (unionType.getBaseType() != null) {
922 resolveExtendedSubtypeAsUnion(unionGenTOBuilder, unionType, regularExpressions,
924 } else if (unionType instanceof UnionTypeDefinition) {
925 generatedTOBuilders.addAll(resolveUnionSubtypeAsUnion(unionGenTOBuilder, (UnionTypeDefinition) unionType,
926 basePackageName, parentNode));
927 } else if (unionType instanceof EnumTypeDefinition) {
928 final Enumeration enumeration = addInnerEnumerationToTypeBuilder((EnumTypeDefinition) unionType,
929 unionTypeName, unionGenTOBuilder);
930 updateUnionTypeAsProperty(unionGenTOBuilder, enumeration, unionTypeName);
932 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(unionType,
934 updateUnionTypeAsProperty(unionGenTOBuilder, javaType, unionTypeName);
937 if (!regularExpressions.isEmpty()) {
938 addStringRegExAsConstant(unionGenTOBuilder, regularExpressions);
941 storeGenTO(typedef, unionGenTOBuilder, parentNode);
943 return generatedTOBuilders;
947 * Wraps code which handle case when union subtype is also of the type
948 * <code>UnionType</code>.
950 * In this case the new generated TO is created for union subtype (recursive
952 * {@link #provideGeneratedTOBuildersForUnionTypeDef(String, UnionTypeDefinition,
953 * String, SchemaNode)}
954 * provideGeneratedTOBuilderForUnionTypeDef} and in parent TO builder
955 * <code>parentUnionGenTOBuilder</code> is created property which type is
956 * equal to new generated TO.
958 * @param parentUnionGenTOBuilder
959 * generated TO builder to which is the property with the child
960 * union subtype added
961 * @param basePackageName
962 * string with the name of the module package
963 * @param unionSubtype
964 * type definition which represents union subtype
965 * @return list of generated TO builders. The number of the builders can be
966 * bigger one due to recursive call of
967 * <code>provideGeneratedTOBuildersForUnionTypeDef</code> method.
969 private List<GeneratedTOBuilder> resolveUnionSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final UnionTypeDefinition unionSubtype, final String basePackageName, final SchemaNode parentNode) {
970 final String newTOBuilderName = provideAvailableNameForGenTOBuilder(parentUnionGenTOBuilder.getName());
971 final List<GeneratedTOBuilder> subUnionGenTOBUilders = provideGeneratedTOBuildersForUnionTypeDef(
972 basePackageName, unionSubtype, newTOBuilderName, parentNode);
974 final GeneratedPropertyBuilder propertyBuilder;
975 propertyBuilder = parentUnionGenTOBuilder.addProperty(BindingMapping.getPropertyName(newTOBuilderName));
976 propertyBuilder.setReturnType(subUnionGenTOBUilders.get(0));
977 parentUnionGenTOBuilder.addEqualsIdentity(propertyBuilder);
978 parentUnionGenTOBuilder.addToStringProperty(propertyBuilder);
980 return subUnionGenTOBUilders;
984 * Wraps code which handle case when union subtype is of the type
985 * <code>ExtendedType</code>.
987 * If TO for this type already exists it is used for the creation of the
988 * property in <code>parentUnionGenTOBuilder</code>. In other case the base
989 * type is used for the property creation.
991 * @param parentUnionGenTOBuilder
992 * generated TO builder in which new property is created
993 * @param unionSubtype
994 * type definition of the <code>ExtendedType</code> type which
995 * represents union subtype
996 * @param regularExpressions
997 * list of strings with the regular expressions
999 * parent Schema Node for Extended Subtype
1002 private void resolveExtendedSubtypeAsUnion(final GeneratedTOBuilder parentUnionGenTOBuilder, final TypeDefinition<?> unionSubtype, final List<String> regularExpressions, final SchemaNode parentNode) {
1003 final String unionTypeName = unionSubtype.getQName().getLocalName();
1004 final Type genTO = findGenTO(unionTypeName, unionSubtype);
1005 if (genTO != null) {
1006 updateUnionTypeAsProperty(parentUnionGenTOBuilder, genTO, genTO.getName());
1008 final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionSubtype);
1009 if (unionTypeName.equals(baseType.getQName().getLocalName())) {
1010 final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(baseType,
1012 if (javaType != null) {
1013 updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
1016 if (baseType instanceof StringTypeDefinition) {
1017 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
1023 * Searches for generated TO for <code>searchedTypeDef</code> type
1024 * definition in {@link #genTypeDefsContextMap genTypeDefsContextMap}
1026 * @param searchedTypeName
1027 * string with name of <code>searchedTypeDef</code>
1028 * @return generated TO for <code>searchedTypeDef</code> or
1029 * <code>null</code> it it doesn't exist
1031 private Type findGenTO(final String searchedTypeName, final SchemaNode parentNode) {
1032 final Module typeModule = findParentModule(schemaContext, parentNode);
1033 if (typeModule != null && typeModule.getName() != null) {
1034 final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(typeModule.getName());
1035 final Map<String, Type> genTOs = modulesByDate.get(typeModule.getRevision());
1036 if (genTOs != null) {
1037 return genTOs.get(searchedTypeName);
1044 * Stores generated TO created from <code>genTOBuilder</code> for
1045 * <code>newTypeDef</code> to {@link #genTypeDefsContextMap
1046 * genTypeDefsContextMap} if the module for <code>newTypeDef</code> exists
1049 * type definition for which is <code>genTOBuilder</code> created
1050 * @param genTOBuilder
1051 * generated TO builder which is converted to generated TO and
1054 private void storeGenTO(final TypeDefinition<?> newTypeDef, final GeneratedTOBuilder genTOBuilder, final SchemaNode parentNode) {
1055 if (!(newTypeDef instanceof UnionTypeDefinition)) {
1056 final Module parentModule = findParentModule(schemaContext, parentNode);
1057 if (parentModule != null && parentModule.getName() != null) {
1058 Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1059 Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
1060 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
1066 * Adds a new property with the name <code>propertyName</code> and with type
1067 * <code>type</code> to <code>unonGenTransObject</code>.
1069 * @param unionGenTransObject
1070 * generated TO to which should be property added
1072 * JAVA <code>type</code> of the property which should be added
1073 * to <code>unionGentransObject</code>
1074 * @param propertyName
1075 * string with name of property which should be added to
1076 * <code>unionGentransObject</code>
1078 private static void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type, final String propertyName) {
1079 if (unionGenTransObject != null && type != null && !unionGenTransObject.containsProperty(propertyName)) {
1080 final GeneratedPropertyBuilder propBuilder = unionGenTransObject
1081 .addProperty(BindingMapping.getPropertyName(propertyName));
1082 propBuilder.setReturnType(type);
1084 unionGenTransObject.addEqualsIdentity(propBuilder);
1085 unionGenTransObject.addHashIdentity(propBuilder);
1086 unionGenTransObject.addToStringProperty(propBuilder);
1091 * Converts <code>typedef</code> to the generated TO builder.
1093 * @param basePackageName
1094 * string with name of package to which the module belongs
1096 * type definition from which is the generated TO builder created
1097 * @return generated TO builder which contains data from
1098 * <code>typedef</code> and <code>basePackageName</code>
1100 private static GeneratedTOBuilderImpl typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef, final String moduleName) {
1102 final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typedef.getPath());
1103 final String typeDefTOName = typedef.getQName().getLocalName();
1105 if ((packageName != null) && (typeDefTOName != null)) {
1106 final String genTOName = BindingMapping.getClassName(typeDefTOName);
1107 final GeneratedTOBuilderImpl newType = new GeneratedTOBuilderImpl(packageName, genTOName);
1108 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1110 newType.setDescription(typedefDescription);
1111 newType.setReference(typedef.getReference());
1112 newType.setSchemaPath(typedef.getPath().getPathFromRoot());
1113 newType.setModuleName(moduleName);
1121 * Converts <code>typeDef</code> which should be of the type
1122 * <code>BitsTypeDefinition</code> to <code>GeneratedTOBuilder</code>.
1124 * All the bits of the typeDef are added to returning generated TO as
1127 * @param basePackageName
1128 * string with name of package to which the module belongs
1130 * type definition from which is the generated TO builder created
1131 * @param typeDefName
1132 * string with the name for generated TO builder
1133 * @return generated TO builder which represents <code>typeDef</code>
1134 * @throws IllegalArgumentException
1136 * <li>if <code>typeDef</code> equals null</li>
1137 * <li>if <code>basePackageName</code> equals null</li>
1140 public GeneratedTOBuilder provideGeneratedTOBuilderForBitsTypeDefinition(final String basePackageName, final TypeDefinition<?> typeDef, final String typeDefName, final String moduleName) {
1142 Preconditions.checkArgument(typeDef != null, "typeDef cannot be NULL!");
1143 Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
1145 if (typeDef instanceof BitsTypeDefinition) {
1146 BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
1148 final String typeName = BindingMapping.getClassName(typeDefName);
1149 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
1150 final String typedefDescription = encodeAngleBrackets(typeDef.getDescription());
1152 genTOBuilder.setDescription(typedefDescription);
1153 genTOBuilder.setReference(typeDef.getReference());
1154 genTOBuilder.setSchemaPath(typeDef.getPath().getPathFromRoot());
1155 genTOBuilder.setModuleName(moduleName);
1156 genTOBuilder.setBaseType(typeDef);
1158 final List<Bit> bitList = bitsTypeDefinition.getBits();
1159 GeneratedPropertyBuilder genPropertyBuilder;
1160 for (final Bit bit : bitList) {
1161 String name = bit.getName();
1162 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
1163 genPropertyBuilder.setReadOnly(true);
1164 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
1166 genTOBuilder.addEqualsIdentity(genPropertyBuilder);
1167 genTOBuilder.addHashIdentity(genPropertyBuilder);
1168 genTOBuilder.addToStringProperty(genPropertyBuilder);
1171 return genTOBuilder;
1177 * Converts the pattern constraints from <code>typedef</code> to the list of
1178 * the strings which represents these constraints.
1181 * extended type in which are the pattern constraints sought
1182 * @return list of strings which represents the constraint patterns
1183 * @throws IllegalArgumentException
1184 * if <code>typedef</code> equals null
1187 private static List<String> resolveRegExpressionsFromTypedef(final TypeDefinition<?> typedef) {
1188 Preconditions.checkArgument(typedef != null, "typedef can't be null");
1190 final List<PatternConstraint> patternConstraints;
1191 if (typedef instanceof ExtendedType) {
1192 final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
1193 if (strTypeDef instanceof StringTypeDefinition) {
1194 patternConstraints = ((ExtendedType)typedef).getPatternConstraints();
1196 patternConstraints = ImmutableList.of();
1198 } else if (typedef instanceof StringTypeDefinition) {
1199 // FIXME: run diff against base
1200 patternConstraints = ((StringTypeDefinition) typedef).getPatternConstraints();
1202 patternConstraints = ImmutableList.of();
1205 final List<String> regExps = new ArrayList<>(patternConstraints.size());
1206 for (PatternConstraint patternConstraint : patternConstraints) {
1207 final String regEx = patternConstraint.getRegularExpression();
1208 final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
1209 regExps.add(modifiedRegEx);
1217 * Adds to the <code>genTOBuilder</code> the constant which contains regular
1218 * expressions from the <code>regularExpressions</code>
1220 * @param genTOBuilder
1221 * generated TO builder to which are
1222 * <code>regular expressions</code> added
1223 * @param regularExpressions
1224 * list of string which represent regular expressions
1225 * @throws IllegalArgumentException
1227 * <li>if <code>genTOBuilder</code> equals null</li>
1228 * <li>if <code>regularExpressions</code> equals null</li>
1231 private static void addStringRegExAsConstant(final GeneratedTOBuilder genTOBuilder, final List<String> regularExpressions) {
1232 if (genTOBuilder == null) {
1233 throw new IllegalArgumentException("Generated transfer object builder can't be null");
1235 if (regularExpressions == null) {
1236 throw new IllegalArgumentException("List of regular expressions can't be null");
1238 if (!regularExpressions.isEmpty()) {
1239 genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
1240 regularExpressions);
1245 * Creates generated TO with data about inner extended type
1246 * <code>innerExtendedType</code>, about the package name
1247 * <code>typedefName</code> and about the generated TO name
1248 * <code>typedefName</code>.
1250 * It is supposed that <code>innerExtendedType</code> is already present in
1251 * {@link TypeProviderImpl#genTypeDefsContextMap genTypeDefsContextMap} to
1252 * be possible set it as extended type for the returning generated TO.
1256 * @param innerExtendedType
1257 * extended type which is part of some other extended type
1258 * @param basePackageName
1259 * string with the package name of the module
1262 * @return generated TO which extends generated TO for
1263 * <code>innerExtendedType</code>
1264 * @throws IllegalArgumentException
1266 * <li>if <code>extendedType</code> equals null</li>
1267 * <li>if <code>basePackageName</code> equals null</li>
1268 * <li>if <code>typedefName</code> equals null</li>
1271 private GeneratedTransferObject provideGeneratedTOFromExtendedType(final TypeDefinition<?> typedef, final TypeDefinition<?> innerExtendedType, final String basePackageName, final String moduleName) {
1272 Preconditions.checkArgument(innerExtendedType != null, "Extended type cannot be NULL!");
1273 Preconditions.checkArgument(basePackageName != null, "String with base package name cannot be NULL!");
1275 final String typedefName = typedef.getQName().getLocalName();
1276 final String classTypedefName = BindingMapping.getClassName(typedefName);
1277 final String innerTypeDef = innerExtendedType.getQName().getLocalName();
1278 final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, classTypedefName);
1279 final String typedefDescription = encodeAngleBrackets(typedef.getDescription());
1281 genTOBuilder.setDescription(typedefDescription);
1282 genTOBuilder.setReference(typedef.getReference());
1283 genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
1284 genTOBuilder.setModuleName(moduleName);
1285 genTOBuilder.setTypedef(true);
1286 Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
1287 genTOBuilder.setRestrictions(r);
1288 if (typedef.getStatus() == Status.DEPRECATED) {
1289 genTOBuilder.addAnnotation("", "Deprecated");
1292 if (baseTypeDefForExtendedType(innerExtendedType) instanceof UnionTypeDefinition) {
1293 genTOBuilder.setIsUnion(true);
1296 Map<Date, Map<String, Type>> modulesByDate = null;
1297 Map<String, Type> typeMap = null;
1298 final Module parentModule = findParentModule(schemaContext, innerExtendedType);
1299 if (parentModule != null) {
1300 modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
1301 typeMap = modulesByDate.get(parentModule.getRevision());
1304 if (typeMap != null) {
1305 Type type = typeMap.get(innerTypeDef);
1306 if (type instanceof GeneratedTransferObject) {
1307 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
1310 addUnitsToGenTO(genTOBuilder, typedef.getUnits());
1311 makeSerializable(genTOBuilder);
1313 return genTOBuilder.toInstance();
1317 * Add {@link Serializable} to implemented interfaces of this TO. Also
1318 * compute and add serialVersionUID property.
1321 * transfer object which needs to be serializable
1323 private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
1324 gto.addImplementsType(Types.typeForClass(Serializable.class));
1325 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
1326 prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
1331 * Finds out for each type definition how many immersion (depth) is
1332 * necessary to get to the base type. Every type definition is inserted to
1333 * the map which key is depth and value is list of type definitions with
1334 * equal depth. In next step are lists from this map concatenated to one
1335 * list in ascending order according to their depth. All type definitions
1336 * are in the list behind all type definitions on which depends.
1338 * @param unsortedTypeDefinitions
1339 * list of type definitions which should be sorted by depth
1340 * @return list of type definitions sorted according their each other
1341 * dependencies (type definitions which are depend on other type
1342 * definitions are in list behind them).
1344 private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
1345 final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
1346 List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
1348 Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
1349 for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
1350 final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
1351 List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
1352 if (typeDefinitionsConcreteDepth == null) {
1353 typeDefinitionsConcreteDepth = new ArrayList<TypeDefinition<?>>();
1354 typeDefinitionsDepths.put(depth, typeDefinitionsConcreteDepth);
1356 typeDefinitionsConcreteDepth.add(unsortedTypeDefinition);
1359 // SortedMap guarantees order corresponding to keys in ascending order
1360 for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
1361 sortedTypeDefinition.addAll(v);
1364 return sortedTypeDefinition;
1368 * Returns how many immersion is necessary to get from the type definition
1371 * @param typeDefinition
1372 * type definition for which is depth sought.
1373 * @return number of immersions which are necessary to get from the type
1374 * definition to the base type
1376 private static int getTypeDefinitionDepth(final TypeDefinition<?> typeDefinition) {
1377 // FIXME: rewrite this in a non-recursive manner, without ExtendedType and UnionType
1378 if (typeDefinition == null) {
1381 TypeDefinition<?> baseType = typeDefinition.getBaseType();
1382 if (baseType == null) {
1387 if (baseType.getBaseType() != null) {
1388 depth = depth + getTypeDefinitionDepth(baseType);
1389 } else if (baseType instanceof UnionTypeDefinition) {
1390 List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
1391 int maxChildDepth = 0;
1393 for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
1394 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
1395 if (childDepth > maxChildDepth) {
1396 maxChildDepth = childDepth;
1399 return maxChildDepth;
1405 * Returns string which contains the same value as <code>name</code> but
1406 * integer suffix is incremented by one. If <code>name</code> contains no
1407 * number suffix then number 1 is added.
1410 * string with name of augmented node
1411 * @return string with the number suffix incremented by one (or 1 is added)
1413 private static String provideAvailableNameForGenTOBuilder(final String name) {
1414 Matcher mtch = NUMBERS_PATTERN.matcher(name);
1416 final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
1417 return name.substring(0, mtch.start()) + newSuffix;
1423 public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
1424 if (!Strings.isNullOrEmpty(units)) {
1425 to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
1426 GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
1427 prop.setReturnType(Types.STRING);
1428 to.addToStringProperty(prop);
1433 public String getTypeDefaultConstruction(final LeafSchemaNode node) {
1434 return getTypeDefaultConstruction(node, node.getDefault());
1437 public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
1438 TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1439 QName typeQName = type.getQName();
1440 TypeDefinition<?> base = baseTypeDefForExtendedType(type);
1441 Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
1442 Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
1445 StringBuilder sb = new StringBuilder();
1446 String result = null;
1447 if (base instanceof BinaryTypeDefinition) {
1448 result = binaryToDef(defaultValue);
1449 } else if (base instanceof BitsTypeDefinition) {
1452 Module parent = getParentModule(node);
1453 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1455 if (!(path.hasNext())) {
1456 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
1457 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1458 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1460 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1461 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1462 parentName = BindingMapping.getClassName(parent.getName());
1463 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1465 result = bitsToDef((BitsTypeDefinition) base, className, defaultValue, type.getBaseType() != null);
1466 } else if (base instanceof BooleanTypeDefinition) {
1467 result = typeToDef(Boolean.class, defaultValue);
1468 } else if (base instanceof DecimalTypeDefinition) {
1469 result = typeToDef(BigDecimal.class, defaultValue);
1470 } else if (base instanceof EmptyTypeDefinition) {
1471 result = typeToDef(Boolean.class, defaultValue);
1472 } else if (base instanceof EnumTypeDefinition) {
1473 char[] defValArray = defaultValue.toCharArray();
1474 char first = Character.toUpperCase(defaultValue.charAt(0));
1475 defValArray[0] = first;
1476 String newDefVal = new String(defValArray);
1478 if (type.getBaseType() != null) {
1479 Module m = getParentModule(type);
1480 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1481 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1482 className = packageName + "." + BindingMapping.getClassName(typeQName);
1484 Module parentModule = getParentModule(node);
1485 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1486 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
1487 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1489 result = className + "." + newDefVal;
1490 } else if (base instanceof IdentityrefTypeDefinition) {
1491 throw new UnsupportedOperationException("Cannot get default construction for identityref type");
1492 } else if (base instanceof InstanceIdentifierTypeDefinition) {
1493 throw new UnsupportedOperationException("Cannot get default construction for instance-identifier type");
1494 } else if (BaseTypes.isInt8(base)) {
1495 result = typeToDef(Byte.class, defaultValue);
1496 } else if (BaseTypes.isInt16(base)) {
1497 result = typeToDef(Short.class, defaultValue);
1498 } else if (BaseTypes.isInt32(base)) {
1499 result = typeToDef(Integer.class, defaultValue);
1500 } else if (BaseTypes.isInt64(base)) {
1501 result = typeToDef(Long.class, defaultValue);
1502 } else if (base instanceof LeafrefTypeDefinition) {
1503 result = leafrefToDef(node, (LeafrefTypeDefinition) base, defaultValue);
1504 } else if (base instanceof StringTypeDefinition) {
1505 result = "\"" + defaultValue + "\"";
1506 } else if (BaseTypes.isUint8(base)) {
1507 result = typeToDef(Short.class, defaultValue);
1508 } else if (BaseTypes.isUint16(base)) {
1509 result = typeToDef(Integer.class, defaultValue);
1510 } else if (BaseTypes.isUint32(base)) {
1511 result = typeToDef(Long.class, defaultValue);
1512 } else if (BaseTypes.isUint64(base)) {
1513 result = typeToDef(BigInteger.class, defaultValue);
1514 } else if (base instanceof UnionTypeDefinition) {
1515 result = unionToDef(node);
1521 if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
1522 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
1523 Module m = getParentModule(type);
1524 String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
1525 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
1526 String className = packageName + "." + BindingMapping.getClassName(typeQName);
1527 sb.insert(0, "new " + className + "(");
1528 sb.insert(sb.length(), ')');
1531 return sb.toString();
1534 private static String typeToDef(final Class<?> clazz, final String defaultValue) {
1535 return "new " + clazz.getName() + "(\"" + defaultValue + "\")";
1538 private static String binaryToDef(final String defaultValue) {
1539 StringBuilder sb = new StringBuilder();
1540 BaseEncoding en = BaseEncoding.base64();
1541 byte[] encoded = en.decode(defaultValue);
1542 sb.append("new byte[] {");
1543 for (int i = 0; i < encoded.length; i++) {
1544 sb.append(encoded[i]);
1545 if (i != encoded.length - 1) {
1550 return sb.toString();
1553 private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
1555 private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
1556 List<Bit> bits = new ArrayList<>(type.getBits());
1557 Collections.sort(bits, BIT_NAME_COMPARATOR);
1558 StringBuilder sb = new StringBuilder();
1561 sb.append(className);
1564 for (int i = 0; i < bits.size(); i++) {
1565 if (bits.get(i).getName().equals(defaultValue)) {
1570 if (i != bits.size() - 1) {
1577 return sb.toString();
1580 private Module getParentModule(final SchemaNode node) {
1581 QName qname = node.getPath().getPathFromRoot().iterator().next();
1582 URI namespace = qname.getNamespace();
1583 Date revision = qname.getRevision();
1584 return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1587 private String leafrefToDef(final LeafSchemaNode parentNode, final LeafrefTypeDefinition leafrefType, final String defaultValue) {
1588 Preconditions.checkArgument(leafrefType != null, "Leafref Type Definition reference cannot be NULL!");
1589 Preconditions.checkArgument(leafrefType.getPathStatement() != null,
1590 "The Path Statement for Leafref Type Definition cannot be NULL!");
1592 final RevisionAwareXPath xpath = leafrefType.getPathStatement();
1593 final String strXPath = xpath.toString();
1595 if (strXPath != null) {
1596 if (strXPath.indexOf('[') == -1) {
1597 final Module module = findParentModule(schemaContext, parentNode);
1598 if (module != null) {
1599 final SchemaNode dataNode;
1600 if (xpath.isAbsolute()) {
1601 dataNode = findDataSchemaNode(schemaContext, module, xpath);
1603 dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
1605 String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
1609 return "new java.lang.Object()";
1616 private String unionToDef(final LeafSchemaNode node) {
1617 final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
1621 if (type.getBaseType() != null) {
1622 QName typeQName = type.getQName();
1623 Module module = null;
1624 Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
1625 if (modules.size() > 1) {
1626 for (Module m : modules) {
1627 if (m.getRevision().equals(typeQName.getRevision())) {
1632 if (module == null) {
1633 List<Module> modulesList = new ArrayList<>(modules);
1634 Collections.sort(modulesList, (o1, o2) -> o1.getRevision().compareTo(o2.getRevision()));
1635 module = modulesList.get(0);
1638 module = modules.iterator().next();
1641 String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
1642 className = basePackageName + "." + BindingMapping.getClassName(typeQName);
1644 Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
1645 QName first = path.next();
1646 if (!(path.hasNext())) {
1647 URI namespace = first.getNamespace();
1648 Date revision = first.getRevision();
1649 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1650 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
1651 String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
1652 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
1654 URI namespace = first.getNamespace();
1655 Date revision = first.getRevision();
1656 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
1657 String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
1659 // Backwards compatibility: Union types used to be instantiated in YANG namespace, which is no longer
1660 // the case, as unions are emitted to their correct schema path. Create a proxy instance to meet the
1661 // codepath's expectations
1662 final SchemaPath typePath;
1663 if (type instanceof UnionType) {
1664 typePath = type.getPath();
1666 typePath = UnionType.create(((UnionTypeDefinition)type).getTypes()).getPath();
1669 String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typePath);
1670 className = packageName + "." + BindingMapping.getClassName(node.getQName());
1673 return union(className, node.getDefault(), node);
1676 private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
1677 StringBuilder sb = new StringBuilder();
1679 sb.append(className);
1681 sb.append(defaultValue);
1682 sb.append("\".toCharArray())");
1683 return sb.toString();
1687 public String getConstructorPropertyName(final SchemaNode node) {
1688 if (node instanceof TypeDefinition<?>) {
1696 public String getParamNameFromType(final TypeDefinition<?> type) {
1697 return BindingMapping.getPropertyName(type.getQName().getLocalName());