Skip to content

Instantly share code, notes, and snippets.

@spericas
Created May 13, 2021 19:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spericas/bd5ebbaca792fd63db41437ee854d988 to your computer and use it in GitHub Desktop.
Save spericas/bd5ebbaca792fd63db41437ee854d988 to your computer and use it in GitHub Desktop.
@Path("/greet1") // CDI bean-defining annotation
@RequestScoped // implied by default
public class SampleResource1 {
private final GreetBean greetBean;
// Use @Inject instead of @Context
@Inject
private UriInfo uriInfo;
// Use of @HeaderParam as CDI qualifier
@Inject
@HeaderParam("who")
private String who;
// CDI Injection in constructor
@Inject
public SampleResource1(GreetBean greetingConfig) {
this.greetBean = greetingConfig;
}
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getMessage(@HeaderParam("who") String who) {
return greetBean.getMessage() + " " + who;
}
// Use of @Entity is required
@POST
@Consumes(MediaType.TEXT_PLAIN)
public void putMessage(@QueryParam("override") boolean override, @Entity String message) {
if (greetBean.getMessage().isEmpty() || override) {
greetBean.setMessage(message);
}
}
// No need to use @Suspended with AsyncResponse
@POST
@Path("async")
@Consumes(MediaType.TEXT_PLAIN)
public void putMessageAsync(@QueryParam("override") boolean override, @Entity String message, AsyncResponse ar) {
Executors.newSingleThreadExecutor().submit(() -> {
if (greetBean.getMessage().isEmpty() || override) {
greetBean.setMessage(message);
}
ar.resume("Done");
});
}
// Any JAX-RS bean such as Sse or SseEventSink can be injected without @Context
// They are regular CDI beans produced by JAX-RS implementations
@GET
@Path("sse")
@Produces(MediaType.SERVER_SENT_EVENTS)
public void getMessage(@HeaderParam("who") String who, Sse sse, SseEventSink sseEventSink) {
sseEventSink.send(sse.newEvent(greetBean.getMessage() + " " + who));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment