Information sent using the JAX-RS 2.1 SSE support (in Java EE 8) does not only have to be of String
type – it supports Java primitives (Integer
, Long
etc.), JSON-B
& JAX-B
annotated types as well as custom objects whose encoding process (Java object to on-wire format) is defined using a MessageBodyWriter
implementation
Here is simple example you can try out – no need to setup anything except Docker
!
Meanwhile – here is the code snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@GET | |
@Produces("text/event-stream") | |
public void fetch(@Context Sse sse, @Context SseEventSink eSink) { | |
OutboundSseEvent stringEvent = sse.newEventBuilder() | |
.name("stringEvent") | |
.data(new Date().toString()).build(); | |
eSink.send(stringEvent); | |
OutboundSseEvent primitiveTypeEvent = sse.newEventBuilder() | |
.name("primitiveTypeEvent") | |
.data(System.currentTimeMillis()).build(); | |
eSink.send(primitiveTypeEvent); | |
OutboundSseEvent jsonbType = sse.newEventBuilder() | |
.name("jsonbType") | |
.data(new Employee("test@test", "test", 42)) | |
.mediaType(MediaType.APPLICATION_JSON_TYPE) | |
.build(); | |
eSink.send(jsonbType); | |
OutboundSseEvent jaxbType = sse.newEventBuilder() | |
.name("jaxbType") | |
.data(new Customer("testcut@test", "king")) | |
.mediaType(MediaType.APPLICATION_XML_TYPE) | |
.build(); | |
eSink.send(jaxbType); | |
OutboundSseEvent customObjWithMBW = sse.newEventBuilder() | |
.name("customObjWithMBW") | |
.data(new Student("stud@test", "stud-007")).build(); | |
eSink.send(customObjWithMBW); | |
System.out.println("events sent"); | |
eSink.close(); | |
System.out.println("sink closed"); | |
} |
To summarize
- Multiple
OutboundSseEvent
s have been created – each differing in the data/media type (text, json, xml etc.) - the default SSE media type is
TEXT_PLAIN
, hence does not need to be explicitly specified when dealing withString
data type Employee
class is aJSON-B
annotated classCustomer
is aJAX-B
annotated classStudent
has a customMesaageBodyWriter
implementation
For more details, just refer to the project
Further reading
Cheers!