Skip to content

Instantly share code, notes, and snippets.

@chrislbs
Last active February 3, 2016 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrislbs/b64a9346db07840076b8 to your computer and use it in GitHub Desktop.
Save chrislbs/b64a9346db07840076b8 to your computer and use it in GitHub Desktop.
NullBodyToEmptyJsonContainerFilter for DW 0.7.1
@Provider
@Slf4j
public class NullBodyToEmptyJsonFilter implements ContainerRequestFilter
{
private static final String EMPTY_JSON_OBJECT = "{}";
private static final byte[] EMPTY_JSON_BYTES = EMPTY_JSON_OBJECT.getBytes();
@Override
public ContainerRequest filter(ContainerRequest request) {
MediaType mediaType = request.getMediaType();
String method = request.getMethod();
boolean isMethodPostOrPut = ("POST".equalsIgnoreCase(method) || "PUT".equalsIgnoreCase(method));
boolean isJSON = MediaType.APPLICATION_JSON_TYPE.equals(mediaType);
try
{
byte[] entityBuffer = new byte[1];
int bytesRead = request.getEntityInputStream().read(entityBuffer);
boolean isEntityEmpty = bytesRead == -1;
InputStream entityStream;
if (isMethodPostOrPut && isJSON && isEntityEmpty)
{
log.info("Got an empty entity body with method={} and mediaType={}. Will inject {} into the request",
method, mediaType, EMPTY_JSON_OBJECT);
entityStream = new ByteArrayInputStream(EMPTY_JSON_BYTES);
}
else
{
entityStream = new SequenceInputStream(
new ByteArrayInputStream(entityBuffer),
request.getEntityInputStream());
}
request.setEntityInputStream(entityStream);
}
catch (IOException e)
{
log.error("Caught exception while trying to inject an empty JSON object into the request: {}\n.", e.getMessage(), e);
}
return request;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment