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

The following examples show how to use com.alibaba.csp.sentinel.util.StringUtil#isNotBlank() . 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: SentinelJaxRsQuarkusAdapterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
            .setCount(count)
            .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 2
Source File: VersionController.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@GetMapping("/version")
public Result<String> apiGetVersion() {
    if (StringUtil.isNotBlank(sentinelDashboardVersion)) {
        String res = sentinelDashboardVersion;
        if (sentinelDashboardVersion.contains(VERSION_PATTERN)) {
            res = sentinelDashboardVersion.substring(0, sentinelDashboardVersion.indexOf(VERSION_PATTERN));
        }
        return Result.ofSuccess(res);
    } else {
        return Result.ofFail(1, "getVersion failed: empty version");
    }
}
 
Example 3
Source File: ClientFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
            .setCount(count)
            .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 4
Source File: AbstractSentinelInterceptorSupport.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
protected String getResourceName(String resourceName, /*@NonNull*/ Method method) {
    // If resource name is present in annotation, use this value.
    if (StringUtil.isNotBlank(resourceName)) {
        return resourceName;
    }
    // Parse name of target method.
    return MethodUtil.resolveMethodName(method);
}
 
Example 5
Source File: SentinelSCGAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
private void initFallback() {
	FallbackProperties fallbackProperties = gatewayProperties.getFallback();
	if (fallbackProperties == null
			|| StringUtil.isBlank(fallbackProperties.getMode())) {
		return;
	}
	if (ConfigConstants.FALLBACK_MSG_RESPONSE.equals(fallbackProperties.getMode())) {
		if (StringUtil.isNotBlank(fallbackProperties.getResponseBody())) {
			GatewayCallbackManager.setBlockHandler((exchange, t) -> ServerResponse
					.status(fallbackProperties.getResponseStatus())
					.contentType(
							MediaType.valueOf(fallbackProperties.getContentType()))
					.body(fromValue(fallbackProperties.getResponseBody())));
			logger.info(
					"[Sentinel SpringCloudGateway] using AnonymousBlockRequestHandler, responseStatus: "
							+ fallbackProperties.getResponseStatus()
							+ ", responseBody: "
							+ fallbackProperties.getResponseBody());
		}
	}
	String redirectUrl = fallbackProperties.getRedirect();
	if (ConfigConstants.FALLBACK_REDIRECT.equals(fallbackProperties.getMode())
			&& StringUtil.isNotBlank(redirectUrl)) {
		GatewayCallbackManager
				.setBlockHandler(new RedirectBlockRequestHandler(redirectUrl));
		logger.info(
				"[Sentinel SpringCloudGateway] using RedirectBlockRequestHandler, redirectUrl: "
						+ redirectUrl);
	}
}
 
Example 6
Source File: EtcdConfig.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static String getCharset() {
    String etcdCharset = SentinelConfig.getConfig(CHARSET);
    if (StringUtil.isNotBlank(etcdCharset)) {
        return etcdCharset;
    }
    return SentinelConfig.charset();
}
 
Example 7
Source File: AbstractSentinelAspectSupport.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
protected String getResourceName(String resourceName, /*@NonNull*/ Method method) {
    // If resource name is present in annotation, use this value.
    if (StringUtil.isNotBlank(resourceName)) {
        return resourceName;
    }
    // Parse name of target method.
    return MethodUtil.resolveMethodName(method);
}
 
Example 8
Source File: SentinelWebFluxIntegrationTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
        .setCount(count)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 9
Source File: SentinelSpringMvcIntegrationTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
            .setCount(count)
            .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 10
Source File: FilterUtil.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
public static void blockRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    StringBuffer url = request.getRequestURL();

    if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
        url.append("?").append(request.getQueryString());
    }

    if (StringUtil.isBlank(WebServletConfig.getBlockPage())) {
        writeDefaultBlockedPage(response, WebServletConfig.getBlockPageHttpStatus());
    } else {
        String redirectUrl = WebServletConfig.getBlockPage() + "?http_referer=" + url.toString();
        // Redirect to the customized block page.
        response.sendRedirect(redirectUrl);
    }
}
 
Example 11
Source File: CommonFilterTest.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
        .setCount(count)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 12
Source File: FilterUtil.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
public static void blockRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    StringBuffer url = request.getRequestURL();

    if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
        url.append("?").append(request.getQueryString());
    }

    if (StringUtil.isBlank(WebServletConfig.getBlockPage())) {
        writeDefaultBlockedPage(response);
    } else {
        String redirectUrl = WebServletConfig.getBlockPage() + "?http_referer=" + url.toString();
        // Redirect to the customized block page.
        response.sendRedirect(redirectUrl);
    }
}
 
Example 13
Source File: SentinelSpringMvcIntegrationTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureExceptionRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
            .setCount(count)
            .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_RATIO);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 14
Source File: VersionController.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@GetMapping("/version")
public Result<String> apiGetVersion() {
    if (StringUtil.isNotBlank(sentinelDashboardVersion)) {
        String res = sentinelDashboardVersion;
        if (sentinelDashboardVersion.contains(VERSION_PATTERN)) {
            res = sentinelDashboardVersion.substring(0, sentinelDashboardVersion.indexOf(VERSION_PATTERN));
        }
        return Result.ofSuccess(res);
    } else {
        return Result.ofFail(1, "getVersion failed: empty version");
    }
}
 
Example 15
Source File: ProviderFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void configureRulesFor(String resource, int count, String limitApp) {
    FlowRule rule = new FlowRule()
        .setCount(count)
        .setGrade(RuleConstant.FLOW_GRADE_QPS);
    rule.setResource(resource);
    if (StringUtil.isNotBlank(limitApp)) {
        rule.setLimitApp(limitApp);
    }
    FlowRuleManager.loadRules(Collections.singletonList(rule));
}
 
Example 16
Source File: AuthorityRuleManager.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
public static boolean isValidRule(AuthorityRule rule) {
    return rule != null && !StringUtil.isBlank(rule.getResource())
        && rule.getStrategy() >= 0 && StringUtil.isNotBlank(rule.getLimitApp());
}
 
Example 17
Source File: FlowControllerV1.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@PutMapping("/save.json")
public Result<FlowRuleEntity> updateIfNotNull(HttpServletRequest request, Long id, String app,
                                              String limitApp, String resource, Integer grade,
                                              Double count, Integer strategy, String refResource,
                                              Integer controlBehavior, Integer warmUpPeriodSec,
                                              Integer maxQueueingTimeMs) {
    AuthUser authUser = authService.getAuthUser(request);
    authUser.authTarget(app, PrivilegeType.WRITE_RULE);

    if (id == null) {
        return Result.ofFail(-1, "id can't be null");
    }
    FlowRuleEntity entity = repository.findById(id);
    if (entity == null) {
        return Result.ofFail(-1, "id " + id + " dose not exist");
    }
    if (StringUtil.isNotBlank(app)) {
        entity.setApp(app.trim());
    }
    if (StringUtil.isNotBlank(limitApp)) {
        entity.setLimitApp(limitApp.trim());
    }
    if (StringUtil.isNotBlank(resource)) {
        entity.setResource(resource.trim());
    }
    if (grade != null) {
        if (grade != 0 && grade != 1) {
            return Result.ofFail(-1, "grade must be 0 or 1, but " + grade + " got");
        }
        entity.setGrade(grade);
    }
    if (count != null) {
        entity.setCount(count);
    }
    if (strategy != null) {
        if (strategy != 0 && strategy != 1 && strategy != 2) {
            return Result.ofFail(-1, "strategy must be in [0, 1, 2], but " + strategy + " got");
        }
        entity.setStrategy(strategy);
        if (strategy != 0) {
            if (StringUtil.isBlank(refResource)) {
                return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0");
            }
            entity.setRefResource(refResource.trim());
        }
    }
    if (controlBehavior != null) {
        if (controlBehavior != 0 && controlBehavior != 1 && controlBehavior != 2) {
            return Result.ofFail(-1, "controlBehavior must be in [0, 1, 2], but " + controlBehavior + " got");
        }
        if (controlBehavior == 1 && warmUpPeriodSec == null) {
            return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1");
        }
        if (controlBehavior == 2 && maxQueueingTimeMs == null) {
            return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2");
        }
        entity.setControlBehavior(controlBehavior);
        if (warmUpPeriodSec != null) {
            entity.setWarmUpPeriodSec(warmUpPeriodSec);
        }
        if (maxQueueingTimeMs != null) {
            entity.setMaxQueueingTimeMs(maxQueueingTimeMs);
        }
    }
    Date date = new Date();
    entity.setGmtModified(date);
    try {
        entity = repository.save(entity);
        if (entity == null) {
            return Result.ofFail(-1, "save entity fail");
        }
    } catch (Throwable throwable) {
        logger.error("save error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
    if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
        logger.info("publish flow rules fail after rule update");
    }
    return Result.ofSuccess(entity);
}
 
Example 18
Source File: SystemController.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@GetMapping("/save.json")
@AuthAction(PrivilegeType.WRITE_RULE)
public Result<SystemRuleEntity> apiUpdateIfNotNull(Long id, String app, Double highestSystemLoad,
        Double highestCpuUsage, Long avgRt, Long maxThread, Double qps) {
    if (id == null) {
        return Result.ofFail(-1, "id can't be null");
    }
    SystemRuleEntity entity = repository.findById(id);
    if (entity == null) {
        return Result.ofFail(-1, "id " + id + " dose not exist");
    }

    if (StringUtil.isNotBlank(app)) {
        entity.setApp(app.trim());
    }
    if (highestSystemLoad != null) {
        if (highestSystemLoad < 0) {
            return Result.ofFail(-1, "highestSystemLoad must >= 0");
        }
        entity.setHighestSystemLoad(highestSystemLoad);
    }
    if (highestCpuUsage != null) {
        if (highestCpuUsage < 0) {
            return Result.ofFail(-1, "highestCpuUsage must >= 0");
        }
        if (highestCpuUsage > 1) {
            return Result.ofFail(-1, "highestCpuUsage must <= 1");
        }
        entity.setHighestCpuUsage(highestCpuUsage);
    }
    if (avgRt != null) {
        if (avgRt < 0) {
            return Result.ofFail(-1, "avgRt must >= 0");
        }
        entity.setAvgRt(avgRt);
    }
    if (maxThread != null) {
        if (maxThread < 0) {
            return Result.ofFail(-1, "maxThread must >= 0");
        }
        entity.setMaxThread(maxThread);
    }
    if (qps != null) {
        if (qps < 0) {
            return Result.ofFail(-1, "qps must >= 0");
        }
        entity.setQps(qps);
    }
    Date date = new Date();
    entity.setGmtModified(date);
    try {
        entity = repository.save(entity);
    } catch (Throwable throwable) {
        logger.error("save error:", throwable);
        return Result.ofThrowable(-1, throwable);
    }
    if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
        logger.info("publish system rules fail after rule update");
    }
    return Result.ofSuccess(entity);
}
 
Example 19
Source File: SendMetricCommandHandler.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
@Override
public CommandResponse<String> handle(CommandRequest request) {
    // Note: not thread-safe.
    if (searcher == null) {
        synchronized (lock) {
            String appName = SentinelConfig.getAppName();
            if (appName == null) {
                appName = "";
            }
            if (searcher == null) {
                searcher = new MetricSearcher(MetricWriter.METRIC_BASE_DIR,
                    MetricWriter.formMetricFileName(appName, PidUtil.getPid()));
            }
        }
    }
    String startTimeStr = request.getParam("startTime");
    String endTimeStr = request.getParam("endTime");
    String maxLinesStr = request.getParam("maxLines");
    String identity = request.getParam("identity");
    long startTime = -1;
    int maxLines = 6000;
    if (StringUtil.isNotBlank(startTimeStr)) {
        startTime = Long.parseLong(startTimeStr);
    } else {
        return CommandResponse.ofSuccess("");
    }
    List<MetricNode> list;
    try {
        // Find by end time if set.
        if (StringUtil.isNotBlank(endTimeStr)) {
            long endTime = Long.parseLong(endTimeStr);
            list = searcher.findByTimeAndResource(startTime, endTime, identity);
        } else {
            if (StringUtil.isNotBlank(maxLinesStr)) {
                maxLines = Integer.parseInt(maxLinesStr);
            }
            maxLines = Math.min(maxLines, 12000);
            list = searcher.find(startTime, maxLines);
        }
    } catch (Exception ex) {
        return CommandResponse.ofFailure(new RuntimeException("Error when retrieving metrics", ex));
    }
    if (list == null) {
        list = new ArrayList<>();
    }
    if (StringUtil.isBlank(identity)) {
        addCpuUsageAndLoad(list);
    }
    StringBuilder sb = new StringBuilder();
    for (MetricNode node : list) {
        sb.append(node.toThinString()).append("\n");
    }
    return CommandResponse.ofSuccess(sb.toString());
}
 
Example 20
Source File: FlowControllerV1.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
@PutMapping("/save.json")
@AuthAction(PrivilegeType.WRITE_RULE)
public Result<FlowRuleEntity> apiUpdateFlowRule(Long id, String app,
                                              String limitApp, String resource, Integer grade,
                                              Double count, Integer strategy, String refResource,
                                              Integer controlBehavior, Integer warmUpPeriodSec,
                                              Integer maxQueueingTimeMs) {
    if (id == null) {
        return Result.ofFail(-1, "id can't be null");
    }
    FlowRuleEntity entity = repository.findById(id);
    if (entity == null) {
        return Result.ofFail(-1, "id " + id + " dose not exist");
    }
    if (StringUtil.isNotBlank(app)) {
        entity.setApp(app.trim());
    }
    if (StringUtil.isNotBlank(limitApp)) {
        entity.setLimitApp(limitApp.trim());
    }
    if (StringUtil.isNotBlank(resource)) {
        entity.setResource(resource.trim());
    }
    if (grade != null) {
        if (grade != 0 && grade != 1) {
            return Result.ofFail(-1, "grade must be 0 or 1, but " + grade + " got");
        }
        entity.setGrade(grade);
    }
    if (count != null) {
        entity.setCount(count);
    }
    if (strategy != null) {
        if (strategy != 0 && strategy != 1 && strategy != 2) {
            return Result.ofFail(-1, "strategy must be in [0, 1, 2], but " + strategy + " got");
        }
        entity.setStrategy(strategy);
        if (strategy != 0) {
            if (StringUtil.isBlank(refResource)) {
                return Result.ofFail(-1, "refResource can't be null or empty when strategy!=0");
            }
            entity.setRefResource(refResource.trim());
        }
    }
    if (controlBehavior != null) {
        if (controlBehavior != 0 && controlBehavior != 1 && controlBehavior != 2) {
            return Result.ofFail(-1, "controlBehavior must be in [0, 1, 2], but " + controlBehavior + " got");
        }
        if (controlBehavior == 1 && warmUpPeriodSec == null) {
            return Result.ofFail(-1, "warmUpPeriodSec can't be null when controlBehavior==1");
        }
        if (controlBehavior == 2 && maxQueueingTimeMs == null) {
            return Result.ofFail(-1, "maxQueueingTimeMs can't be null when controlBehavior==2");
        }
        entity.setControlBehavior(controlBehavior);
        if (warmUpPeriodSec != null) {
            entity.setWarmUpPeriodSec(warmUpPeriodSec);
        }
        if (maxQueueingTimeMs != null) {
            entity.setMaxQueueingTimeMs(maxQueueingTimeMs);
        }
    }
    Date date = new Date();
    entity.setGmtModified(date);
    try {
        entity = repository.save(entity);
        if (entity == null) {
            return Result.ofFail(-1, "save entity fail: null");
        }

        publishRules(entity.getApp(), entity.getIp(), entity.getPort()).get(5000, TimeUnit.MILLISECONDS);
        return Result.ofSuccess(entity);
    } catch (Throwable t) {
        Throwable e = t instanceof ExecutionException ? t.getCause() : t;
        logger.error("Error when updating flow rules, app={}, ip={}, ruleId={}", entity.getApp(),
            entity.getIp(), id, e);
        return Result.ofFail(-1, e.getMessage());
    }
}