org.springframework.util.CollectionUtils#isEmpty ( )源码实例Demo

下面列出了org.springframework.util.CollectionUtils#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: syhthems-platform   文件: DataStreamServiceImpl.java
@Override
public List<DataStream> selectByDeviceId(Long deviceId) {
    if (deviceId == null) {
        throw new ServiceException("deviceId 为空");
    }
    DeviceDataStream deviceDataStream = new DeviceDataStream();
    deviceDataStream.setDeviceId(deviceId);
    List<DeviceDataStream> deviceDataStreams = deviceDataStreamService.select(deviceDataStream);
    if (CollectionUtils.isEmpty(deviceDataStreams)) {
        return null;
    }
    Example dataStreamExample = new Example(DataStream.class);
    dataStreamExample.createCriteria().andIn(DataStream.DATA_STREAM_ID,
            deviceDataStreams.stream().map(DeviceDataStream::getDataStreamId).collect(Collectors.toList()));
    return super.selectByExample(dataStreamExample);
}
 
源代码2 项目: herd   文件: BusinessObjectFormatServiceImpl.java
/**
 * Creates a list of attribute definition entities.
 *
 * @param attributeDefinitions the list of attribute definitions
 * @param businessObjectFormatEntity the business object format entity
 *
 * @return the newly created list of attribute definition entities
 */
private List<BusinessObjectDataAttributeDefinitionEntity> createAttributeDefinitionEntities(List<AttributeDefinition> attributeDefinitions,
    BusinessObjectFormatEntity businessObjectFormatEntity)
{
    List<BusinessObjectDataAttributeDefinitionEntity> attributeDefinitionEntities = new ArrayList<>();

    if (!CollectionUtils.isEmpty(attributeDefinitions))
    {
        for (AttributeDefinition attributeDefinition : attributeDefinitions)
        {
            // Create a new business object data attribute definition entity.
            BusinessObjectDataAttributeDefinitionEntity attributeDefinitionEntity = new BusinessObjectDataAttributeDefinitionEntity();
            attributeDefinitionEntities.add(attributeDefinitionEntity);
            attributeDefinitionEntity.setBusinessObjectFormat(businessObjectFormatEntity);
            attributeDefinitionEntity.setName(attributeDefinition.getName());

            // For the "publish" option, default a Boolean null value to "false".
            attributeDefinitionEntity.setPublish(BooleanUtils.isTrue(attributeDefinition.isPublish()));

            // For the "publish for filter" option, default a Boolean null value to "false".
            attributeDefinitionEntity.setPublishForFilter(BooleanUtils.isTrue(attributeDefinition.isPublishForFilter()));
        }
    }

    return attributeDefinitionEntities;
}
 
源代码3 项目: cloud-service   文件: LoginAppUser.java
@JsonIgnore
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
	Collection<GrantedAuthority> collection = new HashSet<>();
	if (!CollectionUtils.isEmpty(sysRoles)) {
		sysRoles.forEach(role -> {
			if (role.getCode().startsWith("ROLE_")) {
				collection.add(new SimpleGrantedAuthority(role.getCode()));
			} else {
				collection.add(new SimpleGrantedAuthority("ROLE_" + role.getCode()));
			}
		});
	}

	if (!CollectionUtils.isEmpty(permissions)) {
		permissions.forEach(per -> {
			collection.add(new SimpleGrantedAuthority(per));
		});
	}

	return collection;
}
 
源代码4 项目: ApiManager   文件: InterfacePDFDto.java
/**
 * 名称根据deep缩进
 * @param responseParam
 */
public void setResponseParam(List<ParamDto> responseParam) {
	if (CollectionUtils.isEmpty(responseParam)){
		this.responseParam = new ArrayList<>();
		return;
	}
	for (ParamDto responseParamDto : responseParam){
		Integer deep = responseParamDto.getDeep();
		if (deep == null){
               responseParamDto.setDeep(0);
			deep = 0;
		}
		// TODO 空格无效
		StringBuilder sb = new StringBuilder("");
		while (deep > 0){
               sb.append(" ");
               deep = deep - 1;
           }
		responseParamDto.setName(sb.toString() +
				(responseParamDto.getName() == null ? "" : responseParamDto.getName()));
	}
	this.responseParam = responseParam;
}
 
源代码5 项目: java-technology-stack   文件: HttpRange.java
/**
 * Convert each {@code HttpRange} into a {@code ResourceRegion}, selecting the
 * appropriate segment of the given {@code Resource} using HTTP Range information.
 * @param ranges the list of ranges
 * @param resource the resource to select the regions from
 * @return the list of regions for the given resource
 * @throws IllegalArgumentException if the sum of all ranges exceeds the
 * resource length.
 * @since 4.3
 */
public static List<ResourceRegion> toResourceRegions(List<HttpRange> ranges, Resource resource) {
	if (CollectionUtils.isEmpty(ranges)) {
		return Collections.emptyList();
	}
	List<ResourceRegion> regions = new ArrayList<>(ranges.size());
	for (HttpRange range : ranges) {
		regions.add(range.toResourceRegion(resource));
	}
	if (ranges.size() > 1) {
		long length = getLengthFor(resource);
		long total = regions.stream().map(ResourceRegion::getCount).reduce(0L, (count, sum) -> sum + count);
		Assert.isTrue(total < length,
				() -> "The sum of all ranges (" + total + ") " +
						"should be less than the resource length (" + length + ")");
	}
	return regions;
}
 
源代码6 项目: datax-web   文件: DataxJsonHelper.java
@Override
public Map<String, Object> buildHBaseReader() {
    DataxHbasePojo dataxHbasePojo = new DataxHbasePojo();
    dataxHbasePojo.setJdbcDatasource(readerDatasource);
    List<Map<String, Object>> columns = Lists.newArrayList();
    for (int i = 0; i < readerColumns.size(); i++) {
        Map<String, Object> column = Maps.newLinkedHashMap();
        column.put("name", readerColumns.get(i));
        column.put("type", "string");
        columns.add(column);
    }
    dataxHbasePojo.setColumns(columns);
    dataxHbasePojo.setReaderHbaseConfig(readerDatasource.getZkAdress());
    String readerTable=!CollectionUtils.isEmpty(readerTables)?readerTables.get(0):Constants.STRING_BLANK;
    dataxHbasePojo.setReaderTable(readerTable);
    dataxHbasePojo.setReaderMode(hbaseReaderDto.getReaderMode());
    dataxHbasePojo.setReaderRange(hbaseReaderDto.getReaderRange());
    return readerPlugin.buildHbase(dataxHbasePojo);
}
 
源代码7 项目: apollo   文件: PermissionController.java
@PreAuthorize(value = "@permissionValidator.hasAssignRolePermission(#appId)")
@PostMapping("/apps/{appId}/envs/{env}/namespaces/{namespaceName}/roles/{roleType}")
public ResponseEntity<Void> assignNamespaceEnvRoleToUser(@PathVariable String appId, @PathVariable String env, @PathVariable String namespaceName,
                                                         @PathVariable String roleType, @RequestBody String user) {
  checkUserExists(user);
  RequestPrecondition.checkArgumentsNotEmpty(user);

  if (!RoleType.isValidRoleType(roleType)) {
    throw new BadRequestException("role type is illegal");
  }

  // validate env parameter
  if (Env.UNKNOWN == Env.transformEnv(env)) {
    throw new BadRequestException("env is illegal");
  }
  Set<String> assignedUser = rolePermissionService.assignRoleToUsers(RoleUtils.buildNamespaceRoleName(appId, namespaceName, roleType, env),
      Sets.newHashSet(user), userInfoHolder.getUser().getUserId());
  if (CollectionUtils.isEmpty(assignedUser)) {
    throw new BadRequestException(user + " already authorized");
  }

  return ResponseEntity.ok().build();
}
 
源代码8 项目: mall   文件: EsProductServiceImpl.java
@Override
public void delete(List<Long> ids) {
    if (!CollectionUtils.isEmpty(ids)) {
        List<EsProduct> esProductList = new ArrayList<>();
        for (Long id : ids) {
            EsProduct esProduct = new EsProduct();
            esProduct.setId(id);
            esProductList.add(esProduct);
        }
        productRepository.deleteAll(esProductList);
    }
}
 
protected void customizeRequest(MutableHttpServerRequest httpServerRequest,
		RestMethodMetadata dubboRestMethodMetadata, RequestMetadata clientMetadata) {

	RequestMetadata dubboRequestMetadata = dubboRestMethodMetadata.getRequest();
	String pathPattern = dubboRequestMetadata.getPath();

	Map<String, String> pathVariables = pathMatcher
			.extractUriTemplateVariables(pathPattern, httpServerRequest.getPath());

	if (!CollectionUtils.isEmpty(pathVariables)) {
		// Put path variables Map into query parameters Map
		httpServerRequest.params(pathVariables);
	}

}
 
源代码10 项目: herd   文件: BusinessObjectDataServiceTestHelper.java
/**
 * Validates business object data against specified arguments and expected (hard coded) test values.
 *
 * @param request the business object data create request
 * @param expectedBusinessObjectDataVersion the expected business object data version
 * @param expectedLatestVersion the expected business
 * @param actualBusinessObjectData the business object data availability object instance to be validated
 */
public void validateBusinessObjectData(BusinessObjectDataCreateRequest request, Integer expectedBusinessObjectDataVersion, Boolean expectedLatestVersion,
    BusinessObjectData actualBusinessObjectData)
{
    BusinessObjectFormatEntity businessObjectFormatEntity = businessObjectFormatDao.getBusinessObjectFormatByAltKey(new BusinessObjectFormatKey(
        org.apache.commons.lang3.StringUtils.isNotBlank(request.getNamespace()) ? request.getNamespace() : AbstractServiceTest.NAMESPACE,
        request.getBusinessObjectDefinitionName(), request.getBusinessObjectFormatUsage(), request.getBusinessObjectFormatFileType(),
        request.getBusinessObjectFormatVersion()));

    List<String> expectedSubPartitionValues =
        CollectionUtils.isEmpty(request.getSubPartitionValues()) ? new ArrayList<>() : request.getSubPartitionValues();

    String expectedStatusCode =
        org.apache.commons.lang3.StringUtils.isNotBlank(request.getStatus()) ? request.getStatus() : BusinessObjectDataStatusEntity.VALID;

    StorageUnitCreateRequest storageUnitCreateRequest = request.getStorageUnits().get(0);

    StorageEntity storageEntity = storageDao.getStorageByName(storageUnitCreateRequest.getStorageName());

    String expectedStorageDirectoryPath =
        storageUnitCreateRequest.getStorageDirectory() != null ? storageUnitCreateRequest.getStorageDirectory().getDirectoryPath() : null;

    List<StorageFile> expectedStorageFiles =
        CollectionUtils.isEmpty(storageUnitCreateRequest.getStorageFiles()) ? null : storageUnitCreateRequest.getStorageFiles();

    List<Attribute> expectedAttributes = CollectionUtils.isEmpty(request.getAttributes()) ? new ArrayList<>() : request.getAttributes();

    validateBusinessObjectData(businessObjectFormatEntity, request.getPartitionValue(), expectedSubPartitionValues, expectedBusinessObjectDataVersion,
        expectedLatestVersion, expectedStatusCode, storageEntity.getName(), expectedStorageDirectoryPath, expectedStorageFiles, expectedAttributes,
        actualBusinessObjectData);
}
 
源代码11 项目: spring-data-jpa-extra   文件: AbstractConverter.java
@Override
public List<D> convert(List<S> source) {
    if (CollectionUtils.isEmpty(source)) {
        return Collections.emptyList();
    }
    List<D> ds = new ArrayList<D>(source.size());
    for (S s : source) {
        ds.add(convert(s));
    }
    assembler(source, ds);
    return ds;
}
 
源代码12 项目: artemis   文件: InstanceRepository.java
public void register(final Set<Instance> instances) {
    if (CollectionUtils.isEmpty(instances)) {
        return;
    }
    _client.unregister(instances);
    updateInstances(instances, RegisterType.register);
}
 
源代码13 项目: halo   文件: StaticDeployHandlers.java
/**
 * Adds static deploy handlers.
 *
 * @param staticDeployHandlers static deploy handler collection
 * @return current file handlers
 */
@NonNull
public StaticDeployHandlers addStaticDeployHandlers(@Nullable Collection<StaticDeployHandler> staticDeployHandlers) {
    if (!CollectionUtils.isEmpty(staticDeployHandlers)) {
        this.staticDeployHandlers.addAll(staticDeployHandlers);
    }
    return this;
}
 
源代码14 项目: pmq   文件: EmailUtil.java
public void sendMail(String title, String content, List<String> rev, int type) {
	if (!soaConfig.isEmailEnable()) {
		return;
	}
	if (!CollectionUtils.isEmpty(rev) || !CollectionUtils.isEmpty(getAdminEmail())||emailVos.size()<3000) {
		try {
			emailVos.add(new EmailVo(title, content+",and send time is "+Util.formateDate(new Date()), rev, type));
		} catch (Exception e) {
			// TODO: handle exception
		}
		// doSendMail(title, content, rev, type);
	}
}
 
源代码15 项目: halo   文件: BeanUtils.java
/**
 * Transforms from source data collection in batch.
 *
 * @param sources     source data collection
 * @param targetClass target class must not be null
 * @param <T>         target class type
 * @return target collection transforming from source data collection.
 * @throws BeanUtilsException if newing target instance failed or copying failed
 */
@NonNull
public static <T> List<T> transformFromInBatch(Collection<?> sources, @NonNull Class<T> targetClass) {
    if (CollectionUtils.isEmpty(sources)) {
        return Collections.emptyList();
    }

    // Transform in batch
    return sources.stream()
        .map(source -> transformFrom(source, targetClass))
        .collect(Collectors.toList());
}
 
源代码16 项目: radar   文件: InstanceService.java
public void heartBeat(List<Long> ids) {
	if (CollectionUtils.isEmpty(ids)) {
		return;
	}
	instanceRepository.heartBeatBatch(ids);
}
 
源代码17 项目: super-cloudops   文件: SubQuery.java
public Builder filter(List<Filter> filterList) {
	if (!CollectionUtils.isEmpty(filterList)) {
		filters.addAll(filterList);
	}
	return this;
}
 
源代码18 项目: unimall   文件: AdminGoodsServiceImpl.java
@Override
@Transactional(rollbackFor = Exception.class)
public String edit(SpuDTO spuDTO, Long adminId) throws ServiceException {
    if (spuDTO.getId() == null) {
        throw new AdminServiceException(ExceptionDefinition.PARAM_CHECK_FAILED);
    }
    if (CollectionUtils.isEmpty(spuDTO.getSkuList())) {
        throw new AdminServiceException(ExceptionDefinition.GOODS_SKU_LIST_EMPTY);
    }
    if (spuDTO.getOriginalPrice() < spuDTO.getPrice() || spuDTO.getPrice() < spuDTO.getVipPrice() || spuDTO.getOriginalPrice() < spuDTO.getVipPrice()) {
        throw new AdminServiceException(ExceptionDefinition.GOODS_PRICE_CHECKED_FAILED);
    }
    Date now = new Date();
    SpuDO spuDO = new SpuDO();
    BeanUtils.copyProperties(spuDTO, spuDO);
    spuDO.setGmtUpdate(now);
    spuMapper.updateById(spuDO);
    List<String> barCodes = new LinkedList<>();
    for (SkuDO skuDO : spuDTO.getSkuList()) {
        if (skuDO.getOriginalPrice() < skuDO.getPrice() || skuDO.getPrice() < skuDO.getVipPrice() || skuDO.getOriginalPrice() < skuDO.getVipPrice()) {
            throw new AdminServiceException(ExceptionDefinition.GOODS_PRICE_CHECKED_FAILED);
        }
        skuDO.setId(null);
        skuDO.setSpuId(spuDO.getId());
        skuDO.setGmtUpdate(now);
        skuDO.setFreezeStock(0);
        if (skuMapper.update(skuDO,
                new EntityWrapper<SkuDO>()
                        .eq("bar_code", skuDO.getBarCode())) <= 0) {
            skuDO.setGmtCreate(now);
            skuMapper.insert(skuDO);
        }
        barCodes.add(skuDO.getBarCode());
    }
    //删除多余barCode
    skuMapper.delete(new EntityWrapper<SkuDO>().eq("spu_id", spuDO.getId()).notIn("bar_code",barCodes));
    //插入spuAttr
    spuAttributeMapper.delete(new EntityWrapper<SpuAttributeDO>().eq("spu_id", spuDTO.getId()));
    insertSpuAttribute(spuDTO, now);
    imgMapper.delete(new EntityWrapper<ImgDO>().eq("biz_id", spuDO.getId()).eq("biz_type", BizType.GOODS.getCode()));
    //插入IMG
    insertSpuImg(spuDTO, spuDO.getId(), now);
    goodsBizService.clearGoodsCache(spuDTO.getId());
    pluginUpdateInvoke(spuDTO.getId());

    cacheComponent.delPrefixKey(GoodsBizService.CA_SPU_PAGE_PREFIX);
    return "ok";
}
 
源代码19 项目: kayenta   文件: ConfigBinConfiguration.java
@Bean
ConfigBinStorageService configBinStorageService(
    ConfigBinResponseConverter configBinConverter,
    ConfigBinConfigurationProperties configBinConfigurationProperties,
    RetrofitClientFactory retrofitClientFactory,
    OkHttpClient okHttpClient,
    AccountCredentialsRepository accountCredentialsRepository) {
  log.debug("Created a ConfigBin StorageService");
  ConfigBinStorageService.ConfigBinStorageServiceBuilder configbinStorageServiceBuilder =
      ConfigBinStorageService.builder();

  for (ConfigBinManagedAccount configBinManagedAccount :
      configBinConfigurationProperties.getAccounts()) {
    String name = configBinManagedAccount.getName();
    String ownerApp = configBinManagedAccount.getOwnerApp();
    String configType = configBinManagedAccount.getConfigType();
    RemoteService endpoint = configBinManagedAccount.getEndpoint();
    List<AccountCredentials.Type> supportedTypes = configBinManagedAccount.getSupportedTypes();

    log.info("Registering ConfigBin account {} with supported types {}.", name, supportedTypes);

    ConfigBinAccountCredentials configbinAccountCredentials =
        ConfigBinAccountCredentials.builder().build();
    ConfigBinNamedAccountCredentials.ConfigBinNamedAccountCredentialsBuilder
        configBinNamedAccountCredentialsBuilder =
            ConfigBinNamedAccountCredentials.builder()
                .name(name)
                .ownerApp(ownerApp)
                .configType(configType)
                .endpoint(endpoint)
                .credentials(configbinAccountCredentials);

    if (!CollectionUtils.isEmpty(supportedTypes)) {
      if (supportedTypes.contains(AccountCredentials.Type.CONFIGURATION_STORE)) {
        ConfigBinRemoteService configBinRemoteService =
            retrofitClientFactory.createClient(
                ConfigBinRemoteService.class,
                configBinConverter,
                configBinManagedAccount.getEndpoint(),
                okHttpClient);
        configBinNamedAccountCredentialsBuilder.remoteService(configBinRemoteService);
      }
      configBinNamedAccountCredentialsBuilder.supportedTypes(supportedTypes);
    }

    ConfigBinNamedAccountCredentials configbinNamedAccountCredentials =
        configBinNamedAccountCredentialsBuilder.build();
    accountCredentialsRepository.save(name, configbinNamedAccountCredentials);
    configbinStorageServiceBuilder.accountName(name);
  }

  ConfigBinStorageService configbinStorageService = configbinStorageServiceBuilder.build();

  log.info(
      "Populated ConfigBinStorageService with {} ConfigBin accounts.",
      configbinStorageService.getAccountNames().size());

  return configbinStorageService;
}
 
@PostMapping("/new.json")
public Result<ApiDefinitionEntity> addApi(HttpServletRequest request, @RequestBody AddApiReqVo reqVo) {
    AuthService.AuthUser authUser = authService.getAuthUser(request);

    String app = reqVo.getApp();
    if (StringUtil.isBlank(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }

    authUser.authTarget(app, AuthService.PrivilegeType.WRITE_RULE);

    ApiDefinitionEntity entity = new ApiDefinitionEntity();
    entity.setApp(app.trim());

    String ip = reqVo.getIp();
    if (StringUtil.isBlank(ip)) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    entity.setIp(ip.trim());

    Integer port = reqVo.getPort();
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    entity.setPort(port);

    // API名称
    String apiName = reqVo.getApiName();
    if (StringUtil.isBlank(apiName)) {
        return Result.ofFail(-1, "apiName can't be null or empty");
    }
    entity.setApiName(apiName.trim());

    // 匹配规则列表
    List<ApiPredicateItemVo> predicateItems = reqVo.getPredicateItems();
    if (CollectionUtils.isEmpty(predicateItems)) {
        return Result.ofFail(-1, "predicateItems can't empty");
    }

    List<ApiPredicateItemEntity> predicateItemEntities = new ArrayList<>();
    for (ApiPredicateItemVo predicateItem : predicateItems) {
        ApiPredicateItemEntity predicateItemEntity = new ApiPredicateItemEntity();

        // 匹配模式
        Integer matchStrategy = predicateItem.getMatchStrategy();
        if (!Arrays.asList(URL_MATCH_STRATEGY_EXACT, URL_MATCH_STRATEGY_PREFIX, URL_MATCH_STRATEGY_REGEX).contains(matchStrategy)) {
            return Result.ofFail(-1, "invalid matchStrategy: " + matchStrategy);
        }
        predicateItemEntity.setMatchStrategy(matchStrategy);

        // 匹配串
        String pattern = predicateItem.getPattern();
        if (StringUtil.isBlank(pattern)) {
            return Result.ofFail(-1, "pattern can't be null or empty");
        }
        predicateItemEntity.setPattern(pattern);

        predicateItemEntities.add(predicateItemEntity);
    }
    entity.setPredicateItems(new LinkedHashSet<>(predicateItemEntities));

    // 检查API名称不能重复
    List<ApiDefinitionEntity> allApis = repository.findAllByMachine(MachineInfo.of(app.trim(), ip.trim(), port));
    if (allApis.stream().map(o -> o.getApiName()).anyMatch(o -> o.equals(apiName.trim()))) {
        return Result.ofFail(-1, "apiName exists: " + apiName);
    }

    Date date = new Date();
    entity.setGmtCreate(date);
    entity.setGmtModified(date);

    try {
        entity = repository.save(entity);
    } catch (Throwable throwable) {
        logger.error("add gateway api error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }

    if (!publishApis(app, ip, port)) {
        logger.warn("publish gateway apis fail after add");
    }

    return Result.ofSuccess(entity);
}