Java Code Examples for com.alibaba.csp.sentinel.util.StringUtil#isBlank()

The following examples show how to use com.alibaba.csp.sentinel.util.StringUtil#isBlank() . 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: FlowRuleApiProvider.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public List<FlowRuleEntity> getRules(String appName) throws Exception {
    if (StringUtil.isBlank(appName)) {
        return new ArrayList<>();
    }
    List<MachineInfo> list = appManagement.getDetailApp(appName).getMachines()
        .stream()
        .filter(MachineInfo::isHealthy)
        .sorted((e1, e2) -> Long.compare(e2.getLastHeartbeat(), e1.getLastHeartbeat())).collect(Collectors.toList());
    if (list.isEmpty()) {
        return new ArrayList<>();
    } else {
        MachineInfo machine = list.get(0);
        return sentinelApiClient.fetchFlowRuleOfMachine(machine.getApp(), machine.getIp(), machine.getPort());
    }
}
 
Example 2
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
public CompletableFuture<List<GatewayFlowRuleEntity>> fetchGatewayFlowRules(String app, String ip, int port) {
    if (StringUtil.isBlank(ip) || port <= 0) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter"));
    }

    try {
        return executeCommand(ip, port, FETCH_GATEWAY_FLOW_RULE_PATH, false)
                .thenApply(r -> {
                    List<GatewayFlowRule> gatewayFlowRules = JSON.parseArray(r, GatewayFlowRule.class);
                    List<GatewayFlowRuleEntity> entities = gatewayFlowRules.stream().map(rule -> GatewayFlowRuleEntity.fromGatewayFlowRule(app, ip, port, rule)).collect(Collectors.toList());
                    return entities;
                });
    } catch (Exception ex) {
        logger.warn("Error when fetching gateway flow rules", ex);
        return AsyncUtils.newFailedFuture(ex);
    }
}
 
Example 3
Source File: AbstractSentinelAspectSupport.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private Method extractFallbackMethod(ProceedingJoinPoint pjp, String fallbackName, Class<?>[] locationClass) {
    if (StringUtil.isBlank(fallbackName)) {
        return null;
    }
    boolean mustStatic = locationClass != null && locationClass.length >= 1;
    Class<?> clazz = mustStatic ? locationClass[0] : pjp.getTarget().getClass();
    MethodWrapper m = ResourceMetadataRegistry.lookupFallback(clazz, fallbackName);
    if (m == null) {
        // First time, resolve the fallback.
        Method method = resolveFallbackInternal(pjp, fallbackName, clazz, mustStatic);
        // Cache the method instance.
        ResourceMetadataRegistry.updateFallbackFor(clazz, fallbackName, method);
        return method;
    }
    if (!m.isPresent()) {
        return null;
    }
    return m.getMethod();
}
 
Example 4
Source File: ModifyClusterClientConfigHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "utf-8");
        RecordLog.info("[ModifyClusterClientConfigHandler] Receiving cluster client config: " + data);
        ClusterClientStateEntity entity = JSON.parseObject(data, ClusterClientStateEntity.class);

        ClusterClientConfigManager.applyNewConfig(entity.toClientConfig());
        ClusterClientConfigManager.applyNewAssignConfig(entity.toAssignConfig());

        return CommandResponse.ofSuccess(CommandConstants.MSG_SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterClientConfigHandler] Decode client cluster config error", e);
        return CommandResponse.ofFailure(e, "decode client cluster config error");
    }
}
 
Example 5
Source File: ModifyClusterFlowRulesCommandHandler.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    String namespace = request.getParam("namespace");
    if (StringUtil.isEmpty(namespace)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty namespace"));
    }
    String data = request.getParam("data");
    if (StringUtil.isBlank(data)) {
        return CommandResponse.ofFailure(new IllegalArgumentException("empty data"));
    }
    try {
        data = URLDecoder.decode(data, "UTF-8");
        RecordLog.info("[ModifyClusterFlowRulesCommandHandler] Receiving cluster flow rules for namespace <{}>: {}", namespace, data);

        List<FlowRule> flowRules = JSONArray.parseArray(data, FlowRule.class);
        ClusterFlowRuleManager.loadRules(namespace, flowRules);

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterFlowRulesCommandHandler] Decode cluster flow rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster flow rules error");
    }
}
 
Example 6
Source File: DegradeRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
public static boolean isValidRule(DegradeRule rule) {
    boolean baseValid = rule != null && !StringUtil.isBlank(rule.getResource())
        && rule.getCount() >= 0 && rule.getTimeWindow() > 0;
    if (!baseValid) {
        return false;
    }
    int maxAllowedRt = Constants.TIME_DROP_VALVE;
    if (rule.getGrade() == RuleConstant.DEGRADE_GRADE_RT) {
        if (rule.getRtSlowRequestAmount() <= 0) {
            return false;
        }
        // Warn for RT mode that exceeds the {@code TIME_DROP_VALVE}.
        if (rule.getCount() > maxAllowedRt) {
            RecordLog.warn(String.format("[DegradeRuleManager] WARN: setting large RT threshold (%.1f ms)"
                    + " in RT mode will not take effect since it exceeds the max allowed value (%d ms)",
                rule.getCount(), maxAllowedRt));
        }
    }

    // Check exception ratio mode.
    if (rule.getGrade() == RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO) {
        return rule.getCount() <= 1 && rule.getMinRequestAmount() > 0;
    }
    return true;
}
 
Example 7
Source File: PingRequestDataWriter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(String entity, ByteBuf target) {
    if (StringUtil.isBlank(entity) || target == null) {
        return;
    }
    byte[] bytes = entity.getBytes();
    target.writeInt(bytes.length);
    target.writeBytes(bytes);
}
 
Example 8
Source File: ParamFlowRuleUtil.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * Check whether the provided rule is valid.
 *
 * @param rule any parameter rule
 * @return true if valid, otherwise false
 */
public static boolean isValidRule(ParamFlowRule rule) {
    return rule != null && !StringUtil.isBlank(rule.getResource()) && rule.getCount() >= 0
        && rule.getGrade() >= 0 && rule.getParamIdx() != null
        && rule.getBurstCount() >= 0 && rule.getControlBehavior() >= 0
        && rule.getDurationInSec() > 0 && rule.getMaxQueueingTimeMs() >= 0
        && checkCluster(rule);
}
 
Example 9
Source File: ParamFlowRuleUtil.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
static Object parseItemValue(String value, String classType) {
    if (value == null) {
        throw new IllegalArgumentException("Null value");
    }
    if (StringUtil.isBlank(classType)) {
        // If the class type is not provided, then treat it as string.
        return value;
    }
    // Handle primitive type.
    if (int.class.toString().equals(classType) || Integer.class.getName().equals(classType)) {
        return Integer.parseInt(value);
    } else if (boolean.class.toString().equals(classType) || Boolean.class.getName().equals(classType)) {
        return Boolean.parseBoolean(value);
    } else if (long.class.toString().equals(classType) || Long.class.getName().equals(classType)) {
        return Long.parseLong(value);
    } else if (double.class.toString().equals(classType) || Double.class.getName().equals(classType)) {
        return Double.parseDouble(value);
    } else if (float.class.toString().equals(classType) || Float.class.getName().equals(classType)) {
        return Float.parseFloat(value);
    } else if (byte.class.toString().equals(classType) || Byte.class.getName().equals(classType)) {
        return Byte.parseByte(value);
    } else if (short.class.toString().equals(classType) || Short.class.getName().equals(classType)) {
        return Short.parseShort(value);
    } else if (char.class.toString().equals(classType)) {
        char[] array = value.toCharArray();
        return array.length > 0 ? array[0] : null;
    }

    return value;
}
 
Example 10
Source File: TransportConfig.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * Get the heartbeat api path. If the machine registry path of the dashboard
 * is modified, then the API path should also be consistent with the API path of the dashboard.
 *
 * @return the heartbeat api path
 * @since 1.7.1
 */
public static String getHeartbeatApiPath() {
    String apiPath = SentinelConfig.getConfig(HEARTBEAT_API_PATH);
    if (StringUtil.isBlank(apiPath)) {
        return HEARTBEAT_DEFAULT_PATH;
    }
    if (!apiPath.startsWith("/")) {
        apiPath = "/" + apiPath;
    }
    return apiPath;
}
 
Example 11
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<ClusterServerStateVO> fetchClusterServerBasicInfo(String ip, int port) {
    if (StringUtil.isBlank(ip) || port <= 0) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter"));
    }
    try {
        return executeCommand(ip, port, FETCH_CLUSTER_SERVER_BASIC_INFO_PATH, false)
            .thenApply(r -> JSON.parseObject(r, ClusterServerStateVO.class));
    } catch (Exception ex) {
        logger.warn("Error when fetching cluster sever all config and basic info", ex);
        return AsyncUtils.newFailedFuture(ex);
    }
}
 
Example 12
Source File: AuthorityRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private Map<String, Set<AuthorityRule>> loadAuthorityConf(List<AuthorityRule> list) {
    Map<String, Set<AuthorityRule>> newRuleMap = new ConcurrentHashMap<>();

    if (list == null || list.isEmpty()) {
        return newRuleMap;
    }

    for (AuthorityRule rule : list) {
        if (!isValidRule(rule)) {
            RecordLog.warn("[AuthorityRuleManager] Ignoring invalid authority rule when loading new rules: " + rule);
            continue;
        }

        if (StringUtil.isBlank(rule.getLimitApp())) {
            rule.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
        }

        String identity = rule.getResource();
        Set<AuthorityRule> ruleSet = newRuleMap.get(identity);
        // putIfAbsent
        if (ruleSet == null) {
            ruleSet = new HashSet<>();
            ruleSet.add(rule);
            newRuleMap.put(identity, ruleSet);
        } else {
            // One resource should only have at most one authority rule, so just ignore redundant rules.
            RecordLog.warn("[AuthorityRuleManager] Ignoring redundant rule: " + rule.toString());
        }
    }

    return newRuleMap;
}
 
Example 13
Source File: PingRequestDataWriter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(String entity, ByteBuf target) {
    if (StringUtil.isBlank(entity) || target == null) {
        return;
    }
    byte[] bytes = entity.getBytes();
    target.writeInt(bytes.length);
    target.writeBytes(bytes);
}
 
Example 14
Source File: AuthorityRuleController.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private <R> Result<R> checkEntityInternal(AuthorityRuleEntity entity) {
    if (entity == null) {
        return Result.ofFail(-1, "bad rule body");
    }
    if (StringUtil.isBlank(entity.getApp())) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    if (StringUtil.isBlank(entity.getIp())) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    if (entity.getPort() == null || entity.getPort() <= 0) {
        return Result.ofFail(-1, "port can't be null");
    }
    if (entity.getRule() == null) {
        return Result.ofFail(-1, "rule can't be null");
    }
    if (StringUtil.isBlank(entity.getResource())) {
        return Result.ofFail(-1, "resource name cannot be null or empty");
    }
    if (StringUtil.isBlank(entity.getLimitApp())) {
        return Result.ofFail(-1, "limitApp should be valid");
    }
    if (entity.getStrategy() != RuleConstant.AUTHORITY_WHITE
        && entity.getStrategy() != RuleConstant.AUTHORITY_BLACK) {
        return Result.ofFail(-1, "Unknown strategy (must be blacklist or whitelist)");
    }
    return null;
}
 
Example 15
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public CompletableFuture<Void> setParamFlowRuleOfMachine(String app, String ip, int port, List<ParamFlowRuleEntity> rules) {
    if (rules == null) {
        return CompletableFuture.completedFuture(null);
    }
    if (StringUtil.isBlank(ip) || port <= 0) {
        return AsyncUtils.newFailedFuture(new IllegalArgumentException("Invalid parameter"));
    }
    try {
        String data = JSON.toJSONString(
            rules.stream().map(ParamFlowRuleEntity::getRule).collect(Collectors.toList())
        );
        Map<String, String> params = new HashMap<>(1);
        params.put("data", data);
        return executeCommand(app, ip, port, SET_PARAM_RULE_PATH, params, true)
            .thenCompose(e -> {
                if (CommandConstants.MSG_SUCCESS.equals(e)) {
                    return CompletableFuture.completedFuture(null);
                } else {
                    logger.warn("Push parameter flow rules to client failed: " + e);
                    return AsyncUtils.newFailedFuture(new RuntimeException(e));
                }
            });
    } catch (Exception ex) {
        logger.warn("Error when setting parameter flow rule", ex);
        return AsyncUtils.newFailedFuture(ex);
    }
}
 
Example 16
Source File: AuthorityRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private Map<String, Set<AuthorityRule>> loadAuthorityConf(List<AuthorityRule> list) {
    Map<String, Set<AuthorityRule>> newRuleMap = new ConcurrentHashMap<>();

    if (list == null || list.isEmpty()) {
        return newRuleMap;
    }

    for (AuthorityRule rule : list) {
        if (!isValidRule(rule)) {
            RecordLog.warn("[AuthorityRuleManager] Ignoring invalid authority rule when loading new rules: " + rule);
            continue;
        }

        if (StringUtil.isBlank(rule.getLimitApp())) {
            rule.setLimitApp(RuleConstant.LIMIT_APP_DEFAULT);
        }

        String identity = rule.getResource();
        Set<AuthorityRule> ruleSet = newRuleMap.get(identity);
        // putIfAbsent
        if (ruleSet == null) {
            ruleSet = new HashSet<>();
            ruleSet.add(rule);
            newRuleMap.put(identity, ruleSet);
        } else {
            // One resource should only have at most one authority rule, so just ignore redundant rules.
            RecordLog.warn("[AuthorityRuleManager] Ignoring redundant rule: " + rule.toString());
        }
    }

    return newRuleMap;
}
 
Example 17
Source File: CommandRequest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public CommandRequest addMetadata(String key, String value) {
    if (StringUtil.isBlank(key)) {
        throw new IllegalArgumentException("Metadata key cannot be empty");
    }
    metadata.put(key, value);
    return this;
}
 
Example 18
Source File: GatewayApiController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@PostMapping("/save.json")
public Result<ApiDefinitionEntity> updateApi(HttpServletRequest request, @RequestBody UpdateApiReqVo 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);

    Long id = reqVo.getId();
    if (id == null) {
        return Result.ofFail(-1, "id can't be null");
    }

    ApiDefinitionEntity entity = repository.findById(id);
    if (entity == null) {
        return Result.ofFail(-1, "api does not exist, id=" + id);
    }

    // 匹配规则列表
    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();

        // 匹配模式
        int 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));

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

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

    if (!publishApis(app, entity.getIp(), entity.getPort())) {
        logger.warn("publish gateway apis fail after update");
    }

    return Result.ofSuccess(entity);
}
 
Example 19
Source File: FlowControllerV1.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private <R> Result<R> checkEntityInternal(FlowRuleEntity entity) {
    if (StringUtil.isBlank(entity.getApp())) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    if (StringUtil.isBlank(entity.getIp())) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    if (entity.getPort() == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    if (StringUtil.isBlank(entity.getLimitApp())) {
        return Result.ofFail(-1, "limitApp can't be null or empty");
    }
    if (StringUtil.isBlank(entity.getResource())) {
        return Result.ofFail(-1, "resource can't be null or empty");
    }
    if (entity.getGrade() == null) {
        return Result.ofFail(-1, "grade can't be null");
    }
    if (entity.getGrade() != 0 && entity.getGrade() != 1) {
        return Result.ofFail(-1, "grade must be 0 or 1, but " + entity.getGrade() + " got");
    }
    if (entity.getCount() == null || entity.getCount() < 0) {
        return Result.ofFail(-1, "count should be at lease zero");
    }
    if (entity.getStrategy() == null) {
        return Result.ofFail(-1, "strategy can't be null");
    }
    if (entity.getStrategy() != 0 && StringUtil.isBlank(entity.getRefResource())) {
        return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0");
    }
    if (entity.getControlBehavior() == null) {
        return Result.ofFail(-1, "controlBehavior can't be null");
    }
    int controlBehavior = entity.getControlBehavior();
    if (controlBehavior == 1 && entity.getWarmUpPeriodSec() == null) {
        return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1");
    }
    if (controlBehavior == 2 && entity.getMaxQueueingTimeMs() == null) {
        return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2");
    }
    if (entity.isClusterMode() && entity.getClusterConfig() == null) {
        return Result.ofFail(-1, "cluster config should be valid");
    }
    return null;
}
 
Example 20
Source File: ResourceMetadataRegistry.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
static void updateBlockHandlerFor(Class<?> clazz, String name, Method method) {
    if (clazz == null || StringUtil.isBlank(name)) {
        throw new IllegalArgumentException("Bad argument");
    }
    BLOCK_HANDLER_MAP.put(getKey(clazz, name), MethodWrapper.wrap(method));
}