org.springframework.data.domain.Pageable Java Examples

The following examples show how to use org.springframework.data.domain.Pageable. 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 check out the related API usage on the sidebar.
Example #1
Source File: ModuleConfigDao.java    From jvm-sandbox-repeater with Apache License 2.0 8 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 #2
Source File: PostController.java    From blog-sharon with Apache License 2.0 7 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 #3
Source File: SolutionService.java    From cubeai with 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 #4
Source File: StudentServiceImpl.java    From DrivingAgency with 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 #5
Source File: EventController.java    From WeBASE-Front with 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 #6
Source File: BadgeResource.java    From TeamDojo with 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 File: SolrPageRequest.java    From dubbox with 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 #8
Source File: EnvironmentServiceTest.java    From heimdall with 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 #9
Source File: PageableParameterBuilderPluginTest.java    From jhipster with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: UserServiceTest.java    From es with 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 #11
Source File: CountryLanguageResource.java    From Spring-5.0-Projects with 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 #12
Source File: GenericActionServiceImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@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 #13
Source File: ControllerExceptionTest.java    From apollo with 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 #14
Source File: CityResource.java    From Spring-5.0-Projects with MIT License 5 votes vote down vote up
/**
 * GET  /cities : get all the cities.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of cities in body
 */
@GetMapping("/cities")
@Timed
public ResponseEntity<List<CityDTO>> getAllCities(Pageable pageable) {
    log.debug("REST request to get a page of Cities");
    Page<CityDTO> page = cityService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/cities");
    return ResponseEntity.ok().headers(headers).body(page.getContent());
}
 
Example #15
Source File: ContentFeedController.java    From halo with 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 #16
Source File: AuditResource.java    From okta-jhipster-microservices-oauth-example with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #17
Source File: CodelessDaoProxy.java    From sca-best-practice with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Page<T> findAll(Class<T> clazz, Pageable pageable) {

    if (isUnpaged(pageable)) {
        return new PageImpl<>(findAll(clazz));
    }

    return findAll(clazz, null, pageable);
}
 
Example #18
Source File: CheckController.java    From logistics-back with 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 File: ExchangeController.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@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 #20
Source File: JdbcTaskExecutionDaoTests.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: MySqlPagingQueryProvider.java    From spring-cloud-task with Apache License 2.0 5 votes vote down vote up
@Override
public String getPageQuery(Pageable pageable) {
	String topClause = new StringBuilder().append("LIMIT ")
			.append(pageable.getOffset()).append(", ").append(pageable.getPageSize())
			.toString();
	return SqlPagingQueryUtils.generateLimitJumpToQuery(this, topClause);
}
 
Example #22
Source File: PictureController.java    From yshopmall with 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 #23
Source File: FileSearchRepository.java    From klask-io with GNU General Public License v3.0 5 votes vote down vote up
@Query("{\"bool\" : {\"must\" : {\"bool\" : {\"should\" : [ {\"field\" : {\"version.raw\" : \"?\"}}, {\"field\" : {\"version.raw\" : \"?\"}} ]}}}}")
Page<File> findByRawVersionIn(Collection<String> version, Pageable pageable);
 
Example #24
Source File: ReleaseHistoryController.java    From apollo with 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
Source File: StockProductServiceOnlineImpl.java    From cloudstreetmarket.com with GNU General Public License v3.0 5 votes vote down vote up
@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 File: UserController.java    From QuizZz with 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 File: UserManageServiceImpl.java    From hermes with 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
Source File: AggregatePageableTest.java    From mongodb-aggregate-query-support with Apache License 2.0 5 votes vote down vote up
@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 File: SearchController.java    From wallride with 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 File: AuditResource.java    From java-microservices-examples with 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);
}