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

io.dropwizard.discovery.core.JacksonInstanceSerializer Maven / Gradle / Ivy

There is a newer version: 2.0.0
Show newest version
package io.dropwizard.discovery.core;

import java.io.ByteArrayOutputStream;
import javax.annotation.Nonnull;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.curator.x.discovery.details.InstanceSerializer;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
import com.fasterxml.jackson.databind.ObjectWriter;

public class JacksonInstanceSerializer implements InstanceSerializer {

    private final TypeReference> typeRef;
    private final ObjectWriter writer;
    private final ObjectReader reader;

    /**
     * Constructor
     *
     * @param mapper
     *            {@link ObjectMapper}
     * @param typeRef
     *            {@link TypeReference}
     */
    public JacksonInstanceSerializer(@Nonnull final ObjectMapper mapper,
            @Nonnull final TypeReference> typeRef) {
        this.reader = mapper.reader();
        this.writer = mapper.writer();
        this.typeRef = typeRef;
    }

    @Override
    public ServiceInstance deserialize(final byte[] bytes) throws Exception {
        return reader.forType(typeRef).readValue(bytes);
    }

    @Override
    public byte[] serialize(final ServiceInstance instance) throws Exception {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        writer.writeValue(out, instance);
        return out.toByteArray();
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy