예제 #1
0
  public static HttpHeaders generatePaginationHttpHeaders(
      Page page, String baseUrl, Integer offset, Integer limit) throws URISyntaxException {

    if (offset == null || offset < MIN_OFFSET) {
      offset = DEFAULT_OFFSET;
    }
    if (limit == null || limit > MAX_LIMIT) {
      limit = DEFAULT_LIMIT;
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("X-Total-Count", "" + page.getTotalElements());
    String link = "";
    if (offset < page.getTotalPages()) {
      link =
          "<"
              + (new URI(baseUrl + "?page=" + (offset + 1) + "&per_page=" + limit)).toString()
              + ">; rel=\"next\",";
    }
    if (offset > 1) {
      link +=
          "<"
              + (new URI(baseUrl + "?page=" + (offset - 1) + "&per_page=" + limit)).toString()
              + ">; rel=\"prev\",";
    }
    link +=
        "<"
            + (new URI(baseUrl + "?page=" + page.getTotalPages() + "&per_page=" + limit)).toString()
            + ">; rel=\"last\","
            + "<"
            + (new URI(baseUrl + "?page=" + 1 + "&per_page=" + limit)).toString()
            + ">; rel=\"first\"";
    headers.add(HttpHeaders.LINK, link);
    return headers;
  }
예제 #2
0
  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;
  }
예제 #3
0
  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 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;
  }
 private void addLastLink(Page<T> page, String pageParam, String sizeParam) {
   if (page.isLast()) {
     Link link =
         buildPageLink(pageParam, page.getTotalPages(), sizeParam, page.getSize(), Link.REL_LAST);
     add(link);
   }
 }
 @Test
 public void testPaging() {
   Page<Institusi> hasilQuery = institusiDao.findAll(new PageRequest(0, 10));
   Assert.assertNotNull(hasilQuery);
   Assert.assertEquals(1, hasilQuery.getTotalPages());
   Assert.assertEquals(2, hasilQuery.getTotalElements());
   Assert.assertEquals(2, hasilQuery.getNumberOfElements());
   Assert.assertEquals(0, institusiDao.findAll(new PageRequest(1, 10)).getNumberOfElements());
 }
예제 #7
0
 @RequestMapping("/userpage")
 public String starpage(Model model, @RequestParam(value = "page", defaultValue = "1") int page) {
   Page<Post> postsPage = postsService.getPosts(page, 5); // 5 постів на сторінку
   model.addAttribute("posts", postsPage.getContent());
   model.addAttribute("pagesCount", postsPage.getTotalPages());
   model.addAttribute("currentPage", page);
   model.addAttribute("currentUser", User.getCurrentUser());
   model.addAttribute("user", User.getCurrentUser());
   return "user_page";
 }
예제 #8
0
 @RequestMapping("/list")
 public String list(Model model, @RequestParam(value = "page", defaultValue = "1") int page) {
   System.out.println("before get posts");
   Page<Post> postsPage = postsService.getAllPosts(page, 5); // 5 постів на сторінку
   model.addAttribute("posts", postsPage.getContent());
   model.addAttribute("pagesCount", postsPage.getTotalPages());
   model.addAttribute("currentPage", page);
   model.addAttribute("currentUser", User.getCurrentUser());
   return "list";
 }
예제 #9
0
  @RequestMapping(
      params = {"page", "size"},
      method = RequestMethod.GET)
  @ResponseBody
  public List<Foo> findPaginated(
      @RequestParam("page") final int page,
      @RequestParam("size") final int size,
      final UriComponentsBuilder uriBuilder,
      final HttpServletResponse response) {
    final Page<Foo> resultPage = service.findPaginated(page, size);
    if (page > resultPage.getTotalPages()) {
      throw new MyResourceNotFoundException();
    }
    eventPublisher.publishEvent(
        new PaginatedResultsRetrievedEvent<Foo>(
            Foo.class, uriBuilder, response, page, resultPage.getTotalPages(), size));

    return resultPage.getContent();
  }
  @SuppressWarnings("unchecked")
  @Override
  public PageDto<Dto> covertToDto(Page<Entity> es) {

    if (es == null) {
      return new PageDto<Dto>(Collections.EMPTY_LIST, 0, 0);
    }

    return new PageDto<Dto>(
        covertToDto(es.getContent()), es.getTotalPages(), es.getTotalElements());
  }
예제 #11
0
  @RequestMapping("")
  public String index(@RequestParam(defaultValue = "1") int page, Model model) {
    Page<Post> posts =
        postService.getAllPublishedPostsByPage(page < 0 ? 1 : page - 1, appSetting.getPageSize());

    model.addAttribute("totalPages", posts.getTotalPages());
    model.addAttribute("posts", posts);
    model.addAttribute("page", page);

    return "home/index";
  }
예제 #12
0
  @Transactional(readOnly = true)
  public ContactListVO findByNameLike(int page, int maxResults, String name) {
    Page<Contact> result = executeQueryFindByName(page, maxResults, name);

    if (shouldExecuteSameQueryInLastPage(page, result)) {
      int lastPage = result.getTotalPages() - 1;
      result = executeQueryFindByName(lastPage, maxResults, name);
    }

    return buildResult(result);
  }
  @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)));
  }
 @Test
 public void testFindPaginatedResources() {
   this.request("repository-based").xmlPost(new Sample("toto"));
   this.request("repository-based").xmlPost(new Sample("titi"));
   Response response = this.request("repository-based").setQueryParameter("page", "1").getXml();
   Page<Sample> samples = response.resource(new TypeReference<Page<Sample>>() {});
   Assertions.assertThat(samples).isNotNull();
   Assertions.assertThat(samples.getContent()).isNotNull();
   Assertions.assertThat(samples.getContent().size()).isEqualTo(2);
   Assertions.assertThat(samples.getTotalPages()).isEqualTo(1);
   Assertions.assertThat(samples.getTotalElements()).isEqualTo(2);
   Assertions.assertThat(samples.getContent().get(0).getName()).isIn("titi", "toto");
   Assertions.assertThat(samples.getContent().get(1).getName()).isIn("titi", "toto");
 }
예제 #15
0
 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());
 }
예제 #16
0
  @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;
  }
예제 #17
0
  protected final List<T> findPaginatedInternal(
      final int page,
      final int size,
      final String sortBy,
      final UriComponentsBuilder uriBuilder,
      final HttpServletResponse response) {
    Page<T> resultPage = null;
    try {
      resultPage = getService().findPaginated(page, size, sortBy);
    } catch (final InvalidDataAccessApiUsageException apiEx) {
      logger.error("InvalidDataAccessApiUsageException on find operation");
      logger.warn("InvalidDataAccessApiUsageException on find operation", apiEx);
      throw new BadRequestException(apiEx);
    }

    if (page > resultPage.getTotalPages()) {
      throw new ResourceNotFoundException();
    }
    eventPublisher.publishEvent(
        new PaginatedResultsRetrievedEvent<T>(
            clazz, uriBuilder, response, page, resultPage.getTotalPages(), size));

    return Lists.newArrayList(resultPage.getContent());
  }
예제 #18
0
  @Transactional(readOnly = true)
  @Override
  public List<Holiday> findHolidays(PageVO pageVO) {
    List<Holiday> holidayList = new ArrayList<Holiday>();

    Sort sort = new Sort(Direction.ASC, "startDate");
    Pageable pageable = new PageRequest(pageVO.getCurrentPage() - 1, pageVO.getPageSize(), sort);

    Page<Holiday> holidayPage =
        holidayRepository.findHolidays2(
            ConfigConstants.LOGICAL_CANCEL_FLAG_NOT_CANCEL, getCurrentYear(), pageable);
    holidayList = holidayPage.getContent();
    pageVO.setTotalPage(holidayPage.getTotalPages());
    pageVO.setTotalRecord(holidayPage.getTotalElements());
    return holidayList;
  }
예제 #19
0
  // Построничное разбиение информации в гриде
  @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);
  }
  /**
   * Gets the link node of the last page.
   *
   * @param page the pagination object
   * @param contextPath current context path of servlet
   * @return the node
   */
  private Element getLastElement(final Page<?> page, final String contextPath) {
    final Element result = new Element("li");

    final Element a = new Element("a");
    a.setAttribute("href", getPagedParams(contextPath, page.getTotalPages() - 1, page.getSize()));
    result.addChild(a);

    final Element icon = new Element("i");
    icon.setAttribute("class", "glyphicon glyphicon-step-forward");

    a.addChild(icon);

    if (page.isLast()) {
      result.setAttribute("class", "disabled");
    }

    return result;
  }
예제 #22
0
  @RequestMapping(value = "{tagName}", method = GET)
  public String showTag(
      @PathVariable String tagName, @RequestParam(defaultValue = "1") int page, Model model) {
    Tag tag = tagService.getTag(tagName);

    if (tag == null) {
      throw new NotFoundException("Tag " + tagName + " is not found.");
    }

    page = page < 1 ? 0 : page - 1;
    Page<Post> posts = postService.findPostsByTag(tagName, page, appSetting.getPageSize());

    model.addAttribute("tag", tag);
    model.addAttribute("posts", posts);
    model.addAttribute("page", page + 1);
    model.addAttribute("totalPages", posts.getTotalPages());

    return "tags/show";
  }
예제 #23
0
  @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;
  }
  @RequestMapping(value = "/list/{phoneNumber}/{code}", method = RequestMethod.GET)
  public ResponseEntity<ResponseWrapper> getNotifications(
      @PathVariable("phoneNumber") String phoneNumber,
      @PathVariable("code") String code,
      @RequestParam(value = "page", required = false) Integer queryPage,
      @RequestParam(value = "size", required = false) Integer queryPageSize) {

    User user = userManagementService.findByInputNumber(phoneNumber);
    final int pageNumber = (queryPage == null) ? 0 : queryPage;
    final int pageSize = (queryPageSize == null) ? pageLength : queryPageSize;

    Page<Notification> pageable =
        notificationService.fetchPagedAndroidNotifications(user, pageNumber, pageSize);
    log.info(
        "pageable size = {}, from page number = {}, with page size = {}",
        pageable.getContent().size(),
        pageNumber,
        pageSize);

    ResponseEntity<ResponseWrapper> responseWrapper;

    if (pageNumber > pageable.getTotalPages()) {
      responseWrapper =
          RestUtil.errorResponse(HttpStatus.BAD_REQUEST, RestMessage.NOTIFICATIONS_FINISHED);
    } else {
      List<NotificationDTO> notificationDTOList =
          pageable
              .getContent()
              .stream()
              .filter(NotificationDTO::isNotificationOfTypeForDTO)
              .map(NotificationDTO::convertToDto)
              .collect(Collectors.toList());
      log.info("number of DTOs created : {}", notificationDTOList.size());
      NotificationWrapper notificationWrapper =
          new NotificationWrapper(pageable, notificationDTOList);
      responseWrapper =
          RestUtil.okayResponseWithData(RestMessage.NOTIFICATIONS, notificationWrapper);
    }

    return responseWrapper;
  }
  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;
  }
  /**
   * 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);
    }
  }
예제 #29
0
 private boolean isUserAfterOrOnLastPage(int page, Page<Contact> result) {
   return page >= result.getTotalPages() - 1;
 }
예제 #30
0
 private ContactListVO buildResult(Page<Contact> result) {
   return new ContactListVO(
       result.getTotalPages(), result.getTotalElements(), result.getContent());
 }