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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: SinkQueryService.java    From alchemy with 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 File: RoleController.java    From mblog with 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 File: ArticleController.java    From Spring-Boot-2.0-Projects with 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 File: JobController.java    From sk-admin with 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
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 #16
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 #17
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 #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: 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 #20
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 #21
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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #28
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 #29
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 #30
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";
}