Search in sources :

Example 6 with OneOfType

use of org.apache.beam.sdk.schemas.logicaltypes.OneOfType in project beam by apache.

the class ProtoByteBuddyUtils method createGetter.

private static <ProtoT> FieldValueGetter createGetter(FieldValueTypeInformation fieldValueTypeInformation, TypeConversionsFactory typeConversionsFactory, Class clazz, Multimap<String, Method> methods, Field field, FieldValueTypeSupplier fieldValueTypeSupplier) {
    if (field.getType().isLogicalType(OneOfType.IDENTIFIER)) {
        OneOfType oneOfType = field.getType().getLogicalType(OneOfType.class);
        // The case accessor method in the proto is named getOneOfNameCase.
        Method caseMethod = getProtoGetter(methods, field.getName() + "_case", FieldType.logicalType(oneOfType.getCaseEnumType()));
        // Create a map of case enum value to getter. This must be sorted, so store in a TreeMap.
        TreeMap<Integer, FieldValueGetter<ProtoT, OneOfType.Value>> oneOfGetters = Maps.newTreeMap();
        Map<String, FieldValueTypeInformation> oneOfFieldTypes = fieldValueTypeSupplier.get(clazz, oneOfType.getOneOfSchema()).stream().collect(Collectors.toMap(FieldValueTypeInformation::getName, f -> f));
        for (Field oneOfField : oneOfType.getOneOfSchema().getFields()) {
            int protoFieldIndex = getFieldNumber(oneOfField);
            FieldValueGetter oneOfFieldGetter = createGetter(oneOfFieldTypes.get(oneOfField.getName()), typeConversionsFactory, clazz, methods, oneOfField, fieldValueTypeSupplier);
            oneOfGetters.put(protoFieldIndex, oneOfFieldGetter);
        }
        return createOneOfGetter(fieldValueTypeInformation, oneOfGetters, clazz, oneOfType, caseMethod);
    } else {
        return JavaBeanUtils.createGetter(fieldValueTypeInformation, typeConversionsFactory);
    }
}
Also used : Arrays(java.util.Arrays) ProtocolMessageEnum(com.google.protobuf.ProtocolMessageEnum) ArrayAccess(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.collection.ArrayAccess) OneOfType(org.apache.beam.sdk.schemas.logicaltypes.OneOfType) TypeCasting(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.assign.TypeCasting) StringValue(com.google.protobuf.StringValue) AsmVisitorWrapper(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.asm.AsmVisitorWrapper) ImmutableMap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap) ByteBuddyUtils(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils) ByteCodeAppender(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.ByteCodeAppender) Label(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.jar.asm.Label) NullConstant(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.constant.NullConstant) Visibility(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.modifier.Visibility) Map(java.util.Map) EnumerationType(org.apache.beam.sdk.schemas.logicaltypes.EnumerationType) MethodReturn(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.member.MethodReturn) Method(java.lang.reflect.Method) ClassLoadingStrategy(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.dynamic.loading.ClassLoadingStrategy) FloatValue(com.google.protobuf.FloatValue) Size(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.ByteCodeAppender.Size) Set(java.util.Set) FieldType(org.apache.beam.sdk.schemas.Schema.FieldType) Collectors(java.util.stream.Collectors) TypeConversion(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversion) InvocationTargetException(java.lang.reflect.InvocationTargetException) FixedValue(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.FixedValue) ByteString(com.google.protobuf.ByteString) BytesValue(com.google.protobuf.BytesValue) FieldValueTypeSupplier(org.apache.beam.sdk.schemas.utils.FieldValueTypeSupplier) List(java.util.List) Type(java.lang.reflect.Type) Modifier(java.lang.reflect.Modifier) ReflectHelpers(org.apache.beam.sdk.util.common.ReflectHelpers) ProtoSchemaTranslator.getFieldNumber(org.apache.beam.sdk.extensions.protobuf.ProtoSchemaTranslator.getFieldNumber) Typing(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.assign.Assigner.Typing) Implementation(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.Implementation) ByteBuddy(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.ByteBuddy) TypeDescription(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription) TypeDescriptor(org.apache.beam.sdk.values.TypeDescriptor) Int64Value(com.google.protobuf.Int64Value) ConvertType(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertType) MethodVariableAccess(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.member.MethodVariableAccess) BoolValue(com.google.protobuf.BoolValue) Experimental(org.apache.beam.sdk.annotations.Experimental) DynamicType(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.dynamic.DynamicType) UInt64Value(com.google.protobuf.UInt64Value) CaseFormat(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.CaseFormat) ClassWithSchema(org.apache.beam.sdk.schemas.utils.ReflectUtils.ClassWithSchema) Timestamp(com.google.protobuf.Timestamp) Supplier(java.util.function.Supplier) FieldAccess(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.member.FieldAccess) InstrumentedType(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.dynamic.scaffold.InstrumentedType) FieldManifestation(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.modifier.FieldManifestation) FieldValueSetter(org.apache.beam.sdk.schemas.FieldValueSetter) Multimap(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Multimap) Kind(org.apache.beam.sdk.annotations.Experimental.Kind) SchemaUserTypeCreator(org.apache.beam.sdk.schemas.SchemaUserTypeCreator) Maps(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Maps) MethodDescription(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.method.MethodDescription) FieldValueTypeInformation(org.apache.beam.sdk.schemas.FieldValueTypeInformation) ForLoadedType(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.type.TypeDescription.ForLoadedType) Row(org.apache.beam.sdk.values.Row) IntegerConstant(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.constant.IntegerConstant) JavaBeanUtils(org.apache.beam.sdk.schemas.utils.JavaBeanUtils) Nullable(org.checkerframework.checker.nullness.qual.Nullable) DoubleValue(com.google.protobuf.DoubleValue) Field(org.apache.beam.sdk.schemas.Schema.Field) Assigner(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.assign.Assigner) Int32Value(com.google.protobuf.Int32Value) Duplication(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.Duplication) Iterator(java.util.Iterator) ReflectUtils(org.apache.beam.sdk.schemas.utils.ReflectUtils) Compound(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.StackManipulation.Compound) ConvertValueForGetter(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertValueForGetter) ElementMatchers(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.matcher.ElementMatchers) UInt32Value(com.google.protobuf.UInt32Value) Lists(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists) ClassWriter(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.jar.asm.ClassWriter) Schema(org.apache.beam.sdk.schemas.Schema) TypeName(org.apache.beam.sdk.schemas.Schema.TypeName) EnumLite(com.google.protobuf.Internal.EnumLite) MessageLite(com.google.protobuf.MessageLite) Duration(com.google.protobuf.Duration) StackManipulation(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.StackManipulation) MethodInvocation(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.implementation.bytecode.member.MethodInvocation) TreeMap(java.util.TreeMap) ConvertValueForSetter(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertValueForSetter) InjectPackageStrategy(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.InjectPackageStrategy) Preconditions(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions) TypeConversionsFactory(org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.TypeConversionsFactory) FieldValueGetter(org.apache.beam.sdk.schemas.FieldValueGetter) ForLoadedMethod(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.method.MethodDescription.ForLoadedMethod) Field(org.apache.beam.sdk.schemas.Schema.Field) FieldValueGetter(org.apache.beam.sdk.schemas.FieldValueGetter) FieldValueTypeInformation(org.apache.beam.sdk.schemas.FieldValueTypeInformation) Method(java.lang.reflect.Method) ForLoadedMethod(org.apache.beam.vendor.bytebuddy.v1_11_0.net.bytebuddy.description.method.MethodDescription.ForLoadedMethod) ByteString(com.google.protobuf.ByteString) OneOfType(org.apache.beam.sdk.schemas.logicaltypes.OneOfType)

Example 7 with OneOfType

use of org.apache.beam.sdk.schemas.logicaltypes.OneOfType in project beam by apache.

the class AvroUtils method convertUnionStrict.

private static Object convertUnionStrict(Object value, org.apache.avro.Schema unionAvroSchema, Schema.FieldType fieldType) {
    checkTypeName(fieldType.getTypeName(), TypeName.LOGICAL_TYPE, "oneOfType");
    checkArgument(fieldType.getLogicalType().getIdentifier().equals(OneOfType.IDENTIFIER));
    OneOfType oneOfType = fieldType.getLogicalType(OneOfType.class);
    int fieldNumber = GenericData.get().resolveUnion(unionAvroSchema, value);
    FieldType baseFieldType = oneOfType.getOneOfSchema().getField(fieldNumber).getType();
    Object convertedValue = convertAvroFieldStrict(value, unionAvroSchema.getTypes().get(fieldNumber), baseFieldType);
    return oneOfType.createValue(fieldNumber, convertedValue);
}
Also used : OneOfType(org.apache.beam.sdk.schemas.logicaltypes.OneOfType) FieldType(org.apache.beam.sdk.schemas.Schema.FieldType)

Example 8 with OneOfType

use of org.apache.beam.sdk.schemas.logicaltypes.OneOfType in project beam by apache.

the class AvroUtils method genericFromBeamField.

@Nullable
private static Object genericFromBeamField(Schema.FieldType fieldType, org.apache.avro.Schema avroSchema, @Nullable Object value) {
    TypeWithNullability typeWithNullability = new TypeWithNullability(avroSchema);
    if (!fieldType.getNullable().equals(typeWithNullability.nullable)) {
        throw new IllegalArgumentException("FieldType " + fieldType + " and AVRO schema " + avroSchema + " don't have matching nullability");
    }
    if (value == null) {
        return value;
    }
    switch(fieldType.getTypeName()) {
        case BYTE:
        case INT16:
        case INT32:
        case INT64:
        case FLOAT:
        case DOUBLE:
        case BOOLEAN:
            return value;
        case STRING:
            return new Utf8((String) value);
        case DECIMAL:
            BigDecimal decimal = (BigDecimal) value;
            LogicalType logicalType = typeWithNullability.type.getLogicalType();
            return new Conversions.DecimalConversion().toBytes(decimal, null, logicalType);
        case DATETIME:
            if (typeWithNullability.type.getType() == Type.INT) {
                ReadableInstant instant = (ReadableInstant) value;
                return (int) Days.daysBetween(Instant.EPOCH, instant).getDays();
            } else if (typeWithNullability.type.getType() == Type.LONG) {
                ReadableInstant instant = (ReadableInstant) value;
                return (long) instant.getMillis();
            } else {
                throw new IllegalArgumentException("Can't represent " + fieldType + " as " + typeWithNullability.type.getType());
            }
        case BYTES:
            return ByteBuffer.wrap((byte[]) value);
        case LOGICAL_TYPE:
            switch(fieldType.getLogicalType().getIdentifier()) {
                case FixedBytes.IDENTIFIER:
                    FixedBytesField fixedBytesField = checkNotNull(FixedBytesField.fromBeamFieldType(fieldType));
                    byte[] byteArray = (byte[]) value;
                    if (byteArray.length != fixedBytesField.getSize()) {
                        throw new IllegalArgumentException("Incorrectly sized byte array.");
                    }
                    return GenericData.get().createFixed(null, (byte[]) value, typeWithNullability.type);
                case EnumerationType.IDENTIFIER:
                    EnumerationType enumerationType = fieldType.getLogicalType(EnumerationType.class);
                    return GenericData.get().createEnum(enumerationType.toString((EnumerationType.Value) value), typeWithNullability.type);
                case OneOfType.IDENTIFIER:
                    OneOfType oneOfType = fieldType.getLogicalType(OneOfType.class);
                    OneOfType.Value oneOfValue = (OneOfType.Value) value;
                    FieldType innerFieldType = oneOfType.getFieldType(oneOfValue);
                    if (typeWithNullability.nullable && oneOfValue.getValue() == null) {
                        return null;
                    } else {
                        return genericFromBeamField(innerFieldType.withNullable(false), typeWithNullability.type.getTypes().get(oneOfValue.getCaseType().getValue()), oneOfValue.getValue());
                    }
                case "NVARCHAR":
                case "VARCHAR":
                case "LONGNVARCHAR":
                case "LONGVARCHAR":
                    return new Utf8((String) value);
                case "DATE":
                    return Days.daysBetween(Instant.EPOCH, (Instant) value).getDays();
                case "TIME":
                    return (int) ((Instant) value).getMillis();
                default:
                    throw new RuntimeException("Unhandled logical type " + fieldType.getLogicalType().getIdentifier());
            }
        case ARRAY:
        case ITERABLE:
            Iterable iterable = (Iterable) value;
            List<Object> translatedArray = Lists.newArrayListWithExpectedSize(Iterables.size(iterable));
            for (Object arrayElement : iterable) {
                translatedArray.add(genericFromBeamField(fieldType.getCollectionElementType(), typeWithNullability.type.getElementType(), arrayElement));
            }
            return translatedArray;
        case MAP:
            Map map = Maps.newHashMap();
            Map<Object, Object> valueMap = (Map<Object, Object>) value;
            for (Map.Entry entry : valueMap.entrySet()) {
                Utf8 key = new Utf8((String) entry.getKey());
                map.put(key, genericFromBeamField(fieldType.getMapValueType(), typeWithNullability.type.getValueType(), entry.getValue()));
            }
            return map;
        case ROW:
            return toGenericRecord((Row) value, typeWithNullability.type);
        default:
            throw new IllegalArgumentException("Unsupported type " + fieldType);
    }
}
Also used : ReadableInstant(org.joda.time.ReadableInstant) ReadableInstant(org.joda.time.ReadableInstant) Instant(org.joda.time.Instant) EnumerationType(org.apache.beam.sdk.schemas.logicaltypes.EnumerationType) LogicalType(org.apache.avro.LogicalType) BigDecimal(java.math.BigDecimal) FieldType(org.apache.beam.sdk.schemas.Schema.FieldType) AvroRuntimeException(org.apache.avro.AvroRuntimeException) Conversions(org.apache.avro.Conversions) Utf8(org.apache.avro.util.Utf8) Map(java.util.Map) HashMap(java.util.HashMap) OneOfType(org.apache.beam.sdk.schemas.logicaltypes.OneOfType) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Aggregations

OneOfType (org.apache.beam.sdk.schemas.logicaltypes.OneOfType)8 Map (java.util.Map)4 Field (org.apache.beam.sdk.schemas.Schema.Field)4 EnumerationType (org.apache.beam.sdk.schemas.logicaltypes.EnumerationType)4 Row (org.apache.beam.sdk.values.Row)4 Nullable (org.checkerframework.checker.nullness.qual.Nullable)4 Method (java.lang.reflect.Method)3 GenericRecord (org.apache.avro.generic.GenericRecord)3 GenericRecordBuilder (org.apache.avro.generic.GenericRecordBuilder)3 Schema (org.apache.beam.sdk.schemas.Schema)3 FieldType (org.apache.beam.sdk.schemas.Schema.FieldType)3 BigDecimal (java.math.BigDecimal)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Collectors (java.util.stream.Collectors)2 AvroRuntimeException (org.apache.avro.AvroRuntimeException)2 Conversions (org.apache.avro.Conversions)2 LogicalType (org.apache.avro.LogicalType)2 Utf8 (org.apache.avro.util.Utf8)2 Experimental (org.apache.beam.sdk.annotations.Experimental)2