org.springframework.data.domain.PageImpl Java Examples

The following examples show how to use org.springframework.data.domain.PageImpl. 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: PaginationUtilUnitTest.java    From e-commerce-microservice with 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, 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 File: PolicyControllerTest.java    From pacbot with 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
Source File: PaginationUtilUnitTest.java    From okta-jhipster-microservices-oauth-example with 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, 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
Source File: DefaultJpaRepository.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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
Source File: PaginationUtilUnitTest.java    From e-commerce-microservice with 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, 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 File: DeveloperServiceTest.java    From heimdall with 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 #7
Source File: UserRolesServiceImpl.java    From pacbot with 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 #8
Source File: PaginationUtilUnitTest.java    From e-commerce-microservice with 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, 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 #9
Source File: ResourceServiceTest.java    From heimdall with 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 #10
Source File: PaginationUtilUnitTest.java    From flair-engine with 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 #11
Source File: ApiServiceTest.java    From heimdall with 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 #12
Source File: MemberDepositService.java    From ZTuoExchange_framework with 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 #13
Source File: RedisServiceImpl.java    From yshopmall with 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 #14
Source File: PaginationUtilUnitTest.java    From okta-jhipster-microservices-oauth-example with 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 #15
Source File: PaginationUtilUnitTest.java    From cubeai with 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 #16
Source File: PaginationUtilUnitTest.java    From cubeai with 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 #17
Source File: OperationServiceTest.java    From heimdall with 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 #18
Source File: PaginationUtilUnitTest.java    From cubeai with 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 #19
Source File: PaginationUtilUnitTest.java    From cubeai with 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 File: SysRedisController.java    From pre with 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 #21
Source File: PaginationUtilUnitTest.java    From okta-jhipster-microservices-oauth-example with 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, 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 #22
Source File: AppServiceTest.java    From heimdall with 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 #23
Source File: PaginationUtilUnitTest.java    From okta-jhipster-microservices-oauth-example with 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 #24
Source File: DefaultJpaRepository.java    From ueboot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #25
Source File: EsProductServiceImpl.java    From BigDataPlatform with GNU General Public License v3.0 5 votes vote down vote up
@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 #26
Source File: TxManagerMsgController.java    From Lottor with 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 #27
Source File: SearchTools.java    From youkefu with 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);
}
 
Example #28
Source File: SearchTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param orgi
 * @param agent
 * @param p
 * @param ps
 * @return
 */
public static PageImpl<UKDataBean> agentapsearch(String orgi , String agent , int p, int ps){
	BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
	queryBuilder.must(termQuery("orgi", orgi)) ;
	queryBuilder.must(termQuery("validresult", "valid")) ;
	queryBuilder.must(termQuery(UKDataContext.UKEFU_SYSTEM_DIS_AGENT, agent)) ;
	queryBuilder.must(termQuery("apstatus", true)) ;		//预约状态
	
	queryBuilder.must(rangeQuery("aptime").to(System.currentTimeMillis())) ;		//预约状态
	
	return search(queryBuilder, p, ps);
}
 
Example #29
Source File: SearchTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param orgi
 * @param agent
 * @param p
 * @param ps
 * @return
 */
public static PageImpl<UKDataBean> aisearch(String orgi , int p, int ps){
	BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
	queryBuilder.must(termQuery("orgi", orgi)) ;
	queryBuilder.must(termQuery("callstatus", UKDataContext.NameStatusTypeEnum.NOTCALL.toString())) ;
	
	queryBuilder.must(termQuery("validresult", "valid")) ;
	queryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAI.toString())) ;
	
	return search(queryBuilder, p, ps);
}
 
Example #30
Source File: SearchTools.java    From youkefu with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param orgi
 * @param agent
 * @param p
 * @param ps
 * @return
 */
public static PageImpl<UKDataBean> ainamesearch(String orgi , String phonenum){
	BoolQueryBuilder queryBuilder = new BoolQueryBuilder();
	queryBuilder.must(termQuery("orgi", orgi)) ;
	queryBuilder.must(termQuery("validresult", "valid")) ;
	queryBuilder.must(termQuery("status", UKDataContext.NamesDisStatusType.DISAI.toString())) ;
	StringBuffer strb = new StringBuffer();
	if(!StringUtils.isBlank(phonenum)) {
		if(phonenum.startsWith("0")) {
			strb.append(phonenum.substring(1)) ;
		}else {
			strb.append(phonenum) ;
		}
	}else {
		strb.append(UKDataContext.UKEFU_SYSTEM_NO_DAT) ;
	}
	queryBuilder.must(new QueryStringQueryBuilder(strb.toString()).defaultOperator(Operator.OR) );
	return search(queryBuilder,0, 1);
}