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

se.fortnox.reactivewizard.db.deserializing.SimpleObjectDeserializer Maven / Gradle / Ivy

There is a newer version: 24.6.0
Show newest version
package se.fortnox.reactivewizard.db.deserializing;

import se.fortnox.reactivewizard.util.PropertyResolver;
import se.fortnox.reactivewizard.util.ReflectionUtil;

import java.lang.reflect.InvocationTargetException;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Map;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Supplier;

/**
 * A deserializer that uses reflection to instantiate an object and set values on it (using setters).
 */
public class SimpleObjectDeserializer {

    /**
     * Create a deserializer.
     * @param cls the class
     * @param metaData the meta data
     * @param  the type of deserializer
     * @return the deserializer
     * @throws SQLException on error
     */
    public static  Deserializer create(Class cls, ResultSetMetaData metaData) throws SQLException {
        Map deserializers = DeserializerUtil.createPropertyDeserializers(
                cls,
                metaData,
                SimpleObjectDeserializer::createRecordPropertyDeserializer);

        Supplier instantiator = ReflectionUtil.instantiator(cls);

        return (rs) -> {
            Object object = instantiator.get();
            for (PropertyDeserializer propertyDeserializer : deserializers.values()) {
                propertyDeserializer.deserialize(rs, object);
            }
            return Optional.of(object);
        };
    }

    private static  PropertyDeserializer createRecordPropertyDeserializer(
            PropertyResolver propertyResolver,
            Deserializer deserializer) {
        BiConsumer setter = propertyResolver.setter();
        return (rs, obj) -> setter.accept(obj, deserializer.deserialize(rs).orElse(null));
    }

    private interface PropertyDeserializer {
        void deserialize(ResultSet rs, I obj) throws SQLException,
            InvocationTargetException, IllegalAccessException,
            InstantiationException;
    }
}