Skip to content

Instantly share code, notes, and snippets.

@leifoolsen
Last active October 23, 2023 18:38
Show Gist options
  • Save leifoolsen/25eb587a5908f9f82902 to your computer and use it in GitHub Desktop.
Save leifoolsen/25eb587a5908f9f82902 to your computer and use it in GitHub Desktop.
JAX-RS: Return a list of entities in a response
@GET
public Response allBooks() {
UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder().clone();
// Given a list of books
List<Book> books = Lists.newArrayList(new Book("1234567890"), new Book("0123456789"));
// Convert to GenericEntity and return in response
GenericEntity<List<Book>> entities = new GenericEntity<List<Book>>(books){};
UriBuilder linkBuilder = uriInfo.getRequestUriBuilder().clone();
return Response
.ok(entities)
.location(uriBuilder.build())
.build();
}
@Test
public void shouldGetAllBooks() {
final Response response = target
.path(BOOK_RESOURCE_PATH)
.request(MediaType.APPLICATION_JSON_TYPE)
.get();
assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
// On client, convert from GenericEntity to a list of actual entities
final List<Book> result = response.readEntity(new GenericType<List<Book>>() {});
// Assert someting on result
assertThat(result, hasSize(greaterThan(0)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment