com.alipay.sofa.rpc.common.utils.StringUtils Java Examples

The following examples show how to use com.alipay.sofa.rpc.common.utils.StringUtils. 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: ModuleFactory.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * parse module load config
 *
 * @param moduleLoadList alias of all config modules
 * @param moduleName     the module name
 * @return need load
 */
static boolean needLoad(String moduleLoadList, String moduleName) {
    String[] activatedModules = StringUtils.splitWithCommaOrSemicolon(moduleLoadList);
    boolean match = false;
    for (String activatedModule : activatedModules) {
        if (StringUtils.ALL.equals(activatedModule)) {
            match = true;
        } else if (activatedModule.equals(moduleName)) {
            match = true;
        } else if (match && (activatedModule.equals("!" + moduleName)
            || activatedModule.equals("-" + moduleName))) {
            match = false;
            break;
        }
    }
    return match;
}
 
Example #2
Source File: DefaultProviderBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 接口可以按方法发布,不在黑名单里且在白名单里,*算在白名单
 *
 * @param includeMethods 包含的方法列表
 * @param excludeMethods 不包含的方法列表
 * @param methodName     方法名
 * @return 方法
 */
protected boolean inList(String includeMethods, String excludeMethods, String methodName) {
    //判断是否在白名单中
    if (!StringUtils.ALL.equals(includeMethods)) {
        if (!inMethodConfigs(includeMethods, methodName)) {
            return false;
        }
    }
    //判断是否在黑白单中
    if (inMethodConfigs(excludeMethods, methodName)) {
        return false;
    }
    //默认还是要发布
    return true;

}
 
Example #3
Source File: SofaRegistrySubscribeCallback.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * merge data
 *
 * @param userData
 * @param configData
 * @return
 */
private ComposeUserData composeUserAndConfigData(UserData userData, ConfigData configData) {

    ComposeUserData result = new ComposeUserData();

    Map<String, List<ProviderInfo>> zoneData = new HashMap<String, List<ProviderInfo>>();
    if (userData == null) {
        return result;
    } else {
        result.setLocalZone(userData.getLocalZone());

        final Map<String, List<String>> listZoneData = userData.getZoneData();
        final String[] configDatas = StringUtils.split(
            configData == null ? StringUtils.EMPTY : configData.getData(), CONFIG_SEPARATOR);
        final List<String> attrData = Arrays.asList(configDatas);
        for (String key : listZoneData.keySet()) {
            final List<ProviderInfo> providerInfos = mergeProviderInfo(listZoneData.get(key), attrData);
            zoneData.put(key, providerInfos);
        }

        result.setZoneData(zoneData);

    }

    return result;
}
 
Example #4
Source File: MessageBuilderTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void buildSofaRequest1() throws Exception {
    Method method = Number.class.getMethod("intValue");
    SofaRequest request = MessageBuilder.buildSofaRequest(Number.class, method,
        new Class[0], StringUtils.EMPTY_STRING_ARRAY);
    Assert.assertEquals(request.getInterfaceName(), Number.class.getName());
    Assert.assertEquals(request.getMethodName(), "intValue");
    Assert.assertArrayEquals(StringUtils.EMPTY_STRING_ARRAY, request.getMethodArgs());
    Assert.assertArrayEquals(StringUtils.EMPTY_STRING_ARRAY, request.getMethodArgSigs());

    method = Comparable.class.getMethod("compareTo", Object.class);
    request = MessageBuilder.buildSofaRequest(Comparable.class, method,
        new Class[] { Object.class }, new Object[] { null });
    Assert.assertEquals(request.getInterfaceName(), Comparable.class.getName());
    Assert.assertEquals(request.getMethodName(), "compareTo");
    Assert.assertArrayEquals(request.getMethodArgs(), new Object[] { null });
    Assert.assertArrayEquals(request.getMethodArgSigs(), new String[] { "java.lang.Object" });
}
 
Example #5
Source File: ZookeeperRegistryDataCacheImpl.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
@Override
public List<RpcProvider> fetchProvidersByService(String serviceName) {
    List<RpcProvider> result = new ArrayList<>();
    if (StringUtils.isEmpty(serviceName)) {
        return result;
    }
    RpcService rpcService = services.get(serviceName);

    if (rpcService != null) {
        result = providers.get(rpcService);
        if (CommonUtils.isNotEmpty(result)) {
            return result;
        }
    }
    return result;
}
 
Example #6
Source File: MeshApiClient.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public boolean registeApplication(ApplicationInfoRequest applicationInfoRequest) {

        final String json = applicationInfoRequest.toJson();
        String result = httpPost(MeshEndpoint.CONFIGS, json);

        if (!StringUtils.equals(result, errorMessage)) {
            final ApplicationInfoResult parse = JSON.parseObject(result,
                ApplicationInfoResult.class);
            if (parse.isSuccess()) {
                return true;
            }
            return false;
        } else {
            return false;
        }

    }
 
Example #7
Source File: SofaRegistryRestClient.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private RpcConsumer convertRpcConsumerFromMap(Map subscriberMap) {
    RpcConsumer consumer = new RpcConsumer();
    consumer.setAppName(getEmptyStringIfNull(subscriberMap, SofaDashboardConstants.APP_NAME));
    consumer.setServiceName(getEmptyStringIfNull(subscriberMap,
        SofaDashboardConstants.REGISTRY_DATA_ID_KEY));
    String processId = getEmptyStringIfNull(subscriberMap,
        SofaDashboardConstants.REGISTRY_PROCESS_ID_KEY);
    if (processId.contains(SofaDashboardConstants.COLON)) {
        consumer.setAddress(processId.split(SofaDashboardConstants.COLON)[0]);
        consumer.setPort(Integer.valueOf(processId.split(SofaDashboardConstants.COLON)[1]));
    } else {
        Object sourceAddress = subscriberMap
            .get(SofaDashboardConstants.REGISTRY_SOURCE_ADDRESS_KEY);
        if (sourceAddress instanceof Map) {
            String ipAddress = getEmptyStringIfNull((Map) sourceAddress,
                SofaDashboardConstants.REGISTRY_IP_KEY);
            String port = getEmptyStringIfNull((Map) sourceAddress, SofaDashboardConstants.PORT);
            consumer.setAddress(ipAddress);
            consumer.setPort(Integer.valueOf(StringUtils.isBlank(port) ? "0" : port));
        }
    }
    Map<String, String> attributes = (Map<String, String>) subscriberMap
        .get(SofaDashboardConstants.REGISTRY_ATTRIBUTES);
    consumer.setParameters(attributes);
    return consumer;
}
 
Example #8
Source File: SofaRegistryRestClient.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
private RpcProvider convertRpcProviderFromMap(Map publisherMap) {
    RpcProvider provider = new RpcProvider();
    provider.setAppName(getEmptyStringIfNull(publisherMap, SofaDashboardConstants.APP_NAME));
    provider.setServiceName(getEmptyStringIfNull(publisherMap,
        SofaDashboardConstants.REGISTRY_DATA_ID_KEY));
    String processId = getEmptyStringIfNull(publisherMap,
        SofaDashboardConstants.REGISTRY_PROCESS_ID_KEY);
    if (processId.contains(SofaDashboardConstants.COLON)) {
        provider.setAddress(processId.split(SofaDashboardConstants.COLON)[0]);
        provider.setPort(Integer.valueOf(processId.split(SofaDashboardConstants.COLON)[1]));
    } else {
        Object sourceAddress = publisherMap
            .get(SofaDashboardConstants.REGISTRY_SOURCE_ADDRESS_KEY);
        if (sourceAddress instanceof Map) {
            String ipAddress = getEmptyStringIfNull((Map) sourceAddress,
                SofaDashboardConstants.REGISTRY_IP_KEY);
            String port = getEmptyStringIfNull((Map) sourceAddress, SofaDashboardConstants.PORT);
            provider.setAddress(ipAddress);
            provider.setPort(Integer.valueOf(StringUtils.isBlank(port) ? "0" : port));
        }
    }
    Map<String, String> attributes = (Map<String, String>) publisherMap
        .get(SofaDashboardConstants.REGISTRY_ATTRIBUTES);
    provider.setParameters(attributes);
    return provider;
}
 
Example #9
Source File: ApplicationStartedListener.java    From sofa-dashboard with Apache License 2.0 6 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ContextRefreshedEvent) {
        String address = environment.getProperty(SofaDashboardConstants.KEY);
        if (StringUtils.isNotBlank(address)) {
            RegistryConfig registryConfig = new RegistryConfig();
            if (address.startsWith(SofaDashboardConstants.ZOOKEEPER_PREFIX)) {
                RegistryConfigureProcessor processor = new ZookeeperConfigurator();
                registryConfig = processor.buildFromAddress(address);
            } else if (address.startsWith(SofaDashboardConstants.SOFA_PREFIX)) {
                registryConfig.setAddress(address.substring(SofaDashboardConstants.SOFA_PREFIX
                    .length()));
                registryConfig.setProtocol(SofaBootRpcConfigConstants.DEFAULT_REGISTRY);
                // config registry type
                Map<String, Object> props = new HashMap<>();
                props.put(SofaDashboardConstants.REGISTRY_TYPE,
                    SofaBootRpcConfigConstants.DEFAULT_REGISTRY);
                PropertySource propertySource = new MapPropertySource(
                    "customRegistryPropertySource", props);
                ((ConfigurableEnvironment) environment).getPropertySources().addLast(
                    propertySource);
            }
            registryDataSyncManager.start(registryConfig);
        }
    }
}
 
Example #10
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 #11
Source File: DefaultConsumerBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Subscribe provider list from direct url
 *
 * @param directUrl direct url of consume config
 * @return Provider group list
 */
protected List<ProviderGroup> subscribeFromDirectUrl(String directUrl) {
    List<ProviderGroup> result = new ArrayList<ProviderGroup>();
    List<ProviderInfo> tmpProviderInfoList = new ArrayList<ProviderInfo>();
    String[] providerStrs = StringUtils.splitWithCommaOrSemicolon(directUrl);
    for (String providerStr : providerStrs) {
        ProviderInfo providerInfo = convertToProviderInfo(providerStr);
        if (providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_SOURCE) == null) {
            providerInfo.setStaticAttr(ProviderInfoAttrs.ATTR_SOURCE, "direct");
        }
        tmpProviderInfoList.add(providerInfo);
    }

    result.add(new ProviderGroup(RpcConstants.ADDRESS_DIRECT_GROUP, tmpProviderInfoList));
    return result;
}
 
Example #12
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 #13
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 #14
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 #15
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 #16
Source File: ProviderHelper.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * Write provider info to url string
 *
 * @param providerInfo Provide info
 * @return the string
 */
public static String toUrl(ProviderInfo providerInfo) {
    String uri = providerInfo.getProtocolType() + "://" + providerInfo.getHost() + ":" + providerInfo.getPort();
    uri += StringUtils.trimToEmpty(providerInfo.getPath());
    StringBuilder sb = new StringBuilder();
    if (providerInfo.getRpcVersion() > 0) {
        sb.append("&").append(ProviderInfoAttrs.ATTR_RPC_VERSION).append("=").append(providerInfo.getRpcVersion());
    }
    if (providerInfo.getSerializationType() != null) {
        sb.append("&").append(ProviderInfoAttrs.ATTR_SERIALIZATION).append("=")
            .append(providerInfo.getSerializationType());
    }
    for (Map.Entry<String, String> entry : providerInfo.getStaticAttrs().entrySet()) {
        sb.append("&").append(entry.getKey()).append("=").append(entry.getValue());
    }
    if (sb.length() > 0) {
        uri += sb.replace(0, 1, "?").toString();
    }
    return uri;
}
 
Example #17
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 #18
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 #19
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 #20
Source File: MeshApiClient.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public boolean unSubscribeService(UnSubscribeServiceRequest request) {
    final String json = JSON.toJSONString(request);

    String result = httpPost(MeshEndpoint.UN_SUBCRIBE, json);

    if (!StringUtils.equals(result, errorMessage)) {
        final UnSubscribeServiceResult parse = JSON.parseObject(result,
            UnSubscribeServiceResult.class);
        if (parse.isSuccess()) {
            return true;
        }
        return false;
    } else {
        return false;
    }
}
 
Example #21
Source File: DefaultConsumerBootstrap.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public List<ProviderGroup> subscribe() {
    List<ProviderGroup> result = null;
    String directUrl = consumerConfig.getDirectUrl();
    if (StringUtils.isNotEmpty(directUrl)) {
        // 如果走直连
        result = subscribeFromDirectUrl(directUrl);
    } else {
        // 没有配置url直连
        List<RegistryConfig> registryConfigs = consumerConfig.getRegistry();
        if (CommonUtils.isNotEmpty(registryConfigs)) {
            // 从多个注册中心订阅服务列表
            result = subscribeFromRegistries();
        }
    }
    return result;
}
 
Example #22
Source File: ExtensionLoader.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
protected void readLine(URL url, String line) {
    String[] aliasAndClassName = parseAliasAndClassName(line);
    if (aliasAndClassName == null || aliasAndClassName.length != 2) {
        return;
    }
    String alias = aliasAndClassName[0];
    String className = aliasAndClassName[1];
    // 读取配置的实现类
    Class tmp;
    try {
        tmp = ClassUtils.forName(className, false);
    } catch (Throwable e) {
        if (LOGGER.isWarnEnabled()) {
            LOGGER.warn("Extension {} of extensible {} is disabled, cause by: {}",
                className, interfaceName, ExceptionUtils.toShortString(e, 2));
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Extension " + className + " of extensible " + interfaceName + " is disabled.", e);
        }
        return;
    }

    loadExtension(alias, tmp, StringUtils.toString(url), className);
}
 
Example #23
Source File: RpcSofaTracer.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private void generateServerErrorContext(Map<String, String> context, SofaRequest request,
                                        SofaTracerSpan serverSpan) {
    //tags
    Map<String, String> tagsWithStr = serverSpan.getTagsWithStr();
    context.put("serviceName", tagsWithStr.get(RpcSpanTags.SERVICE));
    context.put("methodName", tagsWithStr.get(RpcSpanTags.METHOD));
    context.put("protocol", tagsWithStr.get(RpcSpanTags.PROTOCOL));
    context.put("invokeType", tagsWithStr.get(RpcSpanTags.INVOKE_TYPE));

    context.put("callerUrl", tagsWithStr.get(RpcSpanTags.REMOTE_IP));
    context.put("callerApp", tagsWithStr.get(RpcSpanTags.REMOTE_APP));
    context.put("callerZone", tagsWithStr.get(RpcSpanTags.REMOTE_ZONE));
    context.put("callerIdc", tagsWithStr.get(RpcSpanTags.REMOTE_IDC));
    //paramTypes
    if (request != null) {
        context.put("paramTypes", com.alipay.common.tracer.core.utils.StringUtils
            .arrayToString(request.getMethodArgSigs(), '|', "", ""));
    }
}
 
Example #24
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 #25
Source File: SofaRpcSerialization.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public <Response extends ResponseCommand> boolean serializeHeader(Response response)
    throws SerializationException {
    if (response instanceof RpcResponseCommand) {
        RpcInternalContext.getContext().getStopWatch().tick();

        Object responseObject = ((RpcResponseCommand) response).getResponseObject();
        if (responseObject instanceof SofaResponse) {
            SofaResponse sofaResponse = (SofaResponse) responseObject;
            if (sofaResponse.isError() || sofaResponse.getAppResponse() instanceof Throwable) {
                sofaResponse.addResponseProp(RemotingConstants.HEAD_RESPONSE_ERROR, StringUtils.TRUE);
            }
            response.setHeader(mapSerializer.encode(sofaResponse.getResponseProps()));
        }
        return true;
    }
    return false;
}
 
Example #26
Source File: AbstractCluster.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 检测服务节点的一些信息
 *
 * @param providerGroup 服务列表分组
 */
protected void checkProviderInfo(ProviderGroup providerGroup) {
    List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
    if (CommonUtils.isEmpty(providerInfos)) {
        return;
    }
    Iterator<ProviderInfo> iterator = providerInfos.iterator();
    while (iterator.hasNext()) {
        ProviderInfo providerInfo = iterator.next();
        if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
            if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
                LOGGER.warnWithApp(consumerConfig.getAppName(),
                    "Unmatched protocol between consumer [{}] and provider [{}].",
                    consumerConfig.getProtocol(), providerInfo.getProtocolType());
            }
        }
    }
}
 
Example #27
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 #28
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 #29
Source File: RpcLookout.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Create provider id
 *
 * @param model RpcServerLookoutModel
 * @return Id
 */
public Id createMethodProviderId(RpcServerLookoutModel model) {
    Map<String, String> tags = new HashMap<String, String>(5);

    tags.put("app", StringUtils.defaultString(model.getApp()));
    tags.put("service", StringUtils.defaultString(model.getService()));
    tags.put("method", StringUtils.defaultString(model.getMethod()));
    tags.put("protocol", StringUtils.defaultString(model.getProtocol()));
    tags.put("caller_app", StringUtils.defaultString(model.getCallerApp()));

    return rpcLookoutId.fetchProviderStatId().withTags(tags);
}
 
Example #30
Source File: SimpleMapSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 读取一个字符串
 *
 * @param in 输入流程
 * @return 字符串
 * @throws IOException 读取异常
 */
protected String readString(InputStream in) throws IOException {
    int length = readInt(in);
    if (length < 0) {
        return null;
    } else if (length == 0) {
        return StringUtils.EMPTY;
    } else {
        byte[] value = new byte[length];
        in.read(value);
        return StringSerializer.decode(value);
    }
}