Handling custom objects with JAX-RS SSE API

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

public void fetch(@Context Sse sse, @Context SseEventSink eSink) {
OutboundSseEvent stringEvent = sse.newEventBuilder()
.data(new Date().toString()).build();
OutboundSseEvent primitiveTypeEvent = sse.newEventBuilder()
OutboundSseEvent jsonbType = sse.newEventBuilder()
.data(new Employee("test@test", "test", 42))
OutboundSseEvent jaxbType = sse.newEventBuilder()
.data(new Customer("testcut@test", "king"))
OutboundSseEvent customObjWithMBW = sse.newEventBuilder()
.data(new Student("stud@test", "stud-007")).build();
System.out.println("events sent");
System.out.println("sink closed");

To summarize

  • Multiple ​​OutboundSseEvents 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 with String data type
  • ​​​​​Employee class is a JSON-B annotated class
  • Customer is a JAX-B annotated class
  • Student has a custom MesaageBodyWriter implementation

For more details, just refer to the project

Further reading



About Abhishek

Loves Go, NoSQL DBs and messaging systems
This entry was posted in Java, Java EE and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s