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

com.agorapulse.micronaut.amazon.awssdk.dynamodb.BeanIntrospectionAttributeConversionHelper Maven / Gradle / Ivy

The newest version!
/*
 * SPDX-License-Identifier: Apache-2.0
 *
 * Copyright 2018-2024 Agorapulse.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.agorapulse.micronaut.amazon.awssdk.dynamodb;

import io.micronaut.core.beans.BeanIntrospection;
import io.micronaut.core.beans.BeanProperty;
import software.amazon.awssdk.enhanced.dynamodb.MappedTableResource;
import software.amazon.awssdk.services.dynamodb.model.AttributeValue;

import jakarta.inject.Singleton;
import java.util.Map;
import java.util.stream.Collectors;

@Singleton
public class BeanIntrospectionAttributeConversionHelper implements AttributeConversionHelper {

    @Override
    public  Map convert(MappedTableResource table, Map values) {
        BeanIntrospection introspection = EntityIntrospection.getBeanIntrospection(table);
        T instance = introspection.instantiate();
        return values.entrySet().stream().collect(Collectors.toMap(
            Map.Entry::getKey,
            e -> convert(introspection, table, instance, e.getKey(), e.getValue())
        ));
    }

    private  AttributeValue convert(BeanIntrospection introspection, MappedTableResource table, T instance, String key, Object value) {
        if (value == null) {
            return null;
        }

        if (value instanceof AttributeValue) {
            return (AttributeValue) value;
        }

        BeanProperty p = introspection.getProperty(key).orElseThrow(() -> new IllegalArgumentException("Unknown property " + key + " for " + instance));
        p.set(instance, value);
        return table.tableSchema().attributeValue(instance, key);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy