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

The following examples show how to use com.alipay.sofa.rpc.common.utils.StringUtils#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: LocalPreferenceLoadBalancer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public ProviderInfo doSelect(SofaRequest invocation, List<ProviderInfo> providerInfos) {
    String localhost = SystemInfo.getLocalHost();
    if (StringUtils.isEmpty(localhost)) {
        return super.doSelect(invocation, providerInfos);
    }
    List<ProviderInfo> localProviderInfo = new ArrayList<ProviderInfo>();
    for (ProviderInfo providerInfo : providerInfos) { // 解析IP,看是否和本地一致
        if (localhost.equals(providerInfo.getHost())) {
            localProviderInfo.add(providerInfo);
        }
    }
    if (CommonUtils.isNotEmpty(localProviderInfo)) { // 命中本机的服务端
        return super.doSelect(invocation, localProviderInfo);
    } else { // 没有命中本机上的服务端
        return super.doSelect(invocation, providerInfos);
    }
}
 
Example 2
Source File: ZookeeperConfigurator.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
@Override
public RegistryConfig buildFromAddress(String address) {
    String zkAddress = RegistryParseUtil.parseAddress(address,
        SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER);
    Map<String, String> map = RegistryParseUtil.parseParam(address,
        SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER);

    String file = map.get("file");

    if (StringUtils.isEmpty(file)) {
        file = SofaBootRpcConfigConstants.REGISTRY_FILE_PATH_DEFAULT;
    }

    return new RegistryConfig().setAddress(zkAddress).setFile(file)
        .setProtocol(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_ZOOKEEPER)
        .setParameters(map);
}
 
Example 3
Source File: DefaultConsumerBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 取消订阅服务列表
 */
public void unSubscribe() {
    if (StringUtils.isEmpty(consumerConfig.getDirectUrl()) && consumerConfig.isSubscribe()) {
        List<RegistryConfig> registryConfigs = consumerConfig.getRegistry();
        if (registryConfigs != null) {
            for (RegistryConfig registryConfig : registryConfigs) {
                Registry registry = RegistryFactory.getRegistry(registryConfig);
                try {
                    registry.unSubscribe(consumerConfig);
                } catch (Exception e) {
                    String appName = consumerConfig.getAppName();
                    if (LOGGER.isWarnEnabled(appName)) {
                        LOGGER.warnWithApp(appName,
                            "Catch exception when unSubscribe from registry: " + registryConfig.getId()
                                + ", but you can ignore if it's called by JVM shutdown hook", e);
                    }
                }
            }
        }
    }
}
 
Example 4
Source File: NetworkAddressUtil.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
/**
 * 判断 IP 是否符合要求
 *
 * @param ip ip地址,XXX.XXX.XXX.XXX
 * @return 是否符合要求
 */
public static boolean ipEnabled(String ip) {
    if (StringUtils.isEmpty(ip)) {
        return false;
    }

    // 如果IP_RANGES为空,返回true
    if (IP_RANGES.isEmpty()) {
        return true;
    }

    // 遍历IP_RANGES
    for (IpRange ipRange : IP_RANGES) {
        if (ipRange.isEnabled(ip)) {
            return true;
        }
    }

    return false;
}
 
Example 5
Source File: ConfigUniqueNameGenerator.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 唯一标识UniqueName的产生方法,主要用于内部找接口等,格式为interface:version[:uniqueId]
 *
 * @param interfaceConfig 服务提供者或者服务消费者配置
 * @return 配置唯一名字
 */
public static String getUniqueName(AbstractInterfaceConfig interfaceConfig) {
    // 加上 1.0 是为了兼容之前的版本
    String version = interfaceConfig.getVersion();
    String uniqueId = interfaceConfig.getUniqueId();
    return interfaceConfig.getInterfaceId()
        + (StringUtils.isEmpty(version) ? ":1.0" : ":" + version)
        + (StringUtils.isEmpty(uniqueId) ? "" : ":" + uniqueId);
}
 
Example 6
Source File: TracerChecker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private static boolean validateField(String... fileds) {

        LOGGER.info("validateField,value=" + StringUtils.join(fileds, ","));

        for (String field : fileds) {
            if (StringUtils.isEmpty(field)) {
                return false;
            }
        }

        return true;
    }
 
Example 7
Source File: NacosRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void init() {
    if (namingService != null) {
        return;
    }

    String addressInput = registryConfig.getAddress(); // xxx:8848,yyy:8848/namespace
    if (StringUtils.isEmpty(addressInput)) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_EMPTY_ADDRESS, EXT_NAME));
    }
    int idx = addressInput.indexOf(CONTEXT_SEP);
    String namespace;
    String address; // IP地址
    if (idx > 0) {
        address = addressInput.substring(0, idx);
        namespace = addressInput.substring(idx + 1);
        //for host:port/ this scene
        if (StringUtils.isBlank(namespace)) {
            namespace = DEFAULT_NAMESPACE;
        }
    } else {
        address = addressInput;
        namespace = DEFAULT_NAMESPACE;
    }

    defaultCluster = Collections.singletonList(NacosRegistryHelper.DEFAULT_CLUSTER);

    nacosConfig.put(PropertyKeyConst.SERVER_ADDR, address);
    nacosConfig.put(PropertyKeyConst.NAMESPACE, namespace);

    try {
        namingService = NamingFactory.createNamingService(nacosConfig);
    } catch (NacosException e) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_INIT_NACOS_NAMING_SERVICE, address), e);
    }
}
 
Example 8
Source File: GenericMultipleClassLoaderSofaSerializerFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public Deserializer getDeserializer(String type) throws HessianProtocolException {

    // 如果类型在过滤列表, 说明是jdk自带类, 直接委托父类处理
    if (StringUtils.isEmpty(type) || ClassFilter.filterExcludeClass(type)) {
        return super.getDeserializer(type);
    }

    // 如果是数组类型, 且在name过滤列表, 说明jdk类, 直接委托父类处理
    if (type.charAt(0) == ARRAY_PREFIX && ClassFilter.arrayFilter(type)) {
        return super.getDeserializer(type);
    }

    // 查看是否已经包含反序列化器
    Deserializer deserializer = DESERIALIZER_MAP.get(type);
    if (deserializer != null) {
        return deserializer;
    }

    // 新建反序列化器, 如果是java.lang.Class使用GenericClassDeserializer,否则使用GenericDeserializer
    if (ClassFilter.CLASS_NAME.equals(type)) {
        deserializer = GenericClassDeserializer.getInstance();
    } else {
        deserializer = new GenericDeserializer(type);
    }

    DESERIALIZER_MAP.putIfAbsent(type, deserializer);
    return deserializer;
}
 
Example 9
Source File: ConfigUniqueNameGenerator.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 解析唯一标识UniqueName得到接口名
 *
 * @param uniqueName 服务唯一标识
 * @return 接口名
 */
public static String getInterfaceName(String uniqueName) {
    if (StringUtils.isEmpty(uniqueName)) {
        return uniqueName;
    }
    int index = uniqueName.indexOf(':');
    return index < 0 ? uniqueName : uniqueName.substring(0, index);
}
 
Example 10
Source File: RestTracerAdapter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 适配服务端serverReceived
 */
public static void serverReceived(NettyHttpRequest request) {
    try {
        SofaRequest sofaRequest = new SofaRequest();

        HttpHeaders headers = request.getHttpHeaders();
        String rpcTraceContext = headers.getHeaderString(RemotingConstants.NEW_RPC_TRACE_NAME);
        if (StringUtils.isNotBlank(rpcTraceContext)) {
            // 新格式
            sofaRequest.addRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME, rpcTraceContext);
        } else {
            String traceIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_TRACE_ID_KEY);
            String rpcIdKey = headers.getHeaderString(RemotingConstants.HTTP_HEADER_RPC_ID_KEY);
            if (StringUtils.isEmpty(rpcIdKey)) {
                rpcIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.RPC_ID_KEY);
            }
            if (StringUtils.isEmpty(traceIdKey)) {
                traceIdKey = request.getUri().getQueryParameters().getFirst(RemotingConstants.TRACE_ID_KEY);
            }

            if (StringUtils.isNotEmpty(traceIdKey) && StringUtils.isNotEmpty(rpcIdKey)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put(RemotingConstants.TRACE_ID_KEY, traceIdKey);
                map.put(RemotingConstants.RPC_ID_KEY, rpcIdKey);
                String penAttrs = headers.getHeaderString(RemotingConstants.PEN_ATTRS_KEY);
                map.put(RemotingConstants.PEN_ATTRS_KEY, penAttrs);
                sofaRequest.addRequestProp(RemotingConstants.RPC_TRACE_NAME, map);
            }
        }
        Tracers.serverReceived(sofaRequest);

        RestBaggageItemsHandler.decodeBaggageItemsFromRequest(request, sofaRequest);
    } catch (Throwable t) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn(LogCodes.getLog(LogCodes.ERROR_TRACER_UNKNOWN_EXP, "receive", "rest", "server"), t);
        }
    }
}
 
Example 11
Source File: ZookeeperRegistryDataCacheImpl.java    From sofa-dashboard with Apache License 2.0 5 votes vote down vote up
@Override
public List<RpcConsumer> fetchConsumersByService(String serviceName) {
    List<RpcConsumer> result = new ArrayList<>();
    if (StringUtils.isEmpty(serviceName)) {
        return result;
    }
    RpcService rpcService = services.get(serviceName);
    if (rpcService != null) {
        result = consumers.get(rpcService);
        if (CommonUtils.isNotEmpty(result)) {
            return result;
        }
    }
    return result;
}
 
Example 12
Source File: RegistryConfigContainer.java    From sofa-rpc-boot-projects with Apache License 2.0 4 votes vote down vote up
/**
 * @param registryAlias
 * @return
 * @throws SofaBootRpcRuntimeException
 */
public RegistryConfig getRegistryConfig(String registryAlias) throws SofaBootRpcRuntimeException {
    RegistryConfig registryConfig;
    String registryProtocol;
    String registryAddress;

    String currentDefaultAlias;

    if (StringUtils.isNotBlank(customDefaultRegistry)) {
        currentDefaultAlias = customDefaultRegistry;
    } else {
        currentDefaultAlias = DEFAULT_REGISTRY;
    }

    if (StringUtils.isEmpty(registryAlias)) {
        registryAlias = currentDefaultAlias;
    }

    //cloud be mesh,default,zk

    if (registryConfigs.get(registryAlias) != null) {
        return registryConfigs.get(registryAlias);
    }

    // just for new address
    if (DEFAULT_REGISTRY.equalsIgnoreCase(registryAlias)) {
        registryAddress = sofaBootRpcProperties.getRegistryAddress();
    } else if (registryAlias.equals(customDefaultRegistry)) {
        registryAddress = customDefaultRegistryAddress;
    } else {
        registryAddress = sofaBootRpcProperties.getRegistries().get(registryAlias);
    }

    //for worst condition.
    if (StringUtils.isBlank(registryAddress)) {
        registryProtocol = SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL;
    } else {
        final int endIndex = registryAddress.indexOf("://");
        if (endIndex != -1) {
            registryProtocol = registryAddress.substring(0, endIndex);
        } else {
            registryProtocol = registryAlias;
        }
    }

    if (registryConfigMap.get(registryProtocol) != null) {
        RegistryConfigureProcessor registryConfigureProcessor = registryConfigMap.get(registryProtocol);
        registryConfig = registryConfigureProcessor.buildFromAddress(registryAddress);
        registryConfigs.put(registryAlias, registryConfig);
        //不再处理以.分隔的.
        final Environment environment = sofaBootRpcProperties.getEnvironment();
        if (environment.containsProperty(SofaOptions.CONFIG_RPC_REGISTER_REGISTRY_IGNORE)) {
            if (Boolean.TRUE.toString().equalsIgnoreCase(
                environment.getProperty(SofaOptions.CONFIG_RPC_REGISTER_REGISTRY_IGNORE))) {
                registryConfig.setRegister(false);
            }
        }
        return registryConfig;
    } else {
        throw new SofaBootRpcRuntimeException("registry config [" + registryAddress + "] is not supported");
    }
}
 
Example 13
Source File: Curator4ZookeeperRegistry.java    From spring-cloud-sofastack-samples with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void init() {
    if (zkClient != null) {
        return;
    }
    String addressInput = registryConfig.getAddress();
    if (StringUtils.isEmpty(addressInput)) {
        throw new SofaRpcRuntimeException("Address of zookeeper registry is empty.");
    }
    int idx = addressInput.indexOf(CONTEXT_SEP);
    String address;
    if (idx > 0) {
        address = addressInput.substring(0, idx);
        rootPath = addressInput.substring(idx);
        if (!rootPath.endsWith(CONTEXT_SEP)) {
            rootPath += CONTEXT_SEP;
        }
    } else {
        address = addressInput;
        rootPath = CONTEXT_SEP;
    }
    preferLocalFile = !CommonUtils
        .isFalse(registryConfig.getParameter(PARAM_PREFER_LOCAL_FILE));
    ephemeralNode = !CommonUtils.isFalse(registryConfig.getParameter(PARAM_CREATE_EPHEMERAL));
    if (LOGGER.isInfoEnabled()) {
        LOGGER
            .info(
                "Init ZookeeperRegistry with address {}, root path is {}. preferLocalFile:{}, ephemeralNode:{}",
                address, rootPath, preferLocalFile, ephemeralNode);
    }
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    zkClient = CuratorFrameworkFactory.builder().connectString(address)
        .sessionTimeoutMs(registryConfig.getConnectTimeout() * 3)
        .connectionTimeoutMs(registryConfig.getConnectTimeout()).canBeReadOnly(false)
        .retryPolicy(retryPolicy).defaultData(null).build();

    zkClient.getConnectionStateListenable().addListener((client, newState) -> {

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("reconnect to zookeeper,recover provider and consumer data");
        }
        if (newState == ConnectionState.RECONNECTED) {
            recoverRegistryData();
        }
    });
}
 
Example 14
Source File: ZookeeperAdminRegistry.java    From sofa-dashboard with Apache License 2.0 4 votes vote down vote up
@Override
public boolean start(RegistryConfig registryConfig) {

    if (zkClient != null) {
        return true;
    }
    this.registryConfig = registryConfig;
    // xxx:2181,yyy:2181/path1/path2
    String addressInput = registryConfig.getAddress();
    if (StringUtils.isEmpty(addressInput)) {
        throw new SofaRpcRuntimeException("Address of zookeeper registry is empty.");
    }
    int idx = addressInput.indexOf(CONTEXT_SEP);
    String address; // IP地址
    if (idx > 0) {
        address = addressInput.substring(0, idx);
        rootPath = addressInput.substring(idx);
        if (!rootPath.endsWith(CONTEXT_SEP)) {
            // 保证以"/"结尾
            rootPath += CONTEXT_SEP;
        }
    } else {
        address = addressInput;
        rootPath = CONTEXT_SEP;
    }
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    zkClient = CuratorFrameworkFactory.builder().connectString(address)
            .sessionTimeoutMs(registryConfig.getConnectTimeout() * 3)
            .connectionTimeoutMs(registryConfig.getConnectTimeout()).canBeReadOnly(false)
            .retryPolicy(retryPolicy).defaultData(null).build();

    zkClient.getConnectionStateListenable().addListener((client, newState) -> {

        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("reconnect to zookeeper,recover provider and consumer data");
        }
        if (newState == ConnectionState.RECONNECTED) {
            recoverRegistryData();
        }
    });

    if (zkClient == null) {
        LOGGER.warn("Start zookeeper registry must be do init first!");
        return false;
    }
    if (zkClient.getState() == CuratorFrameworkState.STARTED) {
        return true;
    }
    try {
        zkClient.start();
        LOGGER.info("Zookeeper client start success,address is {}", address);
    } catch (Exception e) {
        throw new SofaRpcRuntimeException("Failed to start zookeeper zkClient", e);
    }
    return zkClient.getState() == CuratorFrameworkState.STARTED;
}
 
Example 15
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public synchronized void init() {
    if (zkClient != null) {
        return;
    }
    String addressInput = registryConfig.getAddress(); // xxx:2181,yyy:2181/path1/paht2
    if (StringUtils.isEmpty(addressInput)) {
        throw new SofaRpcRuntimeException(LogCodes.getLog(LogCodes.ERROR_EMPTY_ADDRESS, EXT_NAME));
    }
    int idx = addressInput.indexOf(CONTEXT_SEP);
    String address; // IP地址
    if (idx > 0) {
        address = addressInput.substring(0, idx);
        rootPath = addressInput.substring(idx);
        if (!rootPath.endsWith(CONTEXT_SEP)) {
            rootPath += CONTEXT_SEP; // 保证以"/"结尾
        }
    } else {
        address = addressInput;
        rootPath = CONTEXT_SEP;
    }
    preferLocalFile = !CommonUtils.isFalse(registryConfig.getParameter(PARAM_PREFER_LOCAL_FILE));
    ephemeralNode = !CommonUtils.isFalse(registryConfig.getParameter(PARAM_CREATE_EPHEMERAL));
    if (LOGGER.isInfoEnabled()) {
        LOGGER.info(
            "Init ZookeeperRegistry with address {}, root path is {}. preferLocalFile:{}, ephemeralNode:{}",
            address, rootPath, preferLocalFile, ephemeralNode);
    }
    RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
    CuratorFrameworkFactory.Builder zkClientuilder = CuratorFrameworkFactory.builder()
        .connectString(address)
        .sessionTimeoutMs(registryConfig.getConnectTimeout() * 3)
        .connectionTimeoutMs(registryConfig.getConnectTimeout())
        .canBeReadOnly(false)
        .retryPolicy(retryPolicy)
        .defaultData(null);

    //是否需要添加zk的认证信息
    List<AuthInfo> authInfos = buildAuthInfo();
    if (CommonUtils.isNotEmpty(authInfos)) {
        zkClientuilder = zkClientuilder.aclProvider(getDefaultAclProvider())
            .authorization(authInfos);
    }

    zkClient = zkClientuilder.build();

    zkClient.getConnectionStateListenable().addListener(new ConnectionStateListener() {
        @Override
        public void stateChanged(CuratorFramework client, ConnectionState newState) {

            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("reconnect to zookeeper,recover provider and consumer data");
            }
            if (newState == ConnectionState.RECONNECTED) {
                recoverRegistryData();
            }
        }
    });
}
 
Example 16
Source File: RegistryRouter.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public boolean needToLoad(ConsumerBootstrap consumerBootstrap) {
    ConsumerConfig consumerConfig = consumerBootstrap.getConsumerConfig();
    // 不是直连,且从注册中心订阅配置
    return StringUtils.isEmpty(consumerConfig.getDirectUrl()) && consumerConfig.isSubscribe();
}
 
Example 17
Source File: SofaConfigs.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 解析数字型配置
 *
 * @param appName      应用名
 * @param key          配置项
 * @param defaultValue 默认值
 * @return 配置
 */
public static int getIntegerValue(String appName, String key, int defaultValue) {
    String ret = getStringValue0(appName, key);
    return StringUtils.isEmpty(ret) ? defaultValue : CommonUtils.parseInt(ret, defaultValue);
}
 
Example 18
Source File: SofaConfigs.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 获取配置值
 *
 * @param appName      应用名
 * @param key          配置项
 * @param defaultValue 默认值
 * @return 配置
 */
public static String getStringValue(String appName, String key, String defaultValue) {
    String ret = getStringValue0(appName, key);
    return StringUtils.isEmpty(ret) ? defaultValue : ret.trim();
}
 
Example 19
Source File: SofaConfigs.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 获取Boolean格式的Config
 *
 * @param appName      应用名
 * @param key          配置项
 * @param defaultValue 默认值
 * @return 配置
 */
public static boolean getBooleanValue(String appName, String key, boolean defaultValue) {
    String ret = getStringValue0(appName, key);
    return StringUtils.isEmpty(ret) ? defaultValue : CommonUtils.parseBoolean(ret, defaultValue);
}
 
Example 20
Source File: ConfigUniqueNameGenerator.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 得到服务唯一名称,无需兼容之前的版本
 *
 * @param interfaceConfig 服务提供者或者服务消费者配置
 * @return 服务唯一名称
 * @since 5.4.0
 */
public static String getServiceName(AbstractInterfaceConfig interfaceConfig) {
    String uniqueId = interfaceConfig.getUniqueId();
    return interfaceConfig.getInterfaceId() + (StringUtils.isEmpty(uniqueId) ? "" : ":" + uniqueId);
}