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

estonlabs.cxtl.common.codec.JacksonCodec Maven / Gradle / Ivy

package estonlabs.cxtl.common.codec;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * Jackson backed codec for encoding/decoding
 */
public class JacksonCodec implements Codec{
    private static final Logger LOGGER = LoggerFactory.getLogger(JacksonCodec.class);
    protected final ObjectMapper mapper = new ObjectMapper();
    @Override
    public  String toJson(T pojo) {
        try {
            return mapper.writeValueAsString(pojo);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public  StringBuilder toQueryString(T pojo) {
        return toQueryString(pojo, new StringBuilder());
    }

    @Override
    public  Map toMap(T pojo) {
        return mapper.convertValue(pojo, Map.class);
    }

    @Override
    public  StringBuilder toQueryString(T pojo, StringBuilder builder) {
        if(pojo == null) return null;

        var map = mapper.convertValue(pojo, Map.class);
        return mapToStringBuilder(map,builder);
    }

    @Override
    public  T fromJson(String json, Class type) {
        try {
            return mapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            LOGGER.error("Error decoding "+ json +" into type "+type, e);
            throw new RuntimeException("Error decoding "+ json +" into type "+type, e);
        }
    }

    @Override
    public  T quietFromJson(String json, Class type) {
        try {
            return mapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    @Override
    public  List fromJsonArray(String json, Class type) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionLikeType(List.class,type));
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error decoding "+ json +" into type "+type, e);
        }
    }

    public static StringBuilder mapToStringBuilder(Map fields, StringBuilder builder){
        Map sortedFields = new TreeMap<>(fields);

        for (Map.Entry entry : sortedFields.entrySet()) {
            if (!builder.isEmpty()) {
                builder.append('&');
            }
            if ( entry.getValue() != null) {
                builder.append(entry.getKey()).append('=').append(entry.getValue());
            }
        }
        return builder;
    }
}