Created
January 23, 2015 10:13
-
-
Save jliuhtonen/5285f18a1162e0947ea0 to your computer and use it in GitHub Desktop.
Convert empty Optional<T> to HTTP 204 No Content in Jersey 2
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
package my.rest.api | |
import javax.servlet.http.HttpServletResponse; | |
import javax.ws.rs.container.ContainerRequestContext; | |
import javax.ws.rs.container.ContainerResponseContext; | |
import javax.ws.rs.container.ContainerResponseFilter; | |
import java.io.IOException; | |
import java.util.Optional; | |
public class OptionalResponseFilter implements ContainerResponseFilter { | |
@Override | |
public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) throws IOException { | |
Object entity = response.getEntity(); | |
if(entity != null && isNonPresentOptionalValue(entity)) { | |
response.setStatus(HttpServletResponse.SC_NO_CONTENT); | |
response.setEntity(null); | |
} | |
} | |
private boolean isNonPresentOptionalValue(Object entity) { | |
return entity instanceof Optional<?> && !((Optional)entity).isPresent(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment