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

The following examples show how to use com.alipay.sofa.rpc.common.utils.StringUtils#isBlank() . 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: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * @param path path必须以/结尾
 */
protected synchronized void loadFromFile(String path) {
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Loading extension of extensible {} from path: {}", interfaceName, path);
    }
    // 默认如果不指定文件名字,就是接口名
    String file = StringUtils.isBlank(extensible.file()) ? interfaceName : extensible.file().trim();
    String fullFileName = path + file;
    try {
        ClassLoader classLoader = ClassLoaderUtils.getClassLoader(getClass());
        loadFromClassLoader(classLoader, fullFileName);
    } catch (Throwable t) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Failed to load extension of extensible " + interfaceName + " from path:" + fullFileName,
                t);
        }
    }
}
 
Example 2
Source File: BeanIdMatchFilter.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected void formatId(String ruleId) {
    if (StringUtils.isBlank(ruleId)) {
        return;
    }
    String[] ids = ruleId.split(ID_SPLIT);
    List<String> effectiveId = new ArrayList<String>(ids.length);
    List<String> excludeId = new ArrayList<String>(ids.length);

    for (String id : ids) {
        if (id.startsWith(ID_EXCLUDE)) {
            excludeId.add(id.substring(1));
        } else {
            effectiveId.add(id);
        }
    }
    this.effectiveId = effectiveId;
    this.excludeId = excludeId;
    this.allEffective = false;

}
 
Example 3
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 4
Source File: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected String[] parseAliasAndClassName(String line) {
    if (StringUtils.isBlank(line)) {
        return null;
    }
    line = line.trim();
    int i0 = line.indexOf('#');
    if (i0 == 0 || line.length() == 0) {
        return null; // 当前行是注释 或者 空
    }
    if (i0 > 0) {
        line = line.substring(0, i0).trim();
    }

    String alias = null;
    String className;
    int i = line.indexOf('=');
    if (i > 0) {
        alias = line.substring(0, i).trim(); // 以代码里的为准
        className = line.substring(i + 1).trim();
    } else {
        className = line;
    }
    if (className.length() == 0) {
        return null;
    }
    return new String[] { alias, className };
}
 
Example 5
Source File: ServiceManageController.java    From sofa-dashboard with Apache License 2.0 5 votes vote down vote up
@GetMapping("/all-service")
public List<ServiceModel> queryServiceListByService(@RequestParam("query") String query) {
    List<ServiceModel> data = new ArrayList<>();
    Map<String, RpcService> rpcServices = registryDataCache.fetchService();
    for (Map.Entry<String, RpcService> rpcServiceEntry : rpcServices.entrySet()) {
        final String serviceName = rpcServiceEntry.getKey();
        ServiceModel model = fetchServiceModel(serviceName);
        if (model != null && (serviceName.contains(query) || StringUtils.isBlank(query))) {
            data.add(model);
        }
    }
    return data;
}
 
Example 6
Source File: DynamicConfigKeyHelper.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * The last field of key is actual property key
 */
public static String extractPropertyKey(String key) {
    if (StringUtils.isBlank(key)) {
        return "";
    }
    return key.substring(key.lastIndexOf(KEY_SEPARATOR) + 1);
}
 
Example 7
Source File: ServerFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 确定下Server的host和port
 *
 * @param serverConfig 服务器配置
 */
private static void resolveServerConfig(ServerConfig serverConfig) {
    // 绑定到指定网卡 或全部网卡
    String boundHost = serverConfig.getBoundHost();
    if (boundHost == null) {
        String host = serverConfig.getHost();
        if (StringUtils.isBlank(host)) {
            host = SystemInfo.getLocalHost();
            serverConfig.setHost(host);
            // windows绑定到0.0.0.0的某个端口以后,其它进程还能绑定到该端口
            boundHost = SystemInfo.isWindows() ? host : NetUtils.ANYHOST;
        } else {
            boundHost = host;
        }
        serverConfig.setBoundHost(boundHost);
    }

    // 绑定的端口
    if (serverConfig.isAdaptivePort()) {
        int oriPort = serverConfig.getPort();
        int port = NetUtils.getAvailablePort(boundHost, oriPort,
            RpcConfigs.getIntValue(RpcOptions.SERVER_PORT_END));
        if (port != oriPort) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Changed port from {} to {} because the config port is disabled", oriPort, port);
            }
            serverConfig.setPort(port);
        }
    }
}
 
Example 8
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 9
Source File: TripleClientInvoker.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private void cacheCommonData(ConsumerConfig consumerConfig) {
    String serialization = consumerConfig.getSerialization();
    if (StringUtils.isBlank(serialization)) {
        serialization = getDefaultSerialization();
    }
    this.serialization = serialization;
    this.serializer = SerializerFactory.getSerializer(serialization);
}
 
Example 10
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private boolean parseSampled(Map<String, String> contextMap, SofaTracerSpanContext spanContext) {
    // 新版本中tracer标记不在 baggage 中,兼容老版本
    String oldSampledMark = spanContext.getSysBaggage().get(
        TracerCompatibleConstants.SAMPLING_MARK);
    // 默认不会设置采样标记,即默认采样
    if (StringUtils.isBlank(oldSampledMark) || "true".equals(oldSampledMark)) {
        return true;
    }
    // 除显示获取 tracer 上下文中的采样标记之外,默认全部采样
    String sampledStr = this.getEmptyStringIfNull(contextMap, TracerCompatibleConstants.SAMPLING_MARK);
    return StringUtils.isNotBlank(sampledStr) ? Boolean.valueOf(sampledStr) : true;
}
 
Example 11
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
protected String getEmptyStringIfNull(Map map, String key) {
    if (map == null || map.size() <= 0) {
        return StringUtils.EMPTY;
    }
    Object valueObject = map.get(key);
    String valueStr = null;
    try {
        valueStr = (String) valueObject;
    } catch (Throwable throwable) {
        return StringUtils.EMPTY;
    }
    return StringUtils.isBlank(valueStr) ? StringUtils.EMPTY : valueStr;
}
 
Example 12
Source File: NetworkAddressUtil.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
/**
 * 获得本地的网络地址
 * <p>
 * 在有超过一块网卡时有问题,这里每次只取了第一块网卡绑定的IP地址
 * 当存在这种情况的时候,就需要配置 rpc_enabled_ip_range 参数,用以限制IP范围
 *
 * @return 本地的 IP 地址
 */
public static String getNetworkAddress(String bindNetworkInterface) {
    Enumeration<NetworkInterface> netInterfaces;
    try {
        netInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip;
        while (netInterfaces.hasMoreElements()) {
            boolean useNi = false;
            NetworkInterface ni = netInterfaces.nextElement();
            if (!StringUtils.isBlank(bindNetworkInterface)) {
                if (bindNetworkInterface.equals(ni.getDisplayName()) || bindNetworkInterface.equals(ni.getName())) {
                    useNi = true;
                } else {
                    continue;
                }
            }

            Enumeration<InetAddress> addresses = ni.getInetAddresses();
            while (addresses.hasMoreElements()) {
                ip = addresses.nextElement();
                if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(COLON) == -1
                    && (useNi || ipEnabled(ip.getHostAddress()))) {
                    return ip.getHostAddress();
                }
            }
        }
        return "";
    } catch (Exception e) {
        return "";
    }
}
 
Example 13
Source File: SofaRegistryRestClient.java    From sofa-dashboard with Apache License 2.0 5 votes vote down vote up
/**
 * Extract value from map ,if null return empty String
 *
 * @param map
 * @param key
 * @return
 */
private String getEmptyStringIfNull(Map map, String key) {
    if (map == null || map.size() <= 0) {
        return StringUtils.EMPTY;
    }
    Object valueObject = map.get(key);
    String valueStr;
    try {
        valueStr = (String) valueObject;
    } catch (Throwable throwable) {
        return StringUtils.EMPTY;
    }
    return StringUtils.isBlank(valueStr) ? StringUtils.EMPTY : valueStr;
}
 
Example 14
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
public void serverReceived(SofaRequest request) {

    SofaTraceContext sofaTraceContext = SofaTraceContextHolder.getSofaTraceContext();

    Map<String, String> tags = new HashMap<String, String>();
    //server tags 必须设置
    tags.put(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER);

    String spanStrs = (String) request.getRequestProp(RemotingConstants.NEW_RPC_TRACE_NAME);
    SofaTracerSpanContext spanContext = null;
    if (StringUtils.isBlank(spanStrs)) {
        //老
        Object oldInstanceMap = request.getRequestProp(RemotingConstants.RPC_TRACE_NAME);
        spanContext = this.saveSpanContextAndTags(tags, oldInstanceMap);
    } else {
        //新
        spanContext = SofaTracerSpanContext.deserializeFromString(spanStrs);
    }
    SofaTracerSpan serverSpan;
    //使用客户端的进行初始化,如果上游没有,需要新建
    if (spanContext == null) {
        serverSpan = (SofaTracerSpan) this.sofaTracer.buildSpan(request.getInterfaceName())
            .asChildOf(spanContext)
            .withTag(Tags.SPAN_KIND.getKey(), Tags.SPAN_KIND_SERVER)
            .start();
    } else {
        //有的话,需要new,采样会正确
        serverSpan = new SofaTracerSpan(this.sofaTracer, System.currentTimeMillis(),
            request.getInterfaceName()
            , spanContext, tags);
    }
    //重新获取
    spanContext = serverSpan.getSofaTracerSpanContext();

    // Record server receive event
    serverSpan.log(LogData.SERVER_RECV_EVENT_VALUE);
    //放到线程上下文
    sofaTraceContext.push(serverSpan);
    //rpc 上下文
    if (RpcInternalContext.isAttachmentEnable()) {
        RpcInternalContext context = RpcInternalContext.getContext();
        context.setAttachment(RpcConstants.INTERNAL_KEY_TRACE_ID, spanContext.getTraceId());
        context.setAttachment(RpcConstants.INTERNAL_KEY_SPAN_ID, spanContext.getSpanId());
    }
}
 
Example 15
Source File: DynamicConfigKeyHelper.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
public static boolean isServiceProKey(String key) {
    return !StringUtils.isBlank(key) && (key.startsWith(SERVICE_CONSUMER_PROPERTY_KEY_PREFIX) ||
        key.startsWith(SERVICE_PROVIDER_PROPERTY_KEY_PREFIX));
}
 
Example 16
Source File: DynamicConfigKeyHelper.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
public static boolean isMethodProKey(String key) {
    return !StringUtils.isBlank(key) && (key.startsWith(METHOD_CONSUMER_PROPERTY_KEY_PREFIX) ||
        key.startsWith(METHOD_PROVIDER_PROPERTY_KEY_PREFIX));
}
 
Example 17
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");
    }
}