import java.util.*;
import java.util.concurrent.Future;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.binding.generator.util.BindingGeneratorUtil;
import org.opendaylight.controller.binding.generator.util.ReferencedTypeImpl;
import org.opendaylight.controller.binding.generator.util.Types;
import org.opendaylight.controller.binding.generator.util.generated.type.builder.GeneratedTOBuilderImpl;
import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.*;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.EnumBuilder;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedPropertyBuilder;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTOBuilder;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
+import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
import org.opendaylight.controller.sal.binding.yang.types.TypeProviderImpl;
import org.opendaylight.controller.yang.binding.Notification;
import org.opendaylight.controller.yang.common.QName;
import org.opendaylight.controller.yang.common.RpcResult;
-import org.opendaylight.controller.yang.model.api.*;
+import org.opendaylight.controller.yang.model.api.AugmentationSchema;
+import org.opendaylight.controller.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.controller.yang.model.api.ChoiceNode;
+import org.opendaylight.controller.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.controller.yang.model.api.DataNodeContainer;
+import org.opendaylight.controller.yang.model.api.DataSchemaNode;
+import org.opendaylight.controller.yang.model.api.GroupingDefinition;
+import org.opendaylight.controller.yang.model.api.IdentitySchemaNode;
+import org.opendaylight.controller.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.controller.yang.model.api.LeafSchemaNode;
+import org.opendaylight.controller.yang.model.api.ListSchemaNode;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.NotificationDefinition;
+import org.opendaylight.controller.yang.model.api.RpcDefinition;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.api.SchemaNode;
+import org.opendaylight.controller.yang.model.api.SchemaPath;
+import org.opendaylight.controller.yang.model.api.TypeDefinition;
+import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition;
import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition;
import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
import org.opendaylight.controller.yang.model.util.DataNodeIterator;
import org.opendaylight.controller.yang.model.util.ExtendedType;
import org.opendaylight.controller.yang.model.util.SchemaContextUtil;
+import org.opendaylight.controller.yang.model.util.UnionType;
public final class BindingGeneratorImpl implements BindingGenerator {
final TypeDefinition<?> typeDef = leaf.getType();
Type returnType = null;
- if (!(typeDef instanceof EnumTypeDefinition)) {
+ if (typeDef instanceof EnumTypeDefinition) {
returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef);
- } else {
final EnumTypeDefinition enumTypeDef = enumTypeDefFromExtendedType(typeDef);
final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leafName,
typeBuilder);
returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
}
((TypeProviderImpl) typeProvider).putReferencedType(leaf.getPath(), returnType);
+ } else if (typeDef instanceof UnionType) {
+ GeneratedTOBuilder genTOBuilder = addEnclosedTOToTypeBuilder(typeDef, typeBuilder, leafName);
+ if (genTOBuilder != null) {
+ returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
+ }
+ } else if(typeDef instanceof BitsTypeDefinition) {
+ GeneratedTOBuilder genTOBuilder = addEnclosedTOToTypeBuilder(typeDef, typeBuilder, leafName);
+ if (genTOBuilder != null) {
+ returnType = new ReferencedTypeImpl(genTOBuilder.getPackageName(), genTOBuilder.getName());
+ }
+ } else {
+ returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef);
}
if (returnType != null) {
constructGetter(typeBuilder, leafName, leafDesc, returnType);
- if (!leaf.isConfiguration()) {
- constructSetter(typeBuilder, leafName, leafDesc, returnType);
- }
return true;
}
}
final Type listType = Types.listTypeFor(typeProvider.javaTypeForSchemaDefinitionType(type));
constructGetter(typeBuilder, nodeName, nodeDesc, listType);
- if (!node.isConfiguration()) {
- constructSetter(typeBuilder, nodeName, nodeDesc, listType);
- }
return true;
}
}
final String packageName = packageNameForGeneratedType(basePackageName, schemaNode.getPath());
final GeneratedTypeBuilder rawGenType = addDefaultInterfaceDefinition(packageName, schemaNode);
constructGetter(typeBuilder, listName, schemaNode.getDescription(), Types.listTypeFor(rawGenType));
- if (!schemaNode.isConfiguration()) {
- constructSetter(typeBuilder, listName, schemaNode.getDescription(), Types.listTypeFor(rawGenType));
- }
return true;
}
}
}
return genTOBuilder;
}
+
+
+ private GeneratedTOBuilder addEnclosedTOToTypeBuilder( TypeDefinition<?> typeDef, GeneratedTypeBuilder typeBuilder, String leafName) {
+ String className = parseToClassName(leafName);
+ GeneratedTOBuilder genTOBuilder = null;
+ if (typeDef instanceof UnionType) {
+ genTOBuilder = ((TypeProviderImpl) typeProvider).addUnionGeneratedTypeDefinition(
+ typeBuilder.getPackageName(), typeDef, className);
+ } else if (typeDef instanceof BitsTypeDefinition) {
+ genTOBuilder = ((TypeProviderImpl) typeProvider).bitsTypedefToTransferObject(
+ typeBuilder.getPackageName(), typeDef, className);
+ }
+ if (genTOBuilder != null) {
+ typeBuilder.addEnclosingTransferObject(genTOBuilder);
+ return genTOBuilder;
+ }
+ return null;
+
+ }
+
}
import org.opendaylight.controller.yang.model.api.type.BitsTypeDefinition.Bit;
import org.opendaylight.controller.yang.model.api.type.EnumTypeDefinition.EnumPair;
import org.opendaylight.controller.yang.model.util.ExtendedType;
+import org.opendaylight.controller.yang.model.util.StringType;
import java.util.ArrayList;
import java.util.HashMap;
resolveTypeDefsFromContext();
}
- public void putReferencedType(final SchemaPath refTypePath,
- final Type refType) {
+ public void putReferencedType(final SchemaPath refTypePath, final Type refType) {
if (refTypePath == null) {
- throw new IllegalArgumentException("Path reference of "
- + "Enumeration Type Definition cannot be NULL!");
+ throw new IllegalArgumentException("Path reference of " + "Enumeration Type Definition cannot be NULL!");
}
if (refType == null) {
- throw new IllegalArgumentException("Reference to Enumeration "
- + "Type cannot be NULL!");
+ throw new IllegalArgumentException("Reference to Enumeration " + "Type cannot be NULL!");
}
referencedTypes.put(refTypePath, refType);
}
/*
* (non-Javadoc)
- *
+ *
* @see org.opendaylight.controller.yang.model.type.provider.TypeProvider#
* javaTypeForYangType(java.lang.String)
*/
@Override
public Type javaTypeForYangType(String type) {
- Type t = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
- .javaTypeForYangType(type);
+ Type t = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForYangType(type);
return t;
}
@Override
- public Type javaTypeForSchemaDefinitionType(
- final TypeDefinition<?> typeDefinition) {
+ public Type javaTypeForSchemaDefinitionType(final TypeDefinition<?> typeDefinition) {
Type returnType = null;
if (typeDefinition == null) {
throw new IllegalArgumentException("Type Definition cannot be NULL!");
}
if (typeDefinition.getQName() == null) {
- throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
+ throw new IllegalArgumentException(
+ "Type Definition cannot have non specified QName (QName cannot be NULL!)");
}
if (typeDefinition.getQName().getLocalName() == null) {
throw new IllegalArgumentException("Type Definitions Local Name cannot be NULL!");
returnType = returnTypeForIdentityref(idref);
} else if (baseTypeDef instanceof EnumTypeDefinition) {
final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDef;
- returnType = resolveEnumFromTypeDefinition(enumTypeDef,
- typedefName);
+ returnType = resolveEnumFromTypeDefinition(enumTypeDef, typedefName);
} else {
- final Module module = findParentModuleForTypeDefinition(
- schemaContext, typeDefinition);
+ final Module module = findParentModuleForTypeDefinition(schemaContext, typeDefinition);
if (module != null) {
- final Map<String, Type> genTOs = genTypeDefsContextMap
- .get(module.getName());
+ final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
if (genTOs != null) {
returnType = genTOs.get(typedefName);
}
final IdentityrefTypeDefinition idref = (IdentityrefTypeDefinition) typeDefinition;
returnType = returnTypeForIdentityref(idref);
} else {
- returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
- .javaTypeForSchemaDefinitionType(typeDefinition);
+ returnType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER.javaTypeForSchemaDefinitionType(typeDefinition);
}
}
// TODO: add throw exception when we will be able to resolve ALL yang
return returnType;
}
- public Type generatedTypeForExtendedDefinitionType(
- final TypeDefinition<?> typeDefinition) {
+ public Type generatedTypeForExtendedDefinitionType(final TypeDefinition<?> typeDefinition) {
Type returnType = null;
if (typeDefinition == null) {
throw new IllegalArgumentException("Type Definition cannot be NULL!");
}
if (typeDefinition.getQName() == null) {
- throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
+ throw new IllegalArgumentException(
+ "Type Definition cannot have non specified QName (QName cannot be NULL!)");
}
if (typeDefinition.getQName() == null) {
throw new IllegalArgumentException("Type Definitions Local Name cannot be NULL!");
if (typeDefinition instanceof ExtendedType) {
final TypeDefinition<?> baseTypeDef = baseTypeDefForExtendedType(typeDefinition);
- if (!(baseTypeDef instanceof LeafrefTypeDefinition)
- && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
- final Module module = findParentModuleForTypeDefinition(
- schemaContext, typeDefinition);
+ if (!(baseTypeDef instanceof LeafrefTypeDefinition) && !(baseTypeDef instanceof IdentityrefTypeDefinition)) {
+ final Module module = findParentModuleForTypeDefinition(schemaContext, typeDefinition);
if (module != null) {
- final Map<String, Type> genTOs = genTypeDefsContextMap
- .get(module.getName());
+ final Map<String, Type> genTOs = genTypeDefsContextMap.get(module.getName());
if (genTOs != null) {
returnType = genTOs.get(typedefName);
}
return returnType;
}
- private TypeDefinition<?> baseTypeDefForExtendedType(
- final TypeDefinition<?> extendTypeDef) {
+ private TypeDefinition<?> baseTypeDefForExtendedType(final TypeDefinition<?> extendTypeDef) {
if (extendTypeDef == null) {
throw new IllegalArgumentException("Type Definiition reference cannot be NULL!");
}
if (strXPath.matches(".*//[.* | .*//].*")) {
returnType = Types.typeForClass(Object.class);
} else {
- final Module module = findParentModuleForTypeDefinition(
- schemaContext, leafrefType);
+ final Module module = findParentModuleForTypeDefinition(schemaContext, leafrefType);
if (module != null) {
final DataSchemaNode dataNode;
if (xpath.isAbsolute()) {
- dataNode = findDataSchemaNode(schemaContext, module,
- xpath);
+ dataNode = findDataSchemaNode(schemaContext, module, xpath);
} else {
- dataNode = findDataSchemaNodeForRelativeXPath(
- schemaContext, module, leafrefType, xpath);
+ dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, leafrefType, xpath);
}
if (leafContainsEnumDefinition(dataNode)) {
returnType = referencedTypes.get(dataNode.getPath());
} else if (leafListContainsEnumDefinition(dataNode)) {
- returnType = Types.listTypeFor(referencedTypes
- .get(dataNode.getPath()));
+ returnType = Types.listTypeFor(referencedTypes.get(dataNode.getPath()));
} else {
returnType = resolveTypeFromDataSchemaNode(dataNode);
}
return false;
}
- private Enumeration resolveEnumFromTypeDefinition(
- final EnumTypeDefinition enumTypeDef, final String enumName) {
+ private Enumeration resolveEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final String enumName) {
if (enumTypeDef == null) {
throw new IllegalArgumentException("EnumTypeDefinition reference cannot be NULL!");
}
final String enumerationName = parseToClassName(enumName);
- Module module = findParentModuleForTypeDefinition(schemaContext,
- enumTypeDef);
+ Module module = findParentModuleForTypeDefinition(schemaContext, enumTypeDef);
final String basePackageName = moduleNamespaceToPackageName(module);
- final EnumBuilder enumBuilder = new EnumerationBuilderImpl(
- basePackageName, enumerationName);
+ final EnumBuilder enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
updateEnumPairsFromEnumTypeDef(enumTypeDef, enumBuilder);
return enumBuilder.toInstance(null);
}
- private EnumBuilder resolveInnerEnumFromTypeDefinition(
- final EnumTypeDefinition enumTypeDef, final String enumName,
+ private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final String enumName,
final GeneratedTypeBuilder typeBuilder) {
if (enumTypeDef == null) {
throw new IllegalArgumentException("EnumTypeDefinition reference cannot be NULL!");
}
final String enumerationName = parseToClassName(enumName);
- final EnumBuilder enumBuilder = typeBuilder
- .addEnumeration(enumerationName);
+ final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
updateEnumPairsFromEnumTypeDef(enumTypeDef, enumBuilder);
return enumBuilder;
}
- private void updateEnumPairsFromEnumTypeDef(
- final EnumTypeDefinition enumTypeDef, final EnumBuilder enumBuilder) {
+ private void updateEnumPairsFromEnumTypeDef(final EnumTypeDefinition enumTypeDef, final EnumBuilder enumBuilder) {
if (enumBuilder != null) {
final List<EnumPair> enums = enumTypeDef.getValues();
if (enums != null) {
int listIndex = 0;
for (final EnumPair enumPair : enums) {
if (enumPair != null) {
- final String enumPairName = parseToClassName(enumPair
- .getName());
+ final String enumPairName = parseToClassName(enumPair.getName());
Integer enumPairValue = enumPair.getValue();
if (enumPairValue == null) {
final String moduleName = module.getName();
final String basePackageName = moduleNamespaceToPackageName(module);
- final Set<TypeDefinition<?>> typeDefinitions = module
- .getTypeDefinitions();
+ final Set<TypeDefinition<?>> typeDefinitions = module.getTypeDefinitions();
final Map<String, Type> typeMap = new HashMap<>();
genTypeDefsContextMap.put(moduleName, typeMap);
for (final TypeDefinition<?> typedef : typeDefinitions) {
typedefToGeneratedType(basePackageName, moduleName, typedef);
}
- final List<ExtendedType> extUnions = UnionDependencySort
- .sort(typeDefinitions);
+ final List<ExtendedType> extUnions = UnionDependencySort.sort(typeDefinitions);
for (final ExtendedType extUnionType : extUnions) {
- addUnionGeneratedTypeDefinition(basePackageName,
- extUnionType);
+ addUnionGeneratedTypeDefinition(basePackageName, extUnionType, null);
}
}
}
}
- private Type typedefToGeneratedType(final String basePackageName,
- final String moduleName, final TypeDefinition<?> typedef) {
- if ((basePackageName != null) && (moduleName != null)
- && (typedef != null) && (typedef.getQName() != null)) {
+ private Type typedefToGeneratedType(final String basePackageName, final String moduleName,
+ final TypeDefinition<?> typedef) {
+ if ((basePackageName != null) && (moduleName != null) && (typedef != null) && (typedef.getQName() != null)) {
final String typedefName = typedef.getQName().getLocalName();
final TypeDefinition<?> baseTypeDefinition = baseTypeDefForExtendedType(typedef);
Type returnType;
if (baseTypeDefinition instanceof EnumTypeDefinition) {
final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) baseTypeDefinition;
- returnType = resolveEnumFromTypeDefinition(enumTypeDef,
- typedefName);
+ returnType = resolveEnumFromTypeDefinition(enumTypeDef, typedefName);
} else if (baseTypeDefinition instanceof BitsTypeDefinition) {
final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) baseTypeDefinition;
- returnType = bitsTypedefToTransferObject(bitsTypeDefinition,
- basePackageName, typedefName);
+ GeneratedTOBuilder genTOBuilder = bitsTypedefToTransferObject(basePackageName, bitsTypeDefinition,
+ typedefName);
+ returnType = genTOBuilder.toInstance();
} else {
final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
.javaTypeForSchemaDefinitionType(baseTypeDefinition);
- returnType = wrapJavaTypeIntoTO(basePackageName, typedef,
- javaType);
+ returnType = wrapJavaTypeIntoTO(basePackageName, typedef, javaType);
}
if (returnType != null) {
- final Map<String, Type> typeMap = genTypeDefsContextMap
- .get(moduleName);
+ final Map<String, Type> typeMap = genTypeDefsContextMap.get(moduleName);
if (typeMap != null) {
typeMap.put(typedefName, returnType);
}
return null;
}
- private GeneratedTransferObject wrapJavaTypeIntoTO(
- final String basePackageName, final TypeDefinition<?> typedef,
+ private GeneratedTransferObject wrapJavaTypeIntoTO(final String basePackageName, final TypeDefinition<?> typedef,
final Type javaType) {
if (javaType != null) {
final String typedefName = typedef.getQName().getLocalName();
final String propertyName = parseToValidParamName(typedefName);
- final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(
- basePackageName, typedef);
+ final GeneratedTOBuilder genTOBuilder = typedefToTransferObject(basePackageName, typedef);
- final GeneratedPropertyBuilder genPropBuilder = genTOBuilder
- .addProperty(propertyName);
+ final GeneratedPropertyBuilder genPropBuilder = genTOBuilder.addProperty(propertyName);
genPropBuilder.setReturnType(javaType);
genTOBuilder.addEqualsIdentity(genPropBuilder);
genTOBuilder.addHashIdentity(genPropBuilder);
genTOBuilder.addToStringProperty(genPropBuilder);
- if (javaType == BaseYangTypes.STRING_TYPE) {
- if (typedef instanceof ExtendedType) {
- List<PatternConstraint> patternConstraints = ((ExtendedType) typedef).getPatterns();
- List<String> regularExpressions = new ArrayList<String>();
- String regEx;
- String modifiedRegEx;
- for (PatternConstraint ptrnCons : patternConstraints) {
- regEx = ptrnCons.getRegularExpression();
- modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
- regularExpressions.add(modifiedRegEx);
- }
-
- genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE),
- TypeConstants.PATTERN_CONSTANT_NAME, regularExpressions);
- }
- }
-
+
+ if (typedef instanceof ExtendedType) {
+ final List<String> regExps = resolveRegExpressionsFromTypedef((ExtendedType) typedef);
+ addStringRegExAsConstant(genTOBuilder, regExps);
+ }
+
return genTOBuilder.toInstance();
}
return null;
}
- private void addUnionGeneratedTypeDefinition(final String basePackageName,
- final TypeDefinition<?> typedef) {
+ public GeneratedTOBuilder addUnionGeneratedTypeDefinition(final String basePackageName,
+ final TypeDefinition<?> typedef, String typeDefName) {
if (basePackageName == null) {
throw new IllegalArgumentException("Base Package Name cannot be NULL!");
}
throw new IllegalArgumentException("Type Definition cannot be NULL!");
}
if (typedef.getQName() == null) {
- throw new IllegalArgumentException("Type Definition cannot have non specified QName (QName cannot be NULL!)");
+ throw new IllegalArgumentException(
+ "Type Definition cannot have non specified QName (QName cannot be NULL!)");
}
final TypeDefinition<?> baseTypeDefinition = typedef.getBaseType();
- if ((baseTypeDefinition != null)
- && (baseTypeDefinition instanceof UnionTypeDefinition)) {
+ if ((baseTypeDefinition != null) && (baseTypeDefinition instanceof UnionTypeDefinition)) {
+ final Module parentModule = findParentModuleForTypeDefinition(schemaContext, typedef);
final UnionTypeDefinition unionTypeDef = (UnionTypeDefinition) baseTypeDefinition;
final List<TypeDefinition<?>> unionTypes = unionTypeDef.getTypes();
- final Module parentModule = findParentModuleForTypeDefinition(
- schemaContext, typedef);
Map<String, Type> genTOsMap = null;
if (parentModule != null && parentModule.getName() != null) {
genTOsMap = genTypeDefsContextMap.get(parentModule.getName());
}
- final GeneratedTOBuilder unionGenTransObject = typedefToTransferObject(
- basePackageName, typedef);
- if ((unionTypes != null) && (unionGenTransObject != null)) {
- for (final TypeDefinition<?> unionType : unionTypes) {
- final String typeName = unionType.getQName().getLocalName();
- if (unionType instanceof ExtendedType) {
- final Module unionTypeModule = findParentModuleForTypeDefinition(
- schemaContext, unionType);
- if (unionTypeModule != null
- && unionTypeModule.getName() != null) {
- final Map<String, Type> innerGenTOs = genTypeDefsContextMap
- .get(unionTypeModule.getName());
-
- final GeneratedTransferObject genTransferObject = (GeneratedTransferObject) innerGenTOs
- .get(typeName);
- if (genTransferObject != null) {
- updateUnionTypeAsProperty(unionGenTransObject,
- genTransferObject,
- genTransferObject.getName());
+ final GeneratedTOBuilder unionGenTransObject;
+ if (typeDefName != null && !typeDefName.isEmpty()) {
+ final String typeName = parseToClassName(typeDefName);
+ unionGenTransObject = new GeneratedTOBuilderImpl(basePackageName, typeName);
+ } else {
+ unionGenTransObject = typedefToTransferObject(basePackageName, typedef);
+ }
+ unionGenTransObject.setIsUnion(true);
+
+ final List<String> regularExpressions = new ArrayList<String>();
+ for (final TypeDefinition<?> unionType : unionTypes) {
+ final String typeName = unionType.getQName().getLocalName();
+ if (unionType instanceof ExtendedType) {
+ final Module unionTypeModule = findParentModuleForTypeDefinition(schemaContext, unionType);
+ if (unionTypeModule != null && unionTypeModule.getName() != null) {
+ final Map<String, Type> innerGenTOs = genTypeDefsContextMap.get(unionTypeModule.getName());
+
+ final GeneratedTransferObject genTransferObject = (GeneratedTransferObject) innerGenTOs
+ .get(typeName);
+ if (genTransferObject != null) {
+ updateUnionTypeAsProperty(unionGenTransObject, genTransferObject,
+ genTransferObject.getName());
+ } else {
+ final TypeDefinition<?> baseType = baseTypeDefForExtendedType(unionType);
+ if (typeName.equals(baseType.getQName().getLocalName())) {
+ final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+ .javaTypeForSchemaDefinitionType(baseType);
+ if (javaType != null) {
+ updateUnionTypeAsProperty(unionGenTransObject, javaType, typeName);
+ }
+ }
+ if (baseType instanceof StringType) {
+ regularExpressions.addAll(resolveRegExpressionsFromTypedef((ExtendedType) unionType));
}
}
- } else if (unionType instanceof EnumTypeDefinition) {
- final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(
- (EnumTypeDefinition) unionType, typeName,
- unionGenTransObject);
- final Type enumRefType = new ReferencedTypeImpl(
- enumBuilder.getPackageName(),
- enumBuilder.getName());
- updateUnionTypeAsProperty(unionGenTransObject,
- enumRefType, typeName);
- } else {
- final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
- .javaTypeForSchemaDefinitionType(unionType);
- if (javaType != null) {
- updateUnionTypeAsProperty(unionGenTransObject,
- javaType, typeName);
- }
+ }
+ } else if (unionType instanceof EnumTypeDefinition) {
+ final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition((EnumTypeDefinition) unionType,
+ typeName, unionGenTransObject);
+ final Type enumRefType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
+ updateUnionTypeAsProperty(unionGenTransObject, enumRefType, typeName);
+ } else {
+ final Type javaType = BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+ .javaTypeForSchemaDefinitionType(unionType);
+ if (javaType != null) {
+ updateUnionTypeAsProperty(unionGenTransObject, javaType, typeName);
}
}
- genTOsMap.put(typedef.getQName().getLocalName(),
- unionGenTransObject.toInstance());
}
+ if (!regularExpressions.isEmpty()) {
+ addStringRegExAsConstant(unionGenTransObject, regularExpressions);
+ }
+
+ genTOsMap.put(typedef.getQName().getLocalName(), unionGenTransObject.toInstance());
+ return unionGenTransObject;
}
+ return null;
}
- private void updateUnionTypeAsProperty(
- final GeneratedTOBuilder unionGenTransObject, final Type type,
+ private void updateUnionTypeAsProperty(final GeneratedTOBuilder unionGenTransObject, final Type type,
final String propertyName) {
if (unionGenTransObject != null && type != null) {
- final GeneratedPropertyBuilder propBuilder = unionGenTransObject
- .addProperty(parseToValidParamName(propertyName));
- propBuilder.setReturnType(type);
- propBuilder.setReadOnly(false);
-
- if (!(type instanceof Enumeration)) {
- unionGenTransObject.addEqualsIdentity(propBuilder);
- unionGenTransObject.addHashIdentity(propBuilder);
- unionGenTransObject.addToStringProperty(propBuilder);
+ if (!unionGenTransObject.containsProperty(propertyName)) {
+ final GeneratedPropertyBuilder propBuilder = unionGenTransObject
+ .addProperty(parseToValidParamName(propertyName));
+ propBuilder.setReturnType(type);
+
+ if (!(type instanceof Enumeration)) {
+ unionGenTransObject.addEqualsIdentity(propBuilder);
+ unionGenTransObject.addHashIdentity(propBuilder);
+ unionGenTransObject.addToStringProperty(propBuilder);
+ }
}
}
}
- private GeneratedTOBuilder typedefToTransferObject(
- final String basePackageName, final TypeDefinition<?> typedef) {
+ private GeneratedTOBuilder typedefToTransferObject(final String basePackageName, final TypeDefinition<?> typedef) {
- final String packageName = packageNameForGeneratedType(basePackageName,
- typedef.getPath());
+ final String packageName = packageNameForGeneratedType(basePackageName, typedef.getPath());
final String typeDefTOName = typedef.getQName().getLocalName();
- if ((packageName != null) && (typedef != null)
- && (typeDefTOName != null)) {
+ if ((packageName != null) && (typedef != null) && (typeDefTOName != null)) {
final String genTOName = parseToClassName(typeDefTOName);
- final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(
- packageName, genTOName);
+ final GeneratedTOBuilder newType = new GeneratedTOBuilderImpl(packageName, genTOName);
return newType;
}
return null;
}
- private GeneratedTransferObject bitsTypedefToTransferObject(
- final BitsTypeDefinition bitsTypeDefinition, final String basePackageName, final String typedefName) {
+ public GeneratedTOBuilder bitsTypedefToTransferObject(final String basePackageName,
+ final TypeDefinition<?> typeDef, String typeDefName) {
- if (bitsTypeDefinition == null) {
- throw new IllegalArgumentException("Bits TypeDefinition cannot be NULL!");
+ if (typeDef == null) {
+ throw new IllegalArgumentException("typeDef cannot be NULL!");
}
if (basePackageName == null) {
throw new IllegalArgumentException("Base Package Name cannot be NULL!");
}
- if (typedefName == null) {
- throw new IllegalArgumentException("Type Definition Local Name cannot be NULL!");
+
+ if (typeDef instanceof BitsTypeDefinition) {
+ BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
+
+ final String typeName = parseToClassName(typeDefName);
+ final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
+
+ final List<Bit> bitList = bitsTypeDefinition.getBits();
+ GeneratedPropertyBuilder genPropertyBuilder;
+ for (final Bit bit : bitList) {
+ String name = bit.getName();
+ genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
+ genPropertyBuilder.setReadOnly(false);
+ genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
+
+ genTOBuilder.addEqualsIdentity(genPropertyBuilder);
+ genTOBuilder.addHashIdentity(genPropertyBuilder);
+ genTOBuilder.addToStringProperty(genPropertyBuilder);
+ }
+
+ return genTOBuilder;
}
+ return null;
+ }
- final String typeDefName = parseToClassName(typedefName);
- final GeneratedTOBuilder genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeDefName);
+ private List<String> resolveRegExpressionsFromTypedef(ExtendedType typedef) {
+ final List<String> regExps = new ArrayList<String>();
+ if (typedef == null) {
+ throw new IllegalArgumentException("typedef can't be null");
+ }
+ final TypeDefinition<?> strTypeDef = baseTypeDefForExtendedType(typedef);
+ if (strTypeDef instanceof StringType) {
+ final List<PatternConstraint> patternConstraints = typedef.getPatterns();
+ if (!patternConstraints.isEmpty()) {
+ String regEx;
+ String modifiedRegEx;
+ for (PatternConstraint patternConstraint : patternConstraints) {
+ regEx = patternConstraint.getRegularExpression();
+ modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
+ regExps.add(modifiedRegEx);
+ }
+ }
+ }
+ return regExps;
+ }
- final List<Bit> bitList = bitsTypeDefinition.getBits();
- GeneratedPropertyBuilder genPropertyBuilder;
- for (final Bit bit : bitList) {
- String name = bit.getName();
- genPropertyBuilder = genTOBuilder.addProperty(parseToValidParamName(name));
- genPropertyBuilder.setReadOnly(false);
- genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
+ private void addStringRegExAsConstant(GeneratedTOBuilder genTOBuilder, List<String> regularExpressions) {
+ if (genTOBuilder == null)
+ throw new IllegalArgumentException("genTOBuilder can't be null");
+ if (regularExpressions == null)
+ throw new IllegalArgumentException("regularExpressions can't be null");
- genTOBuilder.addEqualsIdentity(genPropertyBuilder);
- genTOBuilder.addHashIdentity(genPropertyBuilder);
- genTOBuilder.addToStringProperty(genPropertyBuilder);
+ if (!regularExpressions.isEmpty()) {
+ genTOBuilder.addConstant(Types.listTypeFor(BaseYangTypes.STRING_TYPE), TypeConstants.PATTERN_CONSTANT_NAME,
+ regularExpressions);
}
- return genTOBuilder.toInstance();
}
-
+
}
import org.junit.BeforeClass;
import org.junit.Test;
import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
+import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
import org.opendaylight.controller.sal.binding.model.api.Type;
import org.opendaylight.controller.yang.model.api.Module;
import org.opendaylight.controller.yang.model.api.SchemaContext;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
public class AugmentRleativeXPathTest {
assertNotNull("genTypes is null", genTypes);
assertFalse("genTypes is empty", genTypes.isEmpty());
+
+ GeneratedTransferObject gtInterfaceKey = null;
+ GeneratedType gtInterface = null;
+ GeneratedType gtTunnel = null;
+ GeneratedTransferObject gtTunnelKey = null;
- //TODO: implement test
+ for (final Type type : genTypes) {
+ if (type.getName().equals("InterfaceKey") && type.getPackageName().contains("augment._abstract.topology")) {
+ gtInterfaceKey = (GeneratedTransferObject) type;
+ } else if (type.getName().equals("Interface") && type.getPackageName().contains("augment._abstract.topology")) {
+ gtInterface = (GeneratedType) type;
+ } else if (type.getName().equals("Tunnel") && type.getPackageName().contains("augment._abstract.topology")) {
+ gtTunnel = (GeneratedType) type;
+ } else if (type.getName().equals("TunnelKey") && type.getPackageName().contains("augment._abstract.topology")) {
+ gtTunnelKey = (GeneratedTransferObject) type;
+ }
+ }
+
+ // 'Interface
+ assertNotNull("gtInterface is null", gtInterface);
+ final List<MethodSignature> gtInterfaceMethods = gtInterface.getMethodDefinitions();
+ assertNotNull("gtInterfaceMethods is null", gtInterfaceMethods);
+ MethodSignature getIfcKeyMethod = null;
+ for (final MethodSignature method : gtInterfaceMethods) {
+ if (method.getName().equals("getInterfaceKey")) {
+ getIfcKeyMethod = method;
+ break;
+ }
+ }
+ assertNotNull("getIfcKeyMethod is null", getIfcKeyMethod);
+ assertNotNull("getIfcKeyMethod.getReturnType() is null", getIfcKeyMethod.getReturnType());
+ assertFalse("getIfcKeyMethod.getReturnType() should not be Void",
+ getIfcKeyMethod.getReturnType().equals("java.lang.Void"));
+ assertTrue("getIfcKeyMethod.getReturnType().getName() must be InterfaceKey",
+ getIfcKeyMethod.getReturnType().getName().equals("InterfaceKey"));
+
+ // 'InterfaceKey'
+ assertNotNull("gtInterfaceKey is null", gtInterfaceKey);
+ final List<GeneratedProperty> properties = gtInterfaceKey.getProperties();
+ assertNotNull("properties is null", properties);
+ GeneratedProperty gtInterfaceId = null;
+ for (final GeneratedProperty property : properties) {
+ if (property.getName().equals("InterfaceId")) {
+ gtInterfaceId = property;
+ break;
+ }
+ }
+ assertNotNull("gtInterfaceId is null", gtInterfaceId);
+ assertNotNull("gtInterfaceId.getReturnType() is null", gtInterfaceId.getReturnType());
+ assertFalse("gtInterfaceId.getReturnType() should not be Void",
+ gtInterfaceId.getReturnType().equals("java.lang.Void"));
+ assertTrue("gtInterfaceId.getReturnType().getName() must be String",
+ gtInterfaceId.getReturnType().getName().equals("String"));
+
+ // 'Tunnel'
+ assertNotNull("gtTunnel is null", gtTunnel);
+ final List<MethodSignature> tunnelMethods = gtTunnel.getMethodDefinitions();
+ assertNotNull("tunnelMethods is null", tunnelMethods);
+ MethodSignature getTunnelKeyMethod = null;
+ for (MethodSignature method : tunnelMethods) {
+ if (method.getName().equals("getTunnelKey")) {
+ getTunnelKeyMethod = method;
+ break;
+ }
+ }
+ assertNotNull("getTunnelKeyMethod is null", getTunnelKeyMethod);
+ assertNotNull("getTunnelKeyMethod.getReturnType()",
+ getTunnelKeyMethod.getReturnType());
+ assertFalse("getTunnelKeyMethod.getReturnType() should not be Void",
+ getTunnelKeyMethod.getReturnType().equals("java.lang.Void"));
+ assertTrue("getTunnelKeyMethod.getReturnType().getName() must be TunnelKey",
+ getTunnelKeyMethod.getReturnType().getName().equals("TunnelKey"));
+
+ // 'TunnelKey'
+ assertNotNull("gtTunnelKey is null", gtTunnelKey);
+ final List<GeneratedProperty> tunnelKeyProperties = gtTunnelKey.getProperties();
+ assertNotNull("tunnelKeyProperties is null", tunnelKeyProperties);
+
+ GeneratedProperty gtTunnelId = null;
+ for (final GeneratedProperty property : tunnelKeyProperties) {
+ if (property.getName().equals("TunnelId")) {
+ gtTunnelId = property;
+ }
+ }
+ assertNotNull("gtTunnelId is null", gtTunnelId);
+ assertNotNull("gtTunnelId.getReturnType() is null",
+ gtTunnelId.getReturnType());
+ assertFalse("gtTunnelId.getReturnType() should not be Void",
+ gtTunnelId.getReturnType().equals("java.lang.Void"));
+ assertTrue("gtTunnelId.getReturnType().getName() must be Uri",
+ gtTunnelId.getReturnType().getName().equals("Uri"));
}
+
}
assertNotNull("Generated Interface cannot contain NULL reference for " +
"Method Signature Definitions!", methods);
- assertEquals("Expected count of method signature definitions is 21",
- 21, methods.size());
+ assertEquals("Expected count of method signature definitions is 14",
+ 14, methods.size());
Enumeration ianaIfType = null;
for (final MethodSignature method : methods) {
if (method.getName().equals("getType")) {
augment "at:topology/at:network-links/at:network-link" {
leaf interface {
type leafref {
- path "../../../atp:interfaces/atp:interface/atp:interface-id";
+ path "../atp:interfaces/atp:interface/atp:interface-id";
}
}
}
return builder;
}
+ @Override
+ public void addEnclosingTransferObject(final GeneratedTOBuilder genTOBuilder) {
+ if (genTOBuilder == null) {
+ throw new IllegalArgumentException("Parameter genTOBuilder cannot be null!");
+ }
+ enclosingTransferObjects.add(genTOBuilder);
+ }
+
@Override
public void addComment(String comment) {
this.comment = comment;
return builder;
}
- @Override
- public void setAbstract(boolean isAbstract) {
- this.isAbstract = isAbstract;
- }
+ @Override
+ public void setAbstract(boolean isAbstract) {
+ this.isAbstract = isAbstract;
+ }
- @Override
+ @Override
public boolean addImplementsType(Type genType) {
if (genType == null) {
throw new IllegalArgumentException("Type cannot be null");
if (name == null) {
throw new IllegalArgumentException("Name of enumeration cannot be null!");
}
- final EnumBuilder builder = new EnumerationBuilderImpl(
- getFullyQualifiedName(), name);
+ final EnumBuilder builder = new EnumerationBuilderImpl(getFullyQualifiedName(), name);
enumDefinitions.add(builder);
return builder;
}
return builder;
}
+ @Override
+ public boolean containsMethod(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("Parameter name can't be null");
+ }
+ for (MethodSignatureBuilder methodDefinition : methodDefinitions) {
+ if (name.equals(methodDefinition.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
- result = prime * result
- + ((getPackageName() == null) ? 0 : getPackageName().hashCode());
+ result = prime * result + ((getPackageName() == null) ? 0 : getPackageName().hashCode());
return result;
}
private final List<GeneratedPropertyBuilder> equalsProperties = new ArrayList<>();
private final List<GeneratedPropertyBuilder> hashProperties = new ArrayList<>();
private final List<GeneratedPropertyBuilder> toStringProperties = new ArrayList<>();
+ private boolean isUnionType = false;
public GeneratedTOBuilderImpl(String packageName, String name) {
super(packageName, name);
return builder;
}
+ @Override
+ public boolean containsProperty(String name) {
+ if (name == null) {
+ throw new IllegalArgumentException("Parameter name can't be null");
+ }
+ for (GeneratedPropertyBuilder property : properties) {
+ if (name.equals(property.getName())) {
+ return true;
+ }
+ }
+ return false;
+ }
+
/**
* Add new Method Signature definition for Generated Type Builder and
- * returns Method Signature Builder for specifying all Method parameters.
- * <br>
- * Name of Method cannot be <code>null</code>,
- * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
- * <br>
+ * returns Method Signature Builder for specifying all Method parameters. <br>
+ * Name of Method cannot be <code>null</code>, if it is <code>null</code>
+ * the method SHOULD throw {@link IllegalArgumentException} <br>
* By <i>Default</i> the MethodSignatureBuilder SHOULD be pre-set as
- * {@link MethodSignatureBuilder#setAbstract(false)}, {@link MethodSignatureBuilder#setFinal(false)} and
+ * {@link MethodSignatureBuilder#setAbstract(false)},
+ * {@link MethodSignatureBuilder#setFinal(false)} and
* {@link MethodSignatureBuilder#setAccessModifier(PUBLIC)}
- *
- * @param name Name of Method
+ *
+ * @param name
+ * Name of Method
* @return <code>new</code> instance of Method Signature Builder.
*/
@Override
@Override
public GeneratedTransferObject toInstance() {
- return new GeneratedTransferObjectImpl(null, getPackageName(), getName(), getComment(),
- getAnnotations(), isAbstract(), extendsType, getImplementsTypes(), getEnclosedTypes(),
- getEnclosedTransferObjects(), getConstants(), getEnumerations(), getMethodDefinitions(), properties,
- equalsProperties, hashProperties, toStringProperties);
+ return new GeneratedTransferObjectImpl(null, getPackageName(), getName(), getComment(), getAnnotations(),
+ isAbstract(), extendsType, getImplementsTypes(), getEnclosedTypes(), getEnclosedTransferObjects(),
+ getConstants(), getEnumerations(), getMethodDefinitions(), properties, equalsProperties,
+ hashProperties, toStringProperties, isUnionType);
}
@Override
return builder.toString();
}
+ @Override
+ public void setIsUnion(boolean isUnion) {
+ this.isUnionType = isUnion;
+ }
+
private static final class GeneratedTransferObjectImpl extends AbstractGeneratedType implements
GeneratedTransferObject {
private final List<GeneratedProperty> hashCodeProperties;
private final List<GeneratedProperty> stringProperties;
private final GeneratedTransferObject extendsType;
-
- GeneratedTransferObjectImpl(final Type parent,
- final String packageName,
- final String name, final String comment,
- final List<AnnotationTypeBuilder> annotationBuilders,
- final boolean isAbstract,
- final GeneratedTransferObject extendsType,
- final List<Type> implementsTypes,
- final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
- final List<GeneratedTOBuilder> enclosedGenTOBuilders,
- final List<Constant> constants,
- final List<EnumBuilder> enumBuilders,
- final List<MethodSignatureBuilder> methodBuilders,
- final List<GeneratedPropertyBuilder> propBuilders,
- final List<GeneratedPropertyBuilder> equalsBuilders,
- final List<GeneratedPropertyBuilder> hashCodeBuilders,
- final List<GeneratedPropertyBuilder> stringBuilders) {
+ private final boolean isUnionType;
+
+ GeneratedTransferObjectImpl(final Type parent, final String packageName, final String name,
+ final String comment, final List<AnnotationTypeBuilder> annotationBuilders, final boolean isAbstract,
+ final GeneratedTransferObject extendsType, final List<Type> implementsTypes,
+ final List<GeneratedTypeBuilder> enclosedGenTypeBuilders,
+ final List<GeneratedTOBuilder> enclosedGenTOBuilders, final List<Constant> constants,
+ final List<EnumBuilder> enumBuilders, final List<MethodSignatureBuilder> methodBuilders,
+ final List<GeneratedPropertyBuilder> propBuilders, final List<GeneratedPropertyBuilder> equalsBuilders,
+ final List<GeneratedPropertyBuilder> hashCodeBuilders,
+ final List<GeneratedPropertyBuilder> stringBuilders, final boolean isUnionType) {
super(parent, packageName, name, comment, annotationBuilders, isAbstract, implementsTypes,
- enclosedGenTypeBuilders,
- enclosedGenTOBuilders, enumBuilders, constants, methodBuilders);
+ enclosedGenTypeBuilders, enclosedGenTOBuilders, enumBuilders, constants, methodBuilders);
this.extendsType = extendsType;
this.properties = toUnmodifiableProperties(propBuilders);
this.equalsProperties = toUnmodifiableProperties(equalsBuilders);
this.hashCodeProperties = toUnmodifiableProperties(hashCodeBuilders);
this.stringProperties = toUnmodifiableProperties(stringBuilders);
+ this.isUnionType = isUnionType;
+ }
+
+ @Override
+ public boolean isUnionType() {
+ return isUnionType;
}
- private List<GeneratedProperty> toUnmodifiableProperties(
- final List<GeneratedPropertyBuilder> propBuilders) {
+ private List<GeneratedProperty> toUnmodifiableProperties(final List<GeneratedPropertyBuilder> propBuilders) {
final List<GeneratedProperty> properties = new ArrayList<>();
for (final GeneratedPropertyBuilder builder : propBuilders) {
properties.add(builder.toInstance(this));
import org.opendaylight.controller.sal.binding.model.api.AnnotationType;
import org.opendaylight.controller.sal.binding.model.api.MethodSignature;
import org.opendaylight.controller.sal.binding.model.api.Type;
-import org.opendaylight.controller.sal.binding.model.api.type.builder.AnnotationTypeBuilder;
import org.opendaylight.controller.sal.binding.model.api.type.builder.MethodSignatureBuilder;
final class MethodSignatureBuilderImpl extends AbstractTypeMemberBuilder implements MethodSignatureBuilder {
@Override
public MethodSignature toInstance(Type definingType) {
final List<AnnotationType> annotations = toAnnotationTypes();
- return new MethodSignatureImpl(definingType, getName(), annotations,
- getComment(), getAccessModifier(), getReturnType(), parameters, isFinal(), isAbstract);
+ return new MethodSignatureImpl(definingType, getName(), annotations, getComment(), getAccessModifier(),
+ getReturnType(), parameters, isFinal(), isAbstract);
}
-
+
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getName() == null) ? 0 : getName().hashCode());
- result = prime * result
- + ((parameters == null) ? 0 : parameters.hashCode());
- result = prime * result
- + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
+ result = prime * result + ((parameters == null) ? 0 : parameters.hashCode());
+ result = prime * result + ((getReturnType() == null) ? 0 : getReturnType().hashCode());
return result;
}
import java.util.List;
import java.util.Map;
-import org.opendaylight.controller.binding.generator.util.TypeConstants;
import org.opendaylight.controller.sal.binding.model.api.*;
public final class ClassCodeGenerator implements CodeGenerator {
private Map<String, String> imports;
- @Override
- public Writer generate(Type type) throws IOException {
- final Writer writer = new StringWriter();
+ private void generatePackage(Writer writer, String packageName) throws IOException {
+ writer.write(GeneratorUtil.createPackageDeclaration(packageName));
+ writer.write(NL);
+ }
- if (type instanceof GeneratedTransferObject) {
- GeneratedTransferObject genTO = (GeneratedTransferObject) type;
- imports = GeneratorUtil.createImports(genTO);
+ private void generateImports(Writer writer) throws IOException {
+ List<String> importLines = GeneratorUtil.createImportLines(imports, null);
+ for (String line : importLines) {
+ writer.write(line + NL);
+ }
+ writer.write(NL);
+ }
- final String currentPkg = genTO.getPackageName();
- final List<GeneratedProperty> fields = genTO.getProperties();
- final List<Enumeration> enums = genTO.getEnumerations();
- final List<Constant> consts = genTO.getConstantDefinitions();
+ private void generateClassBody(Writer writer, GeneratedTransferObject genTO, String packageName, String indent,
+ boolean isInnerClass) throws IOException {
+ final List<GeneratedProperty> fields = genTO.getProperties();
+ final List<Enumeration> enums = genTO.getEnumerations();
+ final List<Constant> consts = genTO.getConstantDefinitions();
- writer.write(GeneratorUtil.createPackageDeclaration(currentPkg));
- writer.write(NL);
+ writer.write(GeneratorUtil.createClassDeclaration(genTO, indent, imports, genTO.isAbstract(), isInnerClass));
+ writer.write(NL);
+ writer.write(NL);
- List<String> importLines = GeneratorUtil.createImportLines(imports);
- for (String line : importLines) {
- writer.write(line + NL);
+ if (consts != null) {
+ for (Constant con : consts) {
+ writer.write(GeneratorUtil.createConstant(con, indent + TAB, imports, packageName));
+ writer.write(NL);
+ }
+ }
+
+ if (enums != null) {
+ EnumGenerator enumGenerator = new EnumGenerator();
+ for (Enumeration e : enums) {
+ writer.write(enumGenerator.generateInnerEnumeration(e, indent + TAB).toString());
+ writer.write(NL);
+ }
+ }
+
+ writer.write(GeneratorUtil.createStaticInicializationBlock(genTO, indent + TAB));
+
+ if (fields != null) {
+ for (GeneratedProperty field : fields) {
+ writer.write(GeneratorUtil.createField(field, indent + TAB, imports, packageName) + NL);
}
- writer.write(NL);
- writer.write(GeneratorUtil.createClassDeclaration(genTO, "", imports, genTO.isAbstract()));
writer.write(NL);
+ if (genTO.isUnionType()) {
+ writer.write(GeneratorUtil.createConstructors(genTO, indent + TAB, imports, genTO.isAbstract()));
+ } else {
+ writer.write(GeneratorUtil.createConstructor(genTO, indent + TAB, imports, genTO.isAbstract()) + NL);
+ }
writer.write(NL);
- if (consts != null) {
- for (Constant con : consts) {
- writer.write(GeneratorUtil.createConstant(con, TAB, imports, currentPkg));
- writer.write(NL);
+ for (GeneratedProperty field : fields) {
+ writer.write(GeneratorUtil.createGetter(field, indent + TAB, imports, packageName) + NL);
+ if (!field.isReadOnly()) {
+ writer.write(GeneratorUtil.createSetter(field, indent + TAB, imports, packageName) + NL);
}
}
- if (enums != null) {
- EnumGenerator enumGenerator = new EnumGenerator();
- for (Enumeration e : enums) {
- writer.write(enumGenerator.generateInnerEnumeration(e, TAB).toString());
- writer.write(NL);
- }
+ if (!genTO.getHashCodeIdentifiers().isEmpty()) {
+ writer.write(GeneratorUtil.createHashCode(genTO.getHashCodeIdentifiers(), indent + TAB) + NL);
}
- boolean memberPatternListCodeRequired = false;
- memberPatternListCodeRequired = (GeneratorUtil.isConstantInTO(TypeConstants.PATTERN_CONSTANT_NAME, genTO));
- if (fields != null || memberPatternListCodeRequired) {
- if (fields != null) {
- for (GeneratedProperty field : fields) {
- writer.write(GeneratorUtil.createField(field, TAB, imports, currentPkg) + NL);
- }
- }
- if (memberPatternListCodeRequired) {
- writer.write(TAB + PRIVATE + GAP + "List<Pattern>" + GAP + MEMBER_PATTERN_LIST + GAP + ASSIGN + GAP
- + "new ArrayList<Pattern>()" + GAP + SC + NL);
+ if (!genTO.getEqualsIdentifiers().isEmpty()) {
+ writer.write(GeneratorUtil.createEquals(genTO, genTO.getEqualsIdentifiers(), indent + TAB) + NL);
+ }
- }
- writer.write(NL);
- writer.write(GeneratorUtil.createConstructor(genTO, TAB, imports, genTO.isAbstract()) + NL);
- writer.write(NL);
- if (fields != null) {
- for (GeneratedProperty field : fields) {
- writer.write(GeneratorUtil.createGetter(field, TAB, imports, currentPkg) + NL);
- if (!field.isReadOnly()) {
- writer.write(GeneratorUtil.createSetter(field, TAB, imports, currentPkg) + NL);
- }
- }
- writer.write(NL);
-
- if (!genTO.getHashCodeIdentifiers().isEmpty()) {
- writer.write(GeneratorUtil.createHashCode(genTO.getHashCodeIdentifiers(), TAB) + NL);
- }
-
- if (!genTO.getEqualsIdentifiers().isEmpty()) {
- writer.write(GeneratorUtil.createEquals(genTO, genTO.getEqualsIdentifiers(), TAB) + NL);
- }
-
- if (!genTO.getToStringIdentifiers().isEmpty()) {
- writer.write(GeneratorUtil.createToString(genTO, genTO.getToStringIdentifiers(), TAB) + NL);
- }
-
- writer.write(RCB);
- }
+ if (!genTO.getToStringIdentifiers().isEmpty()) {
+ writer.write(GeneratorUtil.createToString(genTO, genTO.getToStringIdentifiers(), indent + TAB) + NL);
}
+
+ writer.write(indent + RCB);
+ }
+ }
+
+ @Override
+ public Writer generate(Type type) throws IOException {
+ final Writer writer = new StringWriter();
+
+ if (type instanceof GeneratedTransferObject) {
+ GeneratedTransferObject genTO = (GeneratedTransferObject) type;
+ imports = GeneratorUtil.createImports(genTO);
+
+ final String currentPkg = genTO.getPackageName();
+
+ generatePackage(writer, currentPkg);
+
+ generateImports(writer);
+
+ generateClassBody(writer, genTO, currentPkg, NO_INDENT, false);
+
+ }
+ return writer;
+ }
+
+ public Writer generateOnlyClass(Type type, Map<String, String> imports) throws IOException {
+ this.imports = imports;
+ Writer writer = new StringWriter();
+
+ if (type instanceof GeneratedTransferObject) {
+ GeneratedTransferObject genTO = (GeneratedTransferObject) type;
+
+ final String currentPkg = "";
+
+ generateClassBody(writer, genTO, currentPkg, TAB, true);
+
}
+
return writer;
}
}
public static final String STRING_PATTERN_LIST = "STRING_PATTERNS";
public static final String MEMBER_PATTERN_LIST = "patterns";
+ public static final String NO_INDENT = "";
+
private Constants() {
}
}
import static org.opendaylight.controller.sal.java.api.generator.Constants.*;
import java.util.ArrayList;
+import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.opendaylight.controller.binding.generator.util.TypeConstants;
import org.opendaylight.controller.sal.binding.model.api.*;
-import org.opendaylight.controller.binding.generator.util.Types;
import org.opendaylight.controller.sal.binding.model.api.Enumeration.Pair;
import org.opendaylight.controller.sal.binding.model.api.MethodSignature.Parameter;
+import org.opendaylight.controller.binding.generator.util.Types;
public final class GeneratorUtil {
public static String createIfcDeclaration(final GeneratedType genType, final String indent,
final Map<String, String> availableImports) {
- return createFileDeclaration(IFC, genType, indent, availableImports, false);
+ return createFileDeclaration(IFC, genType, indent, availableImports, false, false);
}
public static String createClassDeclaration(final GeneratedTransferObject genTransferObject, final String indent,
- final Map<String, String> availableImports, boolean isIdentity) {
- return createFileDeclaration(CLASS, genTransferObject, indent, availableImports, isIdentity);
+ final Map<String, String> availableImports, boolean isIdentity, boolean isInnerClass) {
+ return createFileDeclaration(CLASS, genTransferObject, indent, availableImports, isIdentity, isInnerClass);
}
public static String createPackageDeclaration(final String packageName) {
}
private static String createFileDeclaration(final String type, final GeneratedType genType, final String indent,
- final Map<String, String> availableImports, boolean isIdentity) {
+ final Map<String, String> availableImports, boolean isIdentity, boolean innerClass) {
final StringBuilder builder = new StringBuilder();
final String currentPkg = genType.getPackageName();
builder.append(NL);
}
- if (isIdentity) {
+ if (innerClass) {
+ builder.append(indent + PUBLIC + GAP + STATIC + GAP + FINAL + GAP + type + GAP + genType.getName() + GAP);
+ } else if (isIdentity) {
if (!(CLASS.equals(type))) {
throw new IllegalArgumentException("'identity' has to be generated as a class");
}
- builder.append(PUBLIC + GAP + ABSTRACT + GAP + type + GAP + genType.getName() + GAP);
+ builder.append(indent + PUBLIC + GAP + ABSTRACT + GAP + type + GAP + genType.getName() + GAP);
} else {
- builder.append(PUBLIC + GAP + type + GAP + genType.getName() + GAP);
+ builder.append(indent + PUBLIC + GAP + type + GAP + genType.getName() + GAP);
}
if (genType instanceof GeneratedTransferObject) {
builder.append(indent + PUBLIC + GAP + STATIC + GAP + FINAL + GAP);
builder.append(getExplicitType(constant.getType(), availableImports, currentPkg) + GAP + constant.getName());
builder.append(GAP + "=" + GAP);
- final Object constValue = constant.getValue();
if (constant.getName().equals(TypeConstants.PATTERN_CONSTANT_NAME)) {
- if (constant.getName() == null || constant.getType() == null || constant.getValue() == null)
- throw new IllegalArgumentException();
- if (constValue instanceof List) {
- builder.append("Arrays.asList" + LB);
- final List<?> constantValues = (List<?>) constValue;
- int stringsCount = 0;
- for (Object value : constantValues) {
- if (value instanceof String) {
- if (stringsCount > 0) {
- builder.append(COMMA);
- }
- stringsCount++;
- builder.append(DOUBLE_QUOTE + (String) value + DOUBLE_QUOTE);
- }
- }
- builder.append(RB);
- }
+ return "";
} else {
builder.append(constant.getValue());
}
createComment(builder, comment, indent);
builder.append(NL);
- builder.append(indent);
if (!method.getAnnotations().isEmpty()) {
+ builder.append(indent);
final List<AnnotationType> annotations = method.getAnnotations();
appendAnnotations(builder, annotations);
builder.append(NL);
public static String createConstructor(GeneratedTransferObject genTransferObject, final String indent,
final Map<String, String> availableImports, boolean isIdentity) {
- final StringBuilder builder = new StringBuilder();
+ StringBuilder builder = new StringBuilder();
final String currentPkg = genTransferObject.getPackageName();
final List<GeneratedProperty> properties = genTransferObject.getProperties();
}
}
- builder.append(indent);
- builder.append(isIdentity ? PROTECTED : PUBLIC);
- builder.append(GAP);
- builder.append(genTransferObject.getName());
- builder.append(LB);
+ builder.append(createConstructorDeclarationToLeftParenthesis(genTransferObject, indent, isIdentity));
- if (!ctorParams.isEmpty()) {
- builder.append(getExplicitType(ctorParams.get(0).getReturnType(), availableImports, currentPkg));
- builder.append(" ");
- builder.append(ctorParams.get(0).getName());
- for (int i = 1; i < ctorParams.size(); ++i) {
- final GeneratedProperty param = ctorParams.get(i);
- builder.append(", ");
- builder.append(getExplicitType(param.getReturnType(), availableImports, currentPkg));
- builder.append(GAP);
- builder.append(param.getName());
- }
+ final String parameterSeparator = COMMA + GAP;
+ for (final GeneratedProperty ctorParam : ctorParams) {
+ builder.append(createMethodParamDeclaration(ctorParam, availableImports, currentPkg));
+ builder.append(parameterSeparator);
}
- builder.append(RB + GAP + LCB + NL + indent + TAB + "super();" + NL);
if (!ctorParams.isEmpty()) {
- for (final GeneratedProperty property : ctorParams) {
- builder.append(indent);
- builder.append(TAB);
- builder.append("this.");
- builder.append(property.getName());
- builder.append(" = ");
- builder.append(property.getName());
- builder.append(SC);
- builder.append(NL);
- }
+ builder = builder.delete(builder.length() - parameterSeparator.length(), builder.length());
}
- List<Constant> consts = genTransferObject.getConstantDefinitions();
- for (Constant con : consts) {
- if (con.getName() == null || con.getType() == null || con.getValue() == null)
- continue;
- if (con.getName().equals(TypeConstants.PATTERN_CONSTANT_NAME)) {
- Object values = con.getValue();
- if (values instanceof List) {
- for (Object regEx : (List<?>) values) {
- if (regEx instanceof String) {
- builder.append(indent + TAB + "for (String regEx : " + TypeConstants.PATTERN_CONSTANT_NAME
- + ") {" + NL);
- builder.append(indent + TAB + TAB + "this." + MEMBER_PATTERN_LIST
- + ".add(Pattern.compile(regEx))" + SC + NL);
- builder.append(indent + TAB + RCB + NL);
-
- break;
- }
- }
+ builder.append(createConstructorDeclarationFromRightParenthesis());
+ builder.append(createConstructorSuperCalling(indent));
+ for (final GeneratedProperty ctorParam : ctorParams) {
+ builder.append(createClassAttributeInitialization(indent, ctorParam));
+ }
+
+ builder.append(createConstructorClosingPart(indent));
+ return builder.toString();
+ }
+
+ public static String createConstructors(GeneratedTransferObject genTransferObject, final String indent,
+ final Map<String, String> availableImports, boolean isIdentity) {
+ final StringBuilder builder = new StringBuilder();
+
+ final String currentPkg = genTransferObject.getPackageName();
+ final List<GeneratedProperty> properties = genTransferObject.getProperties();
+ final List<GeneratedProperty> ctorParams = new ArrayList<GeneratedProperty>();
+ if (properties != null) {
+ for (final GeneratedProperty property : properties) {
+ if (property.isReadOnly()) {
+ ctorParams.add(property);
}
}
-
}
+ GeneratedProperty ctorParam;
+ Iterator<GeneratedProperty> iteratorCtorParams = ctorParams.iterator();
+
+ do {
+ ctorParam = null;
+ if (iteratorCtorParams.hasNext()) {
+ ctorParam = iteratorCtorParams.next();
+ }
+ builder.append(createConstructorDeclarationToLeftParenthesis(genTransferObject, indent, isIdentity));
+
+ if (ctorParam != null) {
+ builder.append(createMethodParamDeclaration(ctorParam, availableImports, currentPkg));
+ }
+ builder.append(createConstructorDeclarationFromRightParenthesis());
+ builder.append(createConstructorSuperCalling(indent));
+
+ if (ctorParam != null) {
+ builder.append(createClassAttributeInitialization(indent, ctorParam));
+ }
+
+ builder.append(createConstructorClosingPart(indent));
+ } while (iteratorCtorParams.hasNext());
+
+ return builder.toString();
+ }
+
+ private static String createConstructorDeclarationToLeftParenthesis(GeneratedTransferObject genTransferObject,
+ final String indent, boolean isIdentity) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(indent);
+ builder.append(isIdentity ? PROTECTED : PUBLIC);
+ builder.append(GAP);
+ builder.append(genTransferObject.getName());
+ builder.append(LB);
+ return builder.toString();
+ }
+
+ private static String createConstructorDeclarationFromRightParenthesis() {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(RB + GAP + LCB + NL);
+ return builder.toString();
+ }
+
+ private static String createConstructorSuperCalling(String indent) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(indent + TAB + "super();" + NL);
+ return builder.toString();
+ }
+
+ private static String createConstructorClosingPart(String indent) {
+ final StringBuilder builder = new StringBuilder();
builder.append(indent);
builder.append(RCB);
+ builder.append(NL + NL);
+ return builder.toString();
+ }
+
+ private static String createClassAttributeInitialization(String indent, GeneratedProperty methodParameter) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(indent);
+ builder.append(TAB);
+ builder.append("this.");
+ builder.append(methodParameter.getName());
+ builder.append(" = ");
+ builder.append(methodParameter.getName());
+ builder.append(SC);
+ builder.append(NL);
+ return builder.toString();
+ }
+
+ private static String createMethodParamDeclaration(GeneratedProperty methodParameter,
+ final Map<String, String> availableImports, String currentPkg) {
+ final StringBuilder builder = new StringBuilder();
+ builder.append(getExplicitType(methodParameter.getReturnType(), availableImports, currentPkg));
+ builder.append(GAP);
+ builder.append(methodParameter.getName());
return builder.toString();
}
}
}
- public static Map<String, String> createImports(final GeneratedType genType) {
+ public static Map<String, String> createImports(GeneratedType genType) {
if (genType == null) {
throw new IllegalArgumentException("Generated Type cannot be NULL!");
}
-
final Map<String, String> imports = new LinkedHashMap<>();
+ List<GeneratedType> childGeneratedTypes = genType.getEnclosedTypes();
+ if (!childGeneratedTypes.isEmpty()) {
+ for (GeneratedType genTypeChild : childGeneratedTypes) {
+ imports.putAll(createImports(genTypeChild));
+ }
+ }
+
final List<Constant> constants = genType.getConstantDefinitions();
final List<MethodSignature> methods = genType.getMethodDefinitions();
final List<Type> impl = genType.getImplements();
return imports;
}
+ public static Map<String, String> createChildImports(GeneratedType genType) {
+ Map<String, String> childImports = new LinkedHashMap<>();
+ List<GeneratedType> childGeneratedTypes = genType.getEnclosedTypes();
+ if (!childGeneratedTypes.isEmpty()) {
+ for (GeneratedType genTypeChild : childGeneratedTypes) {
+ createChildImports(genTypeChild);
+ childImports.put(genTypeChild.getName(), genTypeChild.getPackageName());
+ }
+ }
+ return childImports;
+ }
+
private static void putTypeIntoImports(final GeneratedType parentGenType, final Type type,
final Map<String, String> imports) {
if (parentGenType == null) {
}
}
- public static List<String> createImportLines(final Map<String, String> imports) {
+ public static List<String> createImportLines(final Map<String, String> imports,
+ final Map<String, String> innerTypeImports) {
final List<String> importLines = new ArrayList<>();
for (Map.Entry<String, String> entry : imports.entrySet()) {
final String typeName = entry.getKey();
final String packageName = entry.getValue();
+ if (innerTypeImports != null) {
+ String innerTypePackageName = innerTypeImports.get(typeName);
+ if (innerTypePackageName != null) {
+ if (innerTypePackageName.equals(packageName))
+ continue;
+ }
+ }
importLines.add("import " + packageName + "." + typeName + SC);
}
return importLines;
}
return false;
}
+
+ public static String createStaticInicializationBlock(GeneratedTransferObject genTransferObject, String indent) {
+
+ final StringBuilder builder = new StringBuilder();
+
+ List<Constant> constants = genTransferObject.getConstantDefinitions();
+ for (Constant constant : constants) {
+ if (constant.getName() == null || constant.getType() == null || constant.getValue() == null) {
+ continue;
+ }
+ if (constant.getName().equals(TypeConstants.PATTERN_CONSTANT_NAME)) {
+ final Object constValue = constant.getValue();
+ List<String> regularExpressions = new ArrayList<>();
+ if (constValue instanceof List) {
+ builder.append(indent + PUBLIC + GAP + STATIC + GAP + FINAL + GAP + "List<String>" + GAP
+ + TypeConstants.PATTERN_CONSTANT_NAME + GAP + "=" + GAP + "Arrays.asList" + LB);
+ final List<?> constantValues = (List<?>) constValue;
+ int stringsCount = 0;
+ for (Object value : constantValues) {
+ if (value instanceof String) {
+ if (stringsCount > 0) {
+ builder.append(COMMA);
+ }
+ stringsCount++;
+ regularExpressions.add((String) value);
+ builder.append(DOUBLE_QUOTE + (String) value + DOUBLE_QUOTE);
+ }
+ }
+ builder.append(RB + SC + NL);
+ }
+ builder.append(indent + PRIVATE + GAP + STATIC + GAP + FINAL + GAP + "List<Pattern>" + GAP
+ + MEMBER_PATTERN_LIST + GAP + ASSIGN + GAP + "new ArrayList<Pattern>()" + GAP + SC + NL + NL);
+
+ if (!regularExpressions.isEmpty()) {
+ builder.append(indent + STATIC + LCB + NL);
+ builder.append(indent + TAB + "for (String regEx : " + TypeConstants.PATTERN_CONSTANT_NAME + ") {"
+ + NL);
+ builder.append(indent + TAB + TAB + MEMBER_PATTERN_LIST + ".add(Pattern.compile(regEx))" + SC + NL);
+ builder.append(indent + TAB + RCB + NL);
+ builder.append(indent + RCB + NL + NL);
+ }
+
+ }
+ }
+ return builder.toString();
+ }
}
public final class InterfaceGenerator implements CodeGenerator {
private Map<String, String> imports;
+ private Map<String, String> innerTypeImports;
private String generateEnums(List<Enumeration> enums) {
String result = "";
return result;
}
+ public String generateInnerClasses(final List<GeneratedType> generatedTypes) throws IOException {
+ String result = "";
+
+ if (generatedTypes != null) {
+ ClassCodeGenerator classCodeGenerator = new ClassCodeGenerator();
+ for (GeneratedType genType : generatedTypes) {
+ if (genType instanceof GeneratedTransferObject) {
+ result = result + classCodeGenerator.generateOnlyClass(genType, imports).toString();
+ result = result + NL + NL;
+ }
+ }
+ }
+
+ return result;
+ }
+
public Writer generate(Type type) throws IOException {
Writer writer = new StringWriter();
if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
final GeneratedType genType = (GeneratedType) type;
imports = GeneratorUtil.createImports(genType);
+ innerTypeImports = GeneratorUtil.createChildImports(genType);
final String currentPkg = genType.getPackageName();
final List<Constant> constants = genType.getConstantDefinitions();
final List<MethodSignature> methods = genType.getMethodDefinitions();
final List<Enumeration> enums = genType.getEnumerations();
+ final List<GeneratedType> enclosedGeneratedTypes = genType.getEnclosedTypes();
writer.write(GeneratorUtil.createPackageDeclaration(genType.getPackageName()));
writer.write(NL);
- final List<String> importLines = GeneratorUtil.createImportLines(imports);
+ List<String> importLines = GeneratorUtil.createImportLines(imports, innerTypeImports);
+
for (String line : importLines) {
writer.write(line + NL);
}
writer.write(GeneratorUtil.createIfcDeclaration(genType, "", imports));
writer.write(NL);
+ writer.write(generateInnerClasses(enclosedGeneratedTypes));
writer.write(generateEnums(enums));
writer.write(generateConstants(constants, currentPkg));
writer.write(generateMethods(methods, currentPkg));
--- /dev/null
+package org.opendaylight.controller.sal.java.api.generator.test;
+
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.generator.api.BindingGenerator;
+import org.opendaylight.controller.sal.binding.generator.impl.BindingGeneratorImpl;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedProperty;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
+import org.opendaylight.controller.sal.binding.model.api.GeneratedType;
+import org.opendaylight.controller.sal.binding.model.api.Type;
+import org.opendaylight.controller.sal.java.api.generator.ClassCodeGenerator;
+import org.opendaylight.controller.yang.model.api.Module;
+import org.opendaylight.controller.yang.model.api.SchemaContext;
+import org.opendaylight.controller.yang.model.parser.api.YangModelParser;
+import org.opendaylight.controller.yang.parser.impl.YangParserImpl;
+
+public class GenerateInnerClassForBitsAndUnionInLeavesTest {
+
+ private SchemaContext resolveSchemaContextFromFiles(final String... yangFiles) {
+ final YangModelParser parser = new YangParserImpl();
+
+ final List<File> inputFiles = new ArrayList<File>();
+ for (int i = 0; i < yangFiles.length; ++i) {
+ inputFiles.add(new File(yangFiles[i]));
+ }
+
+ final Set<Module> modules = parser.parseYangModels(inputFiles);
+ return parser.resolveSchemaContext(modules);
+ }
+
+ @Test
+ public void testInnerClassCreationForBitsAndUnionsInLeafes() {
+ final String yangTypesPath = getClass().getResource("/bit_and_union_in_leaf.yang").getPath();
+
+ final SchemaContext context = resolveSchemaContextFromFiles(yangTypesPath);
+ assertTrue(context != null);
+
+ final BindingGenerator bindingGen = new BindingGeneratorImpl();
+ final List<Type> genTypes = bindingGen.generateTypes(context);
+ assertTrue(genTypes != null);
+
+ boolean parentContainerFound = false;
+ boolean bitLeafTOFound = false;
+ boolean unionLeafTOFound = false;
+
+ boolean firstBitPropertyFound = false;
+ boolean secondBitPropertyFound = false;
+ boolean thirdBitPropertyFound = false;
+
+ boolean firstBitPropertyTypeOK = false;
+ boolean secondBitPropertyTypeOK = false;
+ boolean thirdBitPropertyTypeOK = false;
+
+ boolean int32UnionPropertyFound = false;
+ boolean int32UnionPropertyTypeOK = false;
+ boolean stringUnionPropertyFound = false;
+ boolean stringUnionPropertyTypeOK = false;
+ boolean uint8UnionPropertyFound = false;
+ boolean uint8UnionPropertyTypeOK = false;
+
+ for (Type type : genTypes) {
+ if (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject)) {
+ if (type.getName().equals("ParentContainer")) {
+ parentContainerFound = true;
+ GeneratedType parentContainer = (GeneratedType) type;
+ List<GeneratedType> enclosedTypes = parentContainer.getEnclosedTypes();
+ for (GeneratedType genType : enclosedTypes) {
+ if (genType instanceof GeneratedTransferObject) {
+ if (genType.getName().equals("BitLeaf")) {
+ bitLeafTOFound = true;
+ GeneratedTransferObject bitLeafTO = (GeneratedTransferObject) genType;
+
+ List<GeneratedProperty> bitLeafProperties = bitLeafTO.getProperties();
+ for (GeneratedProperty bitLeafProperty : bitLeafProperties) {
+ String bitLeafPropertyType = bitLeafProperty.getReturnType().getName();
+ if (bitLeafProperty.getName().equals("firstBit")) {
+ firstBitPropertyFound = true;
+ if (bitLeafPropertyType.equals("Boolean")) {
+ firstBitPropertyTypeOK = true;
+ }
+ } else if (bitLeafProperty.getName().equals("secondBit")) {
+ secondBitPropertyFound = true;
+ if (bitLeafPropertyType.equals("Boolean")) {
+ secondBitPropertyTypeOK = true;
+ }
+ } else if (bitLeafProperty.getName().equals("thirdBit")) {
+ thirdBitPropertyFound = true;
+ if (bitLeafPropertyType.equals("Boolean")) {
+ thirdBitPropertyTypeOK = true;
+ }
+ }
+
+ }
+
+ } else if (genType.getName().equals("UnionLeaf")) {
+ unionLeafTOFound = true;
+ GeneratedTransferObject unionLeafTO = (GeneratedTransferObject) genType;
+
+ List<GeneratedProperty> unionLeafProperties = unionLeafTO.getProperties();
+ for (GeneratedProperty unionLeafProperty : unionLeafProperties) {
+ String unionLeafPropertyType = unionLeafProperty.getReturnType().getName();
+ if (unionLeafProperty.getName().equals("int32")) {
+ int32UnionPropertyFound = true;
+ if (unionLeafPropertyType.equals("Integer")) {
+ int32UnionPropertyTypeOK = true;
+ }
+ } else if (unionLeafProperty.getName().equals("string")) {
+ stringUnionPropertyFound = true;
+ if (unionLeafPropertyType.equals("String")) {
+ stringUnionPropertyTypeOK = true;
+ }
+ } else if (unionLeafProperty.getName().equals("uint8")) {
+ uint8UnionPropertyFound = true;
+ if (unionLeafPropertyType.equals("Short")) {
+ uint8UnionPropertyTypeOK = true;
+ }
+ }
+
+ }
+
+ }
+ }
+ }
+ }
+ }
+ }
+ assertTrue(parentContainerFound);
+
+ assertTrue(bitLeafTOFound);
+ assertTrue(firstBitPropertyFound);
+ assertTrue(secondBitPropertyFound);
+ assertTrue(thirdBitPropertyFound);
+
+ assertTrue(firstBitPropertyTypeOK);
+ assertTrue(secondBitPropertyTypeOK);
+ assertTrue(thirdBitPropertyTypeOK);
+
+ assertTrue(unionLeafTOFound);
+ assertTrue(int32UnionPropertyFound);
+ assertTrue(int32UnionPropertyTypeOK);
+ assertTrue(stringUnionPropertyFound);
+ assertTrue(stringUnionPropertyTypeOK);
+ assertTrue(uint8UnionPropertyFound);
+ assertTrue(uint8UnionPropertyTypeOK);
+
+ }
+}
\ No newline at end of file
--- /dev/null
+module bit-and-union-in-leaf {
+
+ namespace "urn:bit:union:in:leaf";
+ prefix "sbd";
+
+ organization "OPEN DAYLIGHT";
+ contact "http://www.opendaylight.org/";
+
+ revision 2013-06-26 {
+
+ }
+
+ typedef union-typedef {
+ type union {
+ type string {
+ pattern "[a-g]";
+ };
+ type int16;
+ }
+ }
+
+ typedef union-typedef2 {
+ type union {
+ type string;
+ type int16;
+ }
+ }
+
+ container parent-container {
+ leaf bit-leaf {
+ type bits {
+ bit first-bit;
+ bit second-bit;
+ bit third-bit;
+ }
+ }
+
+ leaf union-leaf {
+ type union {
+ type int32;
+ type string {
+ pattern "[a-z]";
+ };
+ type string {
+ pattern "[0-9]*"
+ };
+ type string {
+ pattern "[a-d]*";
+ pattern "[0-5]*";
+ };
+ type uint8;
+ }
+ }
+ }
+}
\ No newline at end of file
/**
* Generated Transfer Object extends {@link GeneratedType} and is designed to
- * represent Java Class. The Generated Transfer Object contains declarations
- * of member fields stored in List of Properties. The Generated Transfer
- * Object can be extended by exactly ONE Generated Transfer Object as Java
- * don't allow multiple inheritance. For retrieval of implementing Generated
- * Types use {@link #getImplements()} method.
- * <br>
- * Every transfer object SHOULD contain equals, hashCode and toString definitions.
- * For this purpose retrieve definitions through {@link #getEqualsIdentifiers
- * ()}, {@link #getHashCodeIdentifiers()} and {@link #getToStringIdentifiers
- * ()}.
- *
+ * represent Java Class. The Generated Transfer Object contains declarations of
+ * member fields stored in List of Properties. The Generated Transfer Object can
+ * be extended by exactly ONE Generated Transfer Object as Java don't allow
+ * multiple inheritance. For retrieval of implementing Generated Types use
+ * {@link #getImplements()} method. <br>
+ * Every transfer object SHOULD contain equals, hashCode and toString
+ * definitions. For this purpose retrieve definitions through
+ * {@link #getEqualsIdentifiers ()}, {@link #getHashCodeIdentifiers()} and
+ * {@link #getToStringIdentifiers ()}.
+ *
*/
public interface GeneratedTransferObject extends GeneratedType {
/**
- * Returns the extending Generated Transfer Object or <code>null</code>
- * if there is no extending Generated Transfer Object.
- *
- * @return the extending Generated Transfer Object or <code>null</code>
- * if there is no extending Generated Transfer Object.
+ * Returns the extending Generated Transfer Object or <code>null</code> if
+ * there is no extending Generated Transfer Object.
+ *
+ * @return the extending Generated Transfer Object or <code>null</code> if
+ * there is no extending Generated Transfer Object.
*/
public GeneratedTransferObject getExtends();
/**
* Returns List of Properties that are declared for Generated Transfer
* Object.
- *
+ *
* @return List of Properties that are declared for Generated Transfer
- * Object.
+ * Object.
*/
public List<GeneratedProperty> getProperties();
/**
* Returns List of Properties that are designated to define equality for
* Generated Transfer Object.
- *
+ *
* @return List of Properties that are designated to define equality for
- * Generated Transfer Object.
+ * Generated Transfer Object.
*/
public List<GeneratedProperty> getEqualsIdentifiers();
/**
* Returns List of Properties that are designated to define identity for
* Generated Transfer Object.
- *
+ *
* @return List of Properties that are designated to define identity for
- * Generated Transfer Object.
+ * Generated Transfer Object.
*/
public List<GeneratedProperty> getHashCodeIdentifiers();
/**
* Returns List of Properties that will be members of toString definition
* for Generated Transfer Object.
- *
+ *
* @return List of Properties that will be members of toString definition
- * for Generated Transfer Object.
+ * for Generated Transfer Object.
*/
public List<GeneratedProperty> getToStringIdentifiers();
+
+ /**
+ * Return boolean value which describe whether Generated Transfer Object
+ * was/wasn't created from union YANG type.
+ *
+ * @return true value if Generated Transfer Object was created from union
+ * YANG type.
+ */
+ @Deprecated
+ public boolean isUnionType();
}
import org.opendaylight.controller.sal.binding.model.api.GeneratedTransferObject;
/**
- * Generated Transfer Object Builder is interface that contains methods to
- * build and instantiate Generated Transfer Object definition.
- *
+ * Generated Transfer Object Builder is interface that contains methods to build
+ * and instantiate Generated Transfer Object definition.
+ *
* @see GeneratedTransferObject
*/
public interface GeneratedTOBuilder extends GeneratedTypeBuilder {
/**
* Add Generated Transfer Object from which will be extended current
- * Generated Transfer Object.
- * <br>
- * By definition Java does not allow multiple
- * inheritance, hence if there is already definition of Generated
- * Transfer Object the extending object will be overwritten by lastly
- * added Generated Transfer Object.
- * <br>
- * If Generated Transfer Object is <code>null</code> the method SHOULD
- * throw {@link IllegalArgumentException}
- *
- * @param genTransObj Generated Transfer Object
+ * Generated Transfer Object. <br>
+ * By definition Java does not allow multiple inheritance, hence if there is
+ * already definition of Generated Transfer Object the extending object will
+ * be overwritten by lastly added Generated Transfer Object. <br>
+ * If Generated Transfer Object is <code>null</code> the method SHOULD throw
+ * {@link IllegalArgumentException}
+ *
+ * @param genTransObj
+ * Generated Transfer Object
*/
public void setExtendsType(final GeneratedTransferObject genTransObj);
/**
* Add new Generated Property definition for Generated Transfer Object
- * Builder and returns Generated Property Builder for specifying Property.
- * <br>
- * Name of Property cannot be <code>null</code>,
- * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
- *
- * @param name Name of Property
+ * Builder and returns Generated Property Builder for specifying Property. <br>
+ * Name of Property cannot be <code>null</code>, if it is <code>null</code>
+ * the method SHOULD throw {@link IllegalArgumentException}
+ *
+ * @param name
+ * Name of Property
* @return <code>new</code> instance of Generated Property Builder.
*/
public GeneratedPropertyBuilder addProperty(final String name);
/**
- * Add Property that will be part of <code>equals</code> definition.
- * <br>
+ * Check whether GeneratedTOBuilder contains property with name
+ * <code>name</code>
+ *
+ * @param name
+ * of property which existance is checked
+ * @return true if property <code>name</code> exists in list of properties.
+ */
+ public boolean containsProperty(final String name);
+
+ /**
+ * Add Property that will be part of <code>equals</code> definition. <br>
* If Generated Property Builder is <code>null</code> the method SHOULD
* throw {@link IllegalArgumentException}
- *
- * @param property Generated Property Builder
- * @return <code>true</code> if addition of Generated Property into list
- * of <code>equals</code> properties is successful.
+ *
+ * @param property
+ * Generated Property Builder
+ * @return <code>true</code> if addition of Generated Property into list of
+ * <code>equals</code> properties is successful.
*/
public boolean addEqualsIdentity(final GeneratedPropertyBuilder property);
/**
- * Add Property that will be part of <code>hashCode</code> definition.
- * <br>
+ * Add Property that will be part of <code>hashCode</code> definition. <br>
* If Generated Property Builder is <code>null</code> the method SHOULD
* throw {@link IllegalArgumentException}
- *
- * @param property Generated Property Builder
- * @return <code>true</code> if addition of Generated Property into list
- * of <code>hashCode</code> properties is successful.
+ *
+ * @param property
+ * Generated Property Builder
+ * @return <code>true</code> if addition of Generated Property into list of
+ * <code>hashCode</code> properties is successful.
*/
public boolean addHashIdentity(final GeneratedPropertyBuilder property);
/**
- * Add Property that will be part of <code>toString</code> definition.
- * <br>
+ * Add Property that will be part of <code>toString</code> definition. <br>
* If Generated Property Builder is <code>null</code> the method SHOULD
* throw {@link IllegalArgumentException}
- *
- * @param property Generated Property Builder
- * @return <code>true</code> if addition of Generated Property into list
- * of <code>toString</code> properties is successful.
+ *
+ * @param property
+ * Generated Property Builder
+ * @return <code>true</code> if addition of Generated Property into list of
+ * <code>toString</code> properties is successful.
*/
public boolean addToStringProperty(final GeneratedPropertyBuilder property);
@Override
public GeneratedTransferObject toInstance();
+
+ /**
+ * Set original YANG type for GeneratedTOBuilder. It is YANG type from which
+ * is this transport object created.
+ *
+ * @param yangType
+ * YangType enum value of original YANG type
+ */
+ public void setIsUnion(boolean isUnion);
}
/**
* Generated Type Builder interface is helper interface for building and
* defining the GeneratedType.
- *
+ *
* @see GeneratedType
*/
public interface GeneratedTypeBuilder extends Type {
/**
* Adds new Enclosing Type into definition of Generated Type and returns
- * <code>new</code> Instance of Generated Type Builder.
- * <br>
- * There is no need of specifying of Package Name because enclosing Type
- * is already defined inside Generated Type with specific package name.
- * <br>
- * The name of enclosing Type cannot be same as Name of parent type and
- * if there is already defined enclosing type with the same name,
- * the new enclosing type will simply overwrite the older definition.
- * <br>
+ * <code>new</code> Instance of Generated Type Builder. <br>
+ * There is no need of specifying of Package Name because enclosing Type is
+ * already defined inside Generated Type with specific package name. <br>
+ * The name of enclosing Type cannot be same as Name of parent type and if
+ * there is already defined enclosing type with the same name, the new
+ * enclosing type will simply overwrite the older definition. <br>
* If the name of enclosing type is <code>null</code> the method SHOULD
* throw {@link IllegalArgumentException}
- *
- * @param name Name of Enclosing Type
+ *
+ * @param name
+ * Name of Enclosing Type
* @return <code>new</code> Instance of Generated Type Builder.
*/
public GeneratedTypeBuilder addEnclosingType(final String name);
/**
- * Adds new Enclosing Transfer Object into definition of Generated Type
- * and returns <code>new</code> Instance of Generated TO Builder.
- * <br>
- * There is no need of specifying of Package Name because enclosing Type
- * is already defined inside Generated Type with specific package name.
- * <br>
- * The name of enclosing Type cannot be same as Name of parent type and
- * if there is already defined enclosing type with the same name,
- * the new enclosing type will simply overwrite the older definition.
- * <br>
+ * Adds new Enclosing Transfer Object into definition of Generated Type and
+ * returns <code>new</code> Instance of Generated TO Builder. <br>
+ * There is no need of specifying of Package Name because enclosing Type is
+ * already defined inside Generated Type with specific package name. <br>
+ * The name of enclosing Type cannot be same as Name of parent type and if
+ * there is already defined enclosing type with the same name, the new
+ * enclosing type will simply overwrite the older definition. <br>
* If the name of enclosing type is <code>null</code> the method SHOULD
* throw {@link IllegalArgumentException}
- *
- * @param name Name of Enclosing Type
+ *
+ * @param name
+ * Name of Enclosing Type
* @return <code>new</code> Instance of Generated Type Builder.
*/
public GeneratedTOBuilder addEnclosingTransferObject(final String name);
/**
- * Adds String definition of comment into Method Signature definition.
+ * Adds new Enclosing Transfer Object <code>genTOBuilder</code> into
+ * definition of Generated Type
+ *
* <br>
+ * There is no need of specifying of Package Name because enclosing Type is
+ * already defined inside Generated Type with specific package name. <br>
+ * The name of enclosing Type cannot be same as Name of parent type and if
+ * there is already defined enclosing type with the same name, the new
+ * enclosing type will simply overwrite the older definition. <br>
+ * If the parameter <code>genTOBuilder</code> of enclosing type is
+ * <code>null</code> the method SHOULD throw
+ * {@link IllegalArgumentException}
+ *
+ * @param <code>genTOBuilder</code> Name of Enclosing Type
+ */
+ public void addEnclosingTransferObject(final GeneratedTOBuilder genTOBuilder);
+
+ /**
+ * Adds String definition of comment into Method Signature definition. <br>
* The comment String MUST NOT contain anny comment specific chars (i.e.
* "/**" or "//") just plain String text description.
- *
- * @param comment Comment String.
+ *
+ * @param comment
+ * Comment String.
*/
public void addComment(final String comment);
- /**
- * The method creates new AnnotationTypeBuilder containing specified
- * package name an annotation name.
- * <br>
- * Neither the package name or annotation name can contain
- * <code>null</code> references. In case that
- * any of parameters contains <code>null</code> the method SHOULD thrown
- * {@link IllegalArgumentException}
- *
- * @param packageName Package Name of Annotation Type
- * @param name Name of Annotation Type
+ /**
+ * The method creates new AnnotationTypeBuilder containing specified package
+ * name an annotation name. <br>
+ * Neither the package name or annotation name can contain <code>null</code>
+ * references. In case that any of parameters contains <code>null</code> the
+ * method SHOULD thrown {@link IllegalArgumentException}
+ *
+ * @param packageName
+ * Package Name of Annotation Type
+ * @param name
+ * Name of Annotation Type
* @return <code>new</code> instance of Annotation Type Builder.
*/
public AnnotationTypeBuilder addAnnotation(final String packageName, final String name);
/**
- * Sets the <code>abstract</code> flag to define Generated Type as <i>abstract</i> type.
- *
- * @param isAbstract abstract flag
+ * Sets the <code>abstract</code> flag to define Generated Type as
+ * <i>abstract</i> type.
+ *
+ * @param isAbstract
+ * abstract flag
*/
public void setAbstract(boolean isAbstract);
/**
* Add Type to implements.
- *
- * @param genType Type to implement
+ *
+ * @param genType
+ * Type to implement
* @return <code>true</code> if the addition of type is successful.
*/
public boolean addImplementsType(final Type genType);
/**
- * Adds Constant definition and returns <code>new</code> Constant instance.
- * <br>
- * By definition Constant MUST be defined by return Type,
- * Name and assigned value. The name SHOULD be defined with cpaital
- * letters. Neither of method parameters can be <code>null</code> and the
- * method SHOULD throw {@link IllegalArgumentException} if the contract
- * is broken.
- *
- * @param type Constant Type
- * @param name Name of Constant
- * @param value Assigned Value
+ * Adds Constant definition and returns <code>new</code> Constant instance. <br>
+ * By definition Constant MUST be defined by return Type, Name and assigned
+ * value. The name SHOULD be defined with cpaital letters. Neither of method
+ * parameters can be <code>null</code> and the method SHOULD throw
+ * {@link IllegalArgumentException} if the contract is broken.
+ *
+ * @param type
+ * Constant Type
+ * @param name
+ * Name of Constant
+ * @param value
+ * Assigned Value
* @return <code>new</code> Constant instance.
*/
- public Constant addConstant(final Type type, final String name,
- final Object value);
+ public Constant addConstant(final Type type, final String name, final Object value);
/**
* Adds new Enumeration definition for Generated Type Builder and returns
- * Enum Builder for specifying all Enum parameters.
- * <br>
- * If there is already Enumeration stored with the same name,
- * the old enum will be simply overwritten byt new enum definition.
- * <br>
- * Name of Enumeration cannot be <code>null</code>,
- * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
- *
- * @param name Enumeration Name
+ * Enum Builder for specifying all Enum parameters. <br>
+ * If there is already Enumeration stored with the same name, the old enum
+ * will be simply overwritten byt new enum definition. <br>
+ * Name of Enumeration cannot be <code>null</code>, if it is
+ * <code>null</code> the method SHOULD throw
+ * {@link IllegalArgumentException}
+ *
+ * @param name
+ * Enumeration Name
* @return <code>new</code> instance of Enumeration Builder.
*/
public EnumBuilder addEnumeration(final String name);
/**
* Add new Method Signature definition for Generated Type Builder and
- * returns Method Signature Builder for specifying all Method parameters.
- * <br>
- * Name of Method cannot be <code>null</code>,
- * if it is <code>null</code> the method SHOULD throw {@link IllegalArgumentException}
- * <br>
+ * returns Method Signature Builder for specifying all Method parameters. <br>
+ * Name of Method cannot be <code>null</code>, if it is <code>null</code>
+ * the method SHOULD throw {@link IllegalArgumentException} <br>
* By <i>Default</i> the MethodSignatureBuilder SHOULD be pre-set as
- * {@link MethodSignatureBuilder#setAbstract(true)}, {@link MethodSignatureBuilder#setFinal(false)} and
+ * {@link MethodSignatureBuilder#setAbstract(true)},
+ * {@link MethodSignatureBuilder#setFinal(false)} and
* {@link MethodSignatureBuilder#setAccessModifier(PUBLIC)}
- *
- * @param name Name of Method
+ *
+ * @param name
+ * Name of Method
* @return <code>new</code> instance of Method Signature Builder.
*/
public MethodSignatureBuilder addMethod(final String name);
/**
- * Returns the <code>new</code> <i>immutable</i> instance of Generated
- * Type.
- *
- * @return the <code>new</code> <i>immutable</i> instance of Generated
- * Type.
+ * Checks if GeneratedTypeBuilder contains method with name
+ * <code>methodName</code>
+ *
+ * @param methodName
+ * is method name
+ */
+ public boolean containsMethod(final String methodName);
+
+ /**
+ * Returns the <code>new</code> <i>immutable</i> instance of Generated Type.
+ *
+ * @return the <code>new</code> <i>immutable</i> instance of Generated Type.
*/
public GeneratedType toInstance();
}
--- /dev/null
+module bit-and-union-in-leaf {
+
+ namespace "urn:bit:union:in:leaf";
+ prefix "sbd";
+
+ organization "OPEN DAYLIGHT";
+ contact "http://www.opendaylight.org/";
+
+ revision 2013-06-26 {
+
+ }
+
+ typedef union-typedef {
+ type union {
+ type string {
+ pattern "[a-g]";
+ };
+ type int16;
+ }
+ }
+
+ typedef union-typedef2 {
+ type union {
+ type string;
+ type int16;
+ }
+ }
+
+ container parent-container {
+ leaf bit-leaf {
+ type bits {
+ bit first-bit;
+ bit second-bit;
+ bit third-bit;
+ }
+ }
+
+ leaf union-leaf {
+ type union {
+ type int32;
+ type string {
+ pattern "[a-z]";
+ };
+ type string {
+ pattern "[0-9]*"
+ };
+ type string {
+ pattern "[a-d]*";
+ pattern "[0-5]*";
+ };
+ type uint8;
+ }
+ }
+ }
+}
\ No newline at end of file