Last active
February 3, 2016 00:48
-
-
Save chrislbs/b64a9346db07840076b8 to your computer and use it in GitHub Desktop.
NullBodyToEmptyJsonContainerFilter for DW 0.7.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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