Bug 8449 - BindingToNormalizedNodeCodec fails to deserialize union of leafrefs 31/60631/3
authorJakub Toth <jakub.toth@pantheon.tech>
Fri, 21 Jul 2017 09:58:08 +0000 (11:58 +0200)
committerJakub Toth <jakub.toth@pantheon.tech>
Fri, 21 Jul 2017 21:05:17 +0000 (21:05 +0000)
Fix problem of leafref in typedef called from union
 *generated part
   *generating of new property of GTO for leaf's union type of typedef
     according to return type of referenced leaf via leafref from typedef
 *codec part
   *getting codec of leaf type according to new generator part of leafref
    in typedef
 *tests

Change-Id: Ibffe4e51ef66f1911c32c71d4f08bbdbdd40e234
Signed-off-by: Jakub Toth <jakub.toth@pantheon.tech>
binding/mdsal-binding-dom-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/UnionTypeCodec.java
binding/mdsal-binding-dom-codec/src/test/java/org/opendaylight/yangtools/binding/data/codec/test/LeafrefSerializeDeserializeTest.java [new file with mode: 0644]
binding/mdsal-binding-generator-impl/src/main/java/org/opendaylight/mdsal/binding/yang/types/TypeProviderImpl.java
binding/mdsal-binding-generator-impl/src/test/java/org/opendaylight/mdsal/binding/generator/impl/UnionTypeDefTest.java
binding/mdsal-binding-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang [new file with mode: 0644]
binding/mdsal-binding-generator-util/src/main/java/org/opendaylight/mdsal/binding/model/util/generated/type/builder/AbstractTypeMemberBuilder.java
binding/mdsal-binding-test-model/src/main/yang/bug8449.yang [new file with mode: 0644]

index ee161a9b537a9cb1288e540ec621da799cd10523..4dac099d1fc459966d33e0fe7df1c31899f5d856 100644 (file)
@@ -12,10 +12,18 @@ import java.lang.reflect.Method;
 import java.util.LinkedHashSet;
 import java.util.Set;
 import java.util.concurrent.Callable;
+import org.opendaylight.mdsal.binding.yang.types.BaseYangTypes;
 import org.opendaylight.yangtools.concepts.Codec;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 
 final class UnionTypeCodec extends ReflectionBasedCodec {
     private final ImmutableSet<UnionValueOptionContext> typeCodecs;
@@ -29,19 +37,74 @@ final class UnionTypeCodec extends ReflectionBasedCodec {
                                            final BindingCodecContext bindingCodecContext) {
         return () -> {
             final Set<UnionValueOptionContext> values = new LinkedHashSet<>();
-            for (TypeDefinition<?> subtype : unionType.getTypes()) {
-                Method valueGetter = unionCls.getMethod("get" + BindingMapping.getClassName(subtype.getQName()));
-                Class<?> valueType = valueGetter.getReturnType();
-                Codec<Object, Object> valueCodec = bindingCodecContext.getCodec(valueType, subtype);
-                values.add(new UnionValueOptionContext(unionCls, valueType, valueGetter, valueCodec));
+            for (final TypeDefinition<?> subtype : unionType.getTypes()) {
+                if (subtype instanceof LeafrefTypeDefinition) {
+                    addLeafrefValueCodec(unionCls, unionType, bindingCodecContext, values, subtype);
+                } else {
+                    final Method valueGetter =
+                            unionCls.getMethod("get" + BindingMapping.getClassName(subtype.getQName()));
+                    final Class<?> valueType = valueGetter.getReturnType();
+                    final Codec<Object, Object> valueCodec = bindingCodecContext.getCodec(valueType, subtype);
+
+                    values.add(new UnionValueOptionContext(unionCls, valueType, valueGetter, valueCodec));
+                }
             }
+
             return new UnionTypeCodec(unionCls, values);
         };
     }
 
+    /**
+     * Prepare codec for type from leaf's return type of leafref.
+     *
+     * @param unionCls
+     *            - union class
+     * @param unionType
+     *            - union type
+     * @param bindingCodecContext
+     *            - binding codec context
+     * @param values
+     *            - union values
+     * @param subtype
+     *            - subtype of union
+     * @throws NoSuchMethodException
+     */
+    private static void addLeafrefValueCodec(final Class<?> unionCls, final UnionTypeDefinition unionType,
+            final BindingCodecContext bindingCodecContext, final Set<UnionValueOptionContext> values,
+            final TypeDefinition<?> subtype) throws NoSuchMethodException {
+        final SchemaContext schemaContext = bindingCodecContext.getRuntimeContext().getSchemaContext();
+        final Module module = schemaContext.findModuleByNamespaceAndRevision(subtype.getQName().getNamespace(),
+                subtype.getQName().getRevision());
+        final RevisionAwareXPath xpath = ((LeafrefTypeDefinition) subtype).getPathStatement();
+        // find schema node in schema context by xpath of leafref
+        final SchemaNode dataNode;
+        if (xpath.isAbsolute()) {
+            dataNode = SchemaContextUtil.findDataSchemaNode(schemaContext, module, xpath);
+        } else {
+            dataNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, module, unionType, xpath);
+        }
+        final String className = BindingMapping.getClassName(unionCls.getSimpleName());
+        final LeafSchemaNode typeNode = (LeafSchemaNode) dataNode;
+
+        // prepare name of type form return type of referenced leaf
+        final String typeName = BindingMapping.getClassName(BaseYangTypes.BASE_YANG_TYPES_PROVIDER
+                .javaTypeForSchemaDefinitionType(typeNode.getType(), typeNode).getName());
+
+        // get method via reflection from generated code according to
+        // get_TypeName_Value method
+        final Method valueGetterParent = unionCls
+                .getMethod(new StringBuilder("get").append(typeName).append(className).append("Value").toString());
+        final Class<?> returnType = valueGetterParent.getReturnType();
+
+        // prepare codec of union subtype according to return type of referenced
+        // leaf
+        final Codec<Object, Object> valueCodec = bindingCodecContext.getCodec(returnType, subtype);
+        values.add(new UnionValueOptionContext(unionCls, returnType, valueGetterParent, valueCodec));
+    }
+
     @Override
     public Object deserialize(final Object input) {
-        for (UnionValueOptionContext member : typeCodecs) {
+        for (final UnionValueOptionContext member : typeCodecs) {
             final Object ret = member.deserializeUnion(input);
             if (ret != null) {
                 return ret;
@@ -55,7 +118,7 @@ final class UnionTypeCodec extends ReflectionBasedCodec {
     @Override
     public Object serialize(final Object input) {
         if (input != null) {
-            for (UnionValueOptionContext valCtx : typeCodecs) {
+            for (final UnionValueOptionContext valCtx : typeCodecs) {
                 final Object domValue = valCtx.serialize(input);
                 if (domValue != null) {
                     return domValue;
diff --git a/binding/mdsal-binding-dom-codec/src/test/java/org/opendaylight/yangtools/binding/data/codec/test/LeafrefSerializeDeserializeTest.java b/binding/mdsal-binding-dom-codec/src/test/java/org/opendaylight/yangtools/binding/data/codec/test/LeafrefSerializeDeserializeTest.java
new file mode 100644 (file)
index 0000000..c50e082
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2017 Pantheon Technologies s.r.o. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import java.util.Map.Entry;
+import javassist.ClassPool;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.mdsal.binding.generator.util.JavassistUtils;
+import org.opendaylight.yang.gen.v1.bug8449.rev180405.Cont;
+import org.opendaylight.yang.gen.v1.bug8449.rev180405.Cont.Ref;
+import org.opendaylight.yang.gen.v1.bug8449.rev180405.ContBuilder;
+import org.opendaylight.yang.gen.v1.bug8449.rev180405.ContInt32;
+import org.opendaylight.yang.gen.v1.bug8449.rev180405.ContInt32.RefUnionInt32;
+import org.opendaylight.yang.gen.v1.bug8449.rev180405.ContInt32Builder;
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class LeafrefSerializeDeserializeTest extends AbstractBindingRuntimeTest {
+
+    private BindingNormalizedNodeCodecRegistry registry;
+
+    @Override
+    @Before
+    public void setup() {
+        super.setup();
+        final JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault());
+        this.registry = new BindingNormalizedNodeCodecRegistry(StreamWriterGenerator.create(utils));
+        this.registry.onBindingRuntimeContextUpdated(getRuntimeContext());
+    }
+
+    @Test
+    public void listReferenceTest() {
+        final YangInstanceIdentifier contYII = YangInstanceIdentifier.builder().node(Cont.QNAME).build();
+        final InstanceIdentifier<?> fromYangInstanceIdentifier = this.registry.fromYangInstanceIdentifier(contYII);
+        assertNotNull(fromYangInstanceIdentifier);
+
+        final InstanceIdentifier<Cont> BA_II_CONT = InstanceIdentifier.builder(Cont.class).build();
+        final Ref refVal = new Ref("myvalue");
+        final Cont data = new ContBuilder().setRef(refVal).build();
+        final Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> normalizedNode =
+                this.registry.toNormalizedNode(BA_II_CONT, data);
+        assertNotNull(normalizedNode);
+
+        final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode =
+                this.registry.fromNormalizedNode(contYII, normalizedNode.getValue());
+        assertNotNull(fromNormalizedNode);
+        final Cont value = (Cont) fromNormalizedNode.getValue();
+        assertEquals(refVal, value.getRef());
+    }
+
+    @Test
+    public void uint32LeafrefTest() {
+        final YangInstanceIdentifier contYII = YangInstanceIdentifier.builder().node(ContInt32.QNAME).build();
+        final InstanceIdentifier<?> fromYangInstanceIdentifier = this.registry.fromYangInstanceIdentifier(contYII);
+        assertNotNull(fromYangInstanceIdentifier);
+
+        final InstanceIdentifier<ContInt32> BA_II_CONT = InstanceIdentifier.builder(ContInt32.class).build();
+        final RefUnionInt32 refVal = new RefUnionInt32(5l);
+        final ContInt32 data = new ContInt32Builder().setRefUnionInt32(refVal).build();
+        final Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> normalizedNode =
+                this.registry.toNormalizedNode(BA_II_CONT, data);
+        assertNotNull(normalizedNode);
+
+        final Entry<InstanceIdentifier<?>, DataObject> fromNormalizedNode =
+                this.registry.fromNormalizedNode(contYII, normalizedNode.getValue());
+        assertNotNull(fromNormalizedNode);
+        final ContInt32 value = (ContInt32) fromNormalizedNode.getValue();
+        assertEquals(refVal, value.getRefUnionInt32());
+    }
+}
+
index fa4343a7d0db3696bd64462aa5c7cee247862c02..b391190fe0dc67c40a258f8f4d52dff1952a383b 100644 (file)
@@ -11,7 +11,6 @@ import static org.opendaylight.mdsal.binding.model.util.BindingGeneratorUtil.enc
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
-
 import com.google.common.base.Preconditions;
 import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableList;
@@ -195,7 +194,7 @@ public final class TypeProviderImpl implements TypeProvider {
         Preconditions.checkArgument(typeDefinition != null, "Type Definition cannot be NULL!");
         Preconditions.checkArgument(typeDefinition.getQName() != null,
                 "Type Definition cannot have non specified QName (QName cannot be NULL!)");
-        String typedefName = typeDefinition.getQName().getLocalName();
+        final String typedefName = typeDefinition.getQName().getLocalName();
         Preconditions.checkArgument(typedefName != null, "Type Definitions Local Name cannot be NULL!");
 
         // Deal with base types
@@ -227,12 +226,12 @@ public final class TypeProviderImpl implements TypeProvider {
 
         Type returnType = javaTypeForExtendedType(typeDefinition);
         if (r != null && returnType instanceof GeneratedTransferObject) {
-            GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
-            Module module = findParentModule(schemaContext, parentNode);
-            String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
-            String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
-            String genTOName = BindingMapping.getClassName(typedefName);
-            String name = packageName + "." + genTOName;
+            final GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
+            final Module module = findParentModule(schemaContext, parentNode);
+            final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
+            final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
+            final String genTOName = BindingMapping.getClassName(typedefName);
+            final String name = packageName + "." + genTOName;
             if (!(returnType.getFullyQualifiedName().equals(name))) {
                 returnType = shadedTOWithRestrictions(gto, r);
             }
@@ -241,14 +240,14 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private static GeneratedTransferObject shadedTOWithRestrictions(final GeneratedTransferObject gto, final Restrictions r) {
-        GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
-        GeneratedTransferObject parent = gto.getSuperType();
+        final GeneratedTOBuilder gtob = new GeneratedTOBuilderImpl(gto.getPackageName(), gto.getName());
+        final GeneratedTransferObject parent = gto.getSuperType();
         if (parent != null) {
             gtob.setExtendsType(parent);
         }
         gtob.setRestrictions(r);
-        for (GeneratedProperty gp : gto.getProperties()) {
-            GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
+        for (final GeneratedProperty gp : gto.getProperties()) {
+            final GeneratedPropertyBuilder gpb = gtob.addProperty(gp.getName());
             gpb.setValue(gp.getValue());
             gpb.setReadOnly(gp.isReadOnly());
             gpb.setAccessModifier(gp.getAccessModifier());
@@ -292,7 +291,7 @@ public final class TypeProviderImpl implements TypeProvider {
         }
         /////
 
-        Module parentModule = getParentModule(parentNode);
+        final Module parentModule = getParentModule(parentNode);
         if (!leafRefStrippedXPath.isAbsolute()) {
             leafRefValueNode = SchemaContextUtil.findDataSchemaNodeForRelativeXPath(schemaContext, parentModule,
                     parentNode, leafRefStrippedXPath);
@@ -345,7 +344,7 @@ public final class TypeProviderImpl implements TypeProvider {
                 returnType = provideTypeForEnum(enumTypeDef, typedefName, typeDefinition);
             } else {
                 final Module module = findParentModule(schemaContext, typeDefinition);
-                Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
+                final Restrictions r = BindingGeneratorUtil.getRestrictions(typeDefinition);
                 if (module != null) {
                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(module.getName());
                     final Map<String, Type> genTOs = modulesByDate.get(module.getRevision());
@@ -378,11 +377,11 @@ public final class TypeProviderImpl implements TypeProvider {
      *         <code>idref</code>
      */
     private Type provideTypeForIdentityref(final IdentityrefTypeDefinition idref) {
-        QName baseIdQName = idref.getIdentity().getQName();
-        Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
+        final QName baseIdQName = idref.getIdentity().getQName();
+        final Module module = schemaContext.findModuleByNamespaceAndRevision(baseIdQName.getNamespace(),
                 baseIdQName.getRevision());
         IdentitySchemaNode identity = null;
-        for (IdentitySchemaNode id : module.getIdentities()) {
+        for (final IdentitySchemaNode id : module.getIdentities()) {
             if (id.getQName().equals(baseIdQName)) {
                 identity = id;
             }
@@ -393,8 +392,8 @@ public final class TypeProviderImpl implements TypeProvider {
         final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, identity.getPath());
         final String genTypeName = BindingMapping.getClassName(identity.getQName());
 
-        Type baseType = Types.typeForClass(Class.class);
-        Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
+        final Type baseType = Types.typeForClass(Class.class);
+        final Type paramType = Types.wildcardTypeFor(packageName, genTypeName);
         return Types.parameterizedTypeFor(baseType, paramType);
     }
 
@@ -591,7 +590,7 @@ public final class TypeProviderImpl implements TypeProvider {
 
         final String enumerationName = BindingMapping.getClassName(enumName);
 
-        Module module = findParentModule(schemaContext, parentNode);
+        final Module module = findParentModule(schemaContext, parentNode);
         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
 
         final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
@@ -686,7 +685,7 @@ public final class TypeProviderImpl implements TypeProvider {
         Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
         final Module[] modulesArray = new Module[modules.size()];
         int i = 0;
-        for (Module modul : modules) {
+        for (final Module modul : modules) {
             modulesArray[i++] = modul;
         }
         final List<Module> modulesSortedByDependency = org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort
@@ -752,10 +751,10 @@ public final class TypeProviderImpl implements TypeProvider {
                     makeSerializable((GeneratedTOBuilderImpl) genTOBuilder);
                     returnType = genTOBuilder.toInstance();
                     // union builder
-                    GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
+                    final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(genTOBuilder.getPackageName(),
                             genTOBuilder.getName() + "Builder");
                     unionBuilder.setIsUnionBuilder(true);
-                    MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
+                    final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
                     method.setReturnType(returnType);
                     method.addParameter(Types.STRING, "defaultValue");
                     method.setAccessModifier(AccessModifier.PUBLIC);
@@ -857,7 +856,7 @@ public final class TypeProviderImpl implements TypeProvider {
         Preconditions.checkState(!builders.isEmpty(), "No GeneratedTOBuilder objects generated from union %s", typedef);
 
         final GeneratedTOBuilder resultTOBuilder = builders.remove(0);
-        for (GeneratedTOBuilder genTOBuilder : builders) {
+        for (final GeneratedTOBuilder genTOBuilder : builders) {
             resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
         }
 
@@ -1005,6 +1004,21 @@ public final class TypeProviderImpl implements TypeProvider {
                 if (javaType != null) {
                     updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, unionTypeName);
                 }
+            } else if (baseType instanceof LeafrefTypeDefinition) {
+                final Type javaType = javaTypeForSchemaDefinitionType(baseType, parentNode);
+                boolean typeExist = false;
+                for (final GeneratedPropertyBuilder generatedPropertyBuilder : parentUnionGenTOBuilder
+                        .getProperties()) {
+                    final Type origType = ((GeneratedPropertyBuilderImpl) generatedPropertyBuilder).getReturnType();
+                    if (origType != null && javaType != null && javaType == origType) {
+                        typeExist = true;
+                        break;
+                    }
+                }
+                if (!typeExist && javaType != null) {
+                    updateUnionTypeAsProperty(parentUnionGenTOBuilder, javaType, new StringBuilder(javaType.getName())
+                            .append(parentUnionGenTOBuilder.getName()).append("Value").toString());
+                }
             }
             if (baseType instanceof StringTypeDefinition) {
                 regularExpressions.addAll(resolveRegExpressionsFromTypedef(unionSubtype));
@@ -1048,8 +1062,8 @@ public final class TypeProviderImpl implements TypeProvider {
         if (!(newTypeDef instanceof UnionTypeDefinition)) {
             final Module parentModule = findParentModule(schemaContext, parentNode);
             if (parentModule != null && parentModule.getName() != null) {
-                Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
-                Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
+                final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(parentModule.getName());
+                final Map<String, Type> genTOsMap = modulesByDate.get(parentModule.getRevision());
                 genTOsMap.put(newTypeDef.getQName().getLocalName(), genTOBuilder.toInstance());
             }
         }
@@ -1136,7 +1150,7 @@ public final class TypeProviderImpl implements TypeProvider {
         Preconditions.checkArgument(basePackageName != null, "Base Package Name cannot be NULL!");
 
         if (typeDef instanceof BitsTypeDefinition) {
-            BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
+            final BitsTypeDefinition bitsTypeDefinition = (BitsTypeDefinition) typeDef;
 
             final String typeName = BindingMapping.getClassName(typeDefName);
             final GeneratedTOBuilderImpl genTOBuilder = new GeneratedTOBuilderImpl(basePackageName, typeName);
@@ -1151,7 +1165,7 @@ public final class TypeProviderImpl implements TypeProvider {
             final List<Bit> bitList = bitsTypeDefinition.getBits();
             GeneratedPropertyBuilder genPropertyBuilder;
             for (final Bit bit : bitList) {
-                String name = bit.getName();
+                final String name = bit.getName();
                 genPropertyBuilder = genTOBuilder.addProperty(BindingMapping.getPropertyName(name));
                 genPropertyBuilder.setReadOnly(true);
                 genPropertyBuilder.setReturnType(BaseYangTypes.BOOLEAN_TYPE);
@@ -1189,7 +1203,7 @@ public final class TypeProviderImpl implements TypeProvider {
         }
 
         final List<String> regExps = new ArrayList<>(patternConstraints.size());
-        for (PatternConstraint patternConstraint : patternConstraints) {
+        for (final PatternConstraint patternConstraint : patternConstraints) {
             final String regEx = patternConstraint.getRegularExpression();
             final String modifiedRegEx = StringEscapeUtils.escapeJava(regEx);
             regExps.add(modifiedRegEx);
@@ -1269,7 +1283,7 @@ public final class TypeProviderImpl implements TypeProvider {
         genTOBuilder.setSchemaPath(typedef.getPath().getPathFromRoot());
         genTOBuilder.setModuleName(moduleName);
         genTOBuilder.setTypedef(true);
-        Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
+        final Restrictions r = BindingGeneratorUtil.getRestrictions(typedef);
         genTOBuilder.setRestrictions(r);
         if (typedef.getStatus() == Status.DEPRECATED) {
             genTOBuilder.addAnnotation("", "Deprecated");
@@ -1288,7 +1302,7 @@ public final class TypeProviderImpl implements TypeProvider {
         }
 
         if (typeMap != null) {
-            Type type = typeMap.get(innerTypeDef);
+            final Type type = typeMap.get(innerTypeDef);
             if (type instanceof GeneratedTransferObject) {
                 genTOBuilder.setExtendsType((GeneratedTransferObject) type);
             }
@@ -1308,7 +1322,7 @@ public final class TypeProviderImpl implements TypeProvider {
      */
     private static void makeSerializable(final GeneratedTOBuilderImpl gto) {
         gto.addImplementsType(Types.typeForClass(Serializable.class));
-        GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
+        final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("serialVersionUID");
         prop.setValue(Long.toString(BindingGeneratorUtil.computeDefaultSUID(gto)));
         gto.setSUID(prop);
     }
@@ -1329,10 +1343,10 @@ public final class TypeProviderImpl implements TypeProvider {
      */
     private static List<TypeDefinition<?>> sortTypeDefinitionAccordingDepth(
             final Collection<TypeDefinition<?>> unsortedTypeDefinitions) {
-        List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
+        final List<TypeDefinition<?>> sortedTypeDefinition = new ArrayList<>();
 
-        Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
-        for (TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
+        final Map<Integer, List<TypeDefinition<?>>> typeDefinitionsDepths = new TreeMap<>();
+        for (final TypeDefinition<?> unsortedTypeDefinition : unsortedTypeDefinitions) {
             final int depth = getTypeDefinitionDepth(unsortedTypeDefinition);
             List<TypeDefinition<?>> typeDefinitionsConcreteDepth = typeDefinitionsDepths.get(depth);
             if (typeDefinitionsConcreteDepth == null) {
@@ -1343,7 +1357,7 @@ public final class TypeProviderImpl implements TypeProvider {
         }
 
         // SortedMap guarantees order corresponding to keys in ascending order
-        for (List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
+        for (final List<TypeDefinition<?>> v : typeDefinitionsDepths.values()) {
             sortedTypeDefinition.addAll(v);
         }
 
@@ -1364,7 +1378,7 @@ public final class TypeProviderImpl implements TypeProvider {
         if (typeDefinition == null) {
             return 1;
         }
-        TypeDefinition<?> baseType = typeDefinition.getBaseType();
+        final TypeDefinition<?> baseType = typeDefinition.getBaseType();
         if (baseType == null) {
             return 1;
         }
@@ -1373,10 +1387,10 @@ public final class TypeProviderImpl implements TypeProvider {
         if (baseType.getBaseType() != null) {
             depth = depth + getTypeDefinitionDepth(baseType);
         } else if (baseType instanceof UnionTypeDefinition) {
-            List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
+            final List<TypeDefinition<?>> childTypeDefinitions = ((UnionTypeDefinition) baseType).getTypes();
             int maxChildDepth = 0;
             int childDepth = 1;
-            for (TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
+            for (final TypeDefinition<?> childTypeDefinition : childTypeDefinitions) {
                 childDepth = childDepth + getTypeDefinitionDepth(childTypeDefinition);
                 if (childDepth > maxChildDepth) {
                     maxChildDepth = childDepth;
@@ -1397,7 +1411,7 @@ public final class TypeProviderImpl implements TypeProvider {
      * @return string with the number suffix incremented by one (or 1 is added)
      */
     private static String provideAvailableNameForGenTOBuilder(final String name) {
-        Matcher mtch = NUMBERS_PATTERN.matcher(name);
+        final Matcher mtch = NUMBERS_PATTERN.matcher(name);
         if (mtch.find()) {
             final int newSuffix = Integer.valueOf(name.substring(mtch.start())) + 1;
             return name.substring(0, mtch.start()) + newSuffix;
@@ -1409,7 +1423,7 @@ public final class TypeProviderImpl implements TypeProvider {
     public static void addUnitsToGenTO(final GeneratedTOBuilder to, final String units) {
         if (!Strings.isNullOrEmpty(units)) {
             to.addConstant(Types.STRING, "_UNITS", "\"" + units + "\"");
-            GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
+            final GeneratedPropertyBuilder prop = new GeneratedPropertyBuilderImpl("UNITS");
             prop.setReturnType(Types.STRING);
             to.addToStringProperty(prop);
         }
@@ -1421,30 +1435,30 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     public String getTypeDefaultConstruction(final LeafSchemaNode node, final String defaultValue) {
-        TypeDefinition<?> type = CompatUtils.compatLeafType(node);
-        QName typeQName = type.getQName();
-        TypeDefinition<?> base = baseTypeDefForExtendedType(type);
+        final TypeDefinition<?> type = CompatUtils.compatLeafType(node);
+        final QName typeQName = type.getQName();
+        final TypeDefinition<?> base = baseTypeDefForExtendedType(type);
         Preconditions.checkNotNull(type, "Cannot provide default construction for null type of %s", node);
         Preconditions.checkNotNull(defaultValue, "Cannot provide default construction for null default statement of %s",
                 node);
 
-        StringBuilder sb = new StringBuilder();
+        final StringBuilder sb = new StringBuilder();
         String result = null;
         if (base instanceof BinaryTypeDefinition) {
             result = binaryToDef(defaultValue);
         } else if (base instanceof BitsTypeDefinition) {
             String parentName;
             String className;
-            Module parent = getParentModule(node);
-            Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
+            final Module parent = getParentModule(node);
+            final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
             path.next();
             if (!(path.hasNext())) {
                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
-                String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
+                final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             } else {
-                String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
-                String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
+                final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
                 parentName = BindingMapping.getClassName(parent.getName());
                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             }
@@ -1456,20 +1470,20 @@ public final class TypeProviderImpl implements TypeProvider {
         } else if (base instanceof EmptyTypeDefinition) {
             result = typeToBooleanDef(defaultValue);
         } else if (base instanceof EnumTypeDefinition) {
-            char[] defValArray = defaultValue.toCharArray();
-            char first = Character.toUpperCase(defaultValue.charAt(0));
+            final char[] defValArray = defaultValue.toCharArray();
+            final char first = Character.toUpperCase(defaultValue.charAt(0));
             defValArray[0] = first;
-            String newDefVal = new String(defValArray);
+            final String newDefVal = new String(defValArray);
             String className;
             if (type.getBaseType() != null) {
-                Module m = getParentModule(type);
-                String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
-                String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
+                final Module m = getParentModule(type);
+                final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
                 className = packageName + "." + BindingMapping.getClassName(typeQName);
             } else {
-                Module parentModule = getParentModule(node);
-                String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
-                String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
+                final Module parentModule = getParentModule(node);
+                final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, node.getPath());
                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
             }
             result = className + "." + newDefVal;
@@ -1518,10 +1532,10 @@ public final class TypeProviderImpl implements TypeProvider {
 
         if (type.getBaseType() != null && !(base instanceof LeafrefTypeDefinition)
                 && !(base instanceof EnumTypeDefinition) && !(base instanceof UnionTypeDefinition)) {
-            Module m = getParentModule(type);
-            String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
-            String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
-            String className = packageName + "." + BindingMapping.getClassName(typeQName);
+            final Module m = getParentModule(type);
+            final String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
+            final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, type.getPath());
+            final String className = packageName + "." + BindingMapping.getClassName(typeQName);
             sb.insert(0, "new " + className + "(");
             sb.insert(sb.length(), ')');
         }
@@ -1549,9 +1563,9 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private static String binaryToDef(final String defaultValue) {
-        StringBuilder sb = new StringBuilder();
-        BaseEncoding en = BaseEncoding.base64();
-        byte[] encoded = en.decode(defaultValue);
+        final StringBuilder sb = new StringBuilder();
+        final BaseEncoding en = BaseEncoding.base64();
+        final byte[] encoded = en.decode(defaultValue);
         sb.append("new byte[] {");
         for (int i = 0; i < encoded.length; i++) {
             sb.append(encoded[i]);
@@ -1566,9 +1580,9 @@ public final class TypeProviderImpl implements TypeProvider {
     private static final Comparator<Bit> BIT_NAME_COMPARATOR = (o1, o2) -> o1.getName().compareTo(o2.getName());
 
     private static String bitsToDef(final BitsTypeDefinition type, final String className, final String defaultValue, final boolean isExt) {
-        List<Bit> bits = new ArrayList<>(type.getBits());
+        final List<Bit> bits = new ArrayList<>(type.getBits());
         Collections.sort(bits, BIT_NAME_COMPARATOR);
-        StringBuilder sb = new StringBuilder();
+        final StringBuilder sb = new StringBuilder();
         if (!isExt) {
             sb.append("new ");
             sb.append(className);
@@ -1591,9 +1605,9 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private Module getParentModule(final SchemaNode node) {
-        QName qname = node.getPath().getPathFromRoot().iterator().next();
-        URI namespace = qname.getNamespace();
-        Date revision = qname.getRevision();
+        final QName qname = node.getPath().getPathFromRoot().iterator().next();
+        final URI namespace = qname.getNamespace();
+        final Date revision = qname.getRevision();
         return schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
     }
 
@@ -1615,7 +1629,7 @@ public final class TypeProviderImpl implements TypeProvider {
                     } else {
                         dataNode = findDataSchemaNodeForRelativeXPath(schemaContext, module, parentNode, xpath);
                     }
-                    String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
+                    final String result = getTypeDefaultConstruction((LeafSchemaNode) dataNode, defaultValue);
                     return result;
                 }
             } else {
@@ -1632,18 +1646,18 @@ public final class TypeProviderImpl implements TypeProvider {
         String className;
 
         if (type.getBaseType() != null) {
-            QName typeQName = type.getQName();
+            final QName typeQName = type.getQName();
             Module module = null;
-            Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
+            final Set<Module> modules = schemaContext.findModuleByNamespace(typeQName.getNamespace());
             if (modules.size() > 1) {
-                for (Module m : modules) {
+                for (final Module m : modules) {
                     if (m.getRevision().equals(typeQName.getRevision())) {
                         module = m;
                         break;
                     }
                 }
                 if (module == null) {
-                    List<Module> modulesList = new ArrayList<>(modules);
+                    final List<Module> modulesList = new ArrayList<>(modules);
                     Collections.sort(modulesList, (o1, o2) -> o1.getRevision().compareTo(o2.getRevision()));
                     module = modulesList.get(0);
                 }
@@ -1651,24 +1665,24 @@ public final class TypeProviderImpl implements TypeProvider {
                 module = modules.iterator().next();
             }
 
-            String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
+            final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
             className = basePackageName + "." + BindingMapping.getClassName(typeQName);
         } else {
-            Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
-            QName first = path.next();
+            final Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
+            final QName first = path.next();
             if (!(path.hasNext())) {
-                URI namespace = first.getNamespace();
-                Date revision = first.getRevision();
-                Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
+                final URI namespace = first.getNamespace();
+                final Date revision = first.getRevision();
+                final Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
                 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
-                String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
+                final String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             } else {
-                URI namespace = first.getNamespace();
-                Date revision = first.getRevision();
-                Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
-                String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
-                String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
+                final URI namespace = first.getNamespace();
+                final Date revision = first.getRevision();
+                final Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
+                final String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
+                final String packageName = BindingGeneratorUtil.packageNameForGeneratedType(basePackageName, UNION_PATH);
                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
             }
         }
@@ -1676,7 +1690,7 @@ public final class TypeProviderImpl implements TypeProvider {
     }
 
     private static String union(final String className, final String defaultValue, final LeafSchemaNode node) {
-        StringBuilder sb = new StringBuilder();
+        final StringBuilder sb = new StringBuilder();
         sb.append("new ");
         sb.append(className);
         sb.append("(\"");
index f3c4a9f6762fc9e5c2cd5aa47db4918bdbbc8a10..300b2a23963e1081e774f72a51b7552949025cac 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.mdsal.binding.generator.impl;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 
@@ -14,8 +15,10 @@ import java.io.File;
 import java.util.List;
 import org.junit.Test;
 import org.opendaylight.mdsal.binding.generator.api.BindingGenerator;
-import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
+import org.opendaylight.mdsal.binding.model.api.GeneratedProperty;
+import org.opendaylight.mdsal.binding.model.api.GeneratedType;
 import org.opendaylight.mdsal.binding.model.api.Type;
+import org.opendaylight.mdsal.binding.model.util.Types;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
 
@@ -23,8 +26,8 @@ public class UnionTypeDefTest {
 
     @Test
     public void unionTypeResolvingTest() throws Exception {
-        File abstractTopology = new File(getClass().getResource("/union-test-models/abstract-topology.yang").toURI());
-        File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
+        final File abstractTopology = new File(getClass().getResource("/union-test-models/abstract-topology.yang").toURI());
+        final File ietfInetTypes = new File(getClass().getResource("/ietf/ietf-inet-types.yang").toURI());
         final SchemaContext context = YangParserTestUtils.parseYangSources(abstractTopology, ietfInetTypes);
 
         assertNotNull("context is null", context);
@@ -36,4 +39,30 @@ public class UnionTypeDefTest {
 
         // TODO: implement test
     }
+
+    @Test
+    public void unionTypedefLeafrefTest() throws Exception {
+        final File yang = new File(getClass().getResource("/leafref_typedef_union/bug8449.yang").toURI());
+        final SchemaContext schemaContext = YangParserTestUtils.parseYangSources(yang);
+        assertNotNull(schemaContext);
+        final List<Type> generateTypes = new BindingGeneratorImpl(false).generateTypes(schemaContext);
+        assertNotNull(generateTypes);
+        for (final Type type : generateTypes) {
+            if (type.getName().equals("Cont")) {
+                final GeneratedType gt = ((GeneratedType) type);
+                assertNotNull(gt);
+                final GeneratedType refType = gt.getEnclosedTypes().iterator().next();
+                for (final GeneratedProperty generatedProperty : refType.getProperties()) {
+                    switch (generatedProperty.getName()) {
+                        case "stringRefValue":
+                            assertEquals(Types.STRING, generatedProperty.getReturnType());
+                            break;
+                        case "value":
+                            assertEquals(Types.CHAR_ARRAY, generatedProperty.getReturnType());
+                            break;
+                    }
+                }
+            }
+        }
+    }
 }
diff --git a/binding/mdsal-binding-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang b/binding/mdsal-binding-generator-impl/src/test/resources/leafref_typedef_union/bug8449.yang
new file mode 100644 (file)
index 0000000..62d8146
--- /dev/null
@@ -0,0 +1,49 @@
+module bug8449 {
+    yang-version 1;
+    namespace "bug8449";
+    prefix "tst";
+
+    revision "2017-16-05" {
+    }
+
+    typedef name1-ref {
+        type leafref {
+            path "/tst:top/tst:name1";
+        }
+    }
+
+    typedef name2-ref {
+        type leafref {
+            path "/tst:top/tst:name2";
+        }
+    }
+
+    typedef name3-ref {
+        type string;
+    }
+
+    container top {
+        leaf name1 {
+            type string;
+        }
+        leaf name2 {
+            type string;
+        }
+    }
+
+    container test {
+        leaf ref {
+            type name3-ref;
+        }
+    }
+
+    container cont {
+        leaf ref {
+            type union {
+                type name1-ref;
+                type name2-ref;
+            }
+            mandatory true;
+        }
+    }
+}
index 64771279e2c95944acbabdab088a1f945a9ec4f7..6a9d33e72b0658ae493ee13066ed59a242d97613 100644 (file)
@@ -43,7 +43,7 @@ abstract class AbstractTypeMemberBuilder<T extends TypeMemberBuilder<T>> impleme
         return builder;
     }
 
-    protected Type getReturnType() {
+    public Type getReturnType() {
         return this.returnType;
     }
 
diff --git a/binding/mdsal-binding-test-model/src/main/yang/bug8449.yang b/binding/mdsal-binding-test-model/src/main/yang/bug8449.yang
new file mode 100644 (file)
index 0000000..b965242
--- /dev/null
@@ -0,0 +1,60 @@
+module bug8449 {
+    yang-version 1;
+    namespace "bug8449";
+    prefix "tst";
+
+    revision "2017-16-05" {
+    }
+
+    typedef name1-ref {
+        type leafref {
+            path "/tst:top/tst:name1";
+        }
+    }
+
+    typedef name2-ref {
+        type leafref {
+            path "/tst:top/tst:name2";
+        }
+    }
+
+    typedef int32-ref {
+        type leafref {
+            path "/tst:top-int/tst:leaf-int32";
+        }
+    }
+
+    container top-int {
+        leaf leaf-int32 {
+            type uint32;
+        }
+    }
+
+    container top {
+        leaf name1 {
+            type string;
+        }
+        leaf name2 {
+            type string;
+        }
+    }
+
+    container cont-int32 {
+        leaf ref-union-int32 {
+            type union {
+                type int32-ref;
+            }
+        }
+    }
+
+    container cont {
+        leaf ref {
+            type union {
+                type name1-ref;
+                type name2-ref;
+            }
+            mandatory true;
+        }
+    }
+}
+