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

io.prestosql.jdbc.$internal.airlift.json.JsonCodec Maven / Gradle / Ivy

There is a newer version: 350
Show newest version
/*
 * Copyright 2010 Proofpoint, Inc.
 *
 * 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
 *
 *     http://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 io.prestosql.jdbc.$internal.airlift.json;

import io.prestosql.jdbc.$internal.jackson.databind.JavaType;
import io.prestosql.jdbc.$internal.jackson.databind.ObjectMapper;
import io.prestosql.jdbc.$internal.guava.base.Suppliers;
import io.prestosql.jdbc.$internal.guava.reflect.TypeParameter;
import io.prestosql.jdbc.$internal.guava.reflect.TypeToken;
import io.prestosql.jdbc.$internal.airlift.json.LengthLimitedWriter.LengthLimitExceededException;

import java.io.IOException;
import java.io.StringWriter;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Supplier;

import static io.prestosql.jdbc.$internal.jackson.databind.SerializationFeature.INDENT_OUTPUT;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

public class JsonCodec
{
    private static final Supplier OBJECT_MAPPER_SUPPLIER = Suppliers.memoize(
            () -> new ObjectMapperProvider().get().enable(INDENT_OUTPUT))::get;

    public static  JsonCodec jsonCodec(Class type)
    {
        requireNonNull(type, "type is null");

        return new JsonCodec<>(OBJECT_MAPPER_SUPPLIER.get(), type);
    }

    public static  JsonCodec jsonCodec(TypeToken type)
    {
        requireNonNull(type, "type is null");

        return new JsonCodec<>(OBJECT_MAPPER_SUPPLIER.get(), type.getType());
    }

    public static  JsonCodec> listJsonCodec(Class type)
    {
        requireNonNull(type, "type is null");

        Type listType = new TypeToken>() {}
                .where(new TypeParameter() {}, type)
                .getType();

        return new JsonCodec<>(OBJECT_MAPPER_SUPPLIER.get(), listType);
    }

    public static  JsonCodec> listJsonCodec(JsonCodec type)
    {
        requireNonNull(type, "type is null");

        Type listType = new TypeToken>() {}
                .where(new TypeParameter() {}, type.getTypeToken())
                .getType();

        return new JsonCodec<>(OBJECT_MAPPER_SUPPLIER.get(), listType);
    }

    public static  JsonCodec> mapJsonCodec(Class keyType, Class valueType)
    {
        requireNonNull(keyType, "keyType is null");
        requireNonNull(valueType, "valueType is null");

        Type mapType = new TypeToken>() {}
                .where(new TypeParameter() {}, keyType)
                .where(new TypeParameter() {}, valueType)
                .getType();

        return new JsonCodec<>(OBJECT_MAPPER_SUPPLIER.get(), mapType);
    }

    public static  JsonCodec> mapJsonCodec(Class keyType, JsonCodec valueType)
    {
        requireNonNull(keyType, "keyType is null");
        requireNonNull(valueType, "valueType is null");

        Type mapType = new TypeToken>() {}
                .where(new TypeParameter() {}, keyType)
                .where(new TypeParameter() {}, valueType.getTypeToken())
                .getType();

        return new JsonCodec<>(OBJECT_MAPPER_SUPPLIER.get(), mapType);
    }

    private final ObjectMapper mapper;
    private final Type type;
    private final JavaType javaType;

    JsonCodec(ObjectMapper mapper, Type type)
    {
        this.mapper = mapper;
        this.type = type;
        this.javaType = mapper.getTypeFactory().constructType(type);
    }

    /**
     * Gets the type this codec supports.
     */
    public Type getType()
    {
        return type;
    }

    /**
     * Converts the specified json string into an instance of type T.
     *
     * @param json the json string to parse
     * @return parsed response; never null
     * @throws IllegalArgumentException if the json string can not be converted to the type T
     */
    public T fromJson(String json)
            throws IllegalArgumentException
    {
        try {
            return mapper.readerFor(javaType).readValue(json);
        }
        catch (IOException e) {
            throw new IllegalArgumentException(format("Invalid JSON string for %s", javaType), e);
        }
    }

    /**
     * Converts the specified instance to json.
     *
     * @param instance the instance to convert to json
     * @return json string
     * @throws IllegalArgumentException if the specified instance can not be converted to json
     */
    public String toJson(T instance)
            throws IllegalArgumentException
    {
        try {
            return mapper.writerFor(javaType).writeValueAsString(instance);
        }
        catch (IOException e) {
            throw new IllegalArgumentException(format("%s could not be converted to JSON", instance.getClass().getName()), e);
        }
    }

    /**
     * Converts the specified instance to optional json string with a length limit. Returns Optional.empty() if length limit is exceeded.
     *
     * @param instance the instance to convert to json
     * @param lengthLimit the maximum length of the serialized string in characters
     * @return json string
     * @throws IllegalArgumentException if the specified instance can not be converted to json
     */
    public Optional toJsonWithLengthLimit(T instance, int lengthLimit)
    {
        try (StringWriter stringWriter = new StringWriter();
                LengthLimitedWriter lengthLimitedWriter = new LengthLimitedWriter(stringWriter, lengthLimit)) {
            mapper.writeValue(lengthLimitedWriter, instance);
            return Optional.of(stringWriter.getBuffer().toString());
        }
        catch (LengthLimitExceededException e) {
            return Optional.empty();
        }
        catch (IOException e) {
            throw new IllegalArgumentException(format("%s could not be converted to JSON", instance.getClass().getName()), e);
        }
    }

    /**
     * Coverts the specified json bytes (UTF-8) into an instance of type T.
     *
     * @param json the json bytes (UTF-8) to parse
     * @return parsed response; never null
     * @throws IllegalArgumentException if the json bytes can not be converted to the type T
     */
    public T fromJson(byte[] json)
            throws IllegalArgumentException
    {
        try {
            return mapper.readerFor(javaType).readValue(json);
        }
        catch (IOException e) {
            throw new IllegalArgumentException(format("Invalid JSON bytes for %s", javaType), e);
        }
    }

    /**
     * Converts the specified instance to json.
     *
     * @param instance the instance to convert to json
     * @return json bytes (UTF-8)
     * @throws IllegalArgumentException if the specified instance can not be converted to json
     */
    public byte[] toJsonBytes(T instance)
            throws IllegalArgumentException
    {
        try {
            return mapper.writerFor(javaType).writeValueAsBytes(instance);
        }
        catch (IOException e) {
            throw new IllegalArgumentException(format("%s could not be converted to JSON", instance.getClass().getName()), e);
        }
    }

    @SuppressWarnings("unchecked")
    TypeToken getTypeToken()
    {
        return (TypeToken) TypeToken.of(type);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy