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

The following examples show how to use com.alipay.sofa.rpc.common.utils.StringUtils#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: ConsulConfigurator.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
/**
 * 解析配置 value
 *
 * @param config 配置 value
 */
String parseAddress(String config) {
    String address = null;

    if (StringUtils.isNotEmpty(config) && config.startsWith(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_CONSUL)) {
        final String consulProtocol = SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_CONSUL + "://";
        String value = config.substring(consulProtocol.length());
        if (!value.contains("?")) {
            address = value;
        } else {
            int index = value.lastIndexOf('?');
            address = value.substring(0, index);
        }
    }

    return address;
}
 
Example 2
Source File: RegistryParseUtil.java    From sofa-rpc-boot-projects with Apache License 2.0 6 votes vote down vote up
/**
 * Parse address string.
 *
 * @param config the config 
 * @param protocol the protocol 
 * @return the string
 */
public static String parseAddress(String config, String protocol) {
    String address = null;

    if (StringUtils.isNotEmpty(config) && config.startsWith(protocol)) {
        final String nacosProtocol = protocol + "://";
        String value = config.substring(nacosProtocol.length());
        if (!value.contains("?")) {
            address = value;
        } else {
            int index = value.lastIndexOf('?');
            address = value.substring(0, index);
        }
    }

    return address;
}
 
Example 3
Source File: SofaConfigs.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * System.getProperty() > 外部配置 > rpc-config.properties
 *
 * @param appName 应用名
 * @param key     配置项
 * @return 配置
 */
private static String getStringValue0(String appName, String key) {
    String ret = System.getProperty(key);
    if (StringUtils.isNotEmpty(ret)) {
        return ret;
    }
    rLock.lock();
    try {
        for (ExternalConfigLoader configLoader : CONFIG_LOADERS) {
            ret = appName == null ? configLoader.getValue(key)
                : configLoader.getValue(appName, key);
            if (StringUtils.isNotEmpty(ret)) {
                return ret;
            }
        }
    } finally {
        rLock.unlock();
    }
    return getConfig().getProperty(key);
}
 
Example 4
Source File: RegistryUtils.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static String convertInstanceToUrl(String host, int port, Map<String, String> metaData) {
    if (metaData == null) {
        metaData = new HashMap<String, String>();
    }
    String uri = "";
    String protocol = metaData.get(RpcConstants.CONFIG_KEY_PROTOCOL);
    if (StringUtils.isNotEmpty(protocol)) {
        uri = protocol + "://";
    }
    uri += host + ":" + port;

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : metaData.entrySet()) {
        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
    }
    if (sb.length() > 0) {
        uri += sb.replace(0, 1, "?").toString();
    }
    return uri;
}
 
Example 5
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public <Request extends RequestCommand> boolean serializeHeader(Request request, InvokeContext invokeContext)
    throws SerializationException {
    if (request instanceof RpcRequestCommand) {
        RpcInternalContext.getContext().getStopWatch().tick();

        RpcRequestCommand requestCommand = (RpcRequestCommand) request;
        Object requestObject = requestCommand.getRequestObject();
        String service = getTargetServiceName(requestObject);
        if (StringUtils.isNotEmpty(service)) {
            Map<String, String> header = new HashMap<String, String>(16);
            header.put(RemotingConstants.HEAD_SERVICE, service);
            putRequestMetadataToHeader(requestObject, header);
            requestCommand.setHeader(mapSerializer.encode(header));
        }
        return true;
    }
    return false;
}
 
Example 6
Source File: LocalRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static Map<String, ProviderGroup> unMarshal(String context) {
    if (StringUtils.isBlank(context)) {
        return null;
    }
    Map<String, ProviderGroup> map = new HashMap<String, ProviderGroup>();
    String[] lines = StringUtils.split(context, FileUtils.LINE_SEPARATOR);
    for (String line : lines) {
        String[] fields = line.split(SEPARATORSTR);
        if (fields.length > 1) {
            String key = fields[0];
            Set<ProviderInfo> values = new HashSet<ProviderInfo>();
            for (int i = 1; i < fields.length; i++) {
                String pstr = fields[i];
                if (StringUtils.isNotEmpty(pstr)) {
                    ProviderInfo providerInfo = ProviderHelper.toProviderInfo(pstr);
                    providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_SOURCE, "local");
                    values.add(providerInfo);
                }
            }
            map.put(key, new ProviderGroup(new ArrayList<ProviderInfo>(values)));
        }
    }
    return map;
}
 
Example 7
Source File: ZookeeperRegistry.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 创建认证信息
 * @return
 */
private List<AuthInfo> buildAuthInfo() {
    List<AuthInfo> info = new ArrayList<AuthInfo>();

    String scheme = registryConfig.getParameter("scheme");

    //如果存在多个认证信息,则在参数形式为为addAuth=user1:paasswd1,user2:passwd2
    String addAuth = registryConfig.getParameter("addAuth");

    if (StringUtils.isNotEmpty(addAuth)) {
        String[] addAuths = addAuth.split(",");
        for (String singleAuthInfo : addAuths) {
            info.add(new AuthInfo(scheme, singleAuthInfo.getBytes()));
        }
    }

    return info;
}
 
Example 8
Source File: ZookeeperRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Convert child data to attribute list.
 *
 * @param config       the interface config
 * @param overridePath the override path
 * @param currentData  the current data
 * @return the attribute list
 * @throws UnsupportedEncodingException decode exception
 */
static List<Map<String, String>> convertOverrideToAttributes(AbstractInterfaceConfig config,
                                                             String overridePath,
                                                             List<ChildData> currentData)
    throws UnsupportedEncodingException {
    List<Map<String, String>> attributes = new ArrayList<Map<String, String>>();
    if (CommonUtils.isEmpty(currentData)) {
        return attributes;
    }

    for (ChildData childData : currentData) {
        String url = URLDecoder.decode(childData.getPath().substring(overridePath.length() + 1),
            "UTF-8");
        if (config instanceof ConsumerConfig) {
            //If child data contains system local host, convert config to attribute
            if (StringUtils.isNotEmpty(url) && StringUtils.isNotEmpty(SystemInfo.getLocalHost())
                && url.contains("://" + SystemInfo.getLocalHost() + "?")) {
                attributes.add(convertConfigToAttribute(overridePath, childData, false));
            }
        }
    }
    return attributes;
}
 
Example 9
Source File: NacosRegistryHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static String convertInstanceToUrl(Instance instance) {
    Map<String, String> metaData = instance.getMetadata();
    if (metaData == null) {
        metaData = new HashMap<String, String>();
    }
    String uri = "";
    String protocol = metaData.get(RpcConstants.CONFIG_KEY_PROTOCOL);
    if (StringUtils.isNotEmpty(protocol)) {
        uri = protocol + "://";
    }
    uri += instance.getIp() + ":" + instance.getPort();

    StringBuilder sb = new StringBuilder();
    for (Map.Entry<String, String> entry : metaData.entrySet()) {
        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
    }
    if (sb.length() > 0) {
        uri += sb.replace(0, 1, "?").toString();
    }
    return uri;
}
 
Example 10
Source File: ChannelContext.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets header.
 *
 * @param value the value
 * @return the header
 */
public Short getHeaderKey(String value) {
    if (StringUtils.isNotEmpty(value) && headerCache != null) {
        return headerCache.getKey(value);
    }
    return null;
}
 
Example 11
Source File: LocalFileConfigurator.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
/**
 * 读取配置 key ,获取其 value 进行解析。
 */
public String parseConfig(String config) {
    String file = null;
    if (StringUtils.isNotEmpty(config) && config.startsWith(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL) &&
        config.length() > SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL.length()) {
        file = config.substring(SofaBootRpcConfigConstants.REGISTRY_PROTOCOL_LOCAL.length() + COLON.length());
    }

    return file;
}
 
Example 12
Source File: RouterChain.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否需要排除系统过滤器
 *
 * @param customRouters 自定义Router
 * @return 是否排除
 */
private static HashSet<String> parseExcludeRouter(List<Router> customRouters) {
    HashSet<String> excludeKeys = new HashSet<String>();
    if (CommonUtils.isNotEmpty(customRouters)) {
        for (Router router : customRouters) {
            if (router instanceof ExcludeRouter) {
                // 存在需要排除的过滤器
                ExcludeRouter excludeRouter = (ExcludeRouter) router;
                String excludeName = excludeRouter.getExcludeName();
                if (StringUtils.isNotEmpty(excludeName)) {
                    String excludeRouterName = startsWithExcludePrefix(excludeName) ? excludeName.substring(1)
                        : excludeName;
                    if (StringUtils.isNotEmpty(excludeRouterName)) {
                        excludeKeys.add(excludeRouterName);
                    }
                }
                customRouters.remove(router);
            }
        }
    }
    if (!excludeKeys.isEmpty()) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Find exclude routers: {}", excludeKeys);
        }
    }
    return excludeKeys;
}
 
Example 13
Source File: ConsumerInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public SofaResponse invoke(SofaRequest sofaRequest) throws SofaRpcException {
    // 设置下服务器应用
    ProviderInfo providerInfo = RpcInternalContext.getContext().getProviderInfo();
    String appName = providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_APP_NAME);
    if (StringUtils.isNotEmpty(appName)) {
        sofaRequest.setTargetAppName(appName);
    }

    // 目前只是通过client发送给服务端
    return consumerBootstrap.getCluster().sendMsg(providerInfo, sofaRequest);
}
 
Example 14
Source File: SofaRegistry.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 添加额外的属性
 *
 * @param configuratorRegistration 注册或者订阅对象
 * @param group           分组
 */
private void addAttributes(ConfiguratorRegistration configuratorRegistration, String group) {
    // if group == null; group = "DEFAULT_GROUP"
    if (StringUtils.isNotEmpty(group)) {
        configuratorRegistration.setGroup(group);
    }

}
 
Example 15
Source File: RegistryParseUtil.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
/**
 * Parse key value map.
 *
 * @param kv the kv 
 * @return the map
 */
public static Map<String, String> parseKeyValue(String kv) {
    Map<String, String> map = new HashMap<String, String>();
    if (StringUtils.isNotEmpty(kv)) {
        String[] kvSplit = kv.split("=");
        String key = kvSplit[0];
        String value = kvSplit[1];
        map.put(key, value);
    }
    return map;
}
 
Example 16
Source File: ConsulConfigurator.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
private Map<String, String> parseKeyValue(String kv) {
    Map<String, String> map = new HashMap<String, String>();
    if (StringUtils.isNotEmpty(kv)) {
        String[] kvSplit = kv.split("=");
        String key = kvSplit[0];
        String value = kvSplit[1];
        map.put(key, value);
    }
    return map;
}
 
Example 17
Source File: SystemInfo.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 解析物理机地址
 *
 * @return 物理机地址
 */
@VisibleForTesting
static String parseHostMachine() {
    String hostMachine = System.getProperty("host_machine");
    return StringUtils.isNotEmpty(hostMachine) ? hostMachine : null;
}
 
Example 18
Source File: TripleTracerAdapter.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 存入tracer信息
 *
 * @param sofaRequest   SofaRequest
 * @param requestHeader Metadata
 */
public static void beforeSend(SofaRequest sofaRequest, ConsumerConfig consumerConfig, Metadata requestHeader) {

    // 客户端设置请求服务端的Header
    // tracer信息放入request 发到服务端

    Map<String, String> header = new HashMap<String, String>();
    header.put(RemotingConstants.HEAD_METHOD_NAME, sofaRequest.getMethodName());
    header.put(RemotingConstants.HEAD_TARGET_SERVICE, sofaRequest.getTargetServiceUniqueName());
    header.put(RemotingConstants.HEAD_TARGET_APP, sofaRequest.getTargetAppName());
    //客户端的启动
    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();
    //获取并不弹出
    SofaTracerSpan clientSpan = sofaTraceContext.getCurrentSpan();
    if (clientSpan == null) {
        SelfLog.warn("ClientSpan is null.Before call interface=" + sofaRequest.getInterfaceName() + ",method=" +
                sofaRequest.getMethodName());
    } else {
        SofaTracerSpanContext sofaTracerSpanContext = clientSpan.getSofaTracerSpanContext();
        header.put(TripleHeadKeys.HEAD_KEY_TRACE_ID.name(), sofaTracerSpanContext.getTraceId());
        header.put(TripleHeadKeys.HEAD_KEY_RPC_ID.name(), sofaTracerSpanContext.getSpanId());
        header.put(TripleHeadKeys.HEAD_KEY_OLD_TRACE_ID.name(), sofaTracerSpanContext.getTraceId());
        header.put(TripleHeadKeys.HEAD_KEY_OLD_RPC_ID.name(), sofaTracerSpanContext.getSpanId());

        header.put(TripleHeadKeys.HEAD_KEY_BIZ_BAGGAGE_TYPE.name(),
                sofaTracerSpanContext.getBizSerializedBaggage());

        header.put(TripleHeadKeys.HEAD_KEY_SYS_BAGGAGE_TYPE.name(),
                sofaTracerSpanContext.getSysSerializedBaggage());
    }
    //获取 RPC 上下文

    RpcInvokeContext internalContext = RpcInvokeContext.getContext();
    String route = (String) internalContext.get(USERID_KEY);

    if (StringUtils.isNotBlank(route)) {
        Map<String, String> map = new HashMap<>();
        map.put(USERID_KEY, route);
        header.put(TripleHeadKeys.HEAD_KEY_UNIT_INFO.name(), JSONUtils.toJSONString(map));
    }

    if (StringUtils.isNotEmpty(consumerConfig.getUniqueId())) {
        header.put(TripleHeadKeys.HEAD_KEY_SERVICE_VERSION.name(), consumerConfig.getUniqueId());
    }

    header.put(TripleHeadKeys.HEAD_KEY_META_TYPE.name(), "rpc");
    header.put(TripleHeadKeys.HEAD_KEY_CURRENT_APP.name(), (String) sofaRequest.getRequestProp(HEAD_APP_NAME));
    header.put(TripleHeadKeys.HEAD_KEY_CONSUMER_APP.name(), (String) sofaRequest.getRequestProp(HEAD_APP_NAME));

    header.put(TripleHeadKeys.HEAD_KEY_PROTOCOL_TYPE.name(),
            (String) sofaRequest.getRequestProp(RemotingConstants.HEAD_PROTOCOL));
    header.put(TripleHeadKeys.HEAD_KEY_INVOKE_TYPE.name(),
            (String) sofaRequest.getRequestProp(RemotingConstants.HEAD_INVOKE_TYPE));

    final String source = consumerConfig.getParameter("interworking.source");
    if (StringUtils.isNotBlank(source)) {
        header.put(TripleHeadKeys.HEAD_KEY_SOURCE_TENANTID.name(),
                source);
    }

    final String target = consumerConfig.getParameter("interworking.target");
    if (StringUtils.isNotBlank(target)) {
        header.put(TripleHeadKeys.HEAD_KEY_TARGET_TENANTID.name(),
                target);
    }
    for (Map.Entry<String, String> entry : header.entrySet()) {
        if (StringUtils.isNotBlank(entry.getValue())) {
            requestHeader.put(TripleHeadKeys.getKey(entry.getKey()), entry.getValue());
        }
    }
}
 
Example 19
Source File: AbstractHttp2ClientTransport.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
private void addToHeader(HttpHeaders headers, CharSequence key, CharSequence value) {
    if (StringUtils.isNotEmpty(value)) {
        headers.add(key, value);
    }
}
 
Example 20
Source File: DirectUrlRouter.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 是否自动加载
 *
 * @param consumerBootstrap 调用对象
 * @return 是否加载本过滤器
 */
@Override
public boolean needToLoad(ConsumerBootstrap consumerBootstrap) {
    return StringUtils.isNotEmpty(consumerBootstrap.getConsumerConfig().getDirectUrl());
}