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

The following examples show how to use org.springframework.data.domain.PageImpl. 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 check out the related API usage on the sidebar.
Example 1
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 2
Source Project: pacbot   Source File: PolicyControllerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getPoliciesTest() throws Exception {
	Object[] policy = {"PolicyName", "PolicyDesc"};
	List<Object[]> policies = Lists.newArrayList();
	policies.add(policy);
	Page<Object[]> allPolicies = new PageImpl<Object[]>(policies, new PageRequest(0, 1), policies.size());
	
	when(policyService.getPolicies(anyInt(), anyInt(), anyString())).thenReturn(allPolicies);
	mockMvc.perform(get("/policy/list")
			.param("page", "0")
			.param("size", "1")
			.param("searchTerm", StringUtils.EMPTY))
			.andExpect(status().isOk())
			.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
			.andExpect(jsonPath("$.message", is("success")));
}
 
Example 3
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 4
public <S> Page<S> find(String queryString, String queryCount, NamedParams params, Pageable pageable, ResultTransformer transformer) {
    Assert.hasText(queryString, "Query must has text!");
    Assert.hasText(queryCount, "Query count must has text!");
    Assert.notNull(params, "QueryParams must not be null!");
    Assert.notNull(pageable, "PageRequest must not be null!");
    Assert.notNull(transformer, "Transformer must not be null!");

    Query query = em.createQuery(queryString);

    setQueryParams(query, params);
    query.setMaxResults(pageable.getPageSize());
    query.setFirstResult((int) pageable.getOffset());

    List<S> resultList = query.unwrap(QueryImpl.class).setResultTransformer(transformer).list();

    Query countQuery = em.createQuery(queryCount);
    setQueryParams(countQuery, params);
    Long total = (Long) countQuery.getSingleResult();

    Page<S> page = new PageImpl(resultList, pageable, total);

    return page;
}
 
Example 5
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 6
Source Project: ZTuoExchange_framework   Source File: MemberTransactionService.java    License: MIT License 6 votes vote down vote up
public Page<MemberTransactionVO> joinFind(List<Predicate> predicates, PageModel pageModel){
    List<OrderSpecifier> orderSpecifiers = pageModel.getOrderSpecifiers() ;
    JPAQuery<MemberTransactionVO> query = queryFactory.select(Projections.fields(MemberTransactionVO.class,
            QMemberTransaction.memberTransaction.address,
            QMemberTransaction.memberTransaction.amount,
            QMemberTransaction.memberTransaction.createTime.as("createTime"),
            QMemberTransaction.memberTransaction.fee,
            QMemberTransaction.memberTransaction.flag,
            QMemberTransaction.memberTransaction.id.as("id"),
            QMemberTransaction.memberTransaction.symbol,
            QMemberTransaction.memberTransaction.type,
            QMember.member.username.as("memberUsername"),
            QMember.member.mobilePhone.as("phone"),
            QMember.member.email,
            QMember.member.realName.as("memberRealName"),
            QMember.member.id.as("memberId")))
            .from(QMemberTransaction.memberTransaction, QMember.member);
    predicates.add(QMemberTransaction.memberTransaction.memberId.eq(QMember.member.id));
            query.where(predicates.toArray(new BooleanExpression[predicates.size()]));
    query.orderBy(orderSpecifiers.toArray(new OrderSpecifier[orderSpecifiers.size()]));
    List<MemberTransactionVO> list = query.offset((pageModel.getPageNo()-1)*pageModel.getPageSize()).limit(pageModel.getPageSize()).fetch();
    long total = query.fetchCount();
    return new PageImpl<>(list, pageModel.getPageable(), total);
}
 
Example 7
Source Project: ZTuoExchange_framework   Source File: MemberDepositService.java    License: MIT License 6 votes vote down vote up
public Page<MemberDepositVO> page(List<BooleanExpression> predicates,PageModel pageModel){
    JPAQuery<MemberDepositVO> query = queryFactory.select(Projections.fields(MemberDepositVO.class,
            QMemberDeposit.memberDeposit.id.as("id"),
            QMember.member.username,
            QMember.member.id.as("memberId"),
            QMemberDeposit.memberDeposit.address,
            QMemberDeposit.memberDeposit.amount,
            QMemberDeposit.memberDeposit.createTime.as("createTime"),
            QMemberDeposit.memberDeposit.unit)).from(QMember.member,QMemberDeposit.memberDeposit)
            .where(predicates.toArray(new BooleanExpression[predicates.size()]));
    List<OrderSpecifier> orderSpecifiers = pageModel.getOrderSpecifiers();
    query.orderBy(orderSpecifiers.toArray(new OrderSpecifier[orderSpecifiers.size()])) ;
    long total = query.fetchCount() ;
    query.offset(pageModel.getPageSize()*(pageModel.getPageNo()-1)).limit(pageModel.getPageSize());
    List<MemberDepositVO> list = query.fetch() ;
    return new PageImpl<MemberDepositVO>(list,pageModel.getPageable(),total);
}
 
Example 8
Source Project: ZTuoExchange_framework   Source File: AdminAccessLogService.java    License: MIT License 6 votes vote down vote up
public Page<AdminAccessLog> page(List<BooleanExpression> predicates, PageModel pageModel){
    JPAQuery<AdminAccessLog>  query = queryFactory.select(
            Projections.fields(AdminAccessLog.class,
                    QAdminAccessLog.adminAccessLog.id.as("id"),
                    QAdminAccessLog.adminAccessLog.accessIp.as("accessIp"),
                    QAdminAccessLog.adminAccessLog.accessMethod.as("accessMethod"),
                    QAdminAccessLog.adminAccessLog.accessTime.as("accessTime"),
                    QAdminAccessLog.adminAccessLog.adminId.as("adminId"),
                    QAdminAccessLog.adminAccessLog.uri.as("uri"),
                    QAdminAccessLog.adminAccessLog.module.as("module"),
                    QAdminAccessLog.adminAccessLog.operation.as("operation"),
                    QAdmin.admin.username.as("adminName"))
    ).from(QAdminAccessLog.adminAccessLog,QAdmin.admin).where(predicates.toArray(new BooleanExpression[predicates.size()])) ;
    List<OrderSpecifier> orderSpecifiers = pageModel.getOrderSpecifiers() ;
    query.orderBy(orderSpecifiers.toArray(new OrderSpecifier[orderSpecifiers.size()]));
    long total = query.fetchCount() ;
    query.offset(pageModel.getPageSize()*(pageModel.getPageNo()-1)).limit(pageModel.getPageSize());
    List<AdminAccessLog> list = query.fetch() ;
    return new PageImpl<AdminAccessLog>(list,pageModel.getPageable(),total);
}
 
Example 9
Source Project: heimdall   Source File: DeveloperServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listPageable() {
    PageableDTO pageableDTO = new PageableDTO();
    pageableDTO.setLimit(10);
    pageableDTO.setOffset(0);
    List<Developer> developers = new ArrayList<>();
    developers.add(developer);

    Page<Developer> page = new PageImpl<>(developers);

    Mockito.when(developerRepository.findAll(Mockito.any(), Mockito.any(Pageable.class))).thenReturn(page);

    DeveloperPage list = developerService.list(developerDTO, pageableDTO);

    List<Developer> content = list.getContent();

    assertEquals(developers, content);
}
 
Example 10
Source Project: pacbot   Source File: UserRolesServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<UserRolesResponse> getAllUserRoles(String searchTerm, int page, int size) {
	Page<UserRoles> userRoles = userRolesRepository.findAllUserRolesDetails(searchTerm, PageRequest.of(page, size));
	List<UserRolesResponse> allUserRolesList = Lists.newCopyOnWriteArrayList();
	userRoles.getContent().forEach(userRoleDetail -> {
		UserRolesResponse userRolesResponse = new UserRolesResponse();
		if(userRoleDetail != null){
			userRolesResponse.setCreatedBy(userRoleDetail.getOwner());
			userRolesResponse.setCreatedDate(userRoleDetail.getCreatedDate());
			userRolesResponse.setModifiedDate(userRoleDetail.getModifiedDate());
			userRolesResponse.setRoleId(userRoleDetail.getRoleId());
			userRolesResponse.setDescription(userRoleDetail.getRoleDesc());
			userRolesResponse.setRoleName(userRoleDetail.getRoleName());
			userRolesResponse.setUsers(userRoleDetail.getUsers().parallelStream().map(user -> user != null ? user.getUserId() : StringUtils.EMPTY).collect(Collectors.toList()));
			allUserRolesList.add(userRolesResponse);
		} 
	 });
	Page<UserRolesResponse> allUserRoles = new PageImpl<UserRolesResponse>(allUserRolesList, PageRequest.of(page, size), userRoles.getTotalElements());
	return allUserRoles;
}
 
Example 11
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 12
Source Project: heimdall   Source File: ResourceServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listResourcesWithPageable() {

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

     ArrayList<Resource> listResources = new ArrayList<>();

     this.resource.setName("Resource Name");

     listResources.add(resource);

     Page<Resource> page = new PageImpl<>(listResources);

     Mockito.when(apiRepository.findOne(Mockito.anyLong())).thenReturn(api);
     Mockito.when(this.resourceRepository
                            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class)))
            .thenReturn(page);

     ResourcePage resourcePageResp = this.resourceService.list(1L, this.resourceDTO, pageableDTO);

     assertEquals(1L, resourcePageResp.getTotalElements());
     Mockito.verify(this.resourceRepository, Mockito.times(1))
            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class));
}
 
Example 13
Source Project: flair-engine   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content,new PageRequest(6, 50),400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 14
Source Project: heimdall   Source File: ApiServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listApiWithPageableTest() {

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

     List<Api> apis = new ArrayList<>();
     apis.add(api);

     Page<Api> page = new PageImpl<>(apis);

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

     ApiPage apiPageResp = apiService.list(apiDTO, pageableDTO);

     assertEquals(1L, apiPageResp.getTotalElements());
     Mockito.verify(this.apiRepository, Mockito.times(1))
            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class));
}
 
Example 15
Source Project: ZTuoExchange_framework   Source File: MemberDepositService.java    License: MIT License 6 votes vote down vote up
public Page<MemberDepositVO> page(List<BooleanExpression> predicates,PageModel pageModel){
    JPAQuery<MemberDepositVO> query = queryFactory.select(Projections.fields(MemberDepositVO.class,
            QMemberDeposit.memberDeposit.id.as("id"),
            QMember.member.username,
            QMember.member.id.as("memberId"),
            QMemberDeposit.memberDeposit.address,
            QMemberDeposit.memberDeposit.amount,
            QMemberDeposit.memberDeposit.createTime.as("createTime"),
            QMemberDeposit.memberDeposit.unit)).from(QMember.member,QMemberDeposit.memberDeposit)
            .where(predicates.toArray(new BooleanExpression[predicates.size()]));
    List<OrderSpecifier> orderSpecifiers = pageModel.getOrderSpecifiers();
    query.orderBy(orderSpecifiers.toArray(new OrderSpecifier[orderSpecifiers.size()])) ;
    long total = query.fetchCount() ;
    query.offset(pageModel.getPageSize()*(pageModel.getPageNo()-1)).limit(pageModel.getPageSize());
    List<MemberDepositVO> list = query.fetch() ;
    return new PageImpl<MemberDepositVO>(list,pageModel.getPageable(),total);
}
 
Example 16
Source Project: yshopmall   Source File: RedisServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Page<RedisVo> findByKey(String key, Pageable pageable){
    List<RedisVo> redisVos = new ArrayList<>();
    if(!"*".equals(key)){
        key = "*" + key + "*";
    }
    for (Object s : redisTemplate.keys(key)) {
        // 过滤掉权限的缓存
        if (s.toString().indexOf("role::loadPermissionByUser") != -1
                || s.toString().indexOf("user::loadUserByUsername") != -1
                || s.toString().indexOf("wechat") != -1
                || s.toString().indexOf("wxpay") != -1
                || s.toString().indexOf(ShopKeyUtils.getSiteUrl()) != -1) {
            continue;
        }
        DataType dataType = redisTemplate.type(s.toString());
        if(!dataType.code().equals("string")) continue;
        RedisVo redisVo = new RedisVo(s.toString(),redisTemplate.opsForValue().get(s.toString()).toString());
        redisVos.add(redisVo);
    }
    Page<RedisVo> page = new PageImpl<RedisVo>(
            PageUtil.toPage(pageable.getPageNumber(),pageable.getPageSize(),redisVos),
            pageable,
            redisVos.size());
    return page;
}
 
Example 17
@Test
public void greaterSemicolonTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content);
    String query = "Test>;test";
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 2);
    String[] linksData = headerData.split(",");
    assertTrue(linksData.length == 2);
    assertTrue(linksData[0].split(">;").length == 2);
    assertTrue(linksData[1].split(">;").length == 2);
    String expectedData = "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"last\","
            + "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(0L));
}
 
Example 18
Source Project: cubeai   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, new PageRequest(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 19
Source Project: cubeai   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, new PageRequest(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 20
Source Project: heimdall   Source File: OperationServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listOperationsWithPageable() {

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

     ArrayList<Operation> listOperations = new ArrayList<>();

     listOperations.add(operation);

     Page<Operation> page = new PageImpl<>(listOperations);
     Mockito.when(resourceRepository.findByApiIdAndId(Mockito.anyLong(), Mockito.anyLong()))
            .thenReturn(res);
     Mockito.when(this.operationRepository
                            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class)))
            .thenReturn(page);

     OperationPage operationPageResp = this.operationService
               .list(1L, 1L, this.operationDTO, pageableDTO);

     assertEquals(1L, operationPageResp.getTotalElements());
     Mockito.verify(this.operationRepository, Mockito.times(1))
            .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class));
}
 
Example 21
Source Project: cubeai   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void greaterSemicolonTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content);
    String query = "Test>;test";
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 2);
    String[] linksData = headerData.split(",");
    assertTrue(linksData.length == 2);
    assertTrue(linksData[0].split(">;").length == 2);
    assertTrue(linksData[1].split(">;").length == 2);
    String expectedData = "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"last\","
            + "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(0L));
}
 
Example 22
Source Project: cubeai   Source File: PaginationUtilUnitTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, new PageRequest(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 23
Source Project: pre   Source File: SysRedisController.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * 获取所有key
 * @param pageable
 * @return
 */
@GetMapping
public R getAllByPage(Pageable pageable) {
    List<RedisVo> redisList = redisUtil.getAll();
    int totalElements = redisList.size();
    if (pageable == null) {
        pageable = PageRequest.of(0, 10);
    }
    int fromIndex = pageable.getPageSize() * pageable.getPageNumber();
    int toIndex = pageable.getPageSize() * (pageable.getPageNumber() + 1);
    if (toIndex > totalElements) {
        toIndex = totalElements;
    }
    List<RedisVo> indexObjects = redisList.subList(fromIndex, toIndex);
    Page<RedisVo> page = new PageImpl<>(indexObjects, pageable, totalElements);
    return R.ok(page);
}
 
Example 24
@Test
public void generatePaginationHttpHeadersTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content, PageRequest.of(6, 50), 400L);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 4);
    String expectedData = "</api/_search/example?page=7&size=50>; rel=\"next\","
            + "</api/_search/example?page=5&size=50>; rel=\"prev\","
            + "</api/_search/example?page=7&size=50>; rel=\"last\","
            + "</api/_search/example?page=0&size=50>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(400L));
}
 
Example 25
Source Project: heimdall   Source File: AppServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void listAppWithPageableTest() {

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

    List<App> apps = new ArrayList<>();
    apps.add(app);

    AppRequestDTO appRequestDTO = new AppRequestDTO();

    Page<App> page = new PageImpl<>(apps);

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

    AppPage apiPageResp = appService.list(appRequestDTO, pageableDTO);

    assertEquals(1L, apiPageResp.getTotalElements());
    Mockito.verify(this.appRepository, Mockito.times(1))
           .findAll(Mockito.any(Example.class), Mockito.any(Pageable.class));
}
 
Example 26
@Test
public void greaterSemicolonTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content);
    String query = "Test>;test";
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, baseUrl);
    List<String> strHeaders = headers.get(HttpHeaders.LINK);
    assertNotNull(strHeaders);
    assertTrue(strHeaders.size() == 1);
    String headerData = strHeaders.get(0);
    assertTrue(headerData.split(",").length == 2);
    String[] linksData = headerData.split(",");
    assertTrue(linksData.length == 2);
    assertTrue(linksData[0].split(">;").length == 2);
    assertTrue(linksData[1].split(">;").length == 2);
    String expectedData = "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"last\","
            + "</api/_search/example?page=0&size=0&query=Test%3E%3Btest>; rel=\"first\"";
    assertEquals(expectedData, headerData);
    List<String> xTotalCountHeaders = headers.get("X-Total-Count");
    assertTrue(xTotalCountHeaders.size() == 1);
    assertTrue(Long.valueOf(xTotalCountHeaders.get(0)).equals(0L));
}
 
Example 27
private Page<T> getPage(Pageable pageable, String queryString, NamedParams params, String queryCount) {
    Assert.hasText(queryString, "Query must has text!");
    Assert.hasText(queryCount, "Query count must has text!");
    Assert.notNull(params, "QueryParams must not be null!");
    Assert.notNull(pageable, "PageRequest must not be null!");

    Query query = em.createQuery(queryString);

    setQueryParams(query, params);
    query.setMaxResults(pageable.getPageSize());
    query.setFirstResult((int) pageable.getOffset());

    List<T> resultList = query.getResultList();

    Query countQuery = em.createQuery(queryCount);
    setQueryParams(countQuery, params);
    Long total = (Long) countQuery.getSingleResult();

    Page page = new PageImpl(resultList, pageable, total);
    return page;
}
 
Example 28
@Override
public Page<EsProduct> recommend(Long id, Integer pageNum, Integer pageSize) {
    Pageable pageable = PageRequest.of(pageNum, pageSize);
    List<EsProduct> esProductList = productDao.getAllEsProductList(id);
    if (esProductList.size() > 0) {
        EsProduct esProduct = esProductList.get(0);
        String keyword = esProduct.getName();
        Long brandId = esProduct.getBrandId();
        Long productCategoryId = esProduct.getProductCategoryId();
        //根据商品标题、品牌、分类进行搜索
        List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders = new ArrayList<>();
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("name", keyword),
                ScoreFunctionBuilders.weightFactorFunction(8)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("subTitle", keyword),
                ScoreFunctionBuilders.weightFactorFunction(2)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("keywords", keyword),
                ScoreFunctionBuilders.weightFactorFunction(2)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("brandId", brandId),
                ScoreFunctionBuilders.weightFactorFunction(10)));
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("productCategoryId", productCategoryId),
                ScoreFunctionBuilders.weightFactorFunction(6)));
        FunctionScoreQueryBuilder.FilterFunctionBuilder[] builders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[filterFunctionBuilders.size()];
        filterFunctionBuilders.toArray(builders);
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(builders)
                .scoreMode(FunctionScoreQuery.ScoreMode.SUM)
                .setMinScore(2);
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        builder.withQuery(functionScoreQueryBuilder);
        builder.withPageable(pageable);
        NativeSearchQuery searchQuery = builder.build();
        LOGGER.info("DSL:{}", searchQuery.getQuery().toString());
        return productRepository.search(searchQuery);
    }
    return new PageImpl<>(null);
}
 
Example 29
Source Project: Lottor   Source File: TxManagerMsgController.java    License: MIT License 5 votes vote down vote up
@GetMapping("/rollback")
@ResponseBody
@ApiOperation("获取所有的回滚消息")
public List<TxTransactionItem> findRollbackMsgs(@RequestParam(required = false) String sortFiled, @RequestParam(required = false) Boolean desc, @RequestParam(required = false) int pageNum) {
    MongoPageable pageable = new MongoPageable();
    Query query = new Query();
    query.addCriteria(Criteria.where("status").is(TransactionStatusEnum.ROLLBACK.getCode()));
    List<Sort.Order> orders = new ArrayList<Sort.Order>();  //排序
    Sort.Direction direction;
    if (desc != null) {
        direction = desc ? Sort.Direction.DESC : Sort.Direction.ASC;
    } else {
        direction = Sort.Direction.DESC;
    }

    if (sortFiled != null) {
        orders.add(new Sort.Order(direction, sortFiled));
    } else {
        orders.add(new Sort.Order(direction, "createDate"));
    }
    if ((Object) pageNum != null) {
        LogUtil.debug(LOGGER, "query for rollback msgs, pageNum is {}", () -> pageNum);
        pageable.setPagenumber(pageNum);
    } else {
        pageable.setPagenumber(1);
    }
    pageable.setPagesize(pageSize);
    pageable.setSort(new Sort(orders));
    Long count = mongoTemplate.count(query, TxTransactionItem.class, CollectionNameEnum.TxTransactionItem.name());
    // 查询
    List<TxTransactionItem> list = mongoTemplate.find(query.with(pageable), TxTransactionItem.class, CollectionNameEnum.TxTransactionItem.name());
    // 将集合与分页结果封装
    Page<TxTransactionItem> pagelist = new PageImpl<>(list, pageable, count);

    return pagelist.getContent();
}
 
Example 30
Source Project: youkefu   Source File: SearchTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param orgi
 * @param agent
 * @param p
 * @param ps
 * @return
 */
public static PageImpl<UKDataBean> agentsearch(String orgi ,boolean excludeCalled ,  String agent , int p, int ps){
	BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
	queryBuilder.must(termQuery("orgi", orgi)) ;
	if(excludeCalled){
		queryBuilder.must(termQuery("callstatus", UKDataContext.NameStatusTypeEnum.NOTCALL.toString())) ;
	}
	queryBuilder.must(termQuery("validresult", "valid")) ;
	queryBuilder.must(termQuery(UKDataContext.UKEFU_SYSTEM_DIS_AGENT, agent)) ;
	queryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAGENT.toString())) ;
	
	return search(queryBuilder, p, ps);
}