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

The following examples show how to use com.alibaba.csp.sentinel.util.StringUtil#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: FlowControllerV1.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@GetMapping("/rules")
@AuthAction(PrivilegeType.READ_RULE)
public Result<List<FlowRuleEntity>> apiQueryMachineRules(@RequestParam String app,
                                                         @RequestParam String ip,
                                                         @RequestParam Integer port) {

    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    if (StringUtil.isEmpty(ip)) {
        return Result.ofFail(-1, "ip can't be null or empty");
    }
    if (port == null) {
        return Result.ofFail(-1, "port can't be null");
    }
    try {
        List<FlowRuleEntity> rules = sentinelApiClient.fetchFlowRuleOfMachine(app, ip, port);
        rules = repository.saveAll(rules);
        return Result.ofSuccess(rules);
    } catch (Throwable throwable) {
        logger.error("Error when querying flow rules", throwable);
        return Result.ofThrowable(-1, throwable);
    }
}
 
Example 2
Source File: MetricFetcher.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void handleResponse(final HttpResponse response, MachineInfo machine,
                            Map<String, MetricEntity> metricMap) throws Exception {
    int code = response.getStatusLine().getStatusCode();
    if (code != HTTP_OK) {
        return;
    }
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader("Content-type").getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    String body = EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
    if (StringUtil.isEmpty(body) || body.startsWith(NO_METRICS)) {
        //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() + ", bodyStr is empty");
        return;
    }
    String[] lines = body.split("\n");
    //logger.info(machine.getApp() + ":" + machine.getIp() + ":" + machine.getPort() +
    //    ", bodyStr.length()=" + body.length() + ", lines=" + lines.length);
    handleBody(lines, machine, metricMap);
}
 
Example 3
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 4
Source File: ModifyClusterFlowRulesCommandHandler.java    From Sentinel-Dashboard-Nacos 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 <{0}>: {1}", 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 5
Source File: FlowControllerV2.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@GetMapping("/rules")
@AuthAction(PrivilegeType.READ_RULE)
public Result<List<FlowRuleEntity>> apiQueryMachineRules(@RequestParam String app) {

    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app can't be null or empty");
    }
    try {
        List<FlowRuleEntity> rules = ruleProvider.getRules(app);
        if (rules != null && !rules.isEmpty()) {
            for (FlowRuleEntity entity : rules) {
                entity.setApp(app);
                if (entity.getClusterConfig() != null && entity.getClusterConfig().getFlowId() != null) {
                    entity.setId(entity.getClusterConfig().getFlowId());
                }
            }
        }
        rules = repository.saveAll(rules);
        return Result.ofSuccess(rules);
    } catch (Throwable throwable) {
        logger.error("Error when querying flow rules", throwable);
        return Result.ofThrowable(-1, throwable);
    }
}
 
Example 6
Source File: ClusterAssignController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@PostMapping("/all_server/{app}")
public Result<ClusterAppAssignResultVO> apiAssignAllClusterServersOfApp(@PathVariable String app,
                                                                        @RequestBody
                                                                            ClusterAppFullAssignRequest assignRequest) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (assignRequest == null || assignRequest.getClusterMap() == null
        || assignRequest.getRemainingList() == null) {
        return Result.ofFail(-1, "bad request body");
    }
    try {
        return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, assignRequest.getClusterMap(),
            assignRequest.getRemainingList()));
    } catch (Throwable throwable) {
        logger.error("Error when assigning full cluster servers for app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example 7
Source File: ClusterConfigController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private Result<Boolean> checkValidRequest(ClusterModifyRequest request) {
    if (StringUtil.isEmpty(request.getApp())) {
        return Result.ofFail(-1, "app cannot be empty");
    }
    if (StringUtil.isEmpty(request.getIp())) {
        return Result.ofFail(-1, "ip cannot be empty");
    }
    if (request.getPort() == null || request.getPort() < 0) {
        return Result.ofFail(-1, "invalid port");
    }
    if (request.getMode() == null || request.getMode() < 0) {
        return Result.ofFail(-1, "invalid mode");
    }
    if (!checkIfSupported(request.getApp(), request.getIp(), request.getPort())) {
        return unsupportedVersion();
    }
    return null;
}
 
Example 8
Source File: ClusterFlowRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Get all cluster flow rules within a specific namespace.
 *
 * @param namespace valid namespace
 * @return cluster flow rules within the provided namespace
 */
public static List<FlowRule> getFlowRules(String namespace) {
    if (StringUtil.isEmpty(namespace)) {
        return new ArrayList<>();
    }
    List<FlowRule> rules = new ArrayList<>();
    Set<Long> flowIdSet = NAMESPACE_FLOW_ID_MAP.get(namespace);
    if (flowIdSet == null || flowIdSet.isEmpty()) {
        return rules;
    }
    for (Long flowId : flowIdSet) {
        FlowRule rule = FLOW_RULES.get(flowId);
        if (rule != null) {
            rules.add(rule);
        }
    }
    return rules;
}
 
Example 9
Source File: ClusterAssignController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
@PostMapping("/single_server/{app}")
public Result<ClusterAppAssignResultVO> apiAssignSingleClusterServersOfApp(@PathVariable String app,
                                                                           @RequestBody ClusterAppSingleServerAssignRequest assignRequest) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (assignRequest == null || assignRequest.getClusterMap() == null) {
        return Result.ofFail(-1, "bad request body");
    }
    try {
        return Result.ofSuccess(clusterAssignService.applyAssignToApp(app, Collections.singletonList(assignRequest.getClusterMap()),
            assignRequest.getRemainingList()));
    } catch (Throwable throwable) {
        logger.error("Error when assigning single cluster servers for app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example 10
Source File: ClusterConfigController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@GetMapping("/client_state/{app}")
public Result<List<AppClusterClientStateWrapVO>> apiGetClusterClientStateOfApp(@PathVariable String app) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    try {
        return clusterConfigService.getClusterUniversalState(app)
            .thenApply(ClusterEntityUtils::wrapToAppClusterClientState)
            .thenApply(Result::ofSuccess)
            .get();
    } catch (ExecutionException ex) {
        logger.error("Error when fetching cluster token client state of app: " + app, ex.getCause());
        return errorResponse(ex);
    } catch (Throwable throwable) {
        logger.error("Error when fetching cluster token client state of app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example 11
Source File: ClusterConfigController.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@GetMapping("/server_state/{app}")
public Result<List<AppClusterServerStateWrapVO>> apiGetClusterServerStateOfApp(@PathVariable String app) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    try {
        return clusterConfigService.getClusterUniversalState(app)
            .thenApply(ClusterEntityUtils::wrapToAppClusterServerState)
            .thenApply(Result::ofSuccess)
            .get();
    } catch (ExecutionException ex) {
        logger.error("Error when fetching cluster server state of app: " + app, ex.getCause());
        return errorResponse(ex);
    } catch (Throwable throwable) {
        logger.error("Error when fetching cluster server state of app: " + app, throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example 12
Source File: ModifyClusterParamFlowRulesCommandHandler.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("Receiving cluster param rules for namespace <{}> from command handler: {}", namespace, data);

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

        return CommandResponse.ofSuccess(SUCCESS);
    } catch (Exception e) {
        RecordLog.warn("[ModifyClusterParamFlowRulesCommandHandler] Decode cluster param rules error", e);
        return CommandResponse.ofFailure(e, "decode cluster param rules error");
    }
}
 
Example 13
Source File: MachineUtils.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static Optional<Tuple2<String, Integer>> parseCommandIpAndPort(String machineIp) {
    try {
        if (StringUtil.isEmpty(machineIp) || !machineIp.contains("@")) {
            return Optional.empty();
        }
        String[] str = machineIp.split("@");
        if (str.length <= 1) {
            return Optional.empty();
        }
        return Optional.of(Tuple2.of(str[0], Integer.parseInt(str[1])));
    } catch (Exception ex) {
        return Optional.empty();
    }
}
 
Example 14
Source File: FlowRuleNacosProvider.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public List<FlowRuleEntity> getRules(String appName) throws Exception {
    String rules = configService.getConfig(appName + NacosConfigUtil.FLOW_DATA_ID_POSTFIX,
        NacosConfigUtil.GROUP_ID, 3000);
    if (StringUtil.isEmpty(rules)) {
        return new ArrayList<>();
    }
    return converter.convert(rules);
}
 
Example 15
Source File: HttpServerHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private String parseTarget(String uri) {
    if (StringUtil.isEmpty(uri)) {
        return "";
    }

    // Remove the / of the uri as the target(command name)
    // Usually the uri is start with /
    int start = uri.indexOf('/');
    if (start != -1) {
        return uri.substring(start + 1);
    }

    return uri;
}
 
Example 16
Source File: GatewayParamParser.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private String parseUrlParameter(/*@Valid*/ GatewayParamFlowItem item, T request) {
    String paramName = item.getFieldName();
    String pattern = item.getPattern();
    String param = requestItemParser.getUrlParam(request, paramName);
    if (StringUtil.isEmpty(pattern)) {
        return param;
    }
    // Match value according to regex pattern or exact mode.
    return parseWithMatchStrategyInternal(item.getMatchStrategy(), param, pattern);
}
 
Example 17
Source File: ClusterConfigController.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@GetMapping("/state_single")
public Result<ClusterUniversalStateVO> apiGetClusterState(@RequestParam String app,
                                                          @RequestParam String ip,
                                                          @RequestParam Integer port) {
    if (StringUtil.isEmpty(app)) {
        return Result.ofFail(-1, "app cannot be null or empty");
    }
    if (StringUtil.isEmpty(ip)) {
        return Result.ofFail(-1, "ip cannot be null or empty");
    }
    if (port == null || port <= 0) {
        return Result.ofFail(-1, "Invalid parameter: port");
    }
    if (!checkIfSupported(app, ip, port)) {
        return unsupportedVersion();
    }
    try {
        return clusterConfigService.getClusterUniversalState(app, ip, port)
            .thenApply(Result::ofSuccess)
            .get();
    } catch (ExecutionException ex) {
        logger.error("Error when fetching cluster state", ex.getCause());
        return errorResponse(ex);
    } catch (Throwable throwable) {
        logger.error("Error when fetching cluster state", throwable);
        return Result.ofFail(-1, throwable.getMessage());
    }
}
 
Example 18
Source File: SimpleHttpCommandCenter.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
public static void registerCommand(String commandName, CommandHandler handler) {
    if (StringUtil.isEmpty(commandName)) {
        return;
    }

    if (handlerMap.containsKey(commandName)) {
        CommandCenterLog.warn("Register failed (duplicate command): " + commandName);
        return;
    }

    handlerMap.put(commandName, handler);
}
 
Example 19
Source File: RedisConnectionConfig.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
/**
 * @return the RedisConnectionConfig.
 */
public RedisConnectionConfig build() {

    if (redisSentinels.isEmpty() && StringUtil.isEmpty(host)) {
        throw new IllegalStateException(
            "Cannot build a RedisConnectionConfig. One of the following must be provided Host, Socket or "
                + "Sentinel");
    }

    RedisConnectionConfig redisURI = new RedisConnectionConfig();
    redisURI.setHost(host);
    redisURI.setPort(port);

    if (password != null) {
        redisURI.setPassword(password);
    }

    redisURI.setDatabase(database);
    redisURI.setClientName(clientName);

    redisURI.setRedisSentinelMasterId(redisSentinelMasterId);

    for (RedisHostAndPort sentinel : redisSentinels) {
        redisURI.getRedisSentinels().add(
            new RedisConnectionConfig(sentinel.getHost(), sentinel.getPort(), timeout));
    }

    redisURI.setTimeout(timeout);

    return redisURI;
}
 
Example 20
Source File: RedisConnectionConfig.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
/**
 * @return the RedisConnectionConfig.
 */
public RedisConnectionConfig build() {

    if (redisSentinels.isEmpty() && StringUtil.isEmpty(host)) {
        throw new IllegalStateException(
            "Cannot build a RedisConnectionConfig. One of the following must be provided Host, Socket or "
                + "Sentinel");
    }

    RedisConnectionConfig redisURI = new RedisConnectionConfig();
    redisURI.setHost(host);
    redisURI.setPort(port);

    if (password != null) {
        redisURI.setPassword(password);
    }

    redisURI.setDatabase(database);
    redisURI.setClientName(clientName);

    redisURI.setRedisSentinelMasterId(redisSentinelMasterId);

    for (RedisHostAndPort sentinel : redisSentinels) {
        redisURI.getRedisSentinels().add(
            new RedisConnectionConfig(sentinel.getHost(), sentinel.getPort(), timeout));
    }

    redisURI.setTimeout(timeout);

    return redisURI;
}