I need to create a RESTful service which should support async calls in follwing way. When user calls some method he got the http '202' code and url to poll where he can see the status of his request. Currently I use JAX-RS and its annoations:
@Path("")
public interface MyService {
@POST
@Path("/myService/{name}")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
void postSomething(@PathParam("name") String name, MyObject data);
}
Such mapping would expose MyService's postSomething() method by url /myService/{name} which serves POST requests, get 'name' parameter from url and 'data' from request body.
I want that after making this PUT request client get 202 http code and some callback url to poll to get the result once method will be executed.
So the question is:
1. How to make JAX-RS return 202 code?
2. How to pass callback url to the client?
Have the postSomething method return a Response object:
public Response postSomething(@PathParam("name") String name, MyObject data) {
return Response.status(Status.ACCEPTED).build();
}
If you want the callback URI as plain-text in the HTTP Body you could do something like this:
public Response postSomething(@PathParam("name") String name, MyObject data) {
return Response.status(Status.ACCEPTED).entity("http://google.com").build();
}
For generating URIs by resource classes, have a look at UriBuilder
Use @Context HttpServletResponse servletResponse
to get direct control over the servlet's response mechanism.
@PUT
@Path("/myService/{name}")
@Consumes({APPLICATION_XML, APPLICATION_JSON})
void postSomething(@PathParam("name") String name, @Context HttpServletResponse response, MyObject data) {
// ...
response.setStatus(HttpServletResponse.SC_ACCEPTED);
response.setHeader("Location", myURL);
// ...
}