Java Code Examples for com.alipay.sofa.rpc.common.utils.StringUtils#isNotBlank()

The following examples show how to use com.alipay.sofa.rpc.common.utils.StringUtils#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: SofaRegistrySubscribeCallback.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 获得 Sofa Runtime 的日志对象,打印出获得Config Data 信息
 */
private void printConfigData(String dataId, ConfigData configData) {

    StringBuilder sb = new StringBuilder();
    int count = 0;

    if (configData != null && StringUtils.isNotBlank(configData.getData())) {
        final String[] split = StringUtils.split(configData.getData(), CONFIG_SEPARATOR);
        List<String> dataList = Arrays.asList(split);
        for (String provider : dataList) {
            sb.append("  >>> ").append(provider).append("\n");
            count++;
        }
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(LogCodes.getLiteLog(
            "Receive RPC config info: service[{0}]\n  usable config info[{1}]\n{2}",
            dataId, count, sb.toString()));
    }
}
 
Example 2
Source File: BlackListFileLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Override blacklist with override string.
 * 
 * @param originList Origin black list
 * @param overrideStr The override string
 */
static void overrideBlackList(List<String> originList, String overrideStr) {
    List<String> adds = new ArrayList<String>();
    String[] overrideItems = StringUtils.splitWithCommaOrSemicolon(overrideStr);
    for (String overrideItem : overrideItems) {
        if (StringUtils.isNotBlank(overrideItem)) {
            if (overrideItem.startsWith("!") || overrideItem.startsWith("-")) {
                overrideItem = overrideItem.substring(1);
                if ("*".equals(overrideItem) || "default".equals(overrideItem)) {
                    originList.clear();
                } else {
                    originList.remove(overrideItem);
                }
            } else {
                if (!originList.contains(overrideItem)) {
                    adds.add(overrideItem);
                }
            }
        }
    }
    if (adds.size() > 0) {
        originList.addAll(adds);
    }
}
 
Example 3
Source File: BlackListFileLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
static List<String> loadFile(String path) {
    List<String> blackPrefixList = new ArrayList<String>();
    InputStream input = null;
    try {
        input = BlackListFileLoader.class.getResourceAsStream(path);
        if (input != null) {
            readToList(input, "UTF-8", blackPrefixList);
        }
        String overStr = SofaConfigs.getStringValue(SofaOptions.CONFIG_SERIALIZE_BLACKLIST_OVERRIDE, "");
        if (StringUtils.isNotBlank(overStr)) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Serialize blacklist will override with configuration: {}", overStr);
            }
            overrideBlackList(blackPrefixList, overStr);
        }
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error(e.getMessage(), e);
        }
    } finally {
        closeQuietly(input);
    }
    return blackPrefixList;
}
 
Example 4
Source File: MeshRouter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public boolean needToLoad(ConsumerBootstrap consumerBootstrap) {
    ConsumerConfig consumerConfig = consumerBootstrap.getConsumerConfig();
    // 不是直连,且从注册中心订阅配置
    final boolean isDirect = StringUtils.isNotBlank(consumerConfig.getDirectUrl());
    final List<RegistryConfig> registrys = consumerConfig.getRegistry();
    boolean isMesh = false;

    if (registrys != null) {
        for (RegistryConfig registry : registrys) {
            if (registry.getProtocol().equalsIgnoreCase(RpcConstants.REGISTRY_PROTOCOL_MESH)) {
                isMesh = true;
                break;
            }
        }
    }
    return !isDirect && isMesh;
}
 
Example 5
Source File: RegistryConfigContainer.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
/**
 * protocol can be meshed
 *
 * @param protocol
 * @return
 */
public boolean isMeshEnabled(String protocol) {

    String meshConfig = sofaBootRpcProperties.getEnableMesh();
    final Map<String, String> registries = sofaBootRpcProperties.getRegistries();
    if (StringUtils.isNotBlank(meshConfig) && registries != null &&
        registries.get(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_MESH) != null) {
        if (meshConfig.equalsIgnoreCase(SofaBootRpcConfigConstants.ENABLE_MESH_ALL)) {
            return true;
        } else {
            List<String> meshEnableProtocols = Arrays.asList(meshConfig.split(","));
            for (String meshProtocol : meshEnableProtocols) {
                if (StringUtils.equals(meshProtocol, protocol)) {
                    return true;
                }
            }
            return false;
        }
    } else {
        return false;
    }

}
 
Example 6
Source File: HelpTelnetHandler.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public String telnet(AbstractChannel channel, String message) {
    StringBuffer result = new StringBuffer();
    if (StringUtils.isNotBlank(message)) {
        TelnetHandler handler = TelnetHandlerFactory.getHandler(message);
        if (handler != null) {
            result.append(handler.getCommand()).append(LINE)
                .append(handler.getDescription()).append(LINE);
        } else {
            result.append("Not found command : " + message);
        }
    } else {
        result.append("The supported command include:").append(LINE);
        for (Map.Entry<String, TelnetHandler> entry : TelnetHandlerFactory.getAllHandlers().entrySet()) {
            result.append(entry.getKey()).append(" ");
            //result.append(entry.fetchKey() + "\t : " + entry.getValue().getDescription() + "\r\n");
        }
        result.append(LINE);
    }
    return result.toString();
}
 
Example 7
Source File: ConsumerConfig.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Gets proxy class.
 *
 * @return the proxyClass
 */
@Override
public Class<?> getProxyClass() {
    if (proxyClass != null) {
        return proxyClass;
    }
    if (generic) {
        return GenericService.class;
    }
    try {
        if (StringUtils.isNotBlank(interfaceId)) {
            this.proxyClass = ClassUtils.forName(interfaceId);
            if (!RpcConstants.PROTOCOL_TYPE_TRIPLE.equals(protocol) && !proxyClass.isInterface()) {
                throw ExceptionUtils.buildRuntime("consumer.interface",
                    interfaceId, "interfaceId must set interface class, not implement class");
            }
        } else {
            throw ExceptionUtils.buildRuntime("consumer.interface",
                "null", "interfaceId must be not null");
        }
    } catch (RuntimeException t) {
        throw new IllegalStateException(t.getMessage(), t);
    }
    return proxyClass;
}
 
Example 8
Source File: SofaRegistryDataCacheImpl.java    From sofa-dashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<RpcProvider> fetchProvidersByService(String serviceName) {
    List<RpcProvider> result = null;
    if (StringUtils.isNotBlank(serviceName)) {
        result = providerMap.get(serviceName);
    }
    if (result == null) {
        result = new ArrayList<>();
    }
    return result;
}
 
Example 9
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Read the warmUp weight parameter,
 * decide whether to switch the state to the preheating period,
 * and set the corresponding parameters during the preheating period.
 *
 * @param providerInfo the provider info
 */
public static void processWarmUpWeight(ProviderInfo providerInfo) {

    String warmupTimeStr = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_TIME);
    String warmupWeightStr = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT);
    String startTimeStr = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_START_TIME);

    if (StringUtils.isNotBlank(warmupTimeStr) && StringUtils.isNotBlank(warmupWeightStr) &&
        StringUtils.isNotBlank(startTimeStr)) {

        long warmupTime = CommonUtils.parseLong(warmupTimeStr, 0);
        int warmupWeight = CommonUtils.parseInt(warmupWeightStr,
            Integer.parseInt(providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT)));
        long startTime = CommonUtils.parseLong(startTimeStr, 0);
        long warmupEndTime = startTime + warmupTime;

        // set for dynamic
        providerInfo.setDynamicAttr(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT, warmupWeight);
        providerInfo.setDynamicAttr(ProviderInfoAttrs.ATTR_WARM_UP_END_TIME, warmupEndTime);
        providerInfo.setStatus(ProviderStatus.WARMING_UP);
    }

    // remove from static
    providerInfo.getStaticAttrs().remove(ProviderInfoAttrs.ATTR_WARMUP_TIME);
    providerInfo.getStaticAttrs().remove(ProviderInfoAttrs.ATTR_WARMUP_WEIGHT);

}
 
Example 10
Source File: AbstractSofaRpcFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public boolean needToLoad(FilterInvoker invoker) {
    AbstractInterfaceConfig<?, ?> config = invoker.getConfig();

    String enabled = config.getParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED);
    if (StringUtils.isNotBlank(enabled)) {
        return Boolean.parseBoolean(enabled);
    }

    return RpcConfigs.getOrDefaultValue(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, true);
}
 
Example 11
Source File: HystrixFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private boolean isHystrixEnabled(AbstractInterfaceConfig config) {
    String consumerHystrixEnabled = config.getParameter(HystrixConstants.SOFA_HYSTRIX_ENABLED);
    if (StringUtils.isNotBlank(consumerHystrixEnabled)) {
        return Boolean.valueOf(consumerHystrixEnabled);
    }
    return RpcConfigs.getOrDefaultValue(HystrixConstants.SOFA_HYSTRIX_ENABLED, false);
}
 
Example 12
Source File: TripleClientInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * set some custom info
 * @param sofaRequest
 * @param timeout
 * @return
 */
protected CallOptions buildCustomCallOptions(SofaRequest sofaRequest, int timeout) {
    CallOptions tripleCallOptions = CallOptions.DEFAULT;
    final String target = consumerConfig.getParameter("interworking.target");
    if (StringUtils.isNotBlank(target)) {
        tripleCallOptions = tripleCallOptions.withAuthority(target);
    }
    return tripleCallOptions;
}
 
Example 13
Source File: Http2ServerChannelHandler.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected void sendHttp2Response(ChannelHandlerContext ctx, int streamId, HttpResponseStatus status, String result) {
    // Send a frame for the response status
    Http2Headers headers = new DefaultHttp2Headers().status(status.codeAsText());
    if (!HttpResponseStatus.OK.equals(status)) {
        headers.set(RemotingConstants.HEAD_RESPONSE_ERROR, "true");
    }
    if (StringUtils.isNotBlank(result)) {
        ByteBuf data = ctx.alloc().buffer();
        data.writeBytes(result.getBytes(RpcConstants.DEFAULT_CHARSET));
        encoder().writeHeaders(ctx, streamId, headers, 0, false, ctx.newPromise());
        encoder().writeData(ctx, streamId, data, 0, true, ctx.newPromise());
    } else {
        encoder().writeHeaders(ctx, streamId, headers, 0, true, ctx.newPromise());
    }
}
 
Example 14
Source File: HttpTransportUtils.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Parse serialize type from content type
 *
 * @param contentType Content-type of http request
 * @return serialize code
 * @throws SofaRpcException unknown content type
 */
public static byte getSerializeTypeByContentType(String contentType) throws SofaRpcException {
    if (StringUtils.isNotBlank(contentType)) {
        String ct = contentType.toLowerCase();
        if (ct.contains("text/plain") || ct.contains("text/html") || ct.contains("application/json")) {
            return getSerializeTypeByName(RpcConstants.SERIALIZE_JSON);
        } else if (ct.contains(RpcConstants.SERIALIZE_PROTOBUF)) {
            return getSerializeTypeByName(RpcConstants.SERIALIZE_PROTOBUF);
        } else if (ct.contains(RpcConstants.SERIALIZE_HESSIAN)) {
            return getSerializeTypeByName(RpcConstants.SERIALIZE_HESSIAN2);
        }
    }
    throw new SofaRpcException(RpcErrorType.SERVER_DESERIALIZE, LogCodes.getLog(
        LogCodes.ERROR_UNSUPPORTED_CONTENT_TYPE, contentType, RemotingConstants.HEAD_SERIALIZE_TYPE));
}
 
Example 15
Source File: LocalRegistry.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public void init() {

    if (StringUtils.isNotBlank(regFile)) {
        return;
    }

    this.regFile = registryConfig.getFile();
    if (regFile == null) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_LOCAL_FILE_NULL));
    }
    // 先加载一些
    if (subscribe) {
        doLoadCache();
    }
    // 开始扫描
    this.scanPeriod = CommonUtils.parseInt(registryConfig.getParameter("registry.local.scan.period"),
        scanPeriod);
    Runnable task = new Runnable() {
        @Override
        public void run() {
            try {
                // 如果要求备份,那么说明内存中为最新的,无需加载
                doWriteFile();

                // 订阅变化(默认是不订阅的)
                // 检查摘要,如果有有变,则自动重新加载
                if (subscribe && LocalRegistryHelper.checkModified(regFile, lastDigest)) {
                    doLoadCache();
                }
            } catch (Throwable e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
    };
    //启动扫描线程
    scheduledExecutorService = new ScheduledService("LocalRegistry-Back-Load",
        ScheduledService.MODE_FIXEDDELAY,
        task, //定时load任务
        scanPeriod, // 延迟一个周期
        scanPeriod, // 一个周期循环
        TimeUnit.MILLISECONDS
            ).start();

}
 
Example 16
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 适配服务端filter
 *
 * @param requestContext ContainerRequestContext
 */
public static void serverFilter(ContainerRequestContext requestContext) {
    try {
        SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
        SofaTracerSpan serverSpan = sofaTraceContext.getCurrentSpan();
        if (serverSpan != null) {
            RpcInternalContext context = RpcInternalContext.getContext();

            context.setAttachment(RpcConstants.INTERNAL_KEY_SERVER_RECEIVE_TIME, RpcRuntimeContext.now());

            SofaResourceMethodInvoker resourceMethodInvoker = (SofaResourceMethodInvoker)
                    ((PostMatchContainerRequestContext) requestContext)
                        .getResourceMethod();

            SofaResourceFactory factory = resourceMethodInvoker.getResource();
            String serviceName = factory.getServiceName();
            String appName = factory.getAppName();

            if (serviceName == null) {
                serviceName = resourceMethodInvoker.getResourceClass().getName();
            }
            serverSpan.setTag(RpcSpanTags.SERVICE, serviceName);
            if (resourceMethodInvoker.getMethod() != null) {
                serverSpan.setTag(RpcSpanTags.METHOD, resourceMethodInvoker.getMethod().getName());
                //serverSend需要
                context.setAttachment(METHOD_TYPE_STRING, resourceMethodInvoker.getMethod());
            }

            serverSpan.setTag(RpcSpanTags.REMOTE_IP, context.getRemoteHostName()); // 客户端地址

            String remoteAppName = requestContext.getHeaderString(RemotingConstants.HEAD_APP_NAME);
            if (StringUtils.isNotBlank(remoteAppName)) {
                serverSpan.setTag(RpcSpanTags.REMOTE_APP, remoteAppName);
            }
            serverSpan.setTag(RpcSpanTags.PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
            serverSpan.setTag(RpcSpanTags.INVOKE_TYPE, RpcConstants.INVOKER_TYPE_SYNC);
            if (appName == null) {
                appName = (String) RpcRuntimeContext.get(RpcRuntimeContext.KEY_APPNAME);
            }
            serverSpan.setTag(RpcSpanTags.LOCAL_APP, appName);
        }
    } catch (Throwable t) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("the process of rest tracer server filter occur error ", t);
        }
    }
}
 
Example 17
Source File: AllConnectConnectionHolder.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public ClientTransport getAvailableClientTransport(ProviderInfo providerInfo) {
    // 先去存活列表
    ClientTransport transport = aliveConnections.get(providerInfo);
    if (transport != null) {
        return transport;
    }
    // 再去亚健康列表
    transport = subHealthConnections.get(providerInfo);
    if (transport != null) {
        return transport;
    }
    // 最后看看是否第一次调用未初始化
    transport = uninitializedConnections.get(providerInfo);
    if (transport != null) {
        // 未初始化则初始化
        synchronized (this) {
            transport = uninitializedConnections.get(providerInfo);
            if (transport != null) {
                initClientTransport(consumerConfig.getInterfaceId(), providerInfo, transport);
                uninitializedConnections.remove(providerInfo);
            }
            return getAvailableClientTransport(providerInfo);
        }
    }

    if (createConnWhenAbsent) {
        RpcInternalContext context = RpcInternalContext.peekContext();
        String targetIP = (context == null) ? null : (String) context
            .getAttachment(RpcConstants.HIDDEN_KEY_PINPOINT);
        /**
         * RpcInvokeContext.getContext().setTargetUrl() 设置了地址,初始化tcp连接
         */
        if (StringUtils.isNotBlank(targetIP)) {
            ClientTransportConfig transportConfig = providerToClientConfig(providerInfo);
            transport = ClientTransportFactory.getClientTransport(transportConfig);
            initClientTransport(consumerConfig.getInterfaceId(), providerInfo, transport);
        }
    }

    return transport;
}
 
Example 18
Source File: RegistryConfigContainer.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
public RegistryConfigContainer() {
    customDefaultRegistry = System.getProperty(SofaBootRpcConfigConstants.DEFAULT_REGISTRY);
    if (StringUtils.isNotBlank(customDefaultRegistry)) {
        customDefaultRegistryAddress = System.getProperty(customDefaultRegistry);
    }
}
 
Example 19
Source File: SofaRegistryDataCacheImpl.java    From sofa-dashboard with Apache License 2.0 4 votes vote down vote up
@Override
public void addConsumers(String serviceName, List<RpcConsumer> consumerList) {
    if (StringUtils.isNotBlank(serviceName) && consumerList != null) {
        consumerMap.put(serviceName, consumerList);
    }
}
 
Example 20
Source File: SofaRegistryDataCacheImpl.java    From sofa-dashboard with Apache License 2.0 4 votes vote down vote up
@Override
public void addProviders(String serviceName, List<RpcProvider> providerList) {
    if (StringUtils.isNotBlank(serviceName) && providerList != null) {
        providerMap.put(serviceName, providerList);
    }
}