Java Code Examples for org.springframework.data.domain.Pageable

The following examples show how to use org.springframework.data.domain.Pageable. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: WeBASE-Front   Source File: EventController.java    License: Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "getNewBlockEventInfo",
        notes = "get registered NewBlockEvent info by page")
@GetMapping(value = {"newBlockEvent/list/{groupId}/{pageNumber}/{pageSize}",
        "newBlockEvent/list/{groupId}"})
public BasePageResponse getNewBlockEventInfo(@PathVariable("groupId") Integer groupId,
                                             @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                             @PathVariable(value = "pageSize", required = false) Integer pageSize) {
    log.debug("start getNewBlockEventInfo. groupId:{}", groupId);
    List<NewBlockEventInfo> resList;
    if (pageNumber == null || pageSize == null) {
         resList = eventService.getNewBlockInfoList(groupId);
    } else {
        if (pageNumber < 1) {
            return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0);
        }
        Pageable pageable = new PageRequest(pageNumber - 1, pageSize,
                new Sort(Sort.Direction.DESC, "createTime"));
        resList = eventService.getNewBlockInfoList(groupId, pageable);
    }
    log.debug("end getNewBlockEventInfo resList count. {}", resList.size());
    return new BasePageResponse(ConstantCode.RET_SUCCESS, resList, resList.size());
}
 
Example 2
@BeforeEach
public void setup() throws Exception {
    MockitoAnnotations.initMocks(this);
    Method method = this.getClass().getMethod("test", new Class<?>[]{Pageable.class, Integer.class});
    resolver = new TypeResolver();
    RequestHandler handler = new WebMvcRequestHandler(new HandlerMethodResolver(resolver), null, new
        HandlerMethod(this, method));
    DocumentationContext docContext = mock(DocumentationContext.class);
    RequestMappingContext reqContext = new RequestMappingContext(docContext, handler);
    builder = spy(new OperationBuilder(null));
    context = new OperationContext(builder, RequestMethod.GET, reqContext, 0);
    List<TypeNameProviderPlugin> plugins = new LinkedList<>();
    extractor = new TypeNameExtractor(resolver, SimplePluginRegistry.create(plugins), new
        JacksonEnumTypeDeterminer());
    plugin = new PageableParameterBuilderPlugin(extractor, resolver);
}
 
Example 3
Source Project: heimdall   Source File: EnvironmentServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listEnvironmentsWithPageable() {

     PageableDTO pageableDTO = new PageableDTO();
     pageableDTO.setLimit(10);
     pageableDTO.setOffset(0);

     ArrayList<Environment> environments = new ArrayList<>();

     environments.add(environment);

     Page<Environment> page = new PageImpl<>(environments);

     Mockito.when(this.environmentRepository
                            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class)))
            .thenReturn(page);

     EnvironmentPage environmentPageResp = this.environmentService
               .list(this.environmentDTO, pageableDTO);

     assertEquals(1L, environmentPageResp.getTotalElements());
     Mockito.verify(this.environmentRepository, Mockito.times(1))
            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class));
}
 
Example 4
Source Project: es   Source File: UserServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFindAllBySearchAndPageableAndSortAsc() {
    int count = 15;
    User lastUser = null;
    for (int i = 0; i < count; i++) {
        lastUser = userService.save(createUser());
    }

    Sort sortAsc = new Sort(Sort.Direction.ASC, "id");
    Pageable pageable = new PageRequest(0, 5, sortAsc);
    Map<String, Object> searchParams = new HashMap<String, Object>();
    searchParams.put("username_like", "zhang");
    Searchable search = Searchable.newSearchable(searchParams).setPage(pageable);

    Page<User> userPage = userService.findAll(search);
    assertEquals(5, userPage.getNumberOfElements());
    assertFalse(userPage.getContent().contains(lastUser));
    assertTrue(userPage.getContent().get(0).getId() < userPage.getContent().get(1).getId());
}
 
Example 5
Source Project: blog-sharon   Source File: PostController.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 模糊查询文章
 *
 * @param model   Model
 * @param keyword keyword 关键字
 * @param page    page 当前页码
 * @param size    size 每页显示条数
 * @return 模板路径admin/admin_post
 */
@PostMapping(value = "/search")
public String searchPost(Model model,
                         @RequestParam(value = "keyword") String keyword,
                         @RequestParam(value = "page", defaultValue = "0") Integer page,
                         @RequestParam(value = "size", defaultValue = "10") Integer size) {
    try {
        //排序规则
        Sort sort = new Sort(Sort.Direction.DESC, "postId");
        Pageable pageable = PageRequest.of(page, size, sort);
        model.addAttribute("posts", postService.searchPosts(keyword, pageable));
    } catch (Exception e) {
        log.error("未知错误:{}", e.getMessage());
    }
    return "admin/admin_post";
}
 
Example 6
Source Project: TeamDojo   Source File: BadgeResource.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * GET  /badges : get all the badges.
 *
 * @param pageable the pagination information
 * @param skillsId the skillIds to search for
 * @return the ResponseEntity with status 200 (OK) and the list of badges in body
 */
public ResponseEntity<List<BadgeDTO>> getAllBadgesBySkills(
    List<Long> skillsId,
    Pageable pageable) {
    log.debug("REST request to get Badges for Skills: {}", skillsId);

    List<BadgeSkillDTO> badgeSkills = badgeSkillService.findBySkillIdIn(skillsId, pageable);
    List<Long> badgeIds = new ArrayList<>();
    for (BadgeSkillDTO badgeSkill : badgeSkills) {
        badgeIds.add(badgeSkill.getBadgeId());
    }

    Page<BadgeDTO> page = badgeService.findByIdIn(badgeIds, pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/badges");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 7
Source Project: cubeai   Source File: SolutionService.java    License: Apache License 2.0 6 votes vote down vote up
public List<Solution> getAllSolutions(String active, String uuid, String name, String authorLogin, String modelType, String toolkitType,
                           String publishStatus, String publishRequest, String subject1, String subject2, String subject3, String tag, String filter, Pageable pageable) throws Exception {

    List<Solution> solutionsList = new ArrayList<>();
    try {
        solutionsList = ummClient.getSolutions(active, uuid, name, authorLogin, modelType, toolkitType, publishStatus,
            publishRequest, subject1, subject2, subject3, tag, filter, pageable.getPageNumber(), pageable.getPageSize());

        if (null == solutionsList || solutionsList.isEmpty()) {
            logger.debug(" uum returned empty Solution list");
        } else {
            logger.debug(" uum returned Solution list of size :  {} ", solutionsList.size());
        }
    } catch (Exception e) {
        logger.error(" Exception in getSolutions() ", e);
        throw new Exception("Exception in getSolutions() " + e.getMessage());
    }
    logger.debug(" getSolutions() End ");
    return solutionsList;
}
 
Example 8
Source Project: DrivingAgency   Source File: StudentServiceImpl.java    License: MIT License 6 votes vote down vote up
@Override
public List<StudentVo> getAllStudentsByPage(Integer pageNum, Integer pageSize) {
    List<String> collect = agentManageService.listAllAgents().stream().map(AgentVo::getAgentName).collect(Collectors.toList());
    Pageable pageable= PageRequest.of(pageNum-1,pageSize, Sort.by(Sort.Order.desc("studentPrice")));
    Page<Student> all = studentRepository.findAllByOperatorIn(collect,pageable);
    List<StudentVo> studentVos=Lists.newArrayList();
    if (all.isEmpty()){
        return null;
    }
    all.get().filter(student -> student.getStatus().equals(StudentStatus.AVAILABLE.getStatus()))
            .forEach(student -> {
                StudentVo studentVo=new StudentVo();
                BeanUtils.copyProperties(student,studentVo);
                studentVos.add(studentVo);
            });
    return studentVos;
}
 
Example 9
Source Project: jvm-sandbox-repeater   Source File: ModuleConfigDao.java    License: Apache License 2.0 6 votes vote down vote up
public Page<ModuleConfig> selectByParams(@NotNull final ModuleConfigParams params) {
    Pageable pageable = new PageRequest(params.getPage() - 1, params.getSize(), new Sort(Sort.Direction.DESC, "id"));
    return moduleConfigRepository.findAll(
            (root, query, cb) -> {
                List<Predicate> predicates = Lists.newArrayList();
                if (params.getAppName() != null && !params.getAppName().isEmpty()) {
                    predicates.add(cb.equal(root.<String>get("appName"), params.getAppName()));
                }
                if (params.getEnvironment() != null && !params.getEnvironment().isEmpty()) {
                    predicates.add(cb.equal(root.<String>get("environment"), params.getEnvironment()));
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            },
            pageable
    );
}
 
Example 10
Source Project: dubbox   Source File: SolrPageRequest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean equals(Object obj) {

	if (this == obj) {
		return true;
	}
	if (obj == null || !(obj instanceof Pageable)) {
		return false;
	}

	Pageable other = (Pageable) obj;
	if (page != other.getPageNumber()) {
		return false;
	}
	if (size != other.getPageSize()) {
		return false;
	}
	if (sort == null) {
		if (other.getSort() != null) {
			return false;
		}
	} else if (!sort.equals(other.getSort())) {
		return false;
	}
	return true;
}
 
Example 11
Source Project: alchemy   Source File: SinkQueryService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return a {@link Page} of {@link SinkDTO} which matches the criteria from the database.
 * @param criteria The object which holds all the filters, which the entities should match.
 * @param page The page, which should be returned.
 * @return the matching entities.
 */
@Transactional(readOnly = true)
public Page<SinkDTO> findByCriteria(SinkCriteria criteria, Pageable page) {
    log.debug("find by criteria : {}, page: {}", criteria, page);
    final Specification<Sink> specification = createSpecification(criteria);
    return sinkRepository.findAll(specification, page)
        .map(sinkMapper::toDto);
}
 
Example 12
Source Project: mblog   Source File: RoleController.java    License: GNU General Public License v3.0 5 votes vote down vote up
@GetMapping("/list")
public String paging(String name, ModelMap model) {
	Pageable pageable = wrapPageable();
	Page<Role> page = roleService.paging(pageable, name);
	model.put("name", name);
	model.put("page", page);
	return "/admin/role/list";
}
 
Example 13
Source Project: Spring-Boot-2.0-Projects   Source File: ArticleController.java    License: MIT License 5 votes vote down vote up
private Pageable getPageable(Integer page, Integer size) {
    if (page == null || size == null) {
        return PageRequest.of(0, 20);
    }

    return PageRequest.of(page, size, new Sort(Sort.Direction.DESC, "createdDate"));
}
 
Example 14
Source Project: sk-admin   Source File: JobController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("查询岗位")
@ApiOperation("查询岗位")
@GetMapping
@PreAuthorize("@sk.check('job:list','user:list')")
public ResponseEntity<Object> getJobs(JobQuery criteria, Pageable pageable){
    // 数据权限
    criteria.setDeptIds(dataScope.getDeptIds());
    return new ResponseEntity<>(jobService.queryAll(criteria, pageable),HttpStatus.OK);
}
 
Example 15
/**
 * GET  /audits : get a page of AuditEvents between the fromDate and toDate.
 *
 * @param fromDate the start of the time period of AuditEvents to get
 * @param toDate the end of the time period of AuditEvents to get
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
 */
@GetMapping(params = {"fromDate", "toDate"})
public ResponseEntity<List<AuditEvent>> getByDates(
    @RequestParam(value = "fromDate") LocalDate fromDate,
    @RequestParam(value = "toDate") LocalDate toDate,
    Pageable pageable) {

    Page<AuditEvent> page = auditEventService.findByDates(
        fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant(),
        toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant(),
        pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 16
Source Project: halo   Source File: ContentFeedController.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Get sitemap.html.
 *
 * @param model model
 * @return template path: common/web/sitemap_html
 */
@GetMapping(value = "sitemap.html")
public String sitemapHtml(Model model,
                          @PageableDefault(size = Integer.MAX_VALUE, sort = "createTime", direction = DESC) Pageable pageable) {
    model.addAttribute("posts", buildPosts(pageable));
    return "common/web/sitemap_html";
}
 
Example 17
@Override
public Page<UserActivityDTO> getPublicActivity(Pageable pageable) {
	Page<Action> actions = actionRepository.findAllByTypeIn(Lists.newArrayList(UserActivityType.REGISTER,UserActivityType.BUY,UserActivityType.SELL), pageable);
	List<UserActivityDTO> result = new LinkedList<UserActivityDTO>();
	actions.getContent().forEach(
			a -> {
				if(a instanceof AccountActivity){
					UserActivityDTO accountActivity = new UserActivityDTO(
							a.getUser().getUsername(),
							a.getUser().getProfileImg(),
							((AccountActivity)a).getType(),
							((AccountActivity)a).getDate(),
							a.getId()
					);
					accountActivity.setSocialReport(a.getSocialEventAction());
					result.add(accountActivity);
				}
				else if(a instanceof Transaction){
					UserActivityDTO transaction = new UserActivityDTO((Transaction)a);
					transaction.setSocialReport(a.getSocialEventAction());
					result.add(transaction);
				}
			}
		);
	
	return new PageImpl<>(result, pageable, actions.getTotalElements());
}
 
Example 18
Source Project: logistics-back   Source File: CheckController.java    License: MIT License 5 votes vote down vote up
/**
 * 查询所有员工工资
 */
   @RequestMapping(value = "/selectWage", method = RequestMethod.GET)
public Result selectAllWage(@RequestParam("pageNum") int pageNum, @RequestParam("limit") int limit) {
	Pageable pageable = PageRequest.of(pageNum-1, limit);
	Page<EmployeeWage> page = checkService.selectAllWage(pageable);
	Result result  = new Result(200, "SUCCESS", (int) page.getTotalElements(), page.getContent());
	return result;	
}
 
Example 19
Source Project: apollo   Source File: ControllerExceptionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testFindByName() {
  Pageable pageable = PageRequest.of(0, 10);
  List<AppDTO> appDTOs = appController.find("unexist", pageable);
  Assert.assertNotNull(appDTOs);
  Assert.assertEquals(0, appDTOs.size());
}
 
Example 20
Source Project: Spring-5.0-Projects   Source File: CountryLanguageResource.java    License: MIT License 5 votes vote down vote up
/**
 * GET  /country-languages : get all the countryLanguages.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of countryLanguages in body
 */
@GetMapping("/country-languages")
@Timed
public ResponseEntity<List<CountryLanguageDTO>> getAllCountryLanguages(Pageable pageable) {
    log.debug("REST request to get a page of CountryLanguages");
    Page<CountryLanguageDTO> page = countryLanguageService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/country-languages");
    return ResponseEntity.ok().headers(headers).body(page.getContent());
}
 
Example 21
@RequestMapping(value="/{exchange}", method=GET)
@ApiOperation(value = "Get one exchange", notes = "Returns an exchange place")
public ExchangeResource get(
		@ApiParam(value="Exchange id: LSE") @PathVariable(value="exchange") String exchangeId,
		@ApiIgnore @PageableDefault(size=10, page=0, sort={"name"}, direction=Direction.ASC) Pageable pageable){
	return assembler.toResource(exchangeService.get(exchangeId));
}
 
Example 22
private Iterator<TaskExecution> getPageIterator(int pageNum, int pageSize,
		Sort sort) {
	Pageable pageable = (sort == null) ? PageRequest.of(pageNum, pageSize)
			: PageRequest.of(pageNum, pageSize, sort);
	Page<TaskExecution> page = this.dao.findAll(pageable);
	assertThat(page.getTotalElements()).isEqualTo(3);
	assertThat(page.getTotalPages()).isEqualTo(2);
	return page.iterator();
}
 
Example 23
Source Project: yshopmall   Source File: PictureController.java    License: Apache License 2.0 5 votes vote down vote up
@Log("查询图片")
@PreAuthorize("@el.check('pictures:list')")
@GetMapping
@ApiOperation("查询图片")
public ResponseEntity<Object> getRoles(PictureQueryCriteria criteria, Pageable pageable){
    return new ResponseEntity<>(pictureService.queryAll(criteria,pageable),HttpStatus.OK);
}
 
Example 24
Source Project: apollo   Source File: ReleaseHistoryController.java    License: Apache License 2.0 5 votes vote down vote up
@GetMapping("/releases/histories/by_release_id_and_operation")
public PageDTO<ReleaseHistoryDTO> findReleaseHistoryByReleaseIdAndOperation(
    @RequestParam("releaseId") long releaseId,
    @RequestParam("operation") int operation,
    Pageable pageable) {

  Page<ReleaseHistory> result = releaseHistoryService.findByReleaseIdAndOperation(releaseId, operation, pageable);

  return transform2PageDTO(result, pageable);
}
 
Example 25
@Override
@Transactional
public Page<StockProduct> gather(String indexId, String exchangeId,
		MarketId marketId, String startWith,
		Specification<StockProduct> spec, Pageable pageable) {

	Page<StockProduct> stocks = get(indexId, exchangeId, marketId, startWith, spec, pageable, false);
	
	if(AuthenticationUtil.userHasRole(Role.ROLE_OAUTH2)){
		updateStocksAndQuotesFromYahoo(stocks.getContent().stream().collect(Collectors.toSet()));
		return get(indexId, exchangeId, marketId, startWith, spec, pageable, false);
	}
	
	return stocks;
}
 
Example 26
Source Project: QuizZz   Source File: UserController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value = "/{user_id}/quizzes", method = RequestMethod.GET)
@PreAuthorize("permitAll")
@ResponseStatus(HttpStatus.OK)
public Page<Quiz> getQuizzesByUser(Pageable pageable, @PathVariable Long user_id) {
	logger.debug("Requested page " + pageable.getPageNumber() + " from user " + user_id);
	
	User user = userService.find(user_id);
	return quizService.findQuizzesByUser(user, pageable);
}
 
Example 27
Source Project: hermes   Source File: UserManageServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Page<UserCar> findCarByUser(String userId, Integer page, Integer size) {
	// 初始化
	Pageable pageable = Pageables.pageable(page, size);
	List<UserCar> cars = userCarRepository.findByUserId(userId);
	Long total = Long.valueOf(cars.size());
	Page<UserCar> pageCar = new PageImpl<UserCar>(cars, pageable, total);
	return pageCar;
}
 
Example 28
@Test
public void mustNotThrowErrorWhenPageIsOutOfBounds() {
  int scoresLen = SCORE_DOCS.length;
  Pageable pageable = PageRequest.of(2, scoresLen / 2);
  List scoresAfterSkip = pageableRepository.getPageableScores(pageable);
  assertNotNull(scoresAfterSkip);
  assertEquals(scoresAfterSkip.size(), 0);
}
 
Example 29
Source Project: wallride   Source File: SearchController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping
public String search(
		@RequestParam String keyword,
		@PageableDefault(50) Pageable pageable,
		BlogLanguage blogLanguage,
		Model model,
		HttpServletRequest servletRequest) {
	PostSearchRequest request = new PostSearchRequest(blogLanguage.getLanguage()).withKeyword(keyword);
	Page<Post> posts = postService.getPosts(request, pageable);
	model.addAttribute("keyword", keyword);
	model.addAttribute("posts", posts);
	model.addAttribute("pageable", pageable);
	model.addAttribute("pagination", new Pagination<>(posts, servletRequest));
	return "search";
}
 
Example 30
Source Project: java-microservices-examples   Source File: AuditResource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@code GET /audits} : get a page of {@link AuditEvent}s.
 *
 * @param pageable the pagination information.
 * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body.
 */
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(@RequestParam MultiValueMap<String, String> queryParams, UriComponentsBuilder uriBuilder, Pageable pageable) {
    Page<AuditEvent> page = auditEventService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(uriBuilder.queryParams(queryParams), page);
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}