ProvidenceHttpBufferedContent.java

package net.morimekta.providence.client.google;

import com.google.api.client.http.HttpContent;
import net.morimekta.providence.PMessageOrBuilder;
import net.morimekta.providence.PServiceCall;
import net.morimekta.providence.serializer.Serializer;
import net.morimekta.util.Binary;

import javax.annotation.Nonnull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * HTTP content wrapper for providence messages. Use this is the
 * receiving end requires the content to have a known size before
 * it being sent. Otherwise use {@link ProvidenceHttpContent}.
 *
 * @since 1.8.0
 */
public class ProvidenceHttpBufferedContent implements HttpContent {
    private final String type;
    private final Binary binary;

    @SuppressWarnings("unchecked")
    public ProvidenceHttpBufferedContent(@Nonnull PMessageOrBuilder message,
                                         @Nonnull Serializer serializer) throws IOException {
        this.type = serializer.mediaType();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializer.serialize(baos, message);
        this.binary = Binary.wrap(baos.toByteArray());
    }

    @SuppressWarnings("unchecked")
    public ProvidenceHttpBufferedContent(@Nonnull PServiceCall serviceCall,
                                         @Nonnull Serializer serializer) throws IOException {
        this.type = serializer.mediaType();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        serializer.serialize(baos, serviceCall);
        this.binary = Binary.wrap(baos.toByteArray());
    }

    @Override
    public long getLength() {
        return binary.length();
    }

    @Override
    public String getType() {
        return type;
    }

    @Override
    public boolean retrySupported() {
        return true;
    }

    @Override
    public void writeTo(OutputStream out) throws IOException {
        binary.write(out);
    }
}