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

com.icthh.xm.commons.domainevent.outbox.domain.converter.MapToStringConverter Maven / Gradle / Ivy

package com.icthh.xm.commons.domainevent.outbox.domain.converter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import jakarta.persistence.AttributeConverter;
import jakarta.persistence.Converter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Converter
public class MapToStringConverter implements AttributeConverter, String> {

    private final ObjectMapper mapper = new ObjectMapper();

    public MapToStringConverter() {
        mapper.registerModule(new JavaTimeModule());
    }

    @Override
    public String convertToDatabaseColumn(Map data) {
        try {
            return mapper.writeValueAsString(data != null ? data : Map.of());
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Cannot convert map to JSON string", e);
        }
    }

    @Override
    public Map convertToEntityAttribute(String data) {
        TypeReference> typeRef = new TypeReference<>() {
        };
        try {
            return mapper.readValue(StringUtils.isNoneBlank(data) ? data : "{}", typeRef);
        } catch (IOException e) {
            log.warn("Error during String to JSON converting", e);
            return Collections.emptyMap();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy