org.springframework.data.domain.PageRequest Java Examples

The following examples show how to use org.springframework.data.domain.PageRequest. 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: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 8 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Page<QuickReply> getByCon(BoolQueryBuilder boolQueryBuilder, final int p , final int ps) {

	Page<QuickReply> pages  = null ;
	
	QueryBuilder beginFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("begintime")).should(QueryBuilders.rangeQuery("begintime").from(new Date().getTime())) ;
	QueryBuilder endFilter = QueryBuilders.boolQuery().should(QueryBuilders.missingQuery("endtime")).should(QueryBuilders.rangeQuery("endtime").to(new Date().getTime())) ;
	
    NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withFilter(QueryBuilders.boolQuery().must(beginFilter).must(endFilter)).withSort(new FieldSortBuilder("createtime").unmappedType("date").order(SortOrder.DESC));
    
    SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(p, ps)) ;
    if(elasticsearchTemplate.indexExists(QuickReply.class)){
    	pages = elasticsearchTemplate.queryForPage(searchQuery, QuickReply.class);
    }
    return pages ; 
}
 
Example #2
Source File: ModuleConfigDao.java    From jvm-sandbox-repeater with Apache License 2.0 8 votes vote down vote up
public Page<ModuleConfig> selectByParams(@NotNull final ModuleConfigParams params) {
    Pageable pageable = new PageRequest(params.getPage() - 1, params.getSize(), new Sort(Sort.Direction.DESC, "id"));
    return moduleConfigRepository.findAll(
            (root, query, cb) -> {
                List<Predicate> predicates = Lists.newArrayList();
                if (params.getAppName() != null && !params.getAppName().isEmpty()) {
                    predicates.add(cb.equal(root.<String>get("appName"), params.getAppName()));
                }
                if (params.getEnvironment() != null && !params.getEnvironment().isEmpty()) {
                    predicates.add(cb.equal(root.<String>get("environment"), params.getEnvironment()));
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            },
            pageable
    );
}
 
Example #3
Source File: QuickReplyRepositoryImpl.java    From youkefu with Apache License 2.0 7 votes vote down vote up
@Override
public List<QuickReply> getQuickReplyByOrgi(String orgi , String cate,String type, String q) {
	
	List<QuickReply> list  = null ;
	
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	boolQueryBuilder.must(termQuery("orgi" , orgi)) ;
	
	if(!StringUtils.isBlank(cate)){
		boolQueryBuilder.must(termQuery("cate" , cate)) ;
	}
	if(!StringUtils.isBlank(type)){
		boolQueryBuilder.must(termQuery("type" , type)) ;
	}
    if(!StringUtils.isBlank(q)){
    	boolQueryBuilder.must(new QueryStringQueryBuilder(q).defaultOperator(Operator.AND)) ;
    }
	
	NativeSearchQueryBuilder searchQueryBuilder = new NativeSearchQueryBuilder().withQuery(boolQueryBuilder).withSort(new FieldSortBuilder("top").unmappedType("boolean").order(SortOrder.DESC)).withSort(new FieldSortBuilder("updatetime").unmappedType("date").order(SortOrder.DESC));
	SearchQuery searchQuery = searchQueryBuilder.build().setPageable(new PageRequest(0, 10000));
	if(elasticsearchTemplate.indexExists(QuickReply.class)){
		list = elasticsearchTemplate.queryForList(searchQuery, QuickReply.class);
    }
    return list ; 
}
 
Example #4
Source File: PersonRepositoryTest.java    From spring-boot-demo with MIT License 6 votes vote down vote up
/**
 * 自定义高级查询
 */
@Test
public void customAdvanceSelect() {
    // 构造查询条件
    NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
    // 添加基本的分词条件
    queryBuilder.withQuery(QueryBuilders.matchQuery("remark", "东汉"));
    // 排序条件
    queryBuilder.withSort(SortBuilders.fieldSort("age").order(SortOrder.DESC));
    // 分页条件
    queryBuilder.withPageable(PageRequest.of(0, 2));
    Page<Person> people = repo.search(queryBuilder.build());
    log.info("【people】总条数 = {}", people.getTotalElements());
    log.info("【people】总页数 = {}", people.getTotalPages());
    people.forEach(person -> log.info("【person】= {},年龄 = {}", person.getName(), person.getAge()));
}
 
Example #5
Source File: AdminController.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
/**
 * 用户查询.
 *
 * @return
 */
@RequestMapping("/list")
@RequiresPermissions("admin:view")//权限管理;
public ModelAndView userInfo(@RequestParam(value = "start", defaultValue = "0") Integer start,
                             @RequestParam(value = "limit", defaultValue = "5") Integer limit) {
    start = start < 0 ? 0 : start;
    Sort sort = Sort.by(Sort.Order.desc("uid"));
    Pageable pageable = new PageRequest(start, limit, sort);

    Page<Admin> page = adminDao.findAll(pageable);
    //session 由controller 注入参数传入
    Admin adminprincipal = (Admin) SecurityUtils.getSubject().getPrincipal();
    //String loginName = (String) SecurityUtils.getSubject().getPrincipal();
    ModelAndView modelAndView = new ModelAndView("list");
    modelAndView.addObject("page", page);
    modelAndView.addObject("name", adminprincipal.getName());
    modelAndView.addObject("Username", adminprincipal.getUsername());
    modelAndView.addObject("RoleList", adminprincipal.getRoleList());
    return modelAndView;
}
 
Example #6
Source File: CommonQueryService.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
public <T> CommonResponse getPageListByCommonReq(CommonBiParaQueryPageReq<String> req,
        JpaSpecificationExecutor<T> repository) {
    PageRequest pr = (PageRequest) req.convert();
    try {
        if (StringUtils.isEmpty(req.getReqParaValue1()) || StringUtils.isEmpty(req.getReqParaName1())) {
            return ResponseUtils.paramError("para1 should not be empty");
        }
        if (StringUtils.isEmpty(req.getReqParaValue2()) || StringUtils.isEmpty(req.getReqParaName2())) {
            CommonParaQueryPageReq<String> uniReq = new CommonParaQueryPageReq<>();
            BeanUtil.copyProperties(req, uniReq);
            uniReq.setReqParaName(req.getReqParaName1()).setReqParaValue(req.getReqParaValue1());
            return getPageListByCommonReq(uniReq, repository);
        }
        Specification<T> spec = CommonReqParaSpecification.queryByCriteriaEqual(req);
        Page<T> page = repository.findAll(spec, pr);
        CommonPageRes<T> ret = new CommonPageRes<>(req);
        ret.setResult(page.getContent()).setTotalCount(page.getTotalElements()).setPageNo(req.getPageNo())
                .setPageSize(req.getPageSize());
        return ResponseUtils.data(ret);
    } catch (DateException e) {
        return ResponseUtils.paramError("invalid date format " + e.getMessage());
    }
}
 
Example #7
Source File: ByPageTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 分页查询+排序
 */
public void searchByPageAndSort() {
    // 分页:
    int page = 0;
    int size = 5;//每页文档数

    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富"));
    // 搜索,获取结果
    nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size));
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
    for (Product product : products) {
        System.out.println(product);
    }

}
 
Example #8
Source File: ByPageTest.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@Test
/**
 * Description: 分页查询+排序
 */
public void searchByPageAndSort() {
    // 分页:
    int page = 0;
    int size = 5;//每页文档数

    // 构建查询条件
    NativeSearchQueryBuilder nativeSearchQueryBuilderQueryBuilder = new NativeSearchQueryBuilder();
    // 查询词,只能查询一个汉字,或者一个英文单词
    nativeSearchQueryBuilderQueryBuilder.withQuery(QueryBuilders.termQuery("name", "富"));
    // 搜索,获取结果
    nativeSearchQueryBuilderQueryBuilder.withSort(SortBuilders.fieldSort("id").order(SortOrder.DESC));
    nativeSearchQueryBuilderQueryBuilder.withPageable(PageRequest.of(page, size));
    Page<Product> products = productRepository.search(nativeSearchQueryBuilderQueryBuilder.build());
    // 总条数
    for (Product product : products) {
        System.out.println(product);
    }

}
 
Example #9
Source File: RequestLogController.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/requestlog")
    public ModelAndView userlist(@RequestParam(value = "start", defaultValue = "0") Integer start,
                                 @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        start = start < 0 ? 0 : start;
// Sort sort = new Sort(Sort.DEFAULT_DIRECTION, "categoryid","desc");
        Sort sort = new Sort(Sort.Direction.DESC, "id");
// Pageable pageable = new PageRequest(start, limit, sort);
        Pageable pageable = PageRequest.of(start, limit, sort);

        Page<RequestLog> page = requestLogRepository.findAll(pageable);

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//已经拿到session,就可以拿到session中保存的用户信息了。
        System.out.println(request.getSession().getId());
        System.out.println(onlineNum);

        ModelAndView mav = new ModelAndView("systom/log/RequestLog");
        mav.addObject("page", page);
        return mav;
    }
 
Example #10
Source File: ContactsController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/expall")
  @Menu(type = "contacts" , subtype = "contacts")
  public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response) throws IOException {
  	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  	boolQueryBuilder.must(termQuery("datastatus" , false)) ;		//只导出 数据删除状态 为 未删除的 数据
  	Iterable<Contacts> contactsList = contactsRes.findByCreaterAndSharesAndOrgi(super.getUser(request).getId(), super.getUser(request).getId(), super.getOrgi(request),null , null , false, boolQueryBuilder , null , new PageRequest(super.getP(request) , super.getPs(request)));
  	
  	MetadataTable table = metadataRes.findByTablename("uk_contacts") ;
List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
for(Contacts contacts : contactsList){
	values.add(UKTools.transBean2Map(contacts)) ;
}

response.setHeader("content-disposition", "attachment;filename=UCKeFu-Contacts-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  

ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
excelProcess.process();
      return ;
  }
 
Example #11
Source File: MemberTransactionService.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
public Page<MemberTransaction> queryByMember(Long uid, Integer pageNo, Integer pageSize,TransactionType type,String startDate,String endDate,String symbol) throws ParseException {
    //排序方式 (需要倒序 这样    Criteria.sort("id","createTime.desc") ) //参数实体类为字段名
    Sort orders = Criteria.sortStatic("createTime.desc");
    //分页参数
    PageRequest pageRequest = new PageRequest(pageNo-1, pageSize, orders);
    //查询条件
    Criteria<MemberTransaction> specification = new Criteria<MemberTransaction>();
    specification.add(Restrictions.eq("memberId", uid, false));
    if(type != null){
        specification.add(Restrictions.eq("type",type,false));
    }
    if(StringUtils.isNotBlank(startDate) && StringUtils.isNotBlank(endDate)){
        specification.add(Restrictions.gte("createTime",DateUtil.YYYY_MM_DD_MM_HH_SS.parse(startDate+" 00:00:00"),false));
        specification.add(Restrictions.lte("createTime",DateUtil.YYYY_MM_DD_MM_HH_SS.parse(endDate+" 23:59:59"),false));
    }
    if(StringUtils.isNotEmpty(symbol)){
        specification.add(Restrictions.eq("symbol",symbol,false));
    }
    return transactionDao.findAll(specification, pageRequest);
}
 
Example #12
Source File: AgentController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/summary/edit/save")  
@Menu(type = "apps", subtype = "summarysave")
   public ModelAndView saveEditSummary(ModelMap map , HttpServletRequest request , @Valid AgentServiceSummary summary , @Valid String contactsid, @Valid String userid , @Valid String agentserviceid, @Valid String agentuserid ,HttpServletResponse response , @Valid String sort){ 
	if(!StringUtils.isBlank(summary.getId())){
		summary.setOrgi(super.getOrgi(request));
		summary.setCreater(super.getUser(request).getId());
		summary.setCreatetime(new Date());
		summary.setChannel(UKDataContext.ChannelTypeEnum.PHONE.toString());
		serviceSummaryRes.save(summary) ;
		map.addAttribute("contactsid", contactsid);
		map.addAttribute("userid", userid);
		map.addAttribute("contactsid", contactsid);
		map.addAttribute("agentserviceid", agentserviceid);
		map.addAttribute("agentuserid", agentuserid);
	}
	this.getCuragentuser(map, request, response, sort);
	Page<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndUserid(super.getOrgi(request), userid , new PageRequest(0, super.getPs(request), Sort.Direction.DESC, new String[] { "createtime" }));
	//Page<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndAgentserviceid(super.getOrgi(request), agentserviceid,new PageRequest(0, super.getPs(request), Sort.Direction.DESC, new String[] { "createtime" }));
	map.addAttribute("summaryList", summaryList) ;
	map.addAttribute("tagsSummary", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.SUMMARY.toString())) ;
	return request(super.createRequestPageTempletResponse("/apps/agent/summarylist"));
   }
 
Example #13
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 #14
Source File: ConfigService.java    From runscore with Apache License 2.0 6 votes vote down vote up
@Transactional(readOnly = true)
public PageResult<ConfigItemVO> findConfigItemByPage(ConfigItemQueryCondParam param) {
	Specification<ConfigItem> spec = new Specification<ConfigItem>() {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;

		public Predicate toPredicate(Root<ConfigItem> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
			List<Predicate> predicates = new ArrayList<Predicate>();
			if (StrUtil.isNotBlank(param.getConfigCode())) {
				predicates.add(builder.like(root.get("configCode"), "%" + param.getConfigCode() + "%"));
			}
			if (StrUtil.isNotBlank(param.getConfigName())) {
				predicates.add(builder.like(root.get("configName"), "%" + param.getConfigName() + "%"));
			}
			return predicates.size() > 0 ? builder.and(predicates.toArray(new Predicate[predicates.size()])) : null;
		}
	};
	Page<ConfigItem> result = configItemRepo.findAll(spec,
			PageRequest.of(param.getPageNum() - 1, param.getPageSize(), Sort.by(Sort.Order.desc("configCode"))));
	PageResult<ConfigItemVO> pageResult = new PageResult<>(ConfigItemVO.convertFor(result.getContent()),
			param.getPageNum(), param.getPageSize(), result.getTotalElements());
	return pageResult;
}
 
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: NoticeMsgBusinessController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/index")
@Menu(type = "notice", subtype = "noticemsgbus")
public ModelAndView index(ModelMap map , HttpServletRequest request ,HttpServletResponse response ,@Valid String msg) {
	final String orgi = super.getOrgi(request);
	final User user = super.getUser(request) ;
	Page<NoticeMsg> noticeMsgList = noticeMsgRes.findAll(new Specification<NoticeMsg>(){
		@Override
		public Predicate toPredicate(Root<NoticeMsg> root, CriteriaQuery<?> query,CriteriaBuilder cb) {
			List<Predicate> list = new ArrayList<Predicate>();  

			list.add(cb.equal(root.get("orgi").as(String.class), orgi));
			list.add(cb.equal(root.get("target").as(String.class), user.getId()));
			list.add(cb.equal(root.get("type").as(String.class), UKDataContext.NoticeType.BUSINESS.toString()));
			list.add(cb.equal(root.get("datastatus").as(boolean.class), false));
			
			Predicate[] p = new Predicate[list.size()];  
			return cb.and(list.toArray(p));   
		}}, new PageRequest(super.getP(request), super.getPs(request), Sort.Direction.DESC, new String[] { "createtime" }));
	
	
	map.addAttribute("noticeMsgList",noticeMsgList) ;
	map.addAttribute("msg",msg) ;
	map.addAttribute("type",UKDataContext.NoticeType.BUSINESS.toString()) ;
	return request(super.createAppsTempletResponse("/apps/notice/msg/index")) ;
}
 
Example #17
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 #18
Source File: TimeRangeQueryService.java    From WeBASE-Collect-Bee with Apache License 2.0 6 votes vote down vote up
/**
 * page query by a time range.
 * 
 * @param req
 * @param repository
 * @return
 */
public <T> CommonResponse getPageListByTimeRange(TimeRangeQueryReq req, JpaSpecificationExecutor<T> repository) {
    CommonTimeCondition condition = new CommonTimeCondition();
    try {
        condition.setBeginTime(DateUtil.parse(req.getBeginTime())).setEndTime(DateUtil.parse(req.getEndTime()));
    } catch (DateException e) {
        log.error("DateUtil convert error: {}", e.getMessage());
        return ResponseUtils.paramError("invalid time format, " + e.getMessage());
    }
    int pageNo = req.getPageNo();
    int pageSize = req.getPageSize();
    PageRequest pr = (PageRequest) req.convert();
    Specification<T> spec = TimeSpecification.queryByCriteria(condition);
    Page<T> page = repository.findAll(spec, pr);
    CommonPageRes<T> ret = new CommonPageRes<>(req);
    ret.setResult(page.getContent()).setTotalCount(page.getTotalElements()).setPageNo(req.getPageNo())
            .setPageSize(req.getPageSize());
    return ResponseUtils.data(ret);
}
 
Example #19
Source File: FrontTagController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 根据标签路径查询所有文章 分页
 *
 * @param model  model
 * @param tagUrl 标签路径
 * @param page   页码
 *
 * @return String
 */
@GetMapping(value = "{tagUrl}/page/{page}")
public String tags(Model model,
                   @PathVariable("tagUrl") String tagUrl,
                   @PathVariable("page") Integer page) {
    final Tag tag = tagService.findByTagUrl(tagUrl);
    if (null == tag) {
        return this.renderNotFound();
    }
    final Sort sort = new Sort(Sort.Direction.DESC, "postDate");
    int size = 10;
    if (StrUtil.isNotBlank(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()))) {
        size = Integer.parseInt(HaloConst.OPTIONS.get(BlogPropertiesEnum.INDEX_POSTS.getProp()));
    }
    final Pageable pageable = PageRequest.of(page - 1, size, sort);
    final Page<Post> posts = postService.findPostsByTags(tag, pageable);
    final int[] rainbow = PageUtil.rainbow(page, posts.getTotalPages(), 3);
    model.addAttribute("is_tags", true);
    model.addAttribute("posts", posts);
    model.addAttribute("rainbow", rainbow);
    model.addAttribute("tag", tag);
    return this.render("tag");
}
 
Example #20
Source File: AccountRepoTest.java    From staffjoy with MIT License 6 votes vote down vote up
@Test
public void listAccount() {
    Pageable pageRequest = PageRequest.of(0, 2);
    // test empty
    Page<Account> accounts = accountRepo.findAll(pageRequest);
    assertEquals(0, accounts.getTotalElements());

    // create 1 new
    accountRepo.save(newAccount);
    assertEquals(1, accountRepo.count());

    // create 2 more
    newAccount.setId(null);
    accountRepo.save(newAccount);
    assertEquals(2, accountRepo.count());
    newAccount.setId(null);
    accountRepo.save(newAccount);
    assertEquals(3, accountRepo.count());
    accounts = accountRepo.findAll(pageRequest);
    assertEquals(2, accounts.getNumberOfElements());
    pageRequest = pageRequest.next();
    accounts = accountRepo.findAll(pageRequest);
    assertEquals(1, accounts.getNumberOfElements());
    assertEquals(2, accounts.getTotalPages());
    assertEquals(3, accounts.getTotalElements());
}
 
Example #21
Source File: AgentSummaryController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/expall")
  @Menu(type = "agent" , subtype = "agentsummary" , access = false)
  public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response) throws IOException {
  	Iterable<AgentServiceSummary> statusEventList = serviceSummaryRes.findByChannelNotAndOrgi(UKDataContext.ChannelTypeEnum.PHONE.toString() , super.getOrgi(request) , new PageRequest(0, 10000));
  	
  	MetadataTable table = metadataRes.findByTablename("uk_servicesummary") ;
List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
for(AgentServiceSummary statusEvent : statusEventList){
	values.add(UKTools.transBean2Map(statusEvent)) ;
}

response.setHeader("content-disposition", "attachment;filename=UCKeFu-Summary-History-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  

ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
excelProcess.process();
      return ;
  }
 
Example #22
Source File: RecordDao.java    From jvm-sandbox-repeater with Apache License 2.0 6 votes vote down vote up
public Page<Record> selectByAppNameOrTraceId(@NotNull final RecordParams params) {
    Pageable pageable = new PageRequest(params.getPage() - 1, params.getSize(), new Sort(Sort.Direction.DESC,"id"));
    return recordRepository.findAll(
            (root, query, cb) -> {
                List<Predicate> predicates = Lists.newArrayList();
                if (params.getAppName() != null && !params.getAppName().isEmpty()) {
                    predicates.add(cb.equal(root.<String>get("appName"), params.getAppName()));
                }
                if (params.getTraceId() != null && !params.getTraceId().isEmpty()) {
                    predicates.add(cb.equal(root.<String>get("traceId"), params.getTraceId()));
                }
                return cb.and(predicates.toArray(new Predicate[0]));
            },
            pageable
    );
}
 
Example #23
Source File: ExchangeOrderService.java    From ZTuoExchange_framework with MIT License 6 votes vote down vote up
/**
 * 个人中心当前委托
 *
 * @param uid
 * @param symbol
 * @param type
 * @param startTime
 * @param endTime
 * @param pageNo
 * @param pageSize
 * @return
 */
public Page<ExchangeOrder> findPersonalCurrent(Long uid, String symbol, ExchangeOrderType type, String startTime, String endTime, ExchangeOrderDirection direction, int pageNo, int pageSize) {
    Sort orders = new Sort(new Sort.Order(Sort.Direction.DESC, "time"));
    PageRequest pageRequest = new PageRequest(pageNo - 1, pageSize, orders);
    Criteria<ExchangeOrder> specification = new Criteria<ExchangeOrder>();
    if(StringUtils.isNotEmpty(symbol)){
        specification.add(Restrictions.eq("symbol", symbol, true));
    }
    if(type!=null&&StringUtils.isNotEmpty(type.toString())){
        specification.add(Restrictions.eq("type", type, true));
    }
    specification.add(Restrictions.eq("memberId", uid, false));
    if (StringUtils.isNotEmpty(startTime)&&StringUtils.isNotEmpty(endTime) ) {
        specification.add(Restrictions.gte("time", Long.valueOf(startTime), true));
        specification.add(Restrictions.lte("time", Long.valueOf(endTime), true));
    }
    if(direction!=null&&StringUtils.isNotEmpty(direction.toString())){
        specification.add(Restrictions.eq("direction", direction, true));
    }
    specification.add(Restrictions.eq("status", ExchangeOrderStatus.TRADING, false));
    return exchangeOrderRepository.findAll(specification, pageRequest);
}
 
Example #24
Source File: CustomerController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/expall")
  @Menu(type = "customer" , subtype = "customer")
  public void expall(ModelMap map , HttpServletRequest request , HttpServletResponse response) throws IOException {
  	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
  	boolQueryBuilder.must(termQuery("datastatus" , false)) ;		//只导出 数据删除状态 为 未删除的 数据
  	Iterable<EntCustomer> entCustomerList = entCustomerRes.findByCreaterAndSharesAndOrgi(super.getUser(request).getId(), super.getUser(request).getId(),super.getOrgi(request), null , null , false, boolQueryBuilder , null , new PageRequest(super.getP(request) , 10000));
  	
  	MetadataTable table = metadataRes.findByTablename("uk_entcustomer") ;
List<Map<String,Object>> values = new ArrayList<Map<String,Object>>();
for(EntCustomer customer : entCustomerList){
	values.add(UKTools.transBean2Map(customer)) ;
}

response.setHeader("content-disposition", "attachment;filename=UCKeFu-EntCustomer-"+new SimpleDateFormat("yyyy-MM-dd").format(new Date())+".xls");  

ExcelExporterProcess excelProcess = new ExcelExporterProcess( values, table, response.getOutputStream()) ;
excelProcess.process();
      return ;
  }
 
Example #25
Source File: OnlineUserController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
@RequestMapping("/online/chatmsg")
  @Menu(type = "service" , subtype = "chatmsg" , admin= true)
  public ModelAndView onlinechat(ModelMap map , HttpServletRequest request , String id , String title) {
AgentService agentService = agentServiceRes.getOne(id) ; 
AgentUser curragentuser = agentUserRes.findByUseridAndOrgi(agentService.getUserid(), super.getOrgi(request)) ;

map.put("curAgentService", agentService) ;
map.put("curagentuser", curragentuser) ;
if(!StringUtils.isBlank(title)){
	map.put("title", title) ;
}

map.addAttribute("tagsSummary", tagRes.findByOrgiAndTagtype(super.getOrgi(request) , UKDataContext.ModelType.SUMMARY.toString())) ;
if(agentService!=null){
	Page<AgentServiceSummary> summaryList = this.serviceSummaryRes.findByOrgiAndUserid(super.getOrgi(request), agentService.getUserid() , new PageRequest(0, super.getPs(request), Sort.Direction.DESC, new String[] { "createtime" }));
	map.addAttribute("summaryList", summaryList) ;
}

map.put("agentUserMessageList", chatMessageRepository.findByAgentserviceidAndOrgi(agentService.getId() , super.getOrgi(request), new PageRequest(0, 50, Direction.DESC , "updatetime")));

      return request(super.createRequestPageTempletResponse("/apps/service/online/chatmsg"));
  }
 
Example #26
Source File: EventController.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@ApiOperation(value = "getNewBlockEventInfo",
        notes = "get registered NewBlockEvent info by page")
@GetMapping(value = {"newBlockEvent/list/{groupId}/{pageNumber}/{pageSize}",
        "newBlockEvent/list/{groupId}"})
public BasePageResponse getNewBlockEventInfo(@PathVariable("groupId") Integer groupId,
                                             @PathVariable(value = "pageNumber", required = false) Integer pageNumber,
                                             @PathVariable(value = "pageSize", required = false) Integer pageSize) {
    log.debug("start getNewBlockEventInfo. groupId:{}", groupId);
    List<NewBlockEventInfo> resList;
    if (pageNumber == null || pageSize == null) {
         resList = eventService.getNewBlockInfoList(groupId);
    } else {
        if (pageNumber < 1) {
            return new BasePageResponse(ConstantCode.PARAM_ERROR, null, 0);
        }
        Pageable pageable = new PageRequest(pageNumber - 1, pageSize,
                new Sort(Sort.Direction.DESC, "createTime"));
        resList = eventService.getNewBlockInfoList(groupId, pageable);
    }
    log.debug("end getNewBlockEventInfo resList count. {}", resList.size());
    return new BasePageResponse(ConstantCode.RET_SUCCESS, resList, resList.size());
}
 
Example #27
Source File: AttachmentController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 跳转选择附件页面
 *
 * @param model model
 * @param page  page 当前页码
 *
 * @return 模板路径admin/widget/_attachment-select
 */
@GetMapping(value = "/select")
public String selectAttachment(Model model,
                               @RequestParam(value = "page", defaultValue = "0") Integer page,
                               @RequestParam(value = "id", defaultValue = "none") String id,
                               @RequestParam(value = "type", defaultValue = "normal") String type) {
    final Sort sort = new Sort(Sort.Direction.DESC, "attachId");
    final Pageable pageable = PageRequest.of(page, 18, sort);
    final Page<Attachment> attachments = attachmentService.findAll(pageable);
    model.addAttribute("attachments", attachments);
    model.addAttribute("id", id);
    if (StrUtil.equals(type, PostTypeEnum.POST_TYPE_POST.getDesc())) {
        return "admin/widget/_attachment-select-post";
    }
    return "admin/widget/_attachment-select";
}
 
Example #28
Source File: UsersResourceController.java    From youkefu with Apache License 2.0 6 votes vote down vote up
/**
 * 获取当前产品下人员信息
 * @param request
 * @param q
 * @return
 */
private Page<User> getUsers(HttpServletRequest request,String q){
	if(q==null){
		q = "" ;
	}
	Page<User> list = null;
   	if(super.isTenantshare()) {
		List<String> organIdList = new ArrayList<>();
		List<OrgiSkillRel> orgiSkillRelList = orgiSkillRelService.findByOrgi(super.getOrgi(request)) ;
		if(!orgiSkillRelList.isEmpty()) {
			for(OrgiSkillRel rel:orgiSkillRelList) {
				organIdList.add(rel.getSkillid());
			}
		}
		list = userRes.findByOrganInAndDatastatusAndUsernameLike(organIdList,false, "%"+q+"%", new PageRequest(0, 10) );
	}else {
		list = userRes.findByDatastatusAndOrgiAndOrgidAndUsernameLike(false,super.getOrgi(request),super.getOrgid(request), "%"+q+"%" , new PageRequest(0, 10)) ;
	}
   	return list;
   }
 
Example #29
Source File: ContactsController.java    From youkefu with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/index")
@Menu(type = "customer" , subtype = "index")
public ModelAndView index(ModelMap map , HttpServletRequest request , @Valid String q , @Valid String ckind) {
	BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
	if(!StringUtils.isBlank(q)){
    	map.put("q", q) ;
    }
	if(!StringUtils.isBlank(ckind)){
		boolQueryBuilder.must(termQuery("ckind" , ckind)) ;
    	map.put("ckind", ckind) ;
    }
	map.addAttribute("contactsList", contactsRes.findByCreaterAndSharesAndOrgi(super.getUser(request).getId(), super.getUser(request).getId(),super.getOrgi(request), null , null , false, boolQueryBuilder ,q , new PageRequest(super.getP(request) , super.getPs(request)))) ;
	
	return request(super.createAppsTempletResponse("/apps/business/contacts/index"));
}
 
Example #30
Source File: UserServiceIT.java    From java-microservices-examples with Apache License 2.0 5 votes vote down vote up
@Test
public void assertThatAnonymousUserIsNotGet() {
    user.setId(Constants.ANONYMOUS_USER);
    user.setLogin(Constants.ANONYMOUS_USER);
    if (!userRepository.findOneByLogin(Constants.ANONYMOUS_USER).isPresent()) {
        userRepository.save(user);
    }
    final PageRequest pageable = PageRequest.of(0, (int) userRepository.count());
    final Page<UserDTO> allManagedUsers = userService.getAllManagedUsers(pageable);
    assertThat(allManagedUsers.getContent().stream()
        .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin())))
        .isTrue();
}