raupach
raupach

Reputation: 3102

Request right after Response?

I am a bit lost with the following scenario:

My webservice consumes POST requests with form data. I have to reply with 200 OK or otherwise the senders thinks the request failed.

Immediately after answering with 200 I would like to proceed to call another webservice on a remote host with some of the data I have just received.

My webservice consumes the POST request with the @GET annotation. That works I can read all the form data. To call the other webservice I used the Jersey Client API. That works fine too.

I just can't figure out how to switch from switching from one call to another. Everything is programmed with Jersey 2 and deployed in Tomcat, so no real Application Server. There is no full Java EE stack available.

Am I missing some middleware? Do I need to implement a custom event-loop or some message broker?

Upvotes: 2

Views: 332

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208964

Not sure if there's any "standard" way to handle this, but there's a CompletionCallback we can register with an AyncResponse.

CompletionCallback:

A request processing callback that receives request processing completion events.

A completion callback is invoked when the whole request processing is over, i.e. once a response for the request has been processed and sent back to the client or in when an unmapped exception or error is being propagated to the container.

The AsyncResponse is meant to handle requests asynchronously , but we can immediately call resume to treat it like it was synchronous. A simple example would be something like

@Path("/callback")
public class AsyncCallback {
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    public void postWithAsync(@Suspended AsyncResponse asyncResponse,  
                                         SomeObject object) {

        asyncResponse.register(new CompletionCallback() {
            @Override
            public void onComplete(Throwable error) {
                if (error == null) {
                    System.out.println("Processing new Request");
                } else {
                    System.out.println("Exception in Request handling");
                }
            }
        });
        Response response = Response.ok("Success").build();
        // Carry on like nothing happened
        asyncResponse.resume(response);
    }
}

You can see more explanation at Asynchronous Server-side Callbacks

Upvotes: 1

Related Questions