JAX-RS 2.1 Java API for RESTful Web Services was released this week. According to Santiago Pericas-Geertsen, principal member of technical staff at Oracle and specifications lead for the JSR, JAX-RS 2.1 will include support for server-sent events, JSON-B and improved support for JSON-P. The API will also have a reactive extension to the client API, with built-in support for Java 8 CompletionStage and an extension point for other reactive APIs like RxJava.
According to the JAX-RS 2.1 specs, the goals for the release include annotations for POJOs, flexible API with high-level support for common HTTP usage patterns and applications including WebDAV and the Atom Publishing Protocol. The API will support various HTTP entity body content types, servlet containers and JAX-WS Providers. The API will support Java EE features and components within a web resource class.
InfoQ spoke to Pericas-Geertsen, who elaborated on server-sent events:
Server-sent-event (SSE) resources inject a special type called SseEventSink and produce text/event-stream. SSE clients use a SseEventSource to read events from a connection.
This mechanism uses long-lived connections and broadcasting, which provides improved performance over polling and resource-intensive, short-lived connections.
The following block illustrates the usage of SSE.
Server:
@GET @Produces(MediaType.SERVER_SENT_EVENTS) public void getMessageQueue(@Context Sse sse, @Context SseEventSink eventSink) { // Resource method is invoked when a client subscribes to an event stream. // That implies that sending events will most likely happen from different // context - thread / event handler / etc, so common implementation of the // resource method will store the eventSink instance and the application // logic will retrieve it when an event should be emitted to the client. // sending events: eventSink.send(sse.newEvent("event1")); } Client:
WebTarget target = ClientBuilder.newClient().target("server-sent-events"); SseEventSource eventSource = SseEventSource.target(target).build(); // EventSource#register(Consumer<InboundSseEvent>) // Registered event handler will print the received message. eventSource.register(System.out::println); // Subscribe to the event stream. eventSource.open(); Pericas-Geertsen added:
-
JAX-RS 2.1 is fully backward compatible with previous releases.
-
The new features integrate very well with the existing JAX-RS concepts. For example, simply injecting a method call in a client invocation can switch processing from synchronous to reactive.
-
SSE relies on streaming HTTP-based connections so it is a natural extension to the existing APIs.
Since the API will use annotations and lambda expressions extensively, it will support applications developed in Java SE 8 or later.