All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.atleon.avro.AvroSerialization Maven / Gradle / Ivy

There is a newer version: 0.28.3
Show newest version
package io.atleon.avro;

import io.atleon.util.FieldResolution;
import io.atleon.util.TypeResolution;
import io.atleon.util.ValueResolution;
import org.apache.avro.Schema;
import org.apache.avro.reflect.AvroIgnore;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public final class AvroSerialization {

    private AvroSerialization() {

    }

    public static Schema generateWriterSchema(Object data, Function typeSchemaLoader) {
        return generateWriterSchema(data, data.getClass(), typeSchemaLoader);
    }

    private static Schema generateWriterSchema(Object data, Type type, Function typeSchemaLoader) {
        return TypeResolution.isGenericClass(data.getClass()) && !TypeResolution.isDataStructure(data.getClass()) ?
            Schema.createRecord(data.getClass().getCanonicalName(), null, null, false, generateWriterSchemaFields(data, typeSchemaLoader)) :
            typeSchemaLoader.apply(type instanceof TypeVariable ? data.getClass() : type);
    }

    private static List generateWriterSchemaFields(Object data, Function typeSchemaLoader) {
        return FieldResolution.getAllFields(data.getClass()).stream()
            .filter(AvroSerialization::shouldGenerateWriterSchemaField)
            .map(field -> generateWriterSchemaField(field, ValueResolution.getFieldValue(data, field), typeSchemaLoader))
            .filter(writerSchemaField -> !AvroSchemas.isNull(writerSchemaField.schema()))
            .collect(Collectors.toList());
    }

    private static boolean shouldGenerateWriterSchemaField(Field field) {
        return !Modifier.isStatic(field.getModifiers()) &&
            !Modifier.isTransient(field.getModifiers()) &&
            !field.isAnnotationPresent(AvroIgnore.class);
    }

    private static Schema.Field generateWriterSchemaField(Field field, Object value, Function typeSchemaLoader) {
        Schema fieldSchema = AvroSchemas.getOrSupply(value, () -> generateWriterSchema(value, field.getGenericType(), typeSchemaLoader));
        return new Schema.Field(field.getName(), fieldSchema, null, Object.class.cast(null));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy