Java Code Examples for org.springframework.util.CollectionUtils#isEmpty()
The following examples show how to use
org.springframework.util.CollectionUtils#isEmpty() .
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: PermissionController.java From apollo with Apache License 2.0 | 6 votes |
@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(); }
Example 2
Source File: DataStreamServiceImpl.java From syhthems-platform with MIT License | 6 votes |
@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); }
Example 3
Source File: BusinessObjectFormatServiceImpl.java From herd with Apache License 2.0 | 6 votes |
/** * 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; }
Example 4
Source File: DataxJsonHelper.java From datax-web with MIT License | 6 votes |
@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); }
Example 5
Source File: HttpRange.java From java-technology-stack with MIT License | 6 votes |
/** * 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; }
Example 6
Source File: LoginAppUser.java From cloud-service with MIT License | 6 votes |
@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; }
Example 7
Source File: InterfacePDFDto.java From ApiManager with GNU Affero General Public License v3.0 | 6 votes |
/** * 名称根据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; }
Example 8
Source File: EsProductServiceImpl.java From mall with Apache License 2.0 | 5 votes |
@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); } }
Example 9
Source File: BeanUtils.java From halo with GNU General Public License v3.0 | 5 votes |
/** * 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()); }
Example 10
Source File: EmailUtil.java From pmq with Apache License 2.0 | 5 votes |
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); } }
Example 11
Source File: StaticDeployHandlers.java From halo with GNU General Public License v3.0 | 5 votes |
/** * 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; }
Example 12
Source File: InstanceRepository.java From artemis with Apache License 2.0 | 5 votes |
public void register(final Set<Instance> instances) { if (CollectionUtils.isEmpty(instances)) { return; } _client.unregister(instances); updateInstances(instances, RegisterType.register); }
Example 13
Source File: AbstractConverter.java From spring-data-jpa-extra with Apache License 2.0 | 5 votes |
@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; }
Example 14
Source File: BusinessObjectDataServiceTestHelper.java From herd with Apache License 2.0 | 5 votes |
/** * 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); }
Example 15
Source File: DubboTransporterInterceptor.java From spring-cloud-alibaba with Apache License 2.0 | 5 votes |
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); } }
Example 16
Source File: ConfigBinConfiguration.java From kayenta with Apache License 2.0 | 4 votes |
@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; }
Example 17
Source File: GatewayApiController.java From Sentinel-Dashboard-Nacos with Apache License 2.0 | 4 votes |
@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); }
Example 18
Source File: AdminGoodsServiceImpl.java From unimall with Apache License 2.0 | 4 votes |
@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"; }
Example 19
Source File: SubQuery.java From super-cloudops with Apache License 2.0 | 4 votes |
public Builder filter(List<Filter> filterList) { if (!CollectionUtils.isEmpty(filterList)) { filters.addAll(filterList); } return this; }
Example 20
Source File: InstanceService.java From radar with Apache License 2.0 | 4 votes |
public void heartBeat(List<Long> ids) { if (CollectionUtils.isEmpty(ids)) { return; } instanceRepository.heartBeatBatch(ids); }