Java Code Examples for org.apache.commons.collections.CollectionUtils.isNotEmpty()

The following are Jave code examples for showing how to use isNotEmpty() of the org.apache.commons.collections.CollectionUtils class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: xxl-api   File: XxlApiDocumentController.java   View Source Code Vote up 7 votes
@RequestMapping("/delete")
@ResponseBody
public ReturnT<String> delete(int id) {

	// 存在Test记录,拒绝删除
	List<XxlApiTestHistory> historyList = xxlApiTestHistoryDao.loadByDocumentId(id);
	if (CollectionUtils.isNotEmpty(historyList)) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Test记录,不允许删除");
	}

	// 存在Mock记录,拒绝删除
	List<XxlApiMock> mockList = xxlApiMockDao.loadAll(id);
	if (CollectionUtils.isNotEmpty(mockList)) {
		return new ReturnT<String>(ReturnT.FAIL_CODE, "拒绝删除,该接口下存在Mock记录,不允许删除");
	}

	int ret = xxlApiDocumentDao.delete(id);
	return (ret>0)?ReturnT.SUCCESS:ReturnT.FAIL;
}
 
Example 2
Project: Dragonfly   File: MonitorService.java   View Source Code Vote up 7 votes
private float getLoad(Map<String, List<Integer>> fieldIndex, String[] fields, String key) {
    float maxValue = -1.0f;
    int fieldsLen = fields.length;
    List<Integer> indexs = fieldIndex.get(key);
    if (CollectionUtils.isNotEmpty(indexs)) {
        if (Collections.max(indexs) < fieldsLen) {
            for (Integer index : indexs) {
                String value = fields[index];
                if (StringUtils.isNotBlank(value) && value.matches("\\d+\\.?\\d*")) {
                    maxValue = maxValue >= Float.parseFloat(value) ? maxValue : Float.parseFloat(value);
                }
            }
        }
    }
    return maxValue;
}
 
Example 3
Project: Dragonfly   File: CacheDetectorImpl.java   View Source Code Vote up 7 votes
private boolean processCacheByQuick(Task task, int breakNum, CacheResult cacheResult,
    FileMetaData metaData) throws IOException {
    List<String> pieceMd5s;
    if (breakNum == -1) {
        if (StringUtils.isNotBlank(metaData.getRealMd5())) {
            pieceMd5s = getFullPieceMd5s(task, metaData);
            Long fileLen = metaData.getFileLength();
            if (CollectionUtils.isNotEmpty(pieceMd5s)) {
                reportCache(task, fileLen, metaData.getRealMd5(), pieceMd5s);
                cacheResult.setStartPieceNum(breakNum);
                return true;
            }
        }
    }
    return false;
}
 
Example 4
Project: redirector   File: PartnerValidationVisitor.java   View Source Code Vote up 6 votes
@Override
public void visit(Partner item) {
    if (StringUtils.isBlank(item.getId())) {
        getValidationState().pushError(ValidationState.ErrorType.PartnerIdMissing);
    }

    if (item.getProperties().size() < 1) {
        getValidationState().pushError(ValidationState.ErrorType.PartnerPropertiesMissing);
    }

    // validate that we are not deleting partner which is used in some of the rules
    Collection<IfExpression> rules = getValidationState().getRules();
    if (CollectionUtils.isNotEmpty(rules)) {
        StringBuilder errorMsg = new StringBuilder("Partner is used in ");
        boolean hasError = false;

        for (IfExpression rule : rules) {
            // only last IfExpression of a rule contains return.
            // if current IfExpression has another (nested) IfExpression there is no sense
            // to try to validate current return statement (it's null).
            // It's somewhere deeper in nested IfExpression...
            IfExpression lastIfExpression = getLastIfExpressionFromRule(rule);
            for (Expressions partnerIdValue : lastIfExpression.getReturn()) {
                if (item.getId().equals(((Value) partnerIdValue).getValue())) {
                    errorMsg.append(rule.getId()).append(", ");
                    hasError = true;
                    break;
                }
            }
        }

        if (hasError) {
            errorMsg.deleteCharAt(errorMsg.lastIndexOf(","));
            errorMsg.append("rule(s).");
            getValidationState().pushError(ValidationState.ErrorType.PartnerIsInUse, errorMsg.toString());
        }
    }
}
 
Example 5
Project: bohemia   File: CachesManager.java   View Source Code Vote up 6 votes
public void setCaches(Collection<Cache> caches) {
    if (CollectionUtils.isNotEmpty(caches)) {
        for (Cache cache : caches) {
            this.caches.put(cache.getName(), cache);
        }
    }
}
 
Example 6
Project: xq_seckill_microservice   File: EstateServiceImpl.java   View Source Code Vote up 6 votes
@Override
@Transactional(readOnly = true)
public Page<EstateItemDTO> listForSaleByPage(Pageable pageable, Map<String, Object> paramMap) throws Exception {
    String cacheKey = CacheKeyGenerator.generate(EstateItemDTO.class, "listForSaleByPage", pageable, paramMap);

    Page<EstateItemDTO> targetItemPage = new PageX();

    // 读取缓存数据
    targetItemPage = byteRedisClient.getByteObj(cacheKey, targetItemPage.getClass());
    if (targetItemPage != null && CollectionUtils.isNotEmpty(targetItemPage.getContent())) {
        return new PageX(targetItemPage.getContent(), pageable, targetItemPage.getTotalElements());
    } else {
        Page<EstateItemModel> sourceItemPage = estateItemRepository.findAll(EstateItemSpecification.getForSaleSpec(paramMap), pageable);
        List<EstateItemModel> sourceItemList = sourceItemPage.getContent();

        if (CollectionUtils.isNotEmpty(sourceItemList)) {
            List<EstateItemDTO> targetItemList = new ArrayList();
            for (EstateItemModel model : sourceItemList) {
                EstateItemDTO dto = new EstateItemDTO();
                CachedBeanCopier.copy(model, dto);
                if (StringUtils.isBlank(dto.getCoverUrl())) dto.setCoverUrl("/3rd-party/porto/img/blank.jpg");
                dto.setDetailHref("/estate/" + dto.getHouseCode() + ".shtml");
                dto.setTotalPriceStr(dto.getTotalPrice() + "万");
                dto.setUnitPriceStr("单价" + dto.getUnitPrice() + "万");
                dto.setDownPayments(dto.getUnitPriceStr() + ", 首付" + BigDecimal.valueOf(0.3d).multiply(dto.getTotalPrice()).setScale(2, BigDecimal.ROUND_HALF_DOWN) + "万");
                dto.setAreaStr(dto.getArea() + "平米");
                dto.setFocusNumStr(dto.getFocusNum() + "人关注");
                dto.setWatchNumStr(dto.getWatchNum() + "次带看");
                dto.setNewEstate(dto.getUpdateTime().isAfter(TimeUtil.nowDateTime().minusDays(3))); // 是当前日期三天前发布的
                targetItemList.add(dto);
            }
            targetItemPage = new PageX(targetItemList, pageable, sourceItemPage.getTotalElements());

            // 数据写入缓存
            byteRedisClient.setByteObj(cacheKey, targetItemPage, 3600);
        }

        return targetItemPage;
    }
}
 
Example 7
Project: yadaframework   File: YadaSql.java   View Source Code Vote up 6 votes
/**
 * Add a "where aaa in (x, y, z)" clause. Skipped if the collection is null or empty.
 * The collection is converted to a comma-separated strings.
 * <b>NOTE:</b> It is always better to use collections as a parameter, like "aaa in :someCollection"
 * @param attributeName attribute or column name
 * @param values a list of values (e.g. integers)
 */
public YadaSql whereIn(String attributeName, Collection values) {
	if (CollectionUtils.isNotEmpty(values)) {
		String valueListString = StringUtils.join(values, ',');
		where(attributeName + " in ("+valueListString+")");
	}
	return this;
}
 
Example 8
Project: redirector   File: TemplateFlavorRulesService.java   View Source Code Vote up 6 votes
@Override
public OperationResult deleteTemplateRule(String appName, String ruleId) {
    final OperationContextHolder.OperationContext currentContext = OperationContextHolder.getCurrentContext();
    final PendingChangesStatus pendingChangesStatus = currentContext.getPendingChangesStatus();
    SelectServer templates = currentContext.getTemplatePathRules();
    Collection<IfExpression> flavorRules = currentContext.getFlavorRules().getItems();
    boolean containsTemplates = (templates != null && CollectionUtils.isNotEmpty(templates.getItems()));
    IfExpression current =  containsTemplates ? templates.getRule(ruleId) : null;
    flavorRules.addAll(PendingChangeStatusHelper.getPendingFlavorRules(pendingChangesStatus));
    return deleteRule(appName, ruleId, current, flavorRules, ApplicationStatusMode.OFFLINE);
}
 
Example 9
Project: xxl-job   File: XxlJobServiceImpl.java   View Source Code Vote up 6 votes
@Override
public Map<String, Object> dashboardInfo() {

	int jobInfoCount = xxlJobInfoDao.findAllCount();
	int jobLogCount = xxlJobLogDao.triggerCountByHandleCode(-1);
	int jobLogSuccessCount = xxlJobLogDao.triggerCountByHandleCode(ReturnT.SUCCESS_CODE);

	// executor count
	Set<String> executerAddressSet = new HashSet<String>();
	List<XxlJobGroup> groupList = xxlJobGroupDao.findAll();
	if (CollectionUtils.isNotEmpty(groupList)) {
		for (XxlJobGroup group: groupList) {
			List<String> registryList = null;
			if (group.getAddressType() == 0) {
				registryList = JobRegistryMonitorHelper.discover(RegistryConfig.RegistType.EXECUTOR.name(), group.getAppName());
			} else {
				if (StringUtils.isNotBlank(group.getAddressList())) {
					registryList = Arrays.asList(group.getAddressList().split(","));
				}
			}
			if (CollectionUtils.isNotEmpty(registryList)) {
				executerAddressSet.addAll(registryList);
			}
		}
	}
	int executorCount = executerAddressSet.size();

	Map<String, Object> dashboardMap = new HashMap<String, Object>();
	dashboardMap.put("jobInfoCount", jobInfoCount);
	dashboardMap.put("jobLogCount", jobLogCount);
	dashboardMap.put("jobLogSuccessCount", jobLogSuccessCount);
	dashboardMap.put("executorCount", executorCount);
	return dashboardMap;
}
 
Example 10
Project: Dragonfly   File: PeerTaskServiceImpl.java   View Source Code Vote up 6 votes
@Override
public boolean gc(GcMeta gcMeta) {
    boolean result = false;
    if (gcMeta != null) {
        List<String> cids = gcMeta.getCids();
        String taskId = gcMeta.getTaskId();
        if (CollectionUtils.isNotEmpty(cids) && taskId != null) {
            for (String cid : cids) {
                peerTaskRepo.remove(taskId, cid);
            }
        }
        result = true;
    }
    return result;
}
 
Example 11
Project: vind   File: SolrFilterSerializer.java   View Source Code Vote up 6 votes
public Filter coolNamedMethod(Filter.OrFilter filter) {
    final Set<Filter> filters = filter.getChildren().stream()
            .map(f -> checkScopeValidity(f))
            .filter(f -> Objects.nonNull(f))
            .collect(Collectors.toSet());
    if (filters.size() > 1) {
        return Filter.OrFilter.fromSet(filters);
    } else if (CollectionUtils.isNotEmpty(filters)){
        return filters.iterator().next();
    }
    return null;
}
 
Example 12
Project: wish-pay   File: ValidationUtils.java   View Source Code Vote up 6 votes
public static <T> ValidationResult validateProperty(T obj, String propertyName) {
    ValidationResult result = new ValidationResult();
    Set<ConstraintViolation<T>> set = validator.validateProperty(obj, propertyName, Default.class);
    if (CollectionUtils.isNotEmpty(set)) {
        result.setHasErrors(true);
        Map<String, String> errorMsg = Maps.newHashMap();
        for (ConstraintViolation<T> cv : set) {
            errorMsg.put(propertyName, cv.getMessage());
        }
        result.setErrorMsg(errorMsg);
    }
    return result;
}
 
Example 13
Project: xxl-api   File: XxlApiDataTypeServiceImpl.java   View Source Code Vote up 6 votes
/**
 * parse field of datatype (注意,循环引用问题;此处显示最长引用链路长度为5;)
 *
 * @param dataType
 * @param maxRelateLevel
 * @return
 */
private XxlApiDataType fillFileDataType(XxlApiDataType dataType, int maxRelateLevel){
	// init field list
	List<XxlApiDataTypeField> fieldList = xxlApiDataTypeFieldDao.findByParentDatatypeId(dataType.getId());
	dataType.setFieldList(fieldList);
	// parse field list
	if (CollectionUtils.isNotEmpty(dataType.getFieldList()) && maxRelateLevel>0) {
		for (XxlApiDataTypeField field: dataType.getFieldList()) {
			XxlApiDataType fieldDataType = xxlApiDataTypeDao.load(field.getFieldDatatypeId());
			fieldDataType = fillFileDataType(fieldDataType, --maxRelateLevel);
			field.setFieldDatatype(fieldDataType);
		}
	}
	return dataType;
}
 
Example 14
Project: jspider   File: RandomProxyStrategy.java   View Source Code Vote up 6 votes
@Override
public HttpProxy getProxy(List<HttpProxy> httpProxies) {
    if (CollectionUtils.isNotEmpty(httpProxies)) {
        return httpProxies.get(new Random().nextInt(httpProxies.size()-1));
    }
    return null;
}
 
Example 15
Project: jspider   File: SequenceProxyStrategy.java   View Source Code Vote up 6 votes
@Override
public HttpProxy getProxy(List<HttpProxy> httpProxies) {
    if (CollectionUtils.isNotEmpty(httpProxies)) {
        return httpProxies.get(index.getAndIncrement() % httpProxies.size());
    }
    return null;
}
 
Example 16
Project: GoPush   File: PingPongProcessor.java   View Source Code Vote up 6 votes
protected void liveHandShake(List<Object[]> batchReq) {
    if (CollectionUtils.isNotEmpty(batchReq)) {

        batchReq.stream().forEach((ele) -> {
            String device = (String) ele[0];
            int[] idles = (int[]) ele[1];
            redisTemplate.expire(RedisKeyEnum.DEVICE_KEY.getValue() + device, idles[0], TimeUnit.SECONDS);
        });

    }
}
 
Example 17
Project: visitormanagement   File: VisitorResource.java   View Source Code Vote up 5 votes
@RequestMapping(value = "/origins", method = RequestMethod.GET)
@ApiOperation(value = "Fetch visitor categories", response = ResponseDTO.class)
public ResponseEntity<Map<String, Object>> getVisitorOrigin() {
	ResponseEntity<Map<String, Object>> result = ResponseEntity.notFound().build();
	try {
		List<Origin> visitorOrigin = visitorService.getVisitorOriginCategories();
		Collection<VisitorOriginDTO> visitorOriginDTO = originConverter.convertToDTO(visitorOrigin);
		if (CollectionUtils.isNotEmpty(visitorOriginDTO)) {
			ResponseDTO responseDTO = new ResponseDTO(ZvisitorResource.origin.toString(), visitorOriginDTO);
			result = ResponseEntity.ok(responseDTO.getResponse());
		}
	} catch(Exception e) {
		logger.error("Exception while fetching all categories.", e);
		result = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
	}
	return result;
}
 
Example 18
Project: happylifeplat-transaction   File: TxManagerServiceImpl.java   View Source Code Vote up 5 votes
/**
 * 保存事务组 在事务发起方的时候进行调用
 *
 * @param txTransactionGroup 事务组
 * @return true 成功 false 失败
 */
@Override

public Boolean saveTxTransactionGroup(TxTransactionGroup txTransactionGroup) {
    try {
        final String groupId = txTransactionGroup.getId();
        //保存数据 到sortSet
        redisTemplate.opsForZSet()
                .add(CommonConstant.REDIS_KEY_SET, groupId, CommonConstant.REDIS_SCOPE);

        final List<TxTransactionItem> itemList = txTransactionGroup.getItemList();
        if (CollectionUtils.isNotEmpty(itemList)) {
            for (TxTransactionItem item : itemList) {
                redisTemplate.opsForHash().put(cacheKey(groupId), item.getTaskKey(), item);
            }
        }
    } catch (Exception e) {
        return false;
    }

    return true;
}
 
Example 19
Project: X-mall   File: CartServiceImpl.java   View Source Code Vote up 5 votes
private CartVo getCartVoLimit(Integer userId) {
    CartVo cartVo = new CartVo();
    List<Cart> cartList = cartMapper.selectCartByUserId(userId);
    List<CartProductVo> cartProductVoList = Lists.newArrayList();

    BigDecimal cartTotalPrice = new BigDecimal("0");

    if (CollectionUtils.isNotEmpty(cartList)) {
        for (Cart cartItem : cartList) {
            CartProductVo cartProductVo = new CartProductVo();
            cartProductVo.setId(cartItem.getId());
            cartProductVo.setUserId(userId);
            cartProductVo.setProductId(cartItem.getProductId());

            Product product = productMapper.selectByPrimaryKey(cartItem.getProductId());
            if (product != null) {
                cartProductVo.setProductMainImage(product.getMainImage());
                cartProductVo.setProductName(product.getName());
                cartProductVo.setProductSubtitle(product.getSubtitle());
                cartProductVo.setProductStatus(product.getStatus());
                cartProductVo.setProductPrice(product.getPrice());
                cartProductVo.setProductStock(product.getStock());
                //判断库存
                int buyLimitCount = 0;
                if (product.getStock() >= cartItem.getQuantity()) {
                    //库存充足的时候
                    buyLimitCount = cartItem.getQuantity();
                    cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                } else {
                    buyLimitCount = product.getStock();
                    cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FAIL);
                    //购物车中更新有效库存
                    Cart cartForQuantity = new Cart();
                    cartForQuantity.setId(cartItem.getId());
                    cartForQuantity.setQuantity(buyLimitCount);
                    cartMapper.updateByPrimaryKeySelective(cartForQuantity);
                }
                cartProductVo.setQuantity(buyLimitCount);
                //计算总价
                cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                cartProductVo.setProductChecked(cartItem.getChecked());
            }

            if (cartItem.getChecked() == Const.Cart.CHECKED) {
                //如果已经勾选,增加到整个的购物车总价中
                cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
            }
            cartProductVoList.add(cartProductVo);
        }
    }
    cartVo.setCartTotalPrice(cartTotalPrice);
    cartVo.setCartProductVoList(cartProductVoList);
    cartVo.setAllChecked(this.getAllCheckedStatus(userId));
    cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

    return cartVo;
}
 
Example 20
Project: stage-job   File: JobRegistryMonitorHelper.java   View Source Code Vote up 5 votes
public void start(){
	registryThread = new Thread(new Runnable() {
		@Override
		public void run() {
			while (!toStop) {
				try {
					// auto registry group
					List<XxlJobGroup> groupList = XxlJobDynamicScheduler.xxlJobGroupDao.findByAddressType(0);
					if (CollectionUtils.isNotEmpty(groupList)) {

						// remove dead address (admin/executor)
						XxlJobDynamicScheduler.xxlJobRegistryDao.removeDead(RegistryConfig.DEAD_TIMEOUT);

						// fresh online address (admin/executor)
						HashMap<String, List<String>> appAddressMap = new HashMap<String, List<String>>();
						List<XxlJobRegistry> list = XxlJobDynamicScheduler.xxlJobRegistryDao.findAll(RegistryConfig.DEAD_TIMEOUT);
						if (list != null) {
							for (XxlJobRegistry item: list) {
								if (RegistryConfig.RegistType.EXECUTOR.name().equals(item.getRegistryGroup())) {
									String appName = item.getRegistryKey();
									List<String> registryList = appAddressMap.get(appName);
									if (registryList == null) {
										registryList = new ArrayList<String>();
									}

									if (!registryList.contains(item.getRegistryValue())) {
										registryList.add(item.getRegistryValue());
									}
									appAddressMap.put(appName, registryList);
								}
							}
						}

						// fresh group address
						for (XxlJobGroup group: groupList) {
							List<String> registryList = appAddressMap.get(group.getAppName());
							String addressListStr = null;
							if (CollectionUtils.isNotEmpty(registryList)) {
								Collections.sort(registryList);
								addressListStr = StringUtils.join(registryList, ",");
							}
							group.setAddressList(addressListStr);
							XxlJobDynamicScheduler.xxlJobGroupDao.update(group);
						}
					}
				} catch (Exception e) {
					logger.error("job registry instance error:{}", e);
				}
				try {
					TimeUnit.SECONDS.sleep(RegistryConfig.BEAT_TIMEOUT);
				} catch (InterruptedException e) {
					logger.error("job registry instance error:{}", e);
				}
			}
		}
	});
	registryThread.setDaemon(true);
	registryThread.start();
}