Optimally, I would like to be able to do something like this
Request request = new Request("http://someendpoint")
request.onMessage(payload -> System.out.println(payload))
request.onError(error -> error.printStackTrace())
request.onClose(() -> System.out.println("closed"))
request.onConnect(isReconnect -> System.out.println("connected"))
Obviously doesn't have to be exactly like that, just thought it would help explain what I was trying to do.
I have seen that there is some sort of support for this in Jersey. I would like to find an alternative but will use that if nothing else is available.
SSEs are available in JavaEE 8 through JAX-RS 2.1 in the javax.ws.rs.sse package. Unlike requests and responses which can be synchronous or asynchronous, SSEs are asynchronous by nature.
For a demonstration of SSEs have a look at this video by David Delabassee. Your code (which is client-side only) would looks something like this:
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://someendpoint");
SseEventSource eventSource = SseEventSource.target(target)
.reconnectingEvery(5, TimeUnit.SECONDS)
.build();
eventSource.register(payload -> System.out.println(payload), // Consumer<InboundSseEvent>
error -> error.printStackTrace(), // Consumer<Throwable>
() -> System.out.println("no more events"));
eventSource.open();
// and eventually
eventSource.close();
There are no built-in handlers for (re)connection and closing, but you could customize something to have the same effect.
JAX-RS 2.1 is implemented in (at least):