Java Code Examples for org.springframework.data.domain.Page#hasContent()

The following examples show how to use org.springframework.data.domain.Page#hasContent() . 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: DemoCustomerLifecycleBean.java    From Showcase with Apache License 2.0 6 votes vote down vote up
private void createCustomers() {
    Page<Customer> customers = customerBoundaryService.findAllCustomers(new PageRequest(0, 1));

    if (!customers.hasContent()) {
        logger.info("Creating Demo Customers");

        customerBoundaryService.createCustomer(
                "Apple",
                new Address("Apple Street", "1", "12345", "Silicon Valley"));
        customerBoundaryService.createCustomer(
                "Bayer AG",
                new Address("Kaiser-Wilhelm-Allee", "1", "51373", "Leverkusen"));
        customerBoundaryService.createCustomer(
                "Tesa Hamburg",
                new Address("Heykenaukamp", "10", "21147", "Hamburg"));
        customerBoundaryService.createCustomer(
                "NovaTec Consulting GmbH",
                new Address("Dieselstrasse", "18/1", "70771", "Leinfelden-Echterdingen"));
        customerBoundaryService.createCustomer(
                "Daimler AG (Standort Möhringen)",
                new Address("Epplestraße", "225", "70567", "Stuttgart"));
        customerBoundaryService.createCustomer(
                "Continental AG",
                new Address("Vahrenwalder Str.", "9", "30165", "Hannover"));
    }
}
 
Example 2
Source File: CategorySelectController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/{language}/categories/select")
public @ResponseBody List<DomainObjectSelect2Model> select(
		@PathVariable String language,
		@RequestParam(required=false) String keyword) {
	CategorySearchForm form = new CategorySearchForm();
	form.setKeyword(keyword);
	form.setLanguage(language);
	Page<Category> categories = categoryService.getCategories(form.toCategorySearchRequest());

	List<DomainObjectSelect2Model> results = new ArrayList<>();
	if (categories.hasContent()) {
		for (Category category : categories) {
			DomainObjectSelect2Model model = new DomainObjectSelect2Model(category.getId(), category.getName());
			results.add(model);
		}
	}
	return results;
}
 
Example 3
Source File: MessageServiceImpl.java    From sctalk with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public IMGroupMessageEntity getLatestGroupMessage(long groupId) {

    List<? extends IMGroupMessageEntity> messageList = null;

    SearchCriteria<IMGroupMessage> groupMessageSearchCriteria = new SearchCriteria<>();
    groupMessageSearchCriteria.add(JpaRestrictions.eq("groupId", groupId, false));
    groupMessageSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
    Sort sortMessage = new Sort(Sort.Direction.DESC, "created", "id");
    Pageable pageable = new PageRequest(0, 1, sortMessage);
    Page<IMGroupMessage> groupMessageList =
            groupMessageRepository.findAll(groupMessageSearchCriteria, pageable);
    if (groupMessageList.hasContent()) {
        messageList = groupMessageList.getContent();
    }
    
    if (messageList != null && !messageList.isEmpty()) {
        return messageList.get(0);
    }
    return null;
}
 
Example 4
Source File: MessageServiceImpl.java    From sctalk with Apache License 2.0 6 votes vote down vote up
@Override
@Transactional
public IMMessageEntity getLatestMessage(long userId, long toUserId) {
    Long relateId = relationShipService.getRelationId(userId, toUserId, false);

    if (relateId == null || relateId == 0) {
        return null;
    }
    List<? extends IMMessageEntity> messageList = null;
    SearchCriteria<IMMessage> messageSearchCriteria = new SearchCriteria<>();
    messageSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
    messageSearchCriteria.add(JpaRestrictions.eq("relateId", relateId, false));
    Sort sortMessage = new Sort(Sort.Direction.DESC, "created", "id");
    Pageable pageable = new PageRequest(0, 1, sortMessage);
    Page<IMMessage> messagePageList = messageRepository.findAll(messageSearchCriteria, pageable);
    if (messagePageList.hasContent()) {
        messageList = messagePageList.getContent();
    }
    
    if (messageList != null && !messageList.isEmpty()) {
        return messageList.get(0);
    }
    return null;
}
 
Example 5
Source File: PostSelectController.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/{language}/posts/select")
public @ResponseBody List<DomainObjectSelect2Model> select(
		@PathVariable String language,
		@RequestParam(required=false) String keyword) {
	PostSearchRequest request = new PostSearchRequest(language)
			.withStatus(Post.Status.PUBLISHED)
			.withKeyword(keyword);
	Page<Post> posts = postService.getPosts(request, new PageRequest(0, 30));

	List<DomainObjectSelect2Model> results = new ArrayList<>();
	if (posts.hasContent()) {
		for (Post post : posts) {
			DomainObjectSelect2Model model = new DomainObjectSelect2Model(post);
			results.add(model);
		}
	}
	return results;
}
 
Example 6
Source File: UserSelect2Controller.java    From wallride with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value="/{language}/users/select")
public @ResponseBody List<DomainObjectSelect2Model> select(
		@PathVariable String language,
		@RequestParam(required=false) String keyword) {
	UserSearchForm form = new UserSearchForm();
	form.setKeyword(keyword);
	Page<User> users = userService.getUsers(form.toUserSearchRequest());

	List<DomainObjectSelect2Model> results = new ArrayList<>();
	if (users.hasContent()) {
		for (User user : users) {
			DomainObjectSelect2Model model = new DomainObjectSelect2Model(user.getId(), user.toString());
			results.add(model);
		}
	}
	return results;
}
 
Example 7
Source File: ReleaseService.java    From apollo with Apache License 2.0 6 votes vote down vote up
private Collection<String> getBranchReleaseKeys(long releaseId) {
  Page<ReleaseHistory> releaseHistories = releaseHistoryService
      .findByReleaseIdAndOperationInOrderByIdDesc(releaseId, BRANCH_RELEASE_OPERATIONS, FIRST_ITEM);

  if (!releaseHistories.hasContent()) {
    return null;
  }

  Map<String, Object> operationContext = gson
      .fromJson(releaseHistories.getContent().get(0).getOperationContext(), OPERATION_CONTEXT_TYPE_REFERENCE);

  if (operationContext == null || !operationContext.containsKey(ReleaseOperationContext.BRANCH_RELEASE_KEYS)) {
    return null;
  }

  return (Collection<String>) operationContext.get(ReleaseOperationContext.BRANCH_RELEASE_KEYS);
}
 
Example 8
Source File: BaseMovableService.java    From es with Apache License 2.0 5 votes vote down vote up
public M findPreByWeight(Integer weight) {
    Pageable pageable = new PageRequest(0, 1);
    Map<String, Object> searchParams = Maps.newHashMap();
    searchParams.put("weight_lt", weight);
    Sort sort = new Sort(Sort.Direction.DESC, "weight");
    Page<M> page = findAll(Searchable.newSearchable(searchParams).addSort(sort).setPage(pageable));

    if (page.hasContent()) {
        return page.getContent().get(0);
    }
    return null;
}
 
Example 9
Source File: PatientController.java    From spring-boot-jpa with Apache License 2.0 5 votes vote down vote up
/**
 * Search for Patients by name.
 *
 * @param name the name to search on
 * @param pageable a Pageable to restrict results
 * @return A paged result of matching Patients
 */
@GetMapping("/search/by-name")
public Page<Patient> getPatientsHasAnyNameContaining(
		@RequestParam("name") final String name, final Pageable pageable) {
	Page<Patient> pagedResults = this.patientRepository
			.findAll(hasAnyNameContaining(name), pageable);

	if (!pagedResults.hasContent()) {
		throw new NotFoundException(Patient.RESOURCE_PATH,
				"No Patients found matching predicate " + hasAnyNameContaining(name));
	}

	return pagedResults;
}
 
Example 10
Source File: PatientController.java    From spring-boot-jpa with Apache License 2.0 5 votes vote down vote up
/**
 * Another alternative to QBE via QueryDsl Predicates.
 *
 * @param predicate the Predicate to use to query with
 * @param pageable a Pageable to restrict results
 * @return A paged result of matching Patients
 */
@GetMapping("/search/predicate")
public Page<Patient> getPatientsByPredicate(
		@QuerydslPredicate(root = Patient.class) final Predicate predicate, final Pageable pageable) {
	Page<Patient> pagedResults = this.patientRepository.findAll(predicate, pageable);

	if (!pagedResults.hasContent()) {
		throw new NotFoundException(Patient.RESOURCE_PATH,
				"No Patients found matching predicate " + predicate);
	}

	return pagedResults;
}
 
Example 11
Source File: UserStatusHistoryService.java    From es with Apache License 2.0 5 votes vote down vote up
public UserStatusHistory findLastHistory(final User user) {
    Searchable searchable = Searchable.newSearchable()
            .addSearchParam("user_eq", user)
            .addSort(Sort.Direction.DESC, "opDate")
            .setPage(0, 1);

    Page<UserStatusHistory> page = baseRepository.findAll(searchable);

    if (page.hasContent()) {
        return page.getContent().get(0);
    }
    return null;
}
 
Example 12
Source File: MedicationController.java    From spring-boot-jpa with Apache License 2.0 5 votes vote down vote up
@GetMapping
public Page<Medication> getPatients(@PageableDefault(size = DEFAULT_PAGE_SZ) final Pageable pageable) {
	Page<Medication> pagedResults = this.medicationRepository.findAll(pageable);

	if (!pagedResults.hasContent()) {
		throw new NotFoundException(Medication.RESOURCE_PATH, "Medication resources not found");
	}

	return pagedResults;
}
 
Example 13
Source File: BaseMovableService.java    From es with Apache License 2.0 5 votes vote down vote up
private Integer findNextWeight() {
    Searchable searchable = Searchable.newSearchable().setPage(0, 1).addSort(Sort.Direction.DESC, "weight");
    Page<M> page = findAll(searchable);

    if (!page.hasContent()) {
        return stepLength;
    }

    return page.getContent().get(0).getWeight() + stepLength;
}
 
Example 14
Source File: InstanceService.java    From apollo with Apache License 2.0 5 votes vote down vote up
public Page<Instance> findInstancesByNamespace(String appId, String clusterName, String
    namespaceName, Pageable pageable) {
  Page<InstanceConfig> instanceConfigs = instanceConfigRepository.
      findByConfigAppIdAndConfigClusterNameAndConfigNamespaceNameAndDataChangeLastModifiedTimeAfter(appId, clusterName,
          namespaceName, getValidInstanceConfigDate(), pageable);

  List<Instance> instances = Collections.emptyList();
  if (instanceConfigs.hasContent()) {
    Set<Long> instanceIds = instanceConfigs.getContent().stream().map
        (InstanceConfig::getInstanceId).collect(Collectors.toSet());
    instances = findInstancesByIds(instanceIds);
  }

  return new PageImpl<>(instances, pageable, instanceConfigs.getTotalElements());
}
 
Example 15
Source File: MessageServiceController.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * 取消息内容列表(群组)
 * @param userId 用户ID
 * @param toId 对方ID
 * @param messageId 消息ID(查询起始)
 * @param messageCount 消息数
 * @return 消息内容列表
 * @since  1.0
 */
@GetMapping("/groupMessage/messageList")
@Transactional
public BaseModel<List<MessageEntity>> getGroupMessageList(@RequestParam("userId") long userId,
        @RequestParam("groupId") long groupId, @RequestParam("messageId") long messageId,
        @RequestParam("messageCount") int messageCount) {

    Long splt = groupId % 10;
    List<MessageEntity> messageList = null;

    SearchCriteria<IMGroupMessage> groupMessageSearchCriteria = new SearchCriteria<>();
    groupMessageSearchCriteria.add(JpaRestrictions.eq("groupId", groupId, false));
    groupMessageSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
    if (messageId > 0) {
    	//当消息ID参数指定了的时候
    	groupMessageSearchCriteria.add(JpaRestrictions.lte("msgId", messageId, false));
    }
    Sort sortMessage = new Sort(Sort.Direction.DESC, "created", "id");
    Pageable pageable = new PageRequest(0, messageCount, sortMessage);
    Page<IMGroupMessage> groupMessageList =
            groupMessageRepository.findAll(groupMessageSearchCriteria, pageable);
    if (groupMessageList.hasContent()) {
        messageList = messageService.findGroupMessageList(groupMessageList.getContent());
    }
    
    BaseModel<List<MessageEntity>> messageListRes = new BaseModel<>();
    messageListRes.setData(messageList);
    return messageListRes;
}
 
Example 16
Source File: MessageServiceController.java    From sctalk with Apache License 2.0 5 votes vote down vote up
/**
 * 取消息内容列表
 * @param userId 用户ID
 * @param toId 对方ID
 * @param messageId 消息ID(查询起始)
 * @param messageCount 消息数
 * @return 消息内容列表
 * @since  1.0
 */
@GetMapping("/message/messageList")
@Transactional
public BaseModel<List<MessageEntity>> getMessageList(@RequestParam("userId") long userId,
        @RequestParam("toId") long toId, @RequestParam("messageId") long messageId,
        @RequestParam("messageCount") int messageCount) {

    Long relateId = relationShipService.getRelationId(userId, toId, false);

    if (relateId == null || relateId == 0) {
        return new BaseModel<>();
    }
    Long splt = relateId % 10;
    List<MessageEntity> messageList = null;
    SearchCriteria<IMMessage> messageSearchCriteria = new SearchCriteria<>();
    messageSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
    messageSearchCriteria.add(JpaRestrictions.eq("relateId", relateId, false));
    if (messageId > 0) {
    	//当消息ID参数指定了的时候
    	messageSearchCriteria.add(JpaRestrictions.lte("msgId", messageId, false));
    }
    Sort sortMessage = new Sort(Sort.Direction.DESC, "created", "id");
    Pageable pageable = new PageRequest(0, messageCount, sortMessage);
    Page<IMMessage> messagePageList = messageRepository.findAll(messageSearchCriteria, pageable);
    if (messagePageList.hasContent()) {
        messageList = messageService.findMessageList(messagePageList.getContent());
    }
    
    BaseModel<List<MessageEntity>> messageListRes = new BaseModel<>();
    messageListRes.setData(messageList);
    return messageListRes;
}
 
Example 17
Source File: RecordServiceImpl.java    From jvm-sandbox-repeater with Apache License 2.0 5 votes vote down vote up
@Override
public PageResult<RecordBO> query(RecordParams params) {
    Page<Record> page = recordDao.selectByAppNameOrTraceId(params);
    PageResult<RecordBO> result = new PageResult<>();
    if (page.hasContent()) {
        result.setSuccess(true);
        result.setCount(page.getTotalElements());
        result.setTotalPage(page.getTotalPages());
        result.setPageIndex(params.getPage());
        result.setPageSize(params.getSize());
        result.setData(page.getContent().stream().map(recordConverter::convert).collect(Collectors.toList()));
    }
    return result;
}
 
Example 18
Source File: InstanceConfigController.java    From apollo with Apache License 2.0 4 votes vote down vote up
@GetMapping("/by-release")
public PageDTO<InstanceDTO> getByRelease(@RequestParam("releaseId") long releaseId,
                                         Pageable pageable) {
  Release release = releaseService.findOne(releaseId);
  if (release == null) {
    throw new NotFoundException(String.format("release not found for %s", releaseId));
  }
  Page<InstanceConfig> instanceConfigsPage = instanceService.findActiveInstanceConfigsByReleaseKey
      (release.getReleaseKey(), pageable);

  List<InstanceDTO> instanceDTOs = Collections.emptyList();

  if (instanceConfigsPage.hasContent()) {
    Multimap<Long, InstanceConfig> instanceConfigMap = HashMultimap.create();
    Set<String> otherReleaseKeys = Sets.newHashSet();

    for (InstanceConfig instanceConfig : instanceConfigsPage.getContent()) {
      instanceConfigMap.put(instanceConfig.getInstanceId(), instanceConfig);
      otherReleaseKeys.add(instanceConfig.getReleaseKey());
    }

    Set<Long> instanceIds = instanceConfigMap.keySet();

    List<Instance> instances = instanceService.findInstancesByIds(instanceIds);

    if (!CollectionUtils.isEmpty(instances)) {
      instanceDTOs = BeanUtils.batchTransform(InstanceDTO.class, instances);
    }

    for (InstanceDTO instanceDTO : instanceDTOs) {
      Collection<InstanceConfig> configs = instanceConfigMap.get(instanceDTO.getId());
      List<InstanceConfigDTO> configDTOs = configs.stream().map(instanceConfig -> {
        InstanceConfigDTO instanceConfigDTO = new InstanceConfigDTO();
        //to save some space
        instanceConfigDTO.setRelease(null);
        instanceConfigDTO.setReleaseDeliveryTime(instanceConfig.getReleaseDeliveryTime());
        instanceConfigDTO.setDataChangeLastModifiedTime(instanceConfig
            .getDataChangeLastModifiedTime());
        return instanceConfigDTO;
      }).collect(Collectors.toList());
      instanceDTO.setConfigs(configDTOs);
    }
  }

  return new PageDTO<>(instanceDTOs, pageable, instanceConfigsPage.getTotalElements());
}
 
Example 19
Source File: MessageServiceImpl.java    From sctalk with Apache License 2.0 4 votes vote down vote up
@Override
@Transactional
public List<UnreadEntity> getUnreadGroupMsgCount(long userId) {
    // 查询GroupID
    SearchCriteria<IMGroupMember> groupMemberSearchCriteria = new SearchCriteria<>();
    groupMemberSearchCriteria.add(JpaRestrictions.eq("userId", userId, false));
    groupMemberSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
    Sort sort = new Sort(Sort.Direction.DESC, "updated", "id");
    List<IMGroupMember> groupList = groupMemberRepository.findAll(groupMemberSearchCriteria, sort);

    List<UnreadEntity> unreadList = new ArrayList<>();

    HashOperations<String, String, String> hashOptions = redisTemplate.opsForHash();
    if (!groupList.isEmpty()) {
        for (IMGroupMember group : groupList) {
            
            final String groupSetKey = RedisKeys.concat(RedisKeys.GROUP_INFO, group.getGroupId(), RedisKeys.SETTING_INFO);
            final String userUnreadKey = RedisKeys.concat(RedisKeys.GROUP_UNREAD, userId);
            
            // 取群消息数和用户已读数
            String groupCount = hashOptions.get(groupSetKey, RedisKeys.COUNT);
            if (groupCount == null) {
                continue;
            }
            String userCount =
                    hashOptions.get(userUnreadKey, String.valueOf(group.getGroupId()));
            
            Integer unreadCount = userCount != null ? Integer.valueOf(groupCount) - Integer.valueOf(userCount)
                    : Integer.valueOf(groupCount);
            
            if (unreadCount > 0) {

                // 取最后一条记录的消息
                IMGroupMessageEntity lastMessage = null;
                
                SearchCriteria<IMGroupMessage> groupMessageSearchCriteria = new SearchCriteria<>();
                groupMessageSearchCriteria.add(JpaRestrictions.eq("groupId", group.getGroupId(), false));
                groupMessageSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
                Sort sortMessage = new Sort(Sort.Direction.DESC, "created", "id");
                Pageable pageable = new PageRequest(0, 1, sortMessage);
                Page<IMGroupMessage> groupMessageList =
                        groupMessageRepository.findAll(groupMessageSearchCriteria, pageable);
                if (groupMessageList.hasContent()) {
                    lastMessage = groupMessageList.getContent().get(0);
                }

                UnreadEntity unreadEntity = new UnreadEntity();
                unreadEntity.setPeerId(group.getGroupId());
                unreadEntity.setSessionType(IMBaseDefine.SessionType.SESSION_TYPE_GROUP_VALUE);
                unreadEntity.setLaststMsgType(lastMessage.getType());
                unreadEntity.setUnReadCnt(unreadCount);
                if (lastMessage != null) {
                    unreadEntity.setLaststMsgId(lastMessage.getMsgId());
                    unreadEntity.setLaststMsgType(lastMessage.getType());
                    unreadEntity.setLatestMsgFromUserId(lastMessage.getUserId());
                    if (lastMessage.getType() == IMBaseDefine.MsgType.MSG_TYPE_GROUP_TEXT_VALUE) {
                        unreadEntity.setLatestMsgData(lastMessage.getContent());
                    } else if (lastMessage.getType() == IMBaseDefine.MsgType.MSG_TYPE_GROUP_AUDIO_VALUE) {
                        // "[语音]"加密后的字符串
                        byte[] content = SecurityUtils.getInstance().EncryptMsg("[语音]");
                        unreadEntity.setLatestMsgData(Base64Utils.encodeToString(content));
                    } else {
                        // 其他
                        unreadEntity.setLatestMsgData(lastMessage.getContent());
                    }
                }
                unreadList.add(unreadEntity);
            }
        }
    }

    return unreadList;
}
 
Example 20
Source File: MessageServiceImpl.java    From sctalk with Apache License 2.0 4 votes vote down vote up
@Override
@Transactional
public List<UnreadEntity> getUnreadMsgCount(long userId) {

    List<UnreadEntity> unreadList = new ArrayList<>();

    // 查询未读件数
    final String userUnreadKey = RedisKeys.concat(RedisKeys.USER_UNREAD, userId);
    // String unreadKey = "unread_" + userId;
    HashOperations<String, String, String> hashOptions = redisTemplate.opsForHash();
    Map<String, String> mapUnread = hashOptions.entries(userUnreadKey);

    for (Entry<String, String> uread : mapUnread.entrySet()) {
        
        Long fromUserId = Long.valueOf(uread.getKey());
        Long relateId = relationShipService.getRelationId(userId, fromUserId, false);

        // 查询
        UnreadEntity unreadEntity = new UnreadEntity();
        unreadEntity.setPeerId(fromUserId);
        unreadEntity.setSessionType(IMBaseDefine.SessionType.SESSION_TYPE_SINGLE_VALUE);
        unreadEntity.setUnReadCnt(Integer.valueOf(uread.getValue()));

        IMMessageEntity lastMessage = null;
        SearchCriteria<IMMessage> messageSearchCriteria = new SearchCriteria<>();
        messageSearchCriteria.add(JpaRestrictions.eq("status", DBConstant.DELETE_STATUS_OK, false));
        messageSearchCriteria.add(JpaRestrictions.eq("relateId", relateId, false));
        Sort sortMessage = new Sort(Sort.Direction.DESC, "created", "id");
        Pageable pageable = new PageRequest(0, 1, sortMessage);
        Page<IMMessage> messageList = messageRepository.findAll(messageSearchCriteria, pageable);
        if (messageList.hasContent()) {
            lastMessage = messageList.getContent().get(0);
        }

        if (lastMessage != null) {
            unreadEntity.setLaststMsgId(lastMessage.getMsgId());
            unreadEntity.setLaststMsgType(lastMessage.getType());
            unreadEntity.setLatestMsgFromUserId(lastMessage.getUserId());
            if (lastMessage.getType() == IMBaseDefine.MsgType.MSG_TYPE_SINGLE_TEXT_VALUE) {
                unreadEntity.setLatestMsgData(lastMessage.getContent());
            } else if (lastMessage.getType() == IMBaseDefine.MsgType.MSG_TYPE_SINGLE_AUDIO_VALUE) {
                // "[语音]"加密后的字符串
                byte[] content = SecurityUtils.getInstance().EncryptMsg("[语音]");
                unreadEntity.setLatestMsgData(Base64Utils.encodeToString(content));
            } else {
                // 其他
                unreadEntity.setLatestMsgData(lastMessage.getContent());
            }
        }
        unreadList.add(unreadEntity);
    }

    return unreadList;
}