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

ru.yandex.clickhouse.response.ArrayToStringDeserializer Maven / Gradle / Ivy

There is a newer version: 0.3.2
Show newest version
package ru.yandex.clickhouse.response;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import ru.yandex.clickhouse.Jackson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;


class ArrayToStringDeserializer extends JsonDeserializer> {

    private static final LoadingCache> deserializers
            = CacheBuilder.newBuilder()
            .weakKeys()
            .concurrencyLevel(16)
            .maximumSize(10000)
            .build(new CacheLoader>() {
        @Override
        public JsonDeserializer load(DeserializationContext ctxt) throws Exception {
            return  ctxt.findContextualValueDeserializer(TypeFactory.defaultInstance()
                    .constructType(new TypeReference>() {
                    }), null);
        }
    });

    @Override
    public List deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
        JsonDeserializer deserializer;
        try {
             deserializer = deserializers.get(ctxt);
        } catch (ExecutionException e){
            throw new RuntimeException(e);
        }

        final Object deserialized = deserializer.deserialize(jp, ctxt);
        if (!(deserialized instanceof List)){
            throw new IllegalStateException();
        }
        //noinspection unchecked
        final List deserializedList = (List) deserialized;
        List result = new ArrayList();
        for (Object x : deserializedList) {
            String v = null;
            if (x instanceof List) {
                try {
                    v = Jackson.getObjectMapper().writeValueAsString(x);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            } else if (x != null) {
                v = x.toString();
            }
            result.add(v);
        }
        return result;
    }

}