diff --git a/src/main/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListener.java b/src/main/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListener.java index 7dd87f15..e2098bcd 100644 --- a/src/main/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListener.java +++ b/src/main/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListener.java @@ -34,6 +34,7 @@ public void onApplicationEvent(PaginatedResultRetrievedEvent event) { if (header.hasLinks()) { event.getResponse().addHeader(HttpHeaders.LINK, header.toString()); } + event.getResponse().addHeader(Constants.X_TOTAL_COUNT_HEADER, Long.toString(page.getTotalElements())); } private String generateNextPageLink(Page page, UriComponentsBuilder uriBuilder) { diff --git a/src/main/java/cz/cvut/kbss/study/util/Constants.java b/src/main/java/cz/cvut/kbss/study/util/Constants.java index e49f7f38..45369d2f 100644 --- a/src/main/java/cz/cvut/kbss/study/util/Constants.java +++ b/src/main/java/cz/cvut/kbss/study/util/Constants.java @@ -52,4 +52,10 @@ private Constants() { * Name of the request parameter specifying sorting. */ public static final String SORT_PARAM = "sort"; + + /** + * Represents the X-Total-Count HTTP header used to convey the total number of items in paged or otherwise + * restricted response. + */ + public static final String X_TOTAL_COUNT_HEADER = "X-Total-Count"; } diff --git a/src/test/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListenerTest.java b/src/test/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListenerTest.java index 0d582ce9..d326c106 100644 --- a/src/test/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListenerTest.java +++ b/src/test/java/cz/cvut/kbss/study/rest/handler/HateoasPagingListenerTest.java @@ -22,6 +22,7 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -182,4 +183,13 @@ public void generatesFirstAndLastLinksForOnlyPage() { assertThat(lastLink, containsString(pageSize(size))); } + @Test + public void generatesTotalCountHeader() { + final int size = records.size(); + final Page page = new PageImpl<>(records, PageRequest.of(0, size / 2), records.size()); + listener.onApplicationEvent(event(page)); + final String totalCountHeader = responseMock.getHeader(Constants.X_TOTAL_COUNT_HEADER); + assertNotNull(totalCountHeader); + assertEquals(size, Integer.parseInt(totalCountHeader)); + } } \ No newline at end of file