From 180da709e30af2cddea7a4084f9be4b3d65235dc Mon Sep 17 00:00:00 2001 From: Ray Date: Tue, 2 Aug 2022 17:06:30 +0800 Subject: [PATCH] support additional group from env --- .../api/motan/common/MotanConstants.java | 5 ++ .../weibo/api/motan/config/ServiceConfig.java | 36 +++++----- .../support/ProtocolFilterDecorator.java | 57 +++++---------- .../weibo/api/motan/util/MeshProxyUtil.java | 5 +- .../com/weibo/api/motan/util/NetUtils.java | 25 +++---- .../com/weibo/api/motan/util/StringTools.java | 20 ++++-- .../java/com/weibo/api/motan/TestUtils.java | 40 +++++++++++ .../api/motan/config/ServiceConfigTest.java | 72 +++++++++++++++---- .../api/motan/util/MeshProxyUtilTest.java | 26 ++----- .../weibo/api/motan/util/StringToolsTest.java | 55 ++++++++++++++ 10 files changed, 230 insertions(+), 111 deletions(-) create mode 100644 motan-core/src/test/java/com/weibo/api/motan/TestUtils.java create mode 100644 motan-core/src/test/java/com/weibo/api/motan/util/StringToolsTest.java diff --git a/motan-core/src/main/java/com/weibo/api/motan/common/MotanConstants.java b/motan-core/src/main/java/com/weibo/api/motan/common/MotanConstants.java index dcb4a9554..887d3e9be 100644 --- a/motan-core/src/main/java/com/weibo/api/motan/common/MotanConstants.java +++ b/motan-core/src/main/java/com/weibo/api/motan/common/MotanConstants.java @@ -161,6 +161,11 @@ public class MotanConstants { // ------------------ attachment constants ----------------- public static final String ATT_PRINT_TRACE_LOG = "print_trace_log"; // 针对单请求是否打印(access)日志 + // ------------------ common env name ----------------- + public static final String ENV_ADDITIONAL_GROUP = "MOTAN_SERVICE_ADDITIONAL_GROUP"; //motan service 追加导出分组。例如可以自动追加云平台上的分组 + public static final String ENV_MESH_PROXY = "MOTAN_MESH_PROXY"; //使用mesh代理motan请求的环境变量名 + public static final String ENV_MOTAN_IP_PREFIX = "MOTAN_IP_PREFIX"; + private MotanConstants() { } diff --git a/motan-core/src/main/java/com/weibo/api/motan/config/ServiceConfig.java b/motan-core/src/main/java/com/weibo/api/motan/config/ServiceConfig.java index bbabe8eab..e5a15af41 100644 --- a/motan-core/src/main/java/com/weibo/api/motan/config/ServiceConfig.java +++ b/motan-core/src/main/java/com/weibo/api/motan/config/ServiceConfig.java @@ -30,6 +30,7 @@ import com.weibo.api.motan.util.ConcurrentHashSet; import com.weibo.api.motan.util.LoggerUtil; import com.weibo.api.motan.util.NetUtils; +import com.weibo.api.motan.util.StringTools; import org.apache.commons.lang3.StringUtils; import java.util.*; @@ -43,7 +44,7 @@ public class ServiceConfig extends AbstractServiceConfig { private static final long serialVersionUID = -3342374271064293224L; - private static ConcurrentHashSet existingServices = new ConcurrentHashSet(); + private static ConcurrentHashSet existingServices = new ConcurrentHashSet<>(); // 具体到方法的配置 protected List methods; @@ -51,7 +52,7 @@ public class ServiceConfig extends AbstractServiceConfig { private T ref; // service 对应的exporters,用于管理service服务的生命周期 - private List> exporters = new CopyOnWriteArrayList>(); + private List> exporters = new CopyOnWriteArrayList<>(); private Class interfaceClass; private BasicServiceInterfaceConfig basicService; private AtomicBoolean exported = new AtomicBoolean(false); @@ -120,7 +121,7 @@ public synchronized void export() { for (ProtocolConfig protocolConfig : protocols) { Integer port = protocolPorts.get(protocolConfig.getId()); if (port == null) { - throw new MotanServiceException(String.format("Unknow port in service:%s, protocol:%s", interfaceClass.getName(), + throw new MotanServiceException(String.format("Unknown port in service:%s, protocol:%s", interfaceClass.getName(), protocolConfig.getId())); } doExport(protocolConfig, port); @@ -142,7 +143,6 @@ public synchronized void unexport() { } } - @SuppressWarnings("unchecked") private void doExport(ProtocolConfig protocolConfig, int port) { String protocolName = protocolConfig.getName(); if (protocolName == null || protocolName.length() == 0) { @@ -157,7 +157,7 @@ private void doExport(ProtocolConfig protocolConfig, int port) { hostAddress = getLocalHostAddress(); } - Map map = new HashMap(); + Map map = new HashMap<>(); map.put(URLParamType.nodeType.getName(), MotanConstants.NODE_TYPE_SERVICE); map.put(URLParamType.refreshTimestamp.getName(), String.valueOf(System.currentTimeMillis())); @@ -167,23 +167,25 @@ private void doExport(ProtocolConfig protocolConfig, int port) { URL serviceUrl = new URL(protocolName, hostAddress, port, interfaceClass.getName(), map); + String groupString = serviceUrl.getParameter(URLParamType.group.getName(), ""); // do not with default group value + String additionalGroup = System.getenv(MotanConstants.ENV_ADDITIONAL_GROUP); + if (StringUtils.isNotBlank(additionalGroup)) { // check additional groups + groupString = StringUtils.isBlank(groupString) ? additionalGroup : groupString + "," + additionalGroup; + serviceUrl.addParameter(URLParamType.group.getName(), groupString); + } // check multi group. - String groupString = serviceUrl.getGroup(); - if (groupString.contains(MotanConstants.COMMA_SEPARATOR)){ - String[] groups = groupString.split(MotanConstants.COMMA_SEPARATOR); - for (String group : groups){ - if (StringUtils.isNotBlank(group)){ // create new service for each group - URL newGroupServiceUrl = serviceUrl.createCopy(); - newGroupServiceUrl.addParameter(URLParamType.group.getName(), group.trim()); - exportService(hostAddress, protocolName, newGroupServiceUrl); - } + if (groupString.contains(MotanConstants.COMMA_SEPARATOR)) { + for (String group : StringTools.splitSet(groupString, MotanConstants.COMMA_SEPARATOR)) { + URL newGroupServiceUrl = serviceUrl.createCopy(); + newGroupServiceUrl.addParameter(URLParamType.group.getName(), group); + exportService(hostAddress, protocolName, newGroupServiceUrl); } - }else { + } else { exportService(hostAddress, protocolName, serviceUrl); } } - private void exportService(String hostAddress, String protocol, URL serviceUrl){ + private void exportService(String hostAddress, String protocol, URL serviceUrl) { if (serviceExists(serviceUrl)) { LoggerUtil.warn(String.format("%s configService is malformed, for same service (%s) already exists ", interfaceClass.getName(), serviceUrl.getIdentity())); @@ -191,7 +193,7 @@ private void exportService(String hostAddress, String protocol, URL serviceUrl){ interfaceClass.getName(), serviceUrl.getIdentity()), MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR); } LoggerUtil.info("export for service url :" + serviceUrl.toFullStr()); - List urls = new ArrayList(); + List urls = new ArrayList<>(); // injvm 协议只支持注册到本地,其他协议可以注册到local、remote if (MotanConstants.PROTOCOL_INJVM.equals(protocol)) { diff --git a/motan-core/src/main/java/com/weibo/api/motan/protocol/support/ProtocolFilterDecorator.java b/motan-core/src/main/java/com/weibo/api/motan/protocol/support/ProtocolFilterDecorator.java index c66ef1f9c..43958f606 100644 --- a/motan-core/src/main/java/com/weibo/api/motan/protocol/support/ProtocolFilterDecorator.java +++ b/motan-core/src/main/java/com/weibo/api/motan/protocol/support/ProtocolFilterDecorator.java @@ -1,11 +1,11 @@ /* * Copyright 2009-2016 Weibo, Inc. - * + * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under @@ -26,13 +26,11 @@ import com.weibo.api.motan.filter.InitializableFilter; import com.weibo.api.motan.rpc.*; import com.weibo.api.motan.util.LoggerUtil; +import com.weibo.api.motan.util.StringTools; import org.apache.commons.lang3.StringUtils; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; +import java.util.*; import static com.weibo.api.motan.common.MotanConstants.DISABLE_FILTER_PREFIX; @@ -210,7 +208,7 @@ public T getImpl() { */ protected List getFilters(URL url, String key) { // load default filters - List filters = new ArrayList(); + List filters = new ArrayList<>(); List defaultFilters = ExtensionLoader.getExtensionLoader(Filter.class).getExtensions(key); if (defaultFilters != null && defaultFilters.size() > 0) { filters.addAll(defaultFilters); @@ -220,25 +218,26 @@ protected List getFilters(URL url, String key) { String filterStr = url.getParameter(URLParamType.filter.getName()); if (StringUtils.isNotBlank(filterStr)) { HashSet removedFilters = new HashSet<>(); - String[] filterNames = MotanConstants.COMMA_SPLIT_PATTERN.split(filterStr); + Set filterNames = StringTools.splitSet(filterStr, MotanConstants.COMMA_SEPARATOR); for (String fn : filterNames) { - if (StringUtils.isBlank(fn)) { - continue; - } - fn = fn.trim(); - if (fn.startsWith(DISABLE_FILTER_PREFIX)){ // disable filter - if (fn.length() > DISABLE_FILTER_PREFIX.length()){ + if (fn.startsWith(DISABLE_FILTER_PREFIX)) { // disable filter + if (fn.length() > DISABLE_FILTER_PREFIX.length()) { removedFilters.add(fn.substring(DISABLE_FILTER_PREFIX.length()).trim()); } - }else { - addIfAbsent(filters, fn); + } else { + Filter extFilter = ExtensionLoader.getExtensionLoader(Filter.class).getExtension(fn, false); + if (extFilter == null) { + LoggerUtil.warn("filter extension not found. filer name: " + fn); + continue; + } + filters.add(extFilter); } } // remove disabled filters - if (!removedFilters.isEmpty()){ + if (!removedFilters.isEmpty()) { for (String removedName : removedFilters) { - filters.removeIf((filter)-> removedName.equals(filter.getClass().getAnnotation(SpiMeta.class).name())); + filters.removeIf((filter) -> removedName.equals(filter.getClass().getAnnotation(SpiMeta.class).name())); } } } @@ -248,24 +247,4 @@ protected List getFilters(URL url, String key) { Collections.reverse(filters); return filters; } - - private void addIfAbsent(List filters, String extensionName) { - Filter extFilter = ExtensionLoader.getExtensionLoader(Filter.class).getExtension(extensionName, false); - if (extFilter == null) { - LoggerUtil.warn("filter extension not found. filer name: " + extensionName); - return; - } - - boolean exists = false; - for (Filter f : filters) { - if (f.getClass() == extFilter.getClass()) { - exists = true; - break; - } - } - if (!exists) { - filters.add(extFilter); - } - - } } diff --git a/motan-core/src/main/java/com/weibo/api/motan/util/MeshProxyUtil.java b/motan-core/src/main/java/com/weibo/api/motan/util/MeshProxyUtil.java index ce11d037d..28423aa15 100644 --- a/motan-core/src/main/java/com/weibo/api/motan/util/MeshProxyUtil.java +++ b/motan-core/src/main/java/com/weibo/api/motan/util/MeshProxyUtil.java @@ -18,6 +18,7 @@ package com.weibo.api.motan.util; +import com.weibo.api.motan.common.MotanConstants; import com.weibo.api.motan.common.URLParamType; import com.weibo.api.motan.core.extension.ExtensionLoader; import com.weibo.api.motan.registry.RegistryFactory; @@ -32,8 +33,6 @@ * @date 2022/7/14. */ public class MeshProxyUtil { - public static final String MESH_PROXY_ENV_NAME = "MOTAN_MESH_PROXY"; //使用mesh代理motan请求的环境变量名 - // config keys private static final String MODE_KEY = "mode"; // proxy type key private static final String PORT_KEY = "port"; // mesh transport port for client end @@ -155,7 +154,7 @@ private static String getValue(Map configs, String key, String d // 检查是否支持mesh proxy private static void initCheck() { // check env set - String meshProxyString = System.getenv(MESH_PROXY_ENV_NAME); + String meshProxyString = System.getenv(MotanConstants.ENV_MESH_PROXY); if (StringUtils.isNotBlank(meshProxyString)) { LoggerUtil.info("find MOTAN_MESH_PROXY env, value:" + meshProxyString); proxyConfig = parseProxyConfig(meshProxyString); diff --git a/motan-core/src/main/java/com/weibo/api/motan/util/NetUtils.java b/motan-core/src/main/java/com/weibo/api/motan/util/NetUtils.java index 2a70d5fbd..3474941f3 100644 --- a/motan-core/src/main/java/com/weibo/api/motan/util/NetUtils.java +++ b/motan-core/src/main/java/com/weibo/api/motan/util/NetUtils.java @@ -16,6 +16,7 @@ package com.weibo.api.motan.util; +import com.weibo.api.motan.common.MotanConstants; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -40,8 +41,6 @@ public class NetUtils { public static final String ANYHOST = "0.0.0.0"; - public static final String MOTAN_IP_PREFIX = "MOTAN_IP_PREFIX"; - private static volatile InetAddress LOCAL_ADDRESS = null; private static final Pattern LOCAL_IP_PATTERN = Pattern.compile("127(\\.\\d{1,3}){3}$"); @@ -73,14 +72,14 @@ public static InetAddress getLocalAddress() { * 查找策略:首先看是否已经查到ip --> 环境变量中指定的ip --> hostname对应的ip --> 根据连接目标端口得到的本地ip --> 轮询网卡 * * - * @return loca ip + * @return local ip */ public static InetAddress getLocalAddress(Map destHostPorts) { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = null; - String ipPrefix = System.getenv(MOTAN_IP_PREFIX); + String ipPrefix = System.getenv(MotanConstants.ENV_MOTAN_IP_PREFIX); if (StringUtils.isNotBlank(ipPrefix)) { // 环境变量中如果指定了motan使用的ip前缀,则使用与该前缀匹配的网卡ip作为本机ip。 localAddress = getLocalAddressByNetworkInterface(ipPrefix); LoggerUtil.info("get local address by ip prefix: " + ipPrefix + ", address:" + localAddress); @@ -115,7 +114,7 @@ private static InetAddress getLocalAddressByHostname() { return localAddress; } } catch (Throwable e) { - logger.warn("Failed to retriving local address by hostname:" + e); + logger.warn("Failed to retrieving local address by hostname:" + e); } return null; } @@ -129,20 +128,14 @@ private static InetAddress getLocalAddressBySocket(Map destHost String host = entry.getKey(); int port = entry.getValue(); try { - Socket socket = new Socket(); - try { + try (Socket socket = new Socket()) { SocketAddress addr = new InetSocketAddress(host, port); socket.connect(addr, 1000); LoggerUtil.info("get local address from socket. remote host:" + host + ", port:" + port); return socket.getLocalAddress(); - } finally { - try { - socket.close(); - } catch (Throwable e) { - } } } catch (Exception e) { - LoggerUtil.warn(String.format("Failed to retriving local address by connecting to dest host:port(%s:%s) false, e=%s", host, + LoggerUtil.warn(String.format("Failed to retrieving local address by connecting to dest host:port(%s:%s) false, e=%s", host, port, e)); } } @@ -169,16 +162,16 @@ private static InetAddress getLocalAddressByNetworkInterface(String prefix) { } } } catch (Throwable e) { - logger.warn("Failed to retriving ip address, " + e.getMessage(), e); + logger.warn("Failed to retrieving ip address, " + e.getMessage(), e); } } } catch (Throwable e) { - logger.warn("Failed to retriving ip address, " + e.getMessage(), e); + logger.warn("Failed to retrieving ip address, " + e.getMessage(), e); } } } } catch (Throwable e) { - logger.warn("Failed to retriving ip address, " + e.getMessage(), e); + logger.warn("Failed to retrieving ip address, " + e.getMessage(), e); } return null; } diff --git a/motan-core/src/main/java/com/weibo/api/motan/util/StringTools.java b/motan-core/src/main/java/com/weibo/api/motan/util/StringTools.java index 4527490b5..d0dfc19be 100644 --- a/motan-core/src/main/java/com/weibo/api/motan/util/StringTools.java +++ b/motan-core/src/main/java/com/weibo/api/motan/util/StringTools.java @@ -19,15 +19,13 @@ import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; -import java.util.Map; -import java.util.TreeMap; +import java.util.*; import org.apache.commons.lang3.StringUtils; import com.weibo.api.motan.common.MotanConstants; /** - * * String utils * * @author fishermen @@ -72,7 +70,7 @@ public static String urlDecode(String value) { public static String toQueryString(Map ps) { StringBuilder buf = new StringBuilder(); if (ps != null && ps.size() > 0) { - for (Map.Entry entry : new TreeMap(ps).entrySet()) { + for (Map.Entry entry : new TreeMap<>(ps).entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (key != null && key.length() > 0 && value != null && value.length() > 0) { @@ -87,4 +85,18 @@ public static String toQueryString(Map ps) { } return buf.toString(); } + + // 切分string,去重去空 + public static Set splitSet(String str, String regex) { + Set result = new HashSet<>(); + if (str != null) { + String[] strings = str.split(regex); + for (String s : strings) { + if (StringUtils.isNotBlank(s)) { + result.add(s.trim()); + } + } + } + return result; + } } diff --git a/motan-core/src/test/java/com/weibo/api/motan/TestUtils.java b/motan-core/src/test/java/com/weibo/api/motan/TestUtils.java new file mode 100644 index 000000000..200cce3e0 --- /dev/null +++ b/motan-core/src/test/java/com/weibo/api/motan/TestUtils.java @@ -0,0 +1,40 @@ +/* + * + * Copyright 2009-2022 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.weibo.api.motan; + +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.util.Map; + +/** + * @author zhanglei28 + * @date 2022/8/2. + */ +public class TestUtils { + public static Map getModifiableEnvironment() throws Exception { + Class pe = Class.forName("java.lang.ProcessEnvironment"); + Method getenv = pe.getDeclaredMethod("getenv"); + getenv.setAccessible(true); + Object unmodifiableEnvironment = getenv.invoke(null); + Class map = Class.forName("java.util.Collections$UnmodifiableMap"); + Field m = map.getDeclaredField("m"); + m.setAccessible(true); + return (Map) m.get(unmodifiableEnvironment); + } +} diff --git a/motan-core/src/test/java/com/weibo/api/motan/config/ServiceConfigTest.java b/motan-core/src/test/java/com/weibo/api/motan/config/ServiceConfigTest.java index 6b4a17103..1eff8abf9 100644 --- a/motan-core/src/test/java/com/weibo/api/motan/config/ServiceConfigTest.java +++ b/motan-core/src/test/java/com/weibo/api/motan/config/ServiceConfigTest.java @@ -20,11 +20,16 @@ import com.weibo.api.motan.common.MotanConstants; import com.weibo.api.motan.common.URLParamType; import com.weibo.api.motan.protocol.example.IWorld; +import com.weibo.api.motan.rpc.Exporter; import com.weibo.api.motan.rpc.URL; -import org.junit.Test; import java.util.ArrayList; +import java.util.HashSet; import java.util.List; +import java.util.Set; + +import static com.weibo.api.motan.TestUtils.getModifiableEnvironment; +import static com.weibo.api.motan.common.MotanConstants.ENV_ADDITIONAL_GROUP; /** * Service config test @@ -54,7 +59,6 @@ public void tearDown() throws Exception { } } - @Test public void testExport() { serviceConfig.export(); @@ -64,7 +68,6 @@ public void testExport() { } - @Test public void testExportException() { // registry null serviceConfig = mockIWorldServiceConfig(); @@ -78,7 +81,7 @@ public void testExportException() { // export null try { serviceConfig.export(); - assertTrue(false); + fail(); } catch (Exception e) { assertTrue(e.getMessage().contains("export should not empty")); } @@ -88,7 +91,7 @@ public void testExportException() { serviceConfig.setExport("notExist" + ":" + 0); try { serviceConfig.export(); - assertTrue(false); + fail(); } catch (Exception e) { assertTrue(e.getMessage().contains("get extension fail")); } @@ -105,15 +108,14 @@ public void testExportException() { newServiceConfig.setExport(MotanConstants.PROTOCOL_INJVM + ":" + 0); try { newServiceConfig.export(); - assertTrue(false); + fail(); } catch (Exception e) { assertTrue(e.getMessage().contains("for same service")); } } - @Test public void testMethodConfig() { - List methods = new ArrayList(); + List methods = new ArrayList<>(); MethodConfig mc = new MethodConfig(); mc.setName("world"); mc.setRetries(1); @@ -151,7 +153,6 @@ public void testMethodConfig() { } - @Test public void testMultiProtocol() { serviceConfig.setProtocols(getMultiProtocols(MotanConstants.PROTOCOL_INJVM, MotanConstants.PROTOCOL_MOTAN)); serviceConfig.setExport(MotanConstants.PROTOCOL_INJVM + ":" + 0 + "," + MotanConstants.PROTOCOL_MOTAN + ":8002"); @@ -160,21 +161,18 @@ public void testMultiProtocol() { } - @Test - public void testMultiRegitstry() { + public void testMultiRegistry() { serviceConfig.setRegistries(getMultiRegister(MotanConstants.REGISTRY_PROTOCOL_LOCAL, MotanConstants.REGISTRY_PROTOCOL_ZOOKEEPER)); serviceConfig.loadRegistryUrls(); assertEquals(2, serviceConfig.getRegistryUrls().size()); } - @Test public void testMultiGroup() { serviceConfig.setGroup("motan-test1, motan-test2"); serviceConfig.export(); assertEquals(2, serviceConfig.getExporters().size()); } - @Test public void testUnexport() { testExport(); serviceConfig.unexport(); @@ -182,5 +180,53 @@ public void testUnexport() { assertEquals(serviceConfig.getExporters().size(), 0); } + public void testAdditionalGroup() throws Exception { + serviceConfig.setGroup(""); + serviceConfig.export(); + assertEquals(1, serviceConfig.getExporters().size()); + assertEquals(URLParamType.group.getValue(), serviceConfig.getExporters().get(0).getUrl().getGroup()); + + // default group with additional env + reset(); + String envGroup = "envGroup"; + getModifiableEnvironment().put(ENV_ADDITIONAL_GROUP, envGroup); + serviceConfig.setGroup(""); + serviceConfig.export(); + assertEquals(1, serviceConfig.getExporters().size()); + assertEquals(envGroup, serviceConfig.getExporters().get(0).getUrl().getGroup()); + + // group + additional group + reset(); + serviceConfig.export(); + assertEquals(2, serviceConfig.getExporters().size()); + checkGroupNames(group, envGroup); + + // multi group with additional multi group + reset(); + envGroup = "envGroup1, envGroup2, sameGroup"; + getModifiableEnvironment().put(ENV_ADDITIONAL_GROUP, envGroup); + serviceConfig.setGroup("motan-test1, motan-test2, sameGroup"); + serviceConfig.export(); + assertEquals(5, serviceConfig.getExporters().size()); + checkGroupNames("envGroup1", "envGroup2", "sameGroup", "motan-test1", "motan-test2"); + + getModifiableEnvironment().remove(ENV_ADDITIONAL_GROUP); + } + + private void checkGroupNames(String... expectGroupNames) { + Set groupNames = new HashSet<>(); + for (Exporter exporter : serviceConfig.getExporters()) { + groupNames.add(exporter.getUrl().getGroup()); + } + assertEquals(expectGroupNames.length, groupNames.size()); + for (String name : expectGroupNames) { + assertTrue(groupNames.contains(name)); + } + } + + private void reset() throws Exception { + tearDown(); + setUp(); + } } diff --git a/motan-core/src/test/java/com/weibo/api/motan/util/MeshProxyUtilTest.java b/motan-core/src/test/java/com/weibo/api/motan/util/MeshProxyUtilTest.java index 261e7effa..e353e496e 100644 --- a/motan-core/src/test/java/com/weibo/api/motan/util/MeshProxyUtilTest.java +++ b/motan-core/src/test/java/com/weibo/api/motan/util/MeshProxyUtilTest.java @@ -23,13 +23,13 @@ import org.junit.After; import org.junit.Test; -import java.lang.reflect.Field; -import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import static com.weibo.api.motan.TestUtils.getModifiableEnvironment; +import static com.weibo.api.motan.common.MotanConstants.ENV_MESH_PROXY; import static org.junit.Assert.*; /** @@ -45,7 +45,7 @@ public class MeshProxyUtilTest { @After public void tearDown() throws Exception { - getModifiableEnvironment().remove(MeshProxyUtil.MESH_PROXY_ENV_NAME); + getModifiableEnvironment().remove(ENV_MESH_PROXY); } @Test @@ -63,7 +63,7 @@ public void processMeshProxy() throws Exception { check(originRegistryUrls, resultUrl, false, null); // env with minimal param - getModifiableEnvironment().put(MeshProxyUtil.MESH_PROXY_ENV_NAME, "mode:" + mode); // minimal key as default + getModifiableEnvironment().put(ENV_MESH_PROXY, "mode:" + mode); // minimal key as default MeshProxyUtil.reset(); assertEquals(mode, MeshProxyUtil.getProxyConfig().get("mode")); // check init proxy config assertFalse(MeshProxyUtil.setInitChecked(true)); // initChecked is false because not have MeshRegistry extension. so set initChecked true for unit test @@ -85,7 +85,7 @@ public void processMeshProxy() throws Exception { check(originRegistryUrls, resultUrl, false, null); // not proxy client url in server mode mode = "client"; - getModifiableEnvironment().put(MeshProxyUtil.MESH_PROXY_ENV_NAME, "mode:" + mode); // minimal key as default + getModifiableEnvironment().put(ENV_MESH_PROXY, "mode:" + mode); MeshProxyUtil.reset(); MeshProxyUtil.setInitChecked(true); assertEquals(mode, MeshProxyUtil.getProxyConfig().get("mode")); @@ -96,7 +96,7 @@ public void processMeshProxy() throws Exception { check(originRegistryUrls, resultUrl, false, null); // not proxy server url in client mode mode = "all"; - getModifiableEnvironment().put(MeshProxyUtil.MESH_PROXY_ENV_NAME, "mode:" + mode); // minimal key as default + getModifiableEnvironment().put(ENV_MESH_PROXY, "mode:" + mode); MeshProxyUtil.reset(); MeshProxyUtil.setInitChecked(true); assertEquals(mode, MeshProxyUtil.getProxyConfig().get("mode")); @@ -107,7 +107,7 @@ public void processMeshProxy() throws Exception { check(originRegistryUrls, resultUrl, true, proxiedParams); // proxy server url // env with more params - getModifiableEnvironment().put(MeshProxyUtil.MESH_PROXY_ENV_NAME, "mode:" + mode + ",mport:" + mport + ",port:" + port + ",test:" + encodedValue + ", filter:" + agentFilters); // minimal key as default + getModifiableEnvironment().put(ENV_MESH_PROXY, "mode:" + mode + ",mport:" + mport + ",port:" + port + ",test:" + encodedValue + ", filter:" + agentFilters); MeshProxyUtil.reset(); MeshProxyUtil.setInitChecked(true); assertEquals(mode, MeshProxyUtil.getProxyConfig().get("mode")); @@ -150,16 +150,4 @@ private void check(List originRegistryUrls, List resultRegistryUrls, b } } } - - private static Map getModifiableEnvironment() throws Exception { - Class pe = Class.forName("java.lang.ProcessEnvironment"); - Method getenv = pe.getDeclaredMethod("getenv"); - getenv.setAccessible(true); - Object unmodifiableEnvironment = getenv.invoke(null); - Class map = Class.forName("java.util.Collections$UnmodifiableMap"); - Field m = map.getDeclaredField("m"); - m.setAccessible(true); - return (Map) m.get(unmodifiableEnvironment); - } - } \ No newline at end of file diff --git a/motan-core/src/test/java/com/weibo/api/motan/util/StringToolsTest.java b/motan-core/src/test/java/com/weibo/api/motan/util/StringToolsTest.java new file mode 100644 index 000000000..7eefb9b8c --- /dev/null +++ b/motan-core/src/test/java/com/weibo/api/motan/util/StringToolsTest.java @@ -0,0 +1,55 @@ +/* + * + * Copyright 2009-2022 Weibo, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + */ + +package com.weibo.api.motan.util; + +import org.junit.Test; + +import java.util.Set; + +import static org.junit.Assert.*; + +/** + * @author zhanglei28 + * @date 2022/8/2. + */ +public class StringToolsTest { + + @Test + public void testSplitSet() { + checkSet("", ","); + checkSet(null, ","); + checkSet(null, null); + checkSet(" leftSpace", ",", "leftSpace"); + checkSet(" leftSpace,rightSpace ", ",", "leftSpace", "rightSpace"); + checkSet(" value1 , , , value2 ", ",", "value1", "value2"); + checkSet(" value1 , ,sameValue , sameValue ", ",", "value1", "sameValue"); + } + + private void checkSet(String target, String regex, String... expectString) { + Set result = StringTools.splitSet(target, regex); + if (expectString == null || expectString.length == 0) { + assertEquals(0, result.size()); + } else { + assertEquals(expectString.length, result.size()); + for (String s : expectString) { + assertTrue(result.contains(s)); + } + } + } +} \ No newline at end of file