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

The following examples show how to use com.alibaba.csp.sentinel.util.StringUtil#isNotEmpty() . 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: SentinelJaxRsProviderFilter.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {

    try {
        String resourceName = getResourceName(containerRequestContext, resourceInfo);

        if (StringUtil.isNotEmpty(resourceName)) {
            // Parse the request origin using registered origin parser.
            String origin = parseOrigin(containerRequestContext);
            String contextName = getContextName(containerRequestContext);
            ContextUtil.enter(contextName, origin);
            Entry entry = SphU.entry(resourceName, ResourceTypeConstants.COMMON_WEB, EntryType.IN);

            containerRequestContext.setProperty(SENTINEL_JAX_RS_PROVIDER_ENTRY_PROPERTY, entry);
        }
    } catch (BlockException e) {
        try {
            containerRequestContext.abortWith(SentinelJaxRsConfig.getJaxRsFallback().fallbackResponse(containerRequestContext.getUriInfo().getPath(), e));
        } finally {
            ContextUtil.exit();
        }
    }
}
 
Example 2
Source File: MetricFetcher.java    From Sentinel-Dashboard-Nacos 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: RedisDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private RedisClient getRedisSentinelClient(RedisConnectionConfig connectionConfig) {
    char[] password = connectionConfig.getPassword();
    String clientName = connectionConfig.getClientName();
    RedisURI.Builder sentinelRedisUriBuilder = RedisURI.builder();
    for (RedisConnectionConfig config : connectionConfig.getRedisSentinels()) {
        sentinelRedisUriBuilder.withSentinel(config.getHost(), config.getPort());
    }
    if (password != null) {
        sentinelRedisUriBuilder.withPassword(connectionConfig.getPassword());
    }
    if (StringUtil.isNotEmpty(connectionConfig.getClientName())) {
        sentinelRedisUriBuilder.withClientName(clientName);
    }
    sentinelRedisUriBuilder.withSentinelMasterId(connectionConfig.getRedisSentinelMasterId())
        .withTimeout(connectionConfig.getTimeout(), TimeUnit.MILLISECONDS);
    return RedisClient.create(sentinelRedisUriBuilder.build());
}
 
Example 4
Source File: SentinelWebInterceptor.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Override
protected String getResourceName(HttpServletRequest request) {
    // Resolve the Spring Web URL pattern from the request attribute.
    Object resourceNameObject = request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
    if (resourceNameObject == null || !(resourceNameObject instanceof String)) {
        return null;
    }
    String resourceName = (String) resourceNameObject;
    UrlCleaner urlCleaner = config.getUrlCleaner();
    if (urlCleaner != null) {
        resourceName = urlCleaner.clean(resourceName);
    }
    // Add method specification if necessary
    if (StringUtil.isNotEmpty(resourceName) && config.isHttpMethodSpecify()) {
        resourceName = request.getMethod().toUpperCase() + ":" + resourceName;
    }
    return resourceName;
}
 
Example 5
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 6
Source File: RedisDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private RedisClient getRedisStandaloneClient(RedisConnectionConfig connectionConfig) {
    char[] password = connectionConfig.getPassword();
    String clientName = connectionConfig.getClientName();
    RedisURI.Builder redisUriBuilder = RedisURI.builder();
    redisUriBuilder.withHost(connectionConfig.getHost())
        .withPort(connectionConfig.getPort())
        .withDatabase(connectionConfig.getDatabase())
        .withTimeout(Duration.ofMillis(connectionConfig.getTimeout()));
    if (password != null) {
        redisUriBuilder.withPassword(connectionConfig.getPassword());
    }
    if (StringUtil.isNotEmpty(connectionConfig.getClientName())) {
        redisUriBuilder.withClientName(clientName);
    }
    return RedisClient.create(redisUriBuilder.build());
}
 
Example 7
Source File: RedisDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
private RedisClient getRedisSentinelClient(RedisConnectionConfig connectionConfig) {
    char[] password = connectionConfig.getPassword();
    String clientName = connectionConfig.getClientName();
    RedisURI.Builder sentinelRedisUriBuilder = RedisURI.builder();
    for (RedisConnectionConfig config : connectionConfig.getRedisSentinels()) {
        sentinelRedisUriBuilder.withSentinel(config.getHost(), config.getPort());
    }
    if (password != null) {
        sentinelRedisUriBuilder.withPassword(connectionConfig.getPassword());
    }
    if (StringUtil.isNotEmpty(connectionConfig.getClientName())) {
        sentinelRedisUriBuilder.withClientName(clientName);
    }
    sentinelRedisUriBuilder.withSentinelMasterId(connectionConfig.getRedisSentinelMasterId())
        .withTimeout(connectionConfig.getTimeout(), TimeUnit.MILLISECONDS);
    return RedisClient.create(sentinelRedisUriBuilder.build());
}
 
Example 8
Source File: SentinelDefaultTokenServer.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void handleEmbeddedStart() {
    String namespace = ConfigSupplierRegistry.getNamespaceSupplier().get();
    if (StringUtil.isNotEmpty(namespace)) {
        // Mark server global mode as embedded.
        ClusterServerConfigManager.setEmbedded(true);
        if (!ClusterServerConfigManager.getNamespaceSet().contains(namespace)) {
            Set<String> namespaceSet = new HashSet<>(ClusterServerConfigManager.getNamespaceSet());
            namespaceSet.add(namespace);
            ClusterServerConfigManager.loadServerNamespaceSet(namespaceSet);
        }

        // Register self to connection group.
        ConnectionManager.addConnection(namespace, HostNameUtil.getIp());
    }
}
 
Example 9
Source File: GatewayRuleManager.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void cacheRegexPattern(/*@NonNull*/ GatewayParamFlowItem item) {
    String pattern = item.getPattern();
    if (StringUtil.isNotEmpty(pattern) &&
        item.getMatchStrategy() == SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX) {
        if (GatewayRegexCache.getRegexPattern(pattern) == null) {
            GatewayRegexCache.addRegexPattern(pattern);
        }
    }
}
 
Example 10
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private String getBody(HttpResponse response) throws Exception {
    Charset charset = null;
    try {
        String contentTypeStr = response.getFirstHeader(HTTP_HEADER_CONTENT_TYPE).getValue();
        if (StringUtil.isNotEmpty(contentTypeStr)) {
            ContentType contentType = ContentType.parse(contentTypeStr);
            charset = contentType.getCharset();
        }
    } catch (Exception ignore) {
    }
    return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 11
Source File: SentinelDefaultTokenServer.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void handleEmbeddedStart() {
    String namespace = ConfigSupplierRegistry.getNamespaceSupplier().get();
    if (StringUtil.isNotEmpty(namespace)) {
        // Mark server global mode as embedded.
        ClusterServerConfigManager.setEmbedded(true);
        if (!ClusterServerConfigManager.getNamespaceSet().contains(namespace)) {
            Set<String> namespaceSet = new HashSet<>(ClusterServerConfigManager.getNamespaceSet());
            namespaceSet.add(namespace);
            ClusterServerConfigManager.loadServerNamespaceSet(namespaceSet);
        }

        // Register self to connection group.
        ConnectionManager.addConnection(namespace, HostNameUtil.getIp());
    }
}
 
Example 12
Source File: GatewayRuleManager.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void cacheRegexPattern(/*@NonNull*/ GatewayParamFlowItem item) {
    String pattern = item.getPattern();
    if (StringUtil.isNotEmpty(pattern) &&
        item.getMatchStrategy() == SentinelGatewayConstants.PARAM_MATCH_STRATEGY_REGEX) {
        if (GatewayRegexCache.getRegexPattern(pattern) == null) {
            GatewayRegexCache.addRegexPattern(pattern);
        }
    }
}
 
Example 13
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
@Nullable
private <T> CompletableFuture<List<T>> fetchItemsAsync(String ip, int port, String api, String type, Class<T> ruleType) {
    AssertUtil.notEmpty(ip, "Bad machine IP");
    AssertUtil.isTrue(port > 0, "Bad machine port");
    Map<String, String> params = null;
    if (StringUtil.isNotEmpty(type)) {
        params = new HashMap<>(1);
        params.put("type", type);
    }
    return executeCommand(ip, port, api, params, false)
            .thenApply(json -> JSON.parseArray(json, ruleType));
}
 
Example 14
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private String getBody(HttpResponse response) throws Exception {
    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) {
    }
    return EntityUtils.toString(response.getEntity(), charset != null ? charset : DEFAULT_CHARSET);
}
 
Example 15
Source File: SentinelDefaultTokenServer.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private void handleEmbeddedStop() {
    String namespace = ConfigSupplierRegistry.getNamespaceSupplier().get();
    if (StringUtil.isNotEmpty(namespace)) {
        ConnectionManager.removeConnection(namespace, HostNameUtil.getIp());
    }
}
 
Example 16
Source File: RlsAccessLogger.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
public static void log(String info) {
    if (enabled && StringUtil.isNotEmpty(info)) {
        System.out.println(info);
    }
}
 
Example 17
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 4 votes vote down vote up
private boolean isCommandNotFound(int statusCode, String body) {
    return statusCode == 400 && StringUtil.isNotEmpty(body) && body.contains(CommandConstants.MSG_UNKNOWN_COMMAND_PREFIX);
}
 
Example 18
Source File: SentinelApiClient.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private boolean isCommandNotFound(int statusCode, String body) {
    return statusCode == 400 && StringUtil.isNotEmpty(body) && body.contains(CommandConstants.MSG_UNKNOWN_COMMAND_PREFIX);
}
 
Example 19
Source File: SentinelDefaultTokenServer.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 4 votes vote down vote up
private void handleEmbeddedStop() {
    String namespace = ConfigSupplierRegistry.getNamespaceSupplier().get();
    if (StringUtil.isNotEmpty(namespace)) {
        ConnectionManager.removeConnection(namespace, HostNameUtil.getIp());
    }
}
 
Example 20
Source File: SentinelApiClient.java    From Sentinel with Apache License 2.0 3 votes vote down vote up
/**
 * Check wheter target instance (identified by tuple of app-ip:port)
 * supports the form of "xxxxx; xx=xx" in "Content-Type" header.
 * 
 * @param app target app name
 * @param ip target node's address
 * @param port target node's port
 */
protected boolean isSupportEnhancedContentType(String app, String ip, int port) {
    return StringUtil.isNotEmpty(app) && Optional.ofNullable(appManagement.getDetailApp(app))
            .flatMap(e -> e.getMachine(ip, port))
            .flatMap(m -> VersionUtils.parseVersion(m.getVersion())
                .map(v -> v.greaterOrEqual(version171)))
            .orElse(false);
}