當前位置: 首頁>>代碼示例>>Java>>正文


Java Page類代碼示例

本文整理匯總了Java中org.springframework.data.domain.Page的典型用法代碼示例。如果您正苦於以下問題:Java Page類的具體用法?Java Page怎麽用?Java Page使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


Page類屬於org.springframework.data.domain包,在下文中一共展示了Page類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: findBy

import org.springframework.data.domain.Page; //導入依賴的package包/類
@SuppressWarnings({ "rawtypes", "unchecked" })
public PageWrapper<User> findBy(FindUserDTO dto, int page, int size) {
	List<String> roleStr = null;
	String usernameOrEmail;

	if (dto.getRole() == null) {

		if (UserUtils.isAdmin())
			roleStr = Arrays.asList(RoleEnum.PROFESSOR.name(), RoleEnum.STUDENT.name());

		else if (UserUtils.isProfessor())
			roleStr = Arrays.asList(RoleEnum.STUDENT.name());

	} else {
		roleStr = Arrays.asList(dto.getRole().name());
	}

	usernameOrEmail = StringUtils.isEmpty(dto.getUsernameOrEmail()) ? "%%" : "%".concat(dto.getUsernameOrEmail().toLowerCase()).concat("%");

	Pageable pageable = new PageRequest(page, size);
	Page<User> pageInterface = userRepository.findBy(roleStr, usernameOrEmail, pageable);

	return new PageWrapper(pageInterface.getContent(), pageable, pageInterface.getTotalElements());
}
 
開發者ID:edylle,項目名稱:pathological-reports,代碼行數:25,代碼來源:UserService.java

示例2: testFindAllWithRulesRange

import org.springframework.data.domain.Page; //導入依賴的package包/類
/**
 * Default find all, plenty of string rules : lte, gte
 */
@Test
public void testFindAllWithRulesRange() {
	final List<UIRule> rules = new ArrayList<>();
	final BasicRule ruleLTE = new BasicRule();
	ruleLTE.setData("3");
	ruleLTE.setField("dialLong");
	ruleLTE.setOp(RuleOperator.LTE);
	rules.add(ruleLTE);
	final BasicRule ruleGTE = new BasicRule();
	ruleGTE.setData("1");
	ruleGTE.setField("dialLong");
	ruleGTE.setOp(RuleOperator.GTE);
	rules.add(ruleGTE);

	final UiPageRequest uiPageRequest = newAnd10();
	uiPageRequest.getUiFilter().setRules(rules);
	final Map<String, String> mapping = newBaseMapping();
	final Page<SystemDialect> findAll = paginationDao.findAll(SystemDialect.class, uiPageRequest, mapping, null, null);
	Assert.assertTrue(findAll.hasContent());
	Assert.assertEquals(3, findAll.getTotalElements());
	Assert.assertEquals(3, findAll.getContent().size());
}
 
開發者ID:ligoj,項目名稱:bootstrap,代碼行數:26,代碼來源:PaginationDaoTest.java

示例3: getOperinoComponents

import org.springframework.data.domain.Page; //導入依賴的package包/類
/**
     * GET  /operinos/:id/components : get the components linked to the "id" operino.
     *
     * @param id the id of the operino to retrieve components for
     * @return the ResponseEntity with status 200 (OK) and with body the operino, or with status 404 (Not Found)
     */
    @GetMapping("/operinos/{id}/components")
    @Timed
    public ResponseEntity<List<OperinoComponent>> getOperinoComponents(@PathVariable Long id, Pageable pageable) throws URISyntaxException {
        log.debug("REST request to get components for Operino : {}", id);
        Operino operino = operinoService.verifyOwnershipAndGet(id);
        if (operino != null) {
            Page<OperinoComponent> page = operinoComponentService.findAllByOperino(operino, pageable);
            HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/operino-components");
            return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
        } else {
            return ResponseEntity.badRequest()
                    .headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "Not authorized", String.valueOf(id))).build();
        }
//        return ResponseUtil.wrapOrNotFound(Optional.ofNullable(operinoComponentService.findAllByOperino(operino)));
    }
 
開發者ID:AppertaFoundation,項目名稱:Code4Health-Platform,代碼行數:22,代碼來源:OperinoResource.java

示例4: shouldReturnRedirectToFirstPageWhenRequestedPageIsOutOfRange

import org.springframework.data.domain.Page; //導入依賴的package包/類
@Test
public void shouldReturnRedirectToFirstPageWhenRequestedPageIsOutOfRange() {
    final Page<Email> page = mock(Page.class);
    when(page.getTotalElements()).thenReturn(8L);
    when(page.getTotalPages()).thenReturn(2);
    when(page.getNumber()).thenReturn(3);
    when(page.getNumberOfElements()).thenReturn(5);
    when(emailRepository.findAll(any(Pageable.class))).thenReturn(page);

    String result = sut.getAll(3, 5, model);

    assertEquals(EmailController.REDIRECT_EMAIL_LIST_VIEW, result);

    verify(emailRepository).findAll(argThat(matchPageable(3, 5)));
    verifyNoMoreInteractions(emailRepository);
}
 
開發者ID:gessnerfl,項目名稱:fake-smtp-server,代碼行數:17,代碼來源:EmailControllerTest.java

示例5: index

import org.springframework.data.domain.Page; //導入依賴的package包/類
@GetMapping(value = "/")
public String index(Model model) {
    model.addAttribute("home","selected");

    Page<ArticleDto> listArticle = articleService.list(0, ArticleUtils.getIsPublished(),ArticleUtils.getIsTweet());
    model.addAttribute("articleFirst",listArticle.getContent().get(0));
    model.addAttribute("articleLast",listArticle.getContent().get(1));

    model.addAttribute("listArticle",listArticle);

    List<Course> courseList = courseService.getCourseTopN(2);
    model.addAttribute("courseList",courseList);

    List<Document> documentList = storageService.getNewDocumentTopN("index",4);
    model.addAttribute("documentList",documentList);

    return "front/theme/effe/home";
}
 
開發者ID:realxujiang,項目名稱:itweet-boot,代碼行數:19,代碼來源:EffeController.java

示例6: getFormDatas

import org.springframework.data.domain.Page; //導入依賴的package包/類
@ApiOperation(value="分頁查詢表單內容", notes="根據傳進來的查詢參數,獲取表單內容信息")
@ApiImplicitParams({
    @ApiImplicitParam(name = "id", value = "主鍵ID", required = false, dataType = "int", paramType = "query"),
    @ApiImplicitParam(name = "businessKey", value = "業務主鍵KEY,模糊匹配", required = false, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "key", value = "內容鍵,模糊匹配", required = false, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "value", value = "內容值,模糊匹配", required = false, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "tenantId", value = "租戶ID,模糊匹配", required = false, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "page", value = "分頁查詢,開始查詢的頁碼", defaultValue="0", required = false, dataType = "int", paramType = "query"),
    @ApiImplicitParam(name = "size", value = "分頁查詢,每頁顯示的記錄數", defaultValue="10", required = false, dataType = "int", paramType = "query"),
    @ApiImplicitParam(name = "sort", value = "排序的字段,可以多值以逗號分割", required = false, dataType = "string", paramType = "query"),
    @ApiImplicitParam(name = "order", value = "排序的方式,可以為asc或desc,可以多值以逗號分割", required = false, dataType = "string", paramType = "query")
})
@RequestMapping(value = "/form-datas", method = RequestMethod.GET, produces = "application/json")
@ResponseStatus(value = HttpStatus.OK)
public Page<FormData> getFormDatas(@ApiIgnore @RequestParam Map<String, String> requestParams) {
	Criteria<FormData> criteria = new Criteria<FormData>();  
	criteria.add(Restrictions.eq("id", requestParams.get("id"), true)); 
	criteria.add(Restrictions.like("businessKey", requestParams.get("businessKey"), true)); 
	criteria.add(Restrictions.like("key", requestParams.get("key"), true)); 
	criteria.add(Restrictions.like("value", requestParams.get("value"), true)); 
	criteria.add(Restrictions.like("tenantId", requestParams.get("tenantId"), true)); 
	return formDataRepository.findAll(criteria, getPageable(requestParams));
}
 
開發者ID:wengwh,項目名稱:plumdo-work,代碼行數:24,代碼來源:FormDataResource.java

示例7: listUsersInternal

import org.springframework.data.domain.Page; //導入依賴的package包/類
private String listUsersInternal(String search, int pageNumber, Model model) {
    if (search == null) {
        search = "";
    }

    // Page numbers in the URL start with 1
    PageRequest pageable = new PageRequest(pageNumber - 1, MAX_PAGE_SIZE);

    Page<UisUser> usersPage = uisUserService.findAllMatching(search, pageable);
    List<UisUser> users = usersPage.getContent();

    // If the user tries to access a page that doesn't exist
    if (users.size() == 0 && usersPage.getTotalElements() != 0) {
        int lastPage = usersPage.getTotalPages();
        return "redirect:/admin/users/page/" + lastPage + "?search=" + search;
    }

    model.addAttribute("page", usersPage);
    model.addAttribute("search", search);

    return "admin/users";
}
 
開發者ID:university-information-system,項目名稱:uis,代碼行數:23,代碼來源:AdminUsersController.java

示例8: generatePaginationHttpHeaders

import org.springframework.data.domain.Page; //導入依賴的package包/類
public static HttpHeaders generatePaginationHttpHeaders(Page page, String baseUrl) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Total-Count", Long.toString(page.getTotalElements()));
        String link = "";
        if ((page.getNumber() + 1) < page.getTotalPages()) {
            link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\",";
        }
        // prev link
        if ((page.getNumber()) > 0) {
            link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\",";
        }
        // last and first link
        int lastPage = 0;
        if (page.getTotalPages() > 0) {
            lastPage = page.getTotalPages() - 1;
        }
        link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\",";
        link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\"";
        headers.add(HttpHeaders.LINK, link);
        return headers;
    }
 
開發者ID:xm-online,項目名稱:xm-gate,代碼行數:23,代碼來源:PaginationUtil.java

示例9: generatePaginationHttpHeaders

import org.springframework.data.domain.Page; //導入依賴的package包/類
public static HttpHeaders generatePaginationHttpHeaders(Page page, String baseUrl) {

        HttpHeaders headers = new HttpHeaders();
        headers.add("X-Total-Count", "" + Long.toString(page.getTotalElements()));
        String link = "";
        if ((page.getNumber() + 1) < page.getTotalPages()) {
            link = "<" + generateUri(baseUrl, page.getNumber() + 1, page.getSize()) + ">; rel=\"next\",";
        }
        // prev link
        if ((page.getNumber()) > 0) {
            link += "<" + generateUri(baseUrl, page.getNumber() - 1, page.getSize()) + ">; rel=\"prev\",";
        }
        // last and first link
        int lastPage = 0;
        if (page.getTotalPages() > 0) {
            lastPage = page.getTotalPages() - 1;
        }
        link += "<" + generateUri(baseUrl, lastPage, page.getSize()) + ">; rel=\"last\",";
        link += "<" + generateUri(baseUrl, 0, page.getSize()) + ">; rel=\"first\"";
        headers.add(HttpHeaders.LINK, link);
        return headers;
    }
 
開發者ID:mraible,項目名稱:devoxxus-jhipster-microservices-demo,代碼行數:23,代碼來源:PaginationUtil.java

示例10: applyPaginationNotLazy

import org.springframework.data.domain.Page; //導入依賴的package包/類
/**
 * Pagination test without lazy mode.
 */
@Test
public void applyPaginationNotLazy() {
	// create a mock URI info with pagination informations
	final UriInfo uriInfo = newUriInfo();
	final Page<SystemUser> page = Mockito.mock(Page.class);
	final List<SystemUser> list = new ArrayList<>();
	uriInfo.getQueryParameters().putSingle(DataTableAttributes.ECHO, "echo");
	list.add(new SystemUser());
	Mockito.when(page.getContent()).thenReturn(list);
	Mockito.when(page.getTotalElements()).thenReturn(1L);
	final TableItem<SystemUser> pageRequest = paginationJson.applyPagination(uriInfo, page, Function.identity());

	Assert.assertNotNull(pageRequest);
	Assert.assertEquals(1, pageRequest.getData().size());
	Assert.assertEquals(1, pageRequest.getRecordsTotal());
	Assert.assertEquals(1, pageRequest.getRecordsFiltered());
	Assert.assertEquals("echo", pageRequest.getDraw());
	Assert.assertTrue(pageRequest.getData() instanceof ArrayList<?>);
}
 
開發者ID:ligoj,項目名稱:bootstrap,代碼行數:23,代碼來源:PaginationJsonTest.java

示例11: testUsersGet

import org.springframework.data.domain.Page; //導入依賴的package包/類
@Test
@WithMockAuth(id="1")
public void testUsersGet() throws Exception {
    //Telling Mockito to use this mock list every time the findAll method is called on the userRepo
    Pageable pr = new PageRequest(0, 2 , Sort.Direction.ASC, "registrationDate", "id" );
    Page<User> pageofUser = new PageImpl<>(mockUserList);
    
    given(mockUserRepository.findAll(pr)).willReturn(pageofUser);
    //Perform the AP call and check response status code.
    mockMvc.perform(get("/api/users?page=0&size=2")).andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            //.andExpect(jsonPath("$", hasSize(3)))
            .andExpect(jsonPath("$.users[0].id", is(10)))//First user id is 10
            .andExpect(jsonPath("$.users[1].id", is(1))) //Second user id is 1.
            .andExpect(jsonPath("$.users[0].email", is("[email protected]")))
            .andExpect(jsonPath("$.users[1].email", is("[email protected]"))); 
    
    //We verify that we called findAll method once only on the repository.
    verify(mockUserRepository, times(1)).findAll(pr);
    verify(mockUserRepository, times(1)).count();
    
    //We verify that we didnt call anything else on the repository
    verifyNoMoreInteractions(mockUserRepository);
    //We verify that user exist and didnt modify them from the repository
    assertEquals(mockIoannisUser, mockUserRepository.findAll(pr).iterator().next());
}
 
開發者ID:jrtechnologies,項目名稱:yum,代碼行數:27,代碼來源:UsersApiControllerTest.java

示例12: commaTest

import org.springframework.data.domain.Page; //導入依賴的package包/類
@Test
public void commaTest() {
    String baseUrl = "/api/_search/example";
    List<String> content = new ArrayList<>();
    Page<String> page = new PageImpl<>(content);
    String query = "Test1, test2";
    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 expectedData = "</api/_search/example?page=0&size=0&query=Test1%2C+test2>; rel=\"last\","
            + "</api/_search/example?page=0&size=0&query=Test1%2C+test2>; 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));
}
 
開發者ID:pascalgrimaud,項目名稱:qualitoast,代碼行數:20,代碼來源:PaginationUtilUnitTest.java

示例13: searchCity

import org.springframework.data.domain.Page; //導入依賴的package包/類
@Override
public List<City> searchCity(Integer pageNumber,
                             Integer pageSize,
                             String searchContent) {
    // 分頁參數
    Pageable pageable = new PageRequest(pageNumber, pageSize);

    // Function Score Query
    FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("cityname", searchContent)),
                ScoreFunctionBuilders.weightFactorFunction(1000))
            .add(QueryBuilders.boolQuery().should(QueryBuilders.matchQuery("description", searchContent)),
                    ScoreFunctionBuilders.weightFactorFunction(100));

    // 創建搜索 DSL 查詢
    SearchQuery searchQuery = new NativeSearchQueryBuilder()
            .withPageable(pageable)
            .withQuery(functionScoreQueryBuilder).build();

    LOGGER.info("\n searchCity(): searchContent [" + searchContent + "] \n DSL  = \n " + searchQuery.getQuery().toString());

    Page<City> searchPageResults = cityRepository.search(searchQuery);
    return searchPageResults.getContent();
}
 
開發者ID:JeffLi1993,項目名稱:springboot-learning-example,代碼行數:25,代碼來源:CityESServiceImpl.java

示例14: queryCompanys

import org.springframework.data.domain.Page; //導入依賴的package包/類
@ApiOperation(value = "queryCompanys", notes = "獲取 公司分頁")
@GetMapping("/all_company/page")
public ModelResult<List<Company>> queryCompanys(Pageable pageable,
                                                HttpServletRequest request,
                                                HttpServletResponse response) throws URISyntaxException {
    
    ModelResult<List<Company>> result = new ModelResult<>();
    Page<Company> companies = companyMapper.selectAllPageable(pageable);
    result.setData(companies.getContent());
    
    PaginationUtil.setPaginationHttpHeaders(companies, request,response);
    return result;
}
 
開發者ID:sdcuike,項目名稱:spring-boot-oauth2-demo,代碼行數:14,代碼來源:ExampleController.java

示例15: searchUserPosts

import org.springframework.data.domain.Page; //導入依賴的package包/類
@Query("{" +
    "        \"bool\": {" +
    "            \"must\": [" +
    "                {" +
    "                    \"term\": {" +
    "                        \"user.login\": \"?1\"" +
    "                    }" +
    "                }, " +
    "                {" +
    "                    \"bool\": {" +
    "                        \"should\": [" +
    "                            {" +
    "                                \"match\": {" +
    "                                    \"title\": \"?0\"" +
    "                                }" +
    "                            }, " +
    "                            {" +
    "                                \"match\": {" +
    "                                    \"tags.friendly_name\": \"?0\"" +
    "                                }" +
    "                            }" +
    "                        ]" +
    "                    }" +
    "                }" +
    "            ]" +
    "        }" +
    "    }")
Page<Post> searchUserPosts(String query, String login, Pageable pageable);
 
開發者ID:ugouku,項目名稱:shoucang,代碼行數:29,代碼來源:PostSearchRepository.java


注:本文中的org.springframework.data.domain.Page類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。