package io.dropwizard.jersey.errors;
import org.glassfish.jersey.message.MessageBodyWorkers;
import javax.annotation.Nullable;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import static java.util.Objects.requireNonNull;
public abstract class ErrorEntityWriter<T, U> implements MessageBodyWriter<T> {
public ErrorEntityWriter(MediaType contentType, Class<U> representation) {
this.contentType = contentType;
this.representation = representation;
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return requireNonNull(headers).getAcceptableMediaTypes().contains(contentType);
}
@Override
public long getSize(T entity, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return 0;
}
@Override
public void writeTo(T entity,
Class<?> type,
Type genericType,
Annotation[] annotations,
MediaType mediaType,
MultivaluedMap<String, Object> responseHeaders,
OutputStream entityStream)
throws IOException, WebApplicationException {
final MessageBodyWriter<U> writer = requireNonNull(mbw).get().getMessageBodyWriter(representation,
representation, annotations, contentType);
responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType);
writer.writeTo(getRepresentation(entity), representation, representation, annotations,
contentType, responseHeaders, entityStream);
}
protected abstract U getRepresentation(T entity);
private MediaType contentType;
private Class<U> representation;
@Context
@Nullable
private HttpHeaders ;
@Context
@Nullable
private javax.inject.Provider<MessageBodyWorkers> mbw;
}