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

The following are top voted examples for showing how to use org.springframework.data.domain.Page. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: pathological-reports   File: UserService.java   Source Code and License 8 votes vote down vote up
@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());
}
 
Example 2
Project: bootstrap   File: PaginationDaoTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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());
}
 
Example 3
Project: Code4Health-Platform   File: OperinoResource.java   Source Code and License 6 votes vote down vote up
/**
     * 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)));
    }
 
Example 4
Project: fake-smtp-server   File: EmailControllerTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 5
Project: itweet-boot   File: EffeController.java   Source Code and License 6 votes vote down vote up
@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";
}
 
Example 6
Project: plumdo-work   File: FormDataResource.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 7
Project: uis   File: AdminUsersController.java   Source Code and License 6 votes vote down vote up
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";
}
 
Example 8
Project: xm-gate   File: PaginationUtil.java   Source Code and License 6 votes vote down vote up
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;
    }
 
Example 9
Project: devoxxus-jhipster-microservices-demo   File: PaginationUtil.java   Source Code and License 6 votes vote down vote up
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;
    }
 
Example 10
Project: bootstrap   File: PaginationJsonTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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<?>);
}
 
Example 11
Project: yum   File: UsersApiControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 12
Project: qualitoast   File: PaginationUtilUnitTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 13
Project: springboot-learning-example   File: CityESServiceImpl.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 14
Project: spring-boot-oauth2-demo   File: ExampleController.java   Source Code and License 5 votes vote down vote up
@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;
}
 
Example 15
Project: shoucang   File: PostSearchRepository.java   Source Code and License 5 votes vote down vote up
@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);
 
Example 16
Project: spring-backend-boilerplate   File: AdvancedFileObjectQueryRestSupportImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Page<FileObject> listFileObject(DefaultFileObjectQueryParameter queryParameter, User user) {
	String sortedBy = queryParameter.getSortedBy();
	if (StringUtils.isEmpty(sortedBy)) {
		sortedBy = "uploadedAt";
	}
	return fileObjectRepository.findPage(queryParameter,
										 new PageRequest(queryParameter.getStart(),
														 queryParameter.getLimit(),
														 new Sort(Sort.Direction.ASC, sortedBy)));
}
 
Example 17
Project: spring-io   File: SubCategoryResource.java   Source Code and License 5 votes vote down vote up
/**
 * SEARCH  /_search/sub-categories?query=:query : search for the subCategory corresponding
 * to the query.
 *
 * @param query the query of the subCategory search 
 * @param pageable the pagination information
 * @return the result of the search
 */
@GetMapping("/_search/sub-categories")
@Timed
public ResponseEntity<List<SubCategory>> searchSubCategories(@RequestParam String query, @ApiParam Pageable pageable) {
    log.debug("REST request to search for a page of SubCategories for query {}", query);
    Page<SubCategory> page = subCategoryService.search(query, pageable);
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/sub-categories");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 18
Project: SpringBoot_Wechat_Sell   File: OrderMasterRepositoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void findByBuyerOpenid() throws Exception {
    PageRequest request = new PageRequest(1, 3);

    Page<OrderMaster> result = repository.findByBuyerOpenid(OPENID, request);

    Assert.assertNotEquals(0, result.getTotalElements());
}
 
Example 19
Project: role-api   File: HateoasPaginationHeadersBuilderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void addPaginationData_WithLast_AddTotalCountAndLastLink() {
    HttpHeaders initialHeaders = new HttpHeaders();
    
    Page<?> page = buildPage(false, true, false, false);
    
    when(totalCountHeaderBuilder.buildTotal(page)).thenReturn(EXPECTED_TOTAL);
    when(linkHeaderBuilder.buildLast(page)).thenReturn(EXPECTED_LINK);
    
    HttpHeaders endHeaders = hateoasPaginationHeadersBuilder.addPaginationData(initialHeaders, page);

    assertThat(endHeaders, hasEntry(equalTo(ApiHttpHeaders.LINK), hasItem(EXPECTED_LINK)));
    assertThat(endHeaders, hasEntry(equalTo(ApiHttpHeaders.TOTAL_COUNT), hasItem(EXPECTED_TOTAL)));
    assertThat(endHeaders, equalTo(initialHeaders));
}
 
Example 20
Project: JavaQuarkBBS   File: PermissionController.java   Source Code and License 5 votes vote down vote up
@GetMapping
public PageResult getAll(String draw,
                         @RequestParam(required = false, defaultValue = "1") int start,
                         @RequestParam(required = false, defaultValue = "10") int length){
    int pageNo = start/length;
    Page<Permission> page = permissionService.findByPage(pageNo, length);
    PageResult<List<Permission>> result = new PageResult<>(
            draw,
            page.getTotalElements(),
            page.getTotalElements(),
            page.getContent());

    return result;
}
 
Example 21
Project: nixmash-blog   File: SimpleProductRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<Product> findByAvailableTrue() {
	Query query = new SimpleQuery(new Criteria(new SimpleField(Criteria.WILDCARD)).expression(Criteria.WILDCARD));
	query.addFilterQuery(new SimpleQuery(new Criteria(IProduct.DOCTYPE_FIELD).is(SolrDocType.PRODUCT)));
	query.setRows(1000);
	Page<Product> results = getSolrOperations().queryForPage(query, Product.class);
	return results.getContent();
}
 
Example 22
Project: spring-io   File: AuditResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /audits : get a page of AuditEvents.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of AuditEvents in body
 */
@GetMapping
public ResponseEntity<List<AuditEvent>> getAll(@ApiParam Pageable pageable) {
    Page<AuditEvent> page = auditEventService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/management/audits");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 23
Project: xm-ms-entity   File: CommentResource.java   Source Code and License 5 votes vote down vote up
/**
 * SEARCH  /_search/comments?query=:query : search for the comment corresponding
 * to the query.
 *
 * @param query the query of the comment search
 * @param pageable the pagination information
 * @return the result of the search
 */
@GetMapping("/_search/comments")
@Timed
public ResponseEntity<List<Comment>> searchComments(@RequestParam String query, @ApiParam Pageable pageable) {
    log.debug("REST request to search for a page of Comments for query {}", query);
    Page<Comment> page = commentService.search(query, pageable);
    HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/comments");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 24
Project: TorgCRM-Server   File: UserServiceIntTest.java   Source Code and License 5 votes vote down vote up
@Test
@Transactional
public void assertThatAnonymousUserIsNotGet() {
    user.setLogin(Constants.ANONYMOUS_USER);
    if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) {
        userRepository.saveAndFlush(user);
    }
    final PageRequest pageable = new PageRequest(0, (int) userRepository.count());
    final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable);
    assertThat(allManagedUsers.getContent().stream()
        .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
        .isTrue();
}
 
Example 25
Project: ARCLib   File: SolrStore.java   Source Code and License 5 votes vote down vote up
/**
 * Counts all instances that respect the selected {@link Params}.
 *
 * <p>
 *     Though {@link Params} one could specify filtering. For further explanation
 *     see {@link Params}.
 * </p>
 *
 * @param params Parameters to comply with
 * @return Total number of instances
 */
default Long count(Params params) {
    SimpleQuery query = new SimpleQuery();
    query.addCriteria(typeCriteria());
    query.addSort(new Sort(new Sort.Order(Sort.Direction.valueOf(params.getOrder().toString()), params.getSort())));
    query.addProjectionOnField("id");
    query.setPageRequest(new PageRequest(params.getPage(), params.getPageSize()));
    query.addFilterQuery(new SimpleFilterQuery(buildFilters(params)));

    Page<U> page = getTemplate().query(query, getUType());
    return page.getTotalElements();
}
 
Example 26
Project: uckefu   File: UserController.java   Source Code and License 5 votes vote down vote up
@RequestMapping("/fans/list/{userid}")
@Menu(type = "apps" , subtype = "user" , access = true)
public ModelAndView fanslist(HttpServletRequest request , HttpServletResponse response, @PathVariable String userid) throws Exception {
	ModelAndView view = request(super.createAppsTempletResponse("/apps/user/fans")) ; 
	Pageable page = new PageRequest(super.getP(request), super.getPs(request), new Sort(Direction.DESC, "createtime")) ;
	Page<Fans> fansList = fansRes.findByUser(userid, page) ;
	
	List<String> userids = new ArrayList<String>();
	for(Fans fan : fansList){
		userids.add(fan.getCreater()) ;
	}
	if(userids.size()>0){
		view.addObject("fansList",new PageImpl<User>(userRes.findAll(userids), page, fansList.getTotalElements()) ) ;
	}
	
	User curruser = userRes.findById(userid) ;
	if(super.getUser(request).isLogin()){
		view.addObject("fan" , fansRes.findByUserAndCreater(userid , super.getUser(request).getId())) ;
	}
	view.addObject("curruser", curruser) ;
	
	view.addObject("follows", fansRes.countByCreater(userid)) ;
	
	view.addObject("fans", fansRes.countByUser(userid)) ;
	
    return view ;
}
 
Example 27
Project: fat-lining   File: WeightMeasurementsController.java   Source Code and License 5 votes vote down vote up
@GetMapping("all")
public String all(@RequestParam(value = "page", defaultValue = "0") int pageNumber, Model model) {
	if (pageNumber < 0) {
		return "redirect:/measurements/all?page=0";
	} else {
		Page<WeightMeasurement> page = measurementsManager.findAsPageDesc(pageNumber, paginationConfig.getPageSize());
		if (pageNumber >= page.getTotalPages() && page.getTotalElements() > 0) {
			return "redirect:/measurements/all?page=0";
		} else {
			model.addAttribute(FatLiningConstants.FIELD_PAGE, pageWrapperFactory.create(page));
			return FatLiningConstants.VIEW_MEASUREMENTS;
		}
	}
}
 
Example 28
Project: apollo-custom   File: ReleaseHistoryController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/apps/{appId}/clusters/{clusterName}/namespaces/{namespaceName}/releases/histories",
    method = RequestMethod.GET)
public PageDTO<ReleaseHistoryDTO> findReleaseHistoriesByNamespace(
    @PathVariable String appId, @PathVariable String clusterName,
    @PathVariable String namespaceName,
    Pageable pageable) {

  Page<ReleaseHistory> result = releaseHistoryService.findReleaseHistoriesByNamespace(appId, clusterName,
                                                                                      namespaceName, pageable);
  return transform2PageDTO(result, pageable);
}
 
Example 29
Project: apollo-custom   File: ReleaseHistoryController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/releases/histories/by_previous_release_id_and_operation", method = RequestMethod.GET)
public PageDTO<ReleaseHistoryDTO> findReleaseHistoryByPreviousReleaseIdAndOperation(
    @RequestParam("previousReleaseId") long previousReleaseId,
    @RequestParam("operation") int operation,
    Pageable pageable) {

  Page<ReleaseHistory> result = releaseHistoryService.findByPreviousReleaseIdAndOperation(previousReleaseId, operation, pageable);

  return transform2PageDTO(result, pageable);

}
 
Example 30
Project: c4sg-services   File: OrganizationController.java   Source Code and License 5 votes vote down vote up
@CrossOrigin
@RequestMapping(value = "/search", produces = { "application/json" }, method = RequestMethod.GET)
@ApiOperation(value = "Find organization by keyWord", notes = " Returns a list of organizations which has the keyword in name / description / country, AND, which has the opportunities open, AND, which is located in the selected country. The search result is sorted by organization name in ascending order.")
public Page<OrganizationDTO> getOrganizations (
		@ApiParam(value = "Keyword in Name or description or country of organization to return", required = false) @RequestParam(required = false) String keyWord,
		@ApiParam(value = "Countries of organization to return", required = false) @RequestParam(required = false) List<String> countries,
		@ApiParam(value = "Opportunities open in the organization", required = false) @RequestParam(required = false) Boolean open,
		@ApiParam(value = "Status of the organization to return", required = false) @Pattern(regexp="[ADPNC]") @RequestParam(required = false) String status,
		@ApiParam(value = "Category of the organization to return", required = false) @ListEntry @RequestParam(required = false) List<String> category,
	    @ApiParam(value = "Results page you want to retrieve (0..N)",required=false) @RequestParam(required=false) Integer page,
	    @ApiParam(value = "Number of records per page", required=false) @RequestParam(required=false) Integer size)	{
	
   	System.out.println("************** OrganizationController.getOrganizations()" 
               + ": keyWord=" + keyWord 
               + "; countries=" + countries 
               + "; open=" + open 
               + "; status=" + status 
               + "; category=" + category 
               + "; page=" + page 
               + "; size=" + size                 
               + " **************");
   	
	try {
		return organizationService.findByCriteria(keyWord, countries, open, status, category,page,size);
	} catch (Exception e) {
		throw new BadRequestException(e.getMessage());
	}
}
 
Example 31
Project: bootstrap   File: PaginationDaoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Default find all, empty rules, with fetch.
 */
@Test
public void testFindAllWithFetchMany() {
	final List<UIRule> rulesGroupOr = new ArrayList<>();
	final SystemDialect dialect = em.find(SystemDialect.class, lastKnownEntity);
	dialect.setLink(dialect);
	em.flush();

	final BasicRule ruleEQ = new BasicRule();
	ruleEQ.setData(String.valueOf(lastKnownEntity));
	ruleEQ.setField("link.linkImplicitId");
	ruleEQ.setOp(RuleOperator.EQ);
	rulesGroupOr.add(ruleEQ);

	final BasicRule ruleNE = new BasicRule();
	ruleNE.setData(String.valueOf(lastKnownEntity));
	ruleNE.setField("children.dialLong");
	ruleNE.setOp(RuleOperator.EQ);
	rulesGroupOr.add(ruleNE);

	final UiPageRequest uiPageRequest = newOr10();
	uiPageRequest.getUiFilter().setRules(rulesGroupOr);

	final Map<String, String> mapping = new HashMap<>();
	mapping.put("link", "link.id");
	mapping.put("link.linkImplicitId", "link.link");
	mapping.put("children.dialLong", "children.dialLong");
	mapping.put("A.link", "A.link.id");

	final Map<String, JoinType> fetchs = new LinkedHashMap<>();
	fetchs.put("link", JoinType.LEFT);
	fetchs.put("link.link", JoinType.LEFT);
	fetchs.put("linkedChildren.link", JoinType.LEFT);

	final Page<SystemDialect> findAll = paginationDao.findAll(SystemDialect.class, uiPageRequest, mapping, null, fetchs);
	Assert.assertTrue(findAll.hasContent());
	Assert.assertEquals(1, findAll.getContent().size());
	Assert.assertEquals(Integer.valueOf(lastKnownEntity), findAll.getContent().get(0).getId());
}
 
Example 32
Project: ingest-core   File: SubmissionController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(path = "/submissionEnvelopes/{sub_id}/analyses", method = RequestMethod.GET)
ResponseEntity<?> getAnalyses(@PathVariable("sub_id") SubmissionEnvelope submissionEnvelope,
                              Pageable pageable,
                              final PersistentEntityResourceAssembler resourceAssembler) {
    Page<Analysis> analyses = getAnalysisRepository().findBySubmissionEnvelopesIn(submissionEnvelope, pageable);
    return ResponseEntity.ok(getPagedResourcesAssembler().toResource(analyses, resourceAssembler));
}
 
Example 33
Project: alittler-blog   File: UserRestController.java   Source Code and License 5 votes vote down vote up
@GetMapping("/list")
public List<User> list(@RequestParam(value = "name", required = false, defaultValue = "") String name,
		@RequestParam(value = "pageIndex", required = false, defaultValue = "0") int pageIndex,
		@RequestParam(value = "pageSize", required = false, defaultValue = "10") int pageSize) {

	Pageable pageable = new PageRequest(pageIndex, pageSize);
	Page<User> page = userRepository.findByNameLike(name, pageable);

	return page.getContent();
}
 
Example 34
Project: webcron   File: Users.java   Source Code and License 5 votes vote down vote up
/**
 * @param limit {@link Integer}
 * @param page  {@link Integer}
 * @return {@link Page<UserDTO>}
 */
public Page<UserDTO> listUsers(Integer limit, Integer page) {
    Page<UserEntity> usersPage = userRepository.findAll(new PageRequest(page, limit));
    return usersPage.map(source -> UserDTO.builder()
            .id(source.getId())
            .name(source.getName())
            .username(source.getUsername())
            .email(source.getEmail())
            .roles(source.getRoles())
            .status(source.getStatus())
            .created(source.getCreated())
            .modified(source.getModified())
            .build());
}
 
Example 35
Project: nixmash-blog   File: CustomProductRepositoryImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<Product> searchWithCriteria(String searchTerm) {
	logger.debug("Building a product criteria query with search term: {}", searchTerm);

	String[] words = searchTerm.split(" ");

	Criteria conditions = createSearchConditions(words);
	SimpleQuery search = new SimpleQuery(conditions);
	search.addSort(sortByIdDesc());

	Page<Product> results = solrTemplate.queryForPage(search, Product.class);
	return results.getContent();
}
 
Example 36
Project: qualitoast   File: CampagneResource.java   Source Code and License 5 votes vote down vote up
/**
 * GET  /campagnes : get all the campagnes.
 *
 * @param pageable the pagination information
 * @return the ResponseEntity with status 200 (OK) and the list of campagnes in body
 */
@GetMapping("/campagnes")
@Timed
public ResponseEntity<List<Campagne>> getAllCampagnes(Pageable pageable) {
    log.debug("REST request to get a page of Campagnes");
    Page<Campagne> page = campagneService.findAll(pageable);
    HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/campagnes");
    return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
 
Example 37
Project: devops-cstack   File: MessageServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public List<Message> listByUserNoLimitRows(User user)
        throws ServiceException {
    try {
        Pageable pageable = new PageRequest(0, 500, sortByLastNameAsc());
        Page<Message> requestedPage = messageDAO.listByUserAndCuInstance(user, cuInstanceName, pageable);
        return requestedPage.getContent();
    } catch (PersistenceException e) {
        throw new ServiceException(e.getLocalizedMessage(), e);
    }
}
 
Example 38
Project: OperatieBRP   File: PartijController.java   Source Code and License 5 votes vote down vote up
/**
 * Haal een lijst van partijrollen op.
 * @param id id van actie
 * @param parameters request parameters
 * @param pageable paginering
 * @return lijst van partijrol (inclusief paginering en sortering)
 */
@RequestMapping(value = "/{id}/partijrollen", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public final Page<PartijRol> listPartijRol(
        @PathVariable(value = "id") final String id,
        @RequestParam final Map<String, String> parameters,
        @PageableDefault(size = 10) @SortDefault(sort = "datumIngang", direction = Sort.Direction.ASC) final Pageable pageable) {
    parameters.put("partij", id);
    return partijRolController.list(parameters, pageable);
}
 
Example 39
Project: spring-io   File: SubCategoryService.java   Source Code and License 5 votes vote down vote up
/**
 *  Get all the subCategories.
 *  
 *  @param pageable the pagination information
 *  @return the list of entities
 */
@Transactional(readOnly = true)
public Page<SubCategory> findAll(Pageable pageable) {
    log.debug("Request to get all SubCategories");
    Page<SubCategory> result = subCategoryRepository.findAll(pageable);
    return result;
}
 
Example 40
Project: bootstrap   File: PaginationDaoTest.java   Source Code and License 5 votes vote down vote up
/**
 * Default find all, empty rules, with fetch.
 */
@Test
public void testFindAllWithFetchAndJoin() {
	final List<UIRule> rulesGroup = new ArrayList<>();
	final SystemDialect dialect = em.find(SystemDialect.class, lastKnownEntity);
	dialect.setLink(dialect);
	SystemUser user = new SystemUser();
	user.setLogin("anonymous");
	em.persist(user);
	dialect.setUser(user);
	em.flush();

	final BasicRule ruleEQ = new BasicRule();
	ruleEQ.setField("user");
	ruleEQ.setData("anonymous");
	ruleEQ.setOp(RuleOperator.EQ);
	rulesGroup.add(ruleEQ);

	final UiPageRequest uiPageRequest = newAnd();
	uiPageRequest.getUiFilter().setRules(rulesGroup);
	uiPageRequest.setPageSize(10);
	final Map<String, String> mapping = new HashMap<>();
	mapping.put("user", "link.user.login");

	final Map<String, JoinType> fetchs = new LinkedHashMap<>();
	fetchs.put("link.user", JoinType.INNER);
	final Page<SystemDialect> findAll = paginationDao.findAll(SystemDialect.class, uiPageRequest, mapping, null, fetchs);
	Assert.assertTrue(findAll.hasContent());
	Assert.assertEquals(1, findAll.getContent().size());
	Assert.assertEquals(Integer.valueOf(lastKnownEntity), findAll.getContent().get(0).getId());
}