I would like to implement a JsonP interceptor, and I'm using Jersey. (I am using AsyncResponses with Long-polling, and my REST method returns 'void' therefore I can't annotate it with @JSONP)
My problem is I don't know how to get the query params. I need to know the 'callback' method name.
I also tried a regular Servlet filter. It worked, but strangely I got methodname() {my json}
instead of
medhodname({my json})
.
So I tried the Jersey way. Seems like I need a WriterInterceptor, but how do I get the query param?
Here's my code:
@Provider
public class JsonpResponseFilter implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
final String callback = (String)context.getProperty("callback");
if (null != callback) {
context.getOutputStream().write((callback+"(").getBytes());
}
context.proceed();
if (null != callback) {
context.getOutputStream().write(')');
}
}
}
Edit:
I found a way to get the query params, but it seems like hacking to me (see below). There's got to be something simpler or more elegant. Any ideas?
@Provider
public class JsonpResponseFilter implements WriterInterceptor {
@Override
public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
final ServiceLocator locator = ServiceLocatorClientProvider.getServiceLocator(context);
ContainerRequestContext tmp = locator.getService(ContainerRequestContext.class);
List<String> callbacks = tmp.getUriInfo().getQueryParameters().get("callback");
String callback = (null == callbacks)? null:callbacks.get(0);
...
A less hacky solution is to inject a Provider as a field in your class:
@Inject
private Provider<ContainerRequest> containerRequestProvider;
From here, you can access the query params like this:
final ContainerRequest containerRequest = containerRequestProvider.get();
final UriInfo uriInfo = containerRequest.getUriInfo();
final MultivaluedMap<String, String> queryParameters = uriInfo.getQueryParameters();
final List<String> queryParameter = queryParameters.get("q");
...