public static HttpHeaders generatePaginationHttpHeaders(Page<?> page, String baseUrl) throws URISyntaxException { HttpHeaders headers = new HttpHeaders(); headers.add("X-Total-Count", "" + page.getTotalElements()); String link = ""; if ((page.getNumber() + 1) < page.getTotalPages()) { link = "<" + (new URI(baseUrl + "?page=" + (page.getNumber() + 1) + "&size=" + page.getSize())) .toString() + ">; rel=\"next\","; } // prev link if ((page.getNumber()) > 0) { link += "<" + (new URI(baseUrl + "?page=" + (page.getNumber() - 1) + "&size=" + page.getSize())) .toString() + ">; rel=\"prev\","; } // last and first link link += "<" + (new URI(baseUrl + "?page=" + (page.getTotalPages() - 1) + "&size=" + page.getSize())) .toString() + ">; rel=\"last\","; link += "<" + (new URI(baseUrl + "?page=" + 0 + "&size=" + page.getSize())).toString() + ">; rel=\"first\""; headers.add(HttpHeaders.LINK, link); return headers; }
public WebPageDto(Page<T> page, String url) { this.url = url; this.totalPages = page.getTotalPages(); this.totalElements = page.getTotalElements(); this.firstPage = page.isFirstPage(); this.lastPage = page.isLastPage(); this.hasPreviousPage = page.hasPreviousPage(); this.hasNextPage = page.hasNextPage(); this.size = page.getSize(); this.number = page.getNumber() + 1; this.content = page.getContent(); int start, size; if (totalPages <= DEFAULT_PAGES) { start = 1; size = totalPages; } else { if (number <= DEFAULT_PAGES - DEFAULT_PAGES / 2) { start = 1; size = DEFAULT_PAGES; } else if (number >= totalPages - DEFAULT_PAGES / 2) { start = totalPages - DEFAULT_PAGES + 1; size = DEFAULT_PAGES; } else { start = number - DEFAULT_PAGES / 2; size = DEFAULT_PAGES; } } for (int i = 0; i < size; i++) { items.add(new PageItem(start + i, (start + i) == number)); } }
/** * Gets the link node of the previous page. * * @param page the pagination object * @param contextPath current context path of servlet * @return the node */ private Element getPreviousElement(final Page<?> page, final String contextPath) { final Element result = new Element("li"); String url; if (!page.hasPrevious()) { url = getPagedParams(contextPath, 0, page.getSize()); } else { url = getPagedParams(contextPath, page.getNumber() - 1, page.getSize()); } final Element a = new Element("a"); a.setAttribute("href", url); result.addChild(a); final Element icon = new Element("i"); icon.setAttribute("class", "glyphicon glyphicon-triangle-left"); a.addChild(icon); if (!page.hasPrevious()) { result.setAttribute("class", "disabled"); } return result; }
private void addNextLink(Page<T> page, String pageParam, String sizeParam) { if (page.hasNext()) { Link link = buildPageLink(pageParam, page.getNumber() + 1, sizeParam, page.getSize(), Link.REL_NEXT); add(link); } }
/** * Gets the link node of the next page. * * @param page the pagination object * @param contextPath current context path of servlet * @return the node */ private Element getNextElement(final Page<?> page, final String contextPath) { final Element result = new Element("li"); String url; if (!page.hasNext()) { int pageNumber = page.getTotalPages() - 1; url = getPagedParams(contextPath, pageNumber < 0 ? 0 : pageNumber, page.getSize()); } else { url = getPagedParams(contextPath, page.getNumber() + 1, page.getSize()); } final Element a = new Element("a"); a.setAttribute("href", url); result.addChild(a); final Element icon = new Element("i"); icon.setAttribute("class", "glyphicon glyphicon-triangle-right"); a.addChild(icon); if (!page.hasNext()) { result.setAttribute("class", "disabled"); } return result; }
/** * Add all bean properties from the supplied bean to the representation * * @param value * @return */ public ResponseEntityBuilder<ReadableRepresentation> withPage( Page<?> value, String uriTemplate, String... includeFields) { String[] fields = requestedFields == null ? includeFields : requestedFields; // Extract page data such as size, page number representation.withProperty("size", value.getSize()); representation.withProperty("number", value.getNumber()); representation.withProperty("numberOfElements", value.getNumberOfElements()); representation.withProperty("totalElements", value.getTotalElements()); // Next/back links if (value.hasNextPage()) { buildNextLink(representation, request); } if (value.hasPreviousPage()) { buildPreviousLink(representation, request); } // Build the content of the page for (Object object : value.getContent()) { Representation content = converter.convert(object, new UriTemplate(uriTemplate), fields); this.representation.withRepresentation("content", content); } return this; }
@Test public void getTracks() { mockUnauthorizedServer .expect( requestTo( "https://api.soundcloud.com/resolve?url=http://soundcloud.com/mattslip&client_id=someApiKey")) .andExpect(method(GET)) .andRespond(withResponse(jsonResource("testdata/resolveuser"), responseHeaders)); mockUnauthorizedServer .expect(requestTo("https://api.soundcloud.com/users/3510549?client_id=someApiKey")) .andExpect(method(GET)) .andRespond(withResponse(jsonResource("testdata/userprofile"), responseHeaders)); mockUnauthorizedServer .expect(requestTo("https://api.soundcloud.com/users/3510549/tracks?client_id=someApiKey")) .andExpect(method(GET)) .andRespond(withResponse(jsonResource("testdata/tracks"), responseHeaders)); Page<Track> tracksPage = unauthorizedSoundCloud.usersOperations().userOperations("mattslip").getTracks(); List<Track> tracks = tracksPage.getContent(); assertEquals(0, tracksPage.getNumber()); assertEquals(50, tracksPage.getTotalElements()); assertNotNull(tracks); assertEquals(50, tracks.size()); Track firstTrack = tracks.get(0); assertEquals("Kid Sister vs Daft Punk (Monsieur Adi Mashup)", firstTrack.getTitle()); assertEquals( "http://soundcloud.com/monsieuradi/kid-sister-vs-daft-punk", firstTrack.getPermalinkUrl()); assertEquals("39679670", firstTrack.getId()); }
@Test public void getFavoritesByUserId() { mockUnauthorizedServer .expect(requestTo("https://api.soundcloud.com/users/3510549?client_id=someApiKey")) .andExpect(method(GET)) .andRespond(withResponse(jsonResource("testdata/userprofile"), responseHeaders)); mockUnauthorizedServer .expect( requestTo("https://api.soundcloud.com/users/3510549/favorites?client_id=someApiKey")) .andExpect(method(GET)) .andRespond(withResponse(jsonResource("testdata/favorites"), responseHeaders)); Page<Track> tracksPage = unauthorizedSoundCloud.usersOperations().userOperations(3510549).getFavorites(); assertEquals(0, tracksPage.getNumber()); assertEquals(56, tracksPage.getTotalElements()); List<Track> tracks = tracksPage.getContent(); assertNotNull(tracks); assertEquals(50, tracks.size()); Track firstTrack = tracks.get(0); assertEquals("Sneaky Sound System - Big (Oliver Remix)", firstTrack.getTitle()); assertEquals( "http://soundcloud.com/weareoliver/sneaky-sound-system-big-oliver", firstTrack.getPermalinkUrl()); assertEquals("22905377", firstTrack.getId()); }
private void addPreviousLink(Page<T> page, String pageParam, String sizeParam) { if (page.hasPrevious()) { Link link = buildPageLink( pageParam, page.getNumber() - 1, sizeParam, page.getSize(), Link.REL_PREVIOUS); add(link); } }
@Test public void testeListWithPagination() { User bruno = admin("bruno").build(); City cidade = city("São Paulo").build(); Hotel c1 = hotel("A-Hotel", cidade).build(); Hotel c2 = hotel("B-Hotel", cidade).build(); Hotel c3 = hotel("C-Hotel", cidade).build(); Hotel c4 = hotel("D-Hotel", cidade).build(); Hotel c5 = hotel("E-Hotel", cidade).build(); saveall(cidade, c1, c2, c3, c4, c5, bruno); signIn(bruno); Page<HotelDTO> page = get("/hotel") .queryParam("page", "0") .queryParam("size", "2") .expectedStatus(HttpStatus.OK) .getPage(HotelDTO.class); assertThat(page.getNumber(), equalTo(0)); assertThat(page.getSize(), equalTo(2)); assertThat(page.getTotalElements(), equalTo(5l)); assertThat(page.getTotalPages(), equalTo(3)); assertThat(page.getContent(), hasSize(2)); assertThat(page.getContent(), contains(convert.toDTO(c1), convert.toDTO(c2))); page = get("/hotel") .queryParam("size", "2") .queryParam("page", "2") .expectedStatus(HttpStatus.OK) .getPage(HotelDTO.class); assertThat(page.getNumber(), equalTo(2)); assertThat(page.getSize(), equalTo(2)); assertThat(page.getTotalElements(), equalTo(5l)); assertThat(page.getTotalPages(), equalTo(3)); assertThat(page.getContent(), hasSize(1)); assertThat(page.getContent(), contains(convert.toDTO(c5))); }
/** * Adds elements for steps. * * @param page the pagination object * @param contextPath current context path of servlet * @param container the container node of the element */ private void addStepElements( final Page<?> page, final String contextPath, final Element container) { for (int step = 0; step < DEFAULT_STEPS; step++) { // beyond total pages is not allowed if (page.getTotalPages() < step + 1) { continue; } String url; int stepValue; if ((page.getNumber() + DEFAULT_STEPS) <= page.getTotalPages()) { // calculate by page number url = getPagedParams(contextPath, page.getNumber() + step, page.getSize()); stepValue = page.getNumber() + step + 1; } else if (page.getTotalPages() < DEFAULT_STEPS && page.getTotalPages() >= step + 1) { // between step and DEFAULT_STEPS url = getPagedParams(contextPath, step, page.getSize()); stepValue = step + 1; } else { // calculate by totalPages url = getPagedParams( contextPath, page.getTotalPages() - DEFAULT_STEPS + step, page.getSize()); stepValue = page.getTotalPages() - DEFAULT_STEPS + step + 1; } final Element a = new Element("a"); a.setAttribute("href", url); a.addChild(new Text(Integer.toString(stepValue))); final Element li = new Element("li"); li.addChild(a); // set active if (page.getNumber() + 1 == stepValue) { li.setAttribute("class", "active"); } container.addChild(li); } }
public static <S, T> Page<T> mapPage(Page<S> source, Class<T> targetClass) { List<S> sourceList = source.getContent(); List<T> list = new ArrayList<>(); for (int i = 0; i < sourceList.size(); i++) { T target = INSTANCE.map(sourceList.get(i), targetClass); list.add(target); } return new PageImpl<>( list, new PageRequest(source.getNumber(), source.getSize(), source.getSort()), source.getTotalElements()); }
private WebPage(Page<T> page) { number = page.getNumber(); size = page.getSize(); totalPages = page.getTotalPages(); numberOfElements = page.getNumberOfElements(); totalElements = page.getTotalElements(); hasPreviousPage = page.hasPreviousPage(); isFirstPage = page.isFirstPage(); hasNextPage = page.hasNextPage(); isLastPage = page.isLastPage(); content = page.getContent(); hasContent = page.hasContent(); sort = new WebSort(page.getSort()); }
@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json") @ResponseBody public HotelGrid listGrid( @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "rows", required = false) Integer rows, @RequestParam(value = "sidx", required = false) String sortBy, @RequestParam(value = "sord", required = false) String order) { // , @PathVariable("str") String str logger.info("Listing tours for grid with page:{}, rows: {}", page, rows); logger.info("Listing tours for grid woth sort:{}, order: {}", sortBy, order); // Process order by Sort sort = null; String orderBy = sortBy; if (orderBy != null && orderBy.equals("phone")) orderBy = "phone"; if (orderBy != null && order != null) { if (order.equals("desc")) { sort = new Sort(Sort.Direction.DESC, orderBy); } else sort = new Sort(Sort.Direction.ASC, orderBy); } // Construcs page request for current page // Note: page number for Spring Data JPA starts with 0, While jqGrid Starts with 1 // PageRequest pageRequest = null; MyPageRequest myPageRequest = null; if (sort != null) { // pageRequest = new PageRequest(page-1,rows,sort); myPageRequest = new MyPageRequest(page - 1, rows, searchTerm, sort); } else { // pageRequest = new PageRequest(page-1,rows); myPageRequest = new MyPageRequest(page - 1, rows, searchTerm); } // Page<Hotel> hotelPage = hotelService.findAllByPage(pageRequest); Page<Hotel> hotelPage = hotelService.search(myPageRequest); // Construct the grid data that will return as JSON data HotelGrid hotelGrid = new HotelGrid(); hotelGrid.setCurrentPage(hotelPage.getNumber() + 1); hotelGrid.setTotalPages(hotelPage.getTotalPages()); hotelGrid.setTotalRecords(hotelPage.getTotalElements()); hotelGrid.setHotelData(Lists.newArrayList(hotelPage.iterator())); return hotelGrid; }
@Test public void testList() { User bruno = admin("bruno").build(); City cidade = city("São Paulo").build(); Hotel c1 = hotel("Macbook", cidade).build(); Hotel c2 = hotel("IPhone", cidade).build(); saveall(cidade, c1, c2, bruno); signIn(bruno); Page<HotelDTO> page = get("/hotel").expectedStatus(HttpStatus.OK).getPage(HotelDTO.class); assertThat(page.getNumber(), equalTo(0)); assertThat(page.getSize(), equalTo(50)); assertThat(page.getContent(), contains(convert.toDTO(c2), convert.toDTO(c1))); }
@Transactional(readOnly = true) @Override public Page<TodoDTO> findBySearchTerm(String searchTerm, Pageable pageRequest) { LOGGER.info( "Finding todo entries by search term: {} and page request: {}", searchTerm, pageRequest); Page<Todo> searchResultPage = repository.findAll(titleOrDescriptionContainsIgnoreCase(searchTerm), pageRequest); LOGGER.info( "Found {} todo entries. Returned page {} contains {} todo entries", searchResultPage.getTotalElements(), searchResultPage.getNumber(), searchResultPage.getNumberOfElements()); return TodoMapper.mapEntityPageIntoDTOPage(pageRequest, searchResultPage); }
// Построничное разбиение информации в гриде @ResponseBody @RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json") public BanksGrid listGrid( @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "rows", required = false) Integer rows, @RequestParam(value = "sidx", required = false) String sortBy, @RequestParam(value = "sord", required = false) String order) { logger.info("Listing banks for grid with page: {}, rows: {}", page, rows); logger.info("Listing banks for grid with sort: {}, order: {}", sortBy, order); // Process order by Sort sort = null; String orderBy = sortBy; // if (orderBy != null && orderBy.equals("birthDateString")) // orderBy = "birthDate"; if (orderBy != null && order != null) { if (order.equals("desc")) { sort = new Sort(Sort.Direction.DESC, orderBy); } else sort = new Sort(Sort.Direction.ASC, orderBy); } // Constructs page request for current page // Note: page number for Spring Data JPA starts with 0, while jqGrid starts with 1 PageRequest pageRequest = null; if (sort != null) { pageRequest = new PageRequest(page - 1, rows, sort); } else { pageRequest = new PageRequest(page - 1, rows); } Page<Banks> banksPage = banksService.findAllByPage(pageRequest); // Construct the grid data that will return as JSON data BanksGrid banksGrid = new BanksGrid(); banksGrid.setCurrentPage(banksPage.getNumber() + 1); banksGrid.setTotalPages(banksPage.getTotalPages()); banksGrid.setTotalRecords(banksPage.getTotalElements()); banksGrid.setBanksData(Lists.newArrayList(banksPage.iterator())); return banksGrid; }
public PageResource(Page<T> page, String pageParam, String sizeParam) { super(); number = page.getNumber(); size = page.getSize(); numberOfElements = page.getNumberOfElements(); content = page.getContent(); sort = page.getSort(); firstPage = page.isFirst(); lastPage = page.isLast(); totalPages = page.getTotalPages(); totalElements = page.getTotalElements(); addPreviousLink(page, pageParam, sizeParam); addNextLink(page, pageParam, sizeParam); addFirstLink(page, pageParam, sizeParam); addLastLink(page, pageParam, sizeParam); addSelfLink(page, pageParam, sizeParam); }
@RequestMapping("code/code_list") private String codeList( @RequestParam(required = false, defaultValue = "0") Integer page, @RequestParam(required = false, defaultValue = "10") Integer size, @RequestParam(required = false, defaultValue = "DESC") Direction direction, @RequestParam(required = false, defaultValue = "") String searchType, @RequestParam(required = false, defaultValue = "") String searchName, ModelMap modelMap) throws Exception { Sort sort = new Sort( new Order(Direction.DESC, "cmtbCodeId.code"), new Order(Direction.DESC, "codeSeq"), new org.springframework.data.domain.Sort.Order(Direction.ASC, "codeName")); Page<CmtbCode> codePage; if (StringUtils.isNotEmpty(searchName)) { codePage = cmtbCodeRepository.findByCodeNameContaining( searchName, new PageRequest(page, size, sort)); } else { codePage = cmtbCodeRepository.findAll(new PageRequest(page, size, sort)); } CmtbCode cccc = cmtbCodeRepository.findByCodeInfo("00001"); logger.debug("dsdfsdfs = {} ", cccc); PageUtils pageUtils = new PageUtils(); int current = codePage.getNumber() + 1; // int begin = Math.max(1, current - 5); int begin = pageUtils.pagingBegin(current); int end = pageUtils.pagingEnd(codePage.getTotalPages()); logger.debug("pageInfo = ", codePage); modelMap.put("current", current); modelMap.put("begin", begin); modelMap.put("end", end); modelMap.put("searchName", searchName); modelMap.put("codePage", codePage); return "/code/code_list.tiles"; }
@RequestMapping( value = "/questionslist", method = RequestMethod.GET, produces = "application/json") @ResponseBody public QuestionGrid listQuestion( @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "rows", required = false) Integer rows, @RequestParam(value = "sidx", required = false) String sortBy, @RequestParam(value = "sord", required = false) String order) { Sort sort = null; String orderBy = sortBy; if (orderBy != null && orderBy.equals("creationDateString")) orderBy = "creationDate"; if (orderBy != null && order != null) { if (order.equals("desc")) { sort = new Sort(Sort.Direction.DESC, orderBy); } else sort = new Sort(Sort.Direction.ASC, orderBy); } PageRequest pageRequest = null; System.out.println(page + rows); if (sort != null) { pageRequest = new PageRequest(page - 1, rows, sort); } else { pageRequest = new PageRequest(page - 1, rows); } Page<Question> questionPage = questionService.findAllByPage(pageRequest); QuestionGrid questionGrid = new QuestionGrid(); questionGrid.setCurrentPage(questionPage.getNumber() + 1); questionGrid.setTotalPages(questionPage.getTotalPages()); questionGrid.setTotalRecords(questionPage.getTotalElements()); questionGrid.setQuestionData(Lists.newArrayList(questionPage.iterator())); return questionGrid; }
public PagenationHelper(Page<?> page) { int number = page.getNumber(); int totalPages = page.getTotalPages(); this.hiddenPrev = (number == 0); this.hiddenNext = ((totalPages == 0) || (number == totalPages - 1)); this.hiddenPage2 = (totalPages <= 1); this.hiddenPage3 = (totalPages <= 2); this.hiddenPage4 = (totalPages <= 3); this.hiddenPage5 = (totalPages <= 4); this.activePage1 = (number == 0); this.activePage2 = ((MAX_DISP_PAGE - 3 <= totalPages) && (number + 1 == MAX_DISP_PAGE - 3)); this.activePage3 = (((totalPages == MAX_DISP_PAGE - 2) && (number + 1 == MAX_DISP_PAGE - 2)) || ((MAX_DISP_PAGE - 2 < totalPages) && (MAX_DISP_PAGE - 2 <= number + 1) && (number + 1 < totalPages - 1))); this.activePage4 = ((0 < number) && (((totalPages == MAX_DISP_PAGE - 1) && (number + 1 == MAX_DISP_PAGE - 1)) || ((MAX_DISP_PAGE - 1 < totalPages) && (number + 1 == totalPages - 1)))); this.activePage5 = ((0 < number) && (MAX_DISP_PAGE <= totalPages) && (number + 1 == totalPages)); if (totalPages <= MAX_DISP_PAGE) { this.page1PageValue = 0; } else { if (number + 1 <= MAX_DISP_PAGE - 2) { this.page1PageValue = 0; } else if ((MAX_DISP_PAGE - 1 <= number + 1) && (number + 1 <= totalPages - 2)) { this.page1PageValue = number - 2; } else { this.page1PageValue = totalPages - MAX_DISP_PAGE; } } }
@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json") @ResponseBody public NodeGrid listGrid( @RequestParam(value = "page", required = false) Integer page, @RequestParam(value = "rows", required = false) Integer rows, @RequestParam(value = "sidx", required = false) String sortBy, @RequestParam(value = "sord", required = false) String order) { Sort sort = null; String orderBy = sortBy; if (orderBy != null && orderBy.equals("name")) { orderBy = "name"; } if (orderBy != null && order != null) { if (order.equals("desc")) { sort = new Sort(Sort.Direction.DESC, orderBy); } else sort = new Sort(Sort.Direction.ASC, orderBy); } PageRequest pageRequest = null; if (sort != null) { pageRequest = new PageRequest(page - 1, rows, sort); } else { pageRequest = new PageRequest(page - 1, rows); } Page<Node> nodePage = nodeService.findByPage(pageRequest); NodeGrid nodeGrid = new NodeGrid(); nodeGrid.setCurrentPage(nodePage.getNumber() + 1); nodeGrid.setTotalPages(nodePage.getTotalPages()); nodeGrid.setTotalRecords(nodePage.getTotalElements()); List<Node> nodes = Lists.newArrayList(nodePage.iterator()); nodeGrid.setNodeData(checkAccessiblity(nodes)); return nodeGrid; }
private void addSelfLink(Page<T> page, String pageParam, String sizeParam) { Link link = buildPageLink(pageParam, page.getNumber(), sizeParam, page.getSize(), Link.REL_SELF); add(link); }
/** 设置 Spring data JPA 分页对象,转换为本系统分页对象 */ public void setSpringPage(org.springframework.data.domain.Page<T> page) { this.pageNo = page.getNumber(); this.pageSize = page.getSize(); this.count = page.getTotalElements(); this.list = page.getContent(); }