proj_name
stringclasses
157 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
49
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
27
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/HostFilterLoadBalanceListener.java
HostFilterLoadBalanceListener
validateWhitelist
class HostFilterLoadBalanceListener extends AbstractLoadBalanceListener { @Override public void onGetServers(String serviceId, List<? extends Server> servers) { applyHostFilter(serviceId, servers); } private void applyHostFilter(String providerServiceId, List<? extends Server> servers) { RuleEntity ruleEntity = pluginAdapter.getRule(); if (ruleEntity == null) { return; } DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); if (discoveryEntity == null) { return; } HostFilterEntity hostFilterEntity = discoveryEntity.getHostFilterEntity(); if (hostFilterEntity == null) { return; } FilterType filterType = hostFilterEntity.getFilterType(); List<String> globalFilterValueList = hostFilterEntity.getFilterValueList(); Map<String, List<String>> filterMap = hostFilterEntity.getFilterMap(); List<String> filterValueList = filterMap.get(providerServiceId); if (CollectionUtils.isEmpty(globalFilterValueList) && CollectionUtils.isEmpty(filterValueList)) { return; } List<String> allFilterValueList = new ArrayList<String>(); if (CollectionUtils.isNotEmpty(globalFilterValueList)) { allFilterValueList.addAll(globalFilterValueList); } if (CollectionUtils.isNotEmpty(filterValueList)) { allFilterValueList.addAll(filterValueList); } Iterator<? extends Server> iterator = servers.iterator(); while (iterator.hasNext()) { Server server = iterator.next(); String host = server.getHost(); switch (filterType) { case BLACKLIST: if (validateBlacklist(allFilterValueList, host)) { iterator.remove(); } break; case WHITELIST: if (validateWhitelist(allFilterValueList, host)) { iterator.remove(); } break; } } } private boolean validateBlacklist(List<String> allFilterValueList, String host) { for (String filterValue : allFilterValueList) { if (host.startsWith(filterValue)) { return true; } } return false; } private boolean validateWhitelist(List<String> allFilterValueList, String host) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { // Highest priority return HIGHEST_PRECEDENCE; } }
boolean matched = true; for (String filterValue : allFilterValueList) { if (host.startsWith(filterValue)) { matched = false; break; } } return matched;
660
60
720
<methods>public non-sealed void <init>() <variables>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/LoadBalanceListenerExecutor.java
LoadBalanceListenerExecutor
onGetServers
class LoadBalanceListenerExecutor { @Autowired private List<LoadBalanceListener> loadBalanceListenerList; private ZoneAwareLoadBalancer<?> loadBalancer; public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>} public ZoneAwareLoadBalancer<?> getLoadBalancer() { return loadBalancer; } public void setLoadBalancer(ZoneAwareLoadBalancer<?> loadBalancer) { this.loadBalancer = loadBalancer; } }
for (LoadBalanceListener loadBalanceListener : loadBalanceListenerList) { loadBalanceListener.onGetServers(serviceId, servers); }
152
43
195
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/NotificationLoadBalanceListener.java
NotificationLoadBalanceListener
onGetServers
class NotificationLoadBalanceListener extends AbstractLoadBalanceListener { private static final Logger LOG = LoggerFactory.getLogger(NotificationLoadBalanceListener.class); @Override public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return LOWEST_PRECEDENCE; } }
if (servers.size() == 0) { LOG.warn("********** No server instances found for serviceId={}, perhaps they are isolated, filtered or not registered **********", serviceId); }
108
52
160
<methods>public non-sealed void <init>() <variables>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/RegionFilterLoadBalanceListener.java
RegionFilterLoadBalanceListener
applyRegionFilter
class RegionFilterLoadBalanceListener extends AbstractLoadBalanceListener { @Override public void onGetServers(String serviceId, List<? extends Server> servers) { String consumerServiceId = pluginAdapter.getServiceId(); String consumerServiceRegion = pluginAdapter.getRegion(); applyRegionFilter(consumerServiceId, consumerServiceRegion, serviceId, servers); } private void applyRegionFilter(String consumerServiceId, String consumerServiceRegion, String providerServiceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { // After version filter return HIGHEST_PRECEDENCE + 2; } }
// 如果消费端未配置区域号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生 if (StringUtils.isEmpty(consumerServiceRegion)) { return; } RuleEntity ruleEntity = pluginAdapter.getRule(); if (ruleEntity == null) { return; } DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); if (discoveryEntity == null) { return; } RegionFilterEntity regionFilterEntity = discoveryEntity.getRegionFilterEntity(); if (regionFilterEntity == null) { return; } Map<String, List<RegionEntity>> regionEntityMap = regionFilterEntity.getRegionEntityMap(); if (MapUtils.isEmpty(regionEntityMap)) { return; } List<RegionEntity> regionEntityList = regionEntityMap.get(consumerServiceId); if (CollectionUtils.isEmpty(regionEntityList)) { return; } // 当前区域的消费端所能调用提供端的区域号列表 List<String> allNoFilterValueList = null; // 提供端规则未作任何定义 boolean providerConditionDefined = false; for (RegionEntity regionEntity : regionEntityList) { String providerServiceName = regionEntity.getProviderServiceName(); if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) { providerConditionDefined = true; List<String> consumerRegionValueList = regionEntity.getConsumerRegionValueList(); List<String> providerRegionValueList = regionEntity.getProviderRegionValueList(); // 判断consumer-region-value值是否包含当前消费端的区域号 // 如果consumerRegionValueList为空,表示消费端区域列表未指定,那么任意消费端区域可以访问指定区域提供端区域 if (CollectionUtils.isNotEmpty(consumerRegionValueList)) { if (consumerRegionValueList.contains(consumerServiceRegion)) { if (allNoFilterValueList == null) { allNoFilterValueList = new ArrayList<String>(); } if (CollectionUtils.isNotEmpty(providerRegionValueList)) { allNoFilterValueList.addAll(providerRegionValueList); } } // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的区域关系都不匹配 } else { if (allNoFilterValueList == null) { allNoFilterValueList = new ArrayList<String>(); } if (CollectionUtils.isNotEmpty(providerRegionValueList)) { allNoFilterValueList.addAll(providerRegionValueList); } } } } if (allNoFilterValueList != null) { // 当allNoFilterValueList为空列表,意味着区域对应关系未做任何定义(即所有的providerRegionValueList为空),不需要执行过滤,直接返回 if (allNoFilterValueList.isEmpty()) { return; } else { Iterator<? extends Server> iterator = servers.iterator(); while (iterator.hasNext()) { Server server = iterator.next(); String serverRegion = pluginAdapter.getServerRegion(server); if (!allNoFilterValueList.contains(serverRegion)) { iterator.remove(); } } } } else { if (providerConditionDefined) { // 当allNoFilterValueList为null, 意味着定义的区域关系都不匹配,直接清空所有实例 servers.clear(); } }
176
904
1,080
<methods>public non-sealed void <init>() <variables>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/loadbalance/VersionFilterLoadBalanceListener.java
VersionFilterLoadBalanceListener
applyVersionFilter
class VersionFilterLoadBalanceListener extends AbstractLoadBalanceListener { @Override public void onGetServers(String serviceId, List<? extends Server> servers) { String consumerServiceId = pluginAdapter.getServiceId(); String consumerServiceVersion = pluginAdapter.getVersion(); applyVersionFilter(consumerServiceId, consumerServiceVersion, serviceId, servers); } private void applyVersionFilter(String consumerServiceId, String consumerServiceVersion, String providerServiceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { // After host filter return HIGHEST_PRECEDENCE + 1; } }
// 如果消费端未配置版本号,那么它可以调用提供端所有服务,需要符合规范,极力避免该情况发生 if (StringUtils.isEmpty(consumerServiceVersion)) { return; } RuleEntity ruleEntity = pluginAdapter.getRule(); if (ruleEntity == null) { return; } DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); if (discoveryEntity == null) { return; } VersionFilterEntity versionFilterEntity = discoveryEntity.getVersionFilterEntity(); if (versionFilterEntity == null) { return; } Map<String, List<VersionEntity>> versionEntityMap = versionFilterEntity.getVersionEntityMap(); if (MapUtils.isEmpty(versionEntityMap)) { return; } List<VersionEntity> versionEntityList = versionEntityMap.get(consumerServiceId); if (CollectionUtils.isEmpty(versionEntityList)) { return; } // 当前版本的消费端所能调用提供端的版本号列表 List<String> allNoFilterValueList = null; // 提供端规则未作任何定义 boolean providerConditionDefined = false; for (VersionEntity versionEntity : versionEntityList) { String providerServiceName = versionEntity.getProviderServiceName(); if (StringUtils.equalsIgnoreCase(providerServiceName, providerServiceId)) { providerConditionDefined = true; List<String> consumerVersionValueList = versionEntity.getConsumerVersionValueList(); List<String> providerVersionValueList = versionEntity.getProviderVersionValueList(); // 判断consumer-version-value值是否包含当前消费端的版本号 // 如果consumerVersionValueList为空,表示消费端版本列表未指定,那么任意消费端版本可以访问指定版本提供端版本 if (CollectionUtils.isNotEmpty(consumerVersionValueList)) { if (consumerVersionValueList.contains(consumerServiceVersion)) { if (allNoFilterValueList == null) { allNoFilterValueList = new ArrayList<String>(); } if (CollectionUtils.isNotEmpty(providerVersionValueList)) { allNoFilterValueList.addAll(providerVersionValueList); } } // 这里的条件,在每一次循环都不满足,会让allNoFilterValueList为null,意味着定义的版本关系都不匹配 } else { if (allNoFilterValueList == null) { allNoFilterValueList = new ArrayList<String>(); } if (CollectionUtils.isNotEmpty(providerVersionValueList)) { allNoFilterValueList.addAll(providerVersionValueList); } } } } if (allNoFilterValueList != null) { // 当allNoFilterValueList为空列表,意味着版本对应关系未做任何定义(即所有的providerVersionValueList为空),不需要执行过滤,直接返回 if (allNoFilterValueList.isEmpty()) { return; } else { Iterator<? extends Server> iterator = servers.iterator(); while (iterator.hasNext()) { Server server = iterator.next(); String serverVersion = pluginAdapter.getServerVersion(server); if (!allNoFilterValueList.contains(serverVersion)) { iterator.remove(); } } } } else { if (providerConditionDefined) { // 当allNoFilterValueList为null, 意味着定义的版本关系都不匹配,直接清空所有实例 servers.clear(); } }
176
904
1,080
<methods>public non-sealed void <init>() <variables>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/CountFilterRegisterListener.java
CountFilterRegisterListener
onRegisterFailure
class CountFilterRegisterListener extends AbstractRegisterListener { @Autowired @Lazy protected DiscoveryClientDecorator discoveryClient; @Override public void onRegister(Registration registration) { String serviceId = pluginAdapter.getServiceId(); String host = pluginAdapter.getHost(); int port = pluginAdapter.getPort(); applyCountFilter(serviceId, host, port); } private void applyCountFilter(String serviceId, String host, int port) { RuleEntity ruleEntity = pluginAdapter.getRule(); if (ruleEntity == null) { return; } RegisterEntity registerEntity = ruleEntity.getRegisterEntity(); if (registerEntity == null) { return; } CountFilterEntity countFilterEntity = registerEntity.getCountFilterEntity(); if (countFilterEntity == null) { return; } Integer globalFilterValue = countFilterEntity.getFilterValue(); Map<String, Integer> filterMap = countFilterEntity.getFilterMap(); Integer filterValue = filterMap.get(serviceId); // 如果局部值存在,就取局部值,否则取全局值 Integer maxCount = null; if (filterValue != null) { maxCount = filterValue; } else { maxCount = globalFilterValue; } if (maxCount == null) { return; } int count = discoveryClient.getRealInstances(serviceId).size(); if (count >= maxCount) { onRegisterFailure(maxCount, serviceId, host, port); } } private void onRegisterFailure(int maxCount, String serviceId, String host, int port) {<FILL_FUNCTION_BODY>} @Override public void onDeregister(Registration registration) { } @Override public void onSetStatus(Registration registration, String status) { } @Override public void onClose() { } @Override public int getOrder() { // 由于通过服务数来判断是否注册满,需要第一优先级执行,否则服务列表已经被其它监听器过滤过了,其数目就不准确了 // Highest priority return HIGHEST_PRECEDENCE; } }
String description = serviceId + " for " + host + ":" + port + " is rejected to register to Register server, reach max limited count=" + maxCount; pluginEventWapper.fireRegisterFailure(new RegisterFailureEvent(DiscoveryConstant.REACH_MAX_LIMITED_COUNT, description, serviceId, host, port)); throw new DiscoveryException(description);
584
94
678
<methods>public non-sealed void <init>() ,public ServiceRegistry<?> getServiceRegistry() <variables>protected ServiceRegistry<?> serviceRegistry
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/HostFilterRegisterListener.java
HostFilterRegisterListener
applyHostFilter
class HostFilterRegisterListener extends AbstractRegisterListener { @Override public void onRegister(Registration registration) { String serviceId = pluginAdapter.getServiceId(); String host = pluginAdapter.getHost(); int port = pluginAdapter.getPort(); applyHostFilter(serviceId, host, port); } private void applyHostFilter(String serviceId, String host, int port) {<FILL_FUNCTION_BODY>} private void validateBlacklist(FilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) { for (String filterValue : allFilterValueList) { if (host.startsWith(filterValue)) { onRegisterFailure(filterType, allFilterValueList, serviceId, host, port); } } } private void validateWhitelist(FilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) { boolean matched = true; for (String filterValue : allFilterValueList) { if (host.startsWith(filterValue)) { matched = false; break; } } if (matched) { onRegisterFailure(filterType, allFilterValueList, serviceId, host, port); } } private void onRegisterFailure(FilterType filterType, List<String> allFilterValueList, String serviceId, String host, int port) { String description = serviceId + " for " + host + ":" + port + " is rejected to register to Register server, not match host " + filterType + "=" + allFilterValueList; pluginEventWapper.fireRegisterFailure(new RegisterFailureEvent(filterType.toString(), description, serviceId, host, port)); throw new DiscoveryException(description); } @Override public void onDeregister(Registration registration) { } @Override public void onSetStatus(Registration registration, String status) { } @Override public void onClose() { } @Override public int getOrder() { // After count filter return HIGHEST_PRECEDENCE + 1; } }
RuleEntity ruleEntity = pluginAdapter.getRule(); if (ruleEntity == null) { return; } RegisterEntity registerEntity = ruleEntity.getRegisterEntity(); if (registerEntity == null) { return; } HostFilterEntity hostFilterEntity = registerEntity.getHostFilterEntity(); if (hostFilterEntity == null) { return; } FilterType filterType = hostFilterEntity.getFilterType(); List<String> globalFilterValueList = hostFilterEntity.getFilterValueList(); Map<String, List<String>> filterMap = hostFilterEntity.getFilterMap(); List<String> filterValueList = filterMap.get(serviceId); if (CollectionUtils.isEmpty(globalFilterValueList) && CollectionUtils.isEmpty(filterValueList)) { return; } List<String> allFilterValueList = new ArrayList<String>(); if (CollectionUtils.isNotEmpty(globalFilterValueList)) { allFilterValueList.addAll(globalFilterValueList); } if (CollectionUtils.isNotEmpty(filterValueList)) { allFilterValueList.addAll(filterValueList); } switch (filterType) { case BLACKLIST: validateBlacklist(filterType, allFilterValueList, serviceId, host, port); break; case WHITELIST: validateWhitelist(filterType, allFilterValueList, serviceId, host, port); break; }
556
376
932
<methods>public non-sealed void <init>() ,public ServiceRegistry<?> getServiceRegistry() <variables>protected ServiceRegistry<?> serviceRegistry
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/listener/register/RegisterListenerExecutor.java
RegisterListenerExecutor
onSetStatus
class RegisterListenerExecutor { @Autowired private List<RegisterListener> registerListenerList; public void onRegister(Registration registration) { for (RegisterListener registerListener : registerListenerList) { registerListener.onRegister(registration); } } public void onDeregister(Registration registration) { for (RegisterListener registerListener : registerListenerList) { registerListener.onDeregister(registration); } } public void onSetStatus(Registration registration, String status) {<FILL_FUNCTION_BODY>} public void onClose() { for (RegisterListener registerListener : registerListenerList) { registerListener.onClose(); } } }
for (RegisterListener registerListener : registerListenerList) { registerListener.onSetStatus(registration, status); }
186
34
220
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractArrayWeightRandomLoadBalance.java
AbstractArrayWeightRandomLoadBalance
choose
class AbstractArrayWeightRandomLoadBalance<T> implements WeightRandomLoadBalance<T> { @Override public Server choose(List<Server> serverList, T t) {<FILL_FUNCTION_BODY>} }
if (CollectionUtils.isEmpty(serverList)) { return null; } List<Pair<Server, Integer>> weightList = new ArrayList<Pair<Server, Integer>>(); for (Server server : serverList) { int weight = getWeight(server, t); weightList.add(new ImmutablePair<Server, Integer>(server, weight)); } ArrayWeightRandom<Server, Integer> weightRandom = new ArrayWeightRandom<Server, Integer>(weightList); return weightRandom.random();
57
131
188
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractMapWeightRandomLoadBalance.java
AbstractMapWeightRandomLoadBalance
choose
class AbstractMapWeightRandomLoadBalance<T> implements WeightRandomLoadBalance<T> { @Override public Server choose(List<Server> serverList, T t) {<FILL_FUNCTION_BODY>} }
if (CollectionUtils.isEmpty(serverList)) { return null; } List<Pair<Server, Integer>> weightList = new ArrayList<Pair<Server, Integer>>(); for (Server server : serverList) { int weight = getWeight(server, t); weightList.add(new ImmutablePair<Server, Integer>(server, weight)); } MapWeightRandom<Server, Integer> weightRandom = new MapWeightRandom<Server, Integer>(weightList); return weightRandom.random();
57
131
188
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/AbstractWeightRandomLoadBalanceAdapter.java
AbstractWeightRandomLoadBalanceAdapter
checkWeight
class AbstractWeightRandomLoadBalanceAdapter<T> { protected PluginAdapter pluginAdapter; protected PluginContextHolder pluginContextHolder; public AbstractWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter) { this(pluginAdapter, null); } public AbstractWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter, PluginContextHolder pluginContextHolder) { this.pluginAdapter = pluginAdapter; this.pluginContextHolder = pluginContextHolder; } public boolean checkWeight(List<Server> serverList, T t) {<FILL_FUNCTION_BODY>} public abstract T getT(); public abstract int getWeight(Server server, T t); }
for (Server server : serverList) { int weight = getWeight(server, t); if (weight < 0) { return false; } } return true;
171
52
223
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandom.java
ArrayWeightRandom
random
class ArrayWeightRandom<K, V extends Number> { private List<K> items = new ArrayList<>(); private double[] weights; public ArrayWeightRandom(List<Pair<K, V>> pairlist) { calculateWeightS(pairlist); } // 计算权重,初始化或者重新定义权重时使用 public void calculateWeightS(List<Pair<K, V>> pairlist) { items.clear(); // 计算权重总和 double originWeightSum = 0; for (Pair<K, V> pair : pairlist) { double weight = pair.getValue().doubleValue(); if (weight <= 0) { continue; } items.add(pair.getKey()); if (Double.isInfinite(weight)) { weight = 10000.0D; } if (Double.isNaN(weight)) { weight = 1.0D; } originWeightSum += weight; } // 计算每个Item的实际权重比例 double[] actualWeightRatios = new double[items.size()]; int index = 0; for (Pair<K, V> pair : pairlist) { double weight = pair.getValue().doubleValue(); if (weight <= 0) { continue; } actualWeightRatios[index++] = weight / originWeightSum; } // 计算每个Item的权重范围 // 权重范围起始位置 weights = new double[items.size()]; double weightRangeStartPos = 0; for (int i = 0; i < index; i++) { weights[i] = weightRangeStartPos + actualWeightRatios[i]; weightRangeStartPos += actualWeightRatios[i]; } } // 基于权重随机算法选择 public K random() {<FILL_FUNCTION_BODY>} }
double random = ThreadLocalRandom.current().nextDouble(); int index = Arrays.binarySearch(weights, random); if (index < 0) { index = -index - 1; } else { return items.get(index); } if (index < weights.length && random < weights[index]) { return items.get(index); } // 通常不会走到这里,为了保证能得到正确的返回,这里返回第一个 return items.get(0);
490
131
621
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/ArrayWeightRandomProcessor.java
ArrayWeightRandomProcessor
random
class ArrayWeightRandomProcessor<T> implements WeightRandomProcessor<T> { @Override public T random(List<Pair<T, Integer>> weightList) {<FILL_FUNCTION_BODY>} }
if (CollectionUtils.isEmpty(weightList)) { return null; } ArrayWeightRandom<T, Integer> weightRandom = new ArrayWeightRandom<T, Integer>(weightList); return weightRandom.random();
53
60
113
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandom.java
MapWeightRandom
random
class MapWeightRandom<K, V extends Number> { private TreeMap<Double, K> weightMap = new TreeMap<Double, K>(); public MapWeightRandom(List<Pair<K, V>> pairlist) { for (Pair<K, V> pair : pairlist) { double value = pair.getValue().doubleValue(); if (value <= 0) { continue; } double lastWeight = weightMap.size() == 0 ? 0 : weightMap.lastKey().doubleValue(); weightMap.put(value + lastWeight, pair.getKey()); } } public K random() {<FILL_FUNCTION_BODY>} }
if (MapUtils.isEmpty(weightMap)) { throw new DiscoveryException("Weight values are all <= 0 or invalid format"); } double randomWeight = weightMap.lastKey() * Math.random(); SortedMap<Double, K> tailMap = weightMap.tailMap(randomWeight, false); return weightMap.get(tailMap.firstKey());
171
94
265
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/MapWeightRandomProcessor.java
MapWeightRandomProcessor
random
class MapWeightRandomProcessor<T> implements WeightRandomProcessor<T> { @Override public T random(List<Pair<T, Integer>> weightList) {<FILL_FUNCTION_BODY>} }
if (CollectionUtils.isEmpty(weightList)) { return null; } MapWeightRandom<T, Integer> weightRandom = new MapWeightRandom<T, Integer>(weightList); return weightRandom.random();
53
60
113
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/RuleWeightRandomLoadBalanceAdapter.java
RuleWeightRandomLoadBalanceAdapter
getWeight
class RuleWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter<WeightFilterEntity> { public RuleWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter) { super(pluginAdapter); } @Override public WeightFilterEntity getT() { RuleEntity ruleEntity = pluginAdapter.getRule(); if (ruleEntity == null) { return null; } DiscoveryEntity discoveryEntity = ruleEntity.getDiscoveryEntity(); if (discoveryEntity == null) { return null; } WeightFilterEntity weightFilterEntity = discoveryEntity.getWeightFilterEntity(); return weightFilterEntity; } @Override public int getWeight(Server server, WeightFilterEntity weightFilterEntity) {<FILL_FUNCTION_BODY>} }
String providerServiceId = pluginAdapter.getServerServiceId(server); String providerVersion = pluginAdapter.getServerVersion(server); String providerRegion = pluginAdapter.getServerRegion(server); String serviceId = pluginAdapter.getServiceId(); return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, serviceId);
198
91
289
<methods>public void <init>(com.nepxion.discovery.plugin.framework.adapter.PluginAdapter) ,public void <init>(com.nepxion.discovery.plugin.framework.adapter.PluginAdapter, com.nepxion.discovery.plugin.framework.context.PluginContextHolder) ,public boolean checkWeight(List<Server>, com.nepxion.discovery.common.entity.WeightFilterEntity) ,public abstract com.nepxion.discovery.common.entity.WeightFilterEntity getT() ,public abstract int getWeight(Server, com.nepxion.discovery.common.entity.WeightFilterEntity) <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/loadbalance/weight/StrategyWeightRandomLoadBalanceAdapter.java
StrategyWeightRandomLoadBalanceAdapter
getT
class StrategyWeightRandomLoadBalanceAdapter extends AbstractWeightRandomLoadBalanceAdapter<WeightFilterEntity> { public StrategyWeightRandomLoadBalanceAdapter(PluginAdapter pluginAdapter, PluginContextHolder pluginContextHolder) { super(pluginAdapter, pluginContextHolder); } @Override public WeightFilterEntity getT() {<FILL_FUNCTION_BODY>} @Override public int getWeight(Server server, WeightFilterEntity weightFilterEntity) { String providerServiceId = pluginAdapter.getServerServiceId(server); String providerVersion = pluginAdapter.getServerVersion(server); String providerRegion = pluginAdapter.getServerRegion(server); return WeightEntityWrapper.getWeight(weightFilterEntity, providerServiceId, providerVersion, providerRegion, null); } }
if (pluginContextHolder == null) { return null; } WeightFilterEntity weightFilterEntity = new WeightFilterEntity(); String versionWeightValue = pluginContextHolder.getContextRouteVersionWeight(); if (StringUtils.isNotEmpty(versionWeightValue)) { try { List<WeightEntity> weightEntityList = WeightEntityWrapper.parseWeightEntityList(versionWeightValue); weightFilterEntity.setVersionWeightEntityList(weightEntityList); } catch (Exception e) { VersionWeightEntity weightEntity = new VersionWeightEntity(); WeightEntityWrapper.parseWeightEntity(weightEntity, versionWeightValue); weightFilterEntity.setVersionWeightEntity(weightEntity); } } String regionWeightValue = pluginContextHolder.getContextRouteRegionWeight(); if (StringUtils.isNotEmpty(regionWeightValue)) { try { List<WeightEntity> weightEntityList = WeightEntityWrapper.parseWeightEntityList(regionWeightValue); weightFilterEntity.setRegionWeightEntityList(weightEntityList); } catch (Exception e) { RegionWeightEntity weightEntity = new RegionWeightEntity(); WeightEntityWrapper.parseWeightEntity(weightEntity, regionWeightValue); weightFilterEntity.setRegionWeightEntity(weightEntity); } } return weightFilterEntity;
193
323
516
<methods>public void <init>(com.nepxion.discovery.plugin.framework.adapter.PluginAdapter) ,public void <init>(com.nepxion.discovery.plugin.framework.adapter.PluginAdapter, com.nepxion.discovery.plugin.framework.context.PluginContextHolder) ,public boolean checkWeight(List<Server>, com.nepxion.discovery.common.entity.WeightFilterEntity) ,public abstract com.nepxion.discovery.common.entity.WeightFilterEntity getT() ,public abstract int getWeight(Server, com.nepxion.discovery.common.entity.WeightFilterEntity) <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder
Nepxion_Discovery
Discovery/discovery-plugin-framework/discovery-plugin-framework-starter/src/main/java/com/nepxion/discovery/plugin/framework/util/MetadataUtil.java
MetadataUtil
filter
class MetadataUtil { // 过滤设置元数据到Metadata Map public static void filter(Map<String, String> metadata, Environment environment) { // 运维参数元数据的设置方式 // 支持从-Dmetadata.xyz参数获取 Properties properties = System.getProperties(); Set<String> propertyNames = properties.stringPropertyNames(); for (String propertyName : propertyNames) { if (propertyName.startsWith(DiscoveryConstant.METADATA + ".")) { String key = propertyName.substring((DiscoveryConstant.METADATA + ".").length()); String value = properties.get(propertyName).toString(); // -Dmetadata.xyz优先级最高 // 不管元数据是否存在,直接放入或者覆盖 metadata.put(key, value); } } // 统一注册中心元数据的设置方式 // 支持spring.cloud.discovery.metadata.xyz配置获取 Properties enrichProperties = new Properties(); PropertiesUtil.enrichProperties(enrichProperties, environment, DiscoveryConstant.SPRING_CLOUD_DISCOVERY_PREFIX, false, true); Set<String> enrichPropertyNames = enrichProperties.stringPropertyNames(); for (String enrichPropertyName : enrichPropertyNames) { if (enrichPropertyName.startsWith(DiscoveryConstant.METADATA + ".")) { String key = enrichPropertyName.substring((DiscoveryConstant.METADATA + ".").length()); String value = enrichProperties.get(enrichPropertyName).toString(); // spring.cloud.discovery.metadata.xyz优先级最低 // 当元数据不存在,才放入 if (!metadata.containsKey(key)) { metadata.put(key, value); } } } } // 过滤设置元数据到Metadata List // 该方式适用于旧版Consul元数据模式 public static void filter(List<String> metadata, Environment environment) {<FILL_FUNCTION_BODY>} public static int getIndex(List<String> metadata, String key) { for (int i = 0; i < metadata.size(); i++) { String value = metadata.get(i); if (value.startsWith(key + "=")) { return i; } } return -1; } public static boolean containsKey(List<String> metadata, String key) { for (String value : metadata) { if (value.startsWith(key + "=")) { return true; } } return false; } }
// 运维参数元数据的设置方式 // 支持从-Dmetadata.xyz参数获取 Properties properties = System.getProperties(); Set<String> propertyNames = properties.stringPropertyNames(); for (String propertyName : propertyNames) { if (propertyName.startsWith(DiscoveryConstant.METADATA + ".")) { String key = propertyName.substring((DiscoveryConstant.METADATA + ".").length()); String value = properties.get(propertyName).toString(); // -Dmetadata.xyz优先级最高 // 不管元数据是否存在,直接放入或者覆盖 int index = getIndex(metadata, key); if (index > -1) { metadata.set(index, key + "=" + value); } else { metadata.add(key + "=" + value); } } } // 统一注册中心元数据的设置方式 // 支持spring.cloud.discovery.metadata.xyz配置获取 Properties enrichProperties = new Properties(); PropertiesUtil.enrichProperties(enrichProperties, environment, DiscoveryConstant.SPRING_CLOUD_DISCOVERY_PREFIX, false, true); Set<String> enrichPropertyNames = enrichProperties.stringPropertyNames(); for (String enrichPropertyName : enrichPropertyNames) { if (enrichPropertyName.startsWith(DiscoveryConstant.METADATA + ".")) { String key = enrichPropertyName.substring((DiscoveryConstant.METADATA + ".").length()); String value = enrichProperties.get(enrichPropertyName).toString(); // spring.cloud.discovery.metadata.xyz优先级最低 // 当元数据不存在,才放入 int index = getIndex(metadata, key); if (index <= -1) { metadata.add(key + "=" + value); } } }
666
483
1,149
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/adapter/ConsulAdapter.java
ConsulAdapter
getServerMetadata
class ConsulAdapter extends AbstractPluginAdapter { @Override public Map<String, String> getServerMetadata(Server server) {<FILL_FUNCTION_BODY>} }
if (server instanceof ConsulServer) { ConsulServer consulServer = (ConsulServer) server; return consulServer.getMetadata(); } return emptyMetadata; // throw new DiscoveryException("Server instance isn't the type of ConsulServer");
45
73
118
<methods>public non-sealed void <init>() ,public void clearDynamicGlobalRule() ,public void clearDynamicPartialRule() ,public void clearDynamicVersion() ,public java.lang.String getContextPath() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicGlobalRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicPartialRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicRule() ,public java.lang.String getDynamicVersion() ,public java.lang.String getEnvironment() ,public java.lang.String getFormatContextPath() ,public java.lang.String getGroup() ,public java.lang.String getGroupKey() ,public java.lang.String getHost() ,public java.lang.String getInstanceContextPath(ServiceInstance) ,public java.lang.String getInstanceEnvironment(ServiceInstance) ,public java.lang.String getInstanceFormatContextPath(ServiceInstance) ,public java.lang.String getInstanceGroup(ServiceInstance) ,public java.lang.String getInstanceGroupKey(ServiceInstance) ,public Map<java.lang.String,java.lang.String> getInstanceMetadata(ServiceInstance) ,public java.lang.String getInstancePlugin(ServiceInstance) ,public java.lang.String getInstanceProtocol(ServiceInstance) ,public java.lang.String getInstanceRegion(ServiceInstance) ,public java.lang.String getInstanceServiceAppId(ServiceInstance) ,public java.lang.String getInstanceServiceId(ServiceInstance) ,public java.lang.String getInstanceServiceType(ServiceInstance) ,public java.lang.String getInstanceServiceUUId(ServiceInstance) ,public java.lang.String getInstanceVersion(ServiceInstance) ,public java.lang.String getInstanceZone(ServiceInstance) ,public com.nepxion.discovery.common.entity.RuleEntity getLocalRule() ,public java.lang.String getLocalVersion() ,public Map<java.lang.String,java.lang.String> getMetadata() ,public java.lang.String getPlugin() ,public java.lang.String getPluginInfo(java.lang.String) ,public int getPort() ,public java.lang.String getProtocol() ,public java.lang.String getRegion() ,public com.nepxion.discovery.common.entity.RuleEntity getRule() ,public java.lang.String getServerContextPath(Server) ,public java.lang.String getServerEnvironment(Server) ,public java.lang.String getServerFormatContextPath(Server) ,public java.lang.String getServerGroup(Server) ,public java.lang.String getServerGroupKey(Server) ,public java.lang.String getServerPlugin(Server) ,public java.lang.String getServerProtocol(Server) ,public java.lang.String getServerRegion(Server) ,public java.lang.String getServerServiceAppId(Server) ,public java.lang.String getServerServiceId(Server) ,public java.lang.String getServerServiceType(Server) ,public java.lang.String getServerServiceUUId(Server) ,public java.lang.String getServerVersion(Server) ,public java.lang.String getServerZone(Server) ,public java.lang.String getServiceAppId() ,public java.lang.String getServiceId() ,public java.lang.String getServiceType() ,public java.lang.String getServiceUUId() ,public java.lang.String getVersion() ,public java.lang.String getZone() ,public boolean isActive() ,public boolean isInstanceActive(ServiceInstance) ,public boolean isServerActive(Server) ,public void setDynamicGlobalRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicPartialRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicVersion(java.lang.String) ,public void setLocalRule(com.nepxion.discovery.common.entity.RuleEntity) <variables>private java.lang.String applicationType,protected Map<java.lang.String,java.lang.String> emptyMetadata,private java.lang.String groupKey,protected com.nepxion.discovery.plugin.framework.cache.PluginCache pluginCache,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected Registration registration,protected com.nepxion.discovery.plugin.framework.cache.RuleCache ruleCache
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/configuration/ConsulLoadBalanceConfiguration.java
ConsulLoadBalanceConfiguration
ribbonServerList
class ConsulLoadBalanceConfiguration { @Autowired private ConsulClient client; @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @Bean public ServerList<?> ribbonServerList(IClientConfig config, ConsulDiscoveryProperties properties) {<FILL_FUNCTION_BODY>} }
ConsulServerListDecorator serverList = new ConsulServerListDecorator(client, properties); serverList.initWithNiwsConfig(config); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); return serverList;
88
67
155
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/context/ConsulApplicationContextInitializer.java
ConsulApplicationContextInitializer
afterInitialization
class ConsulApplicationContextInitializer extends PluginApplicationContextInitializer { @Override protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof ConsulServiceRegistry) { ConsulServiceRegistry consulServiceRegistry = (ConsulServiceRegistry) bean; return new ConsulServiceRegistryDecorator(consulServiceRegistry, applicationContext); } else if (bean instanceof ConsulDiscoveryProperties) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); ConsulDiscoveryProperties consulDiscoveryProperties = (ConsulDiscoveryProperties) bean; consulDiscoveryProperties.setPreferIpAddress(true); List<String> metadata = consulDiscoveryProperties.getTags(); String groupKey = PluginContextAware.getGroupKey(environment); /*if (!MetadataUtil.containsKey(metadata, groupKey)) { metadata.add(groupKey + "=" + DiscoveryConstant.DEFAULT); } if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.VERSION)) { metadata.add(DiscoveryConstant.VERSION + "=" + DiscoveryConstant.DEFAULT); } if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.REGION)) { metadata.add(DiscoveryConstant.REGION + "=" + DiscoveryConstant.DEFAULT); } if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.ENVIRONMENT)) { metadata.add(DiscoveryConstant.ENVIRONMENT + "=" + DiscoveryConstant.DEFAULT); } if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.ZONE)) { metadata.add(DiscoveryConstant.ZONE + "=" + DiscoveryConstant.DEFAULT); } if (!MetadataUtil.containsKey(metadata, DiscoveryConstant.ACTIVE)) { metadata.add(DiscoveryConstant.ACTIVE + "=" + "false"); }*/ String prefixGroup = getPrefixGroup(applicationContext); if (StringUtils.isNotEmpty(prefixGroup)) { metadata.set(MetadataUtil.getIndex(metadata, groupKey), groupKey + "=" + prefixGroup); } String gitVersion = getGitVersion(applicationContext); if (StringUtils.isNotEmpty(gitVersion)) { metadata.set(MetadataUtil.getIndex(metadata, DiscoveryConstant.VERSION), DiscoveryConstant.VERSION + "=" + gitVersion); } metadata.add(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION + "=" + SpringBootVersion.getVersion()); metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME + "=" + PluginContextAware.getApplicationName(environment)); metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE + "=" + PluginContextAware.getApplicationType(environment)); String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); if (StringUtils.isNotEmpty(applicationGatewayType)) { metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE + "=" + applicationGatewayType); } metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL + "=" + PluginContextAware.getApplicationProtocol(environment)); metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID + "=" + PluginContextAware.getApplicationUUId(environment)); metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN + "=" + DiscoveryType.CONSUL); metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION + "=" + DiscoveryConstant.DISCOVERY_VERSION); String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); if (StringUtils.isNotEmpty(agentVersion)) { metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION + "=" + agentVersion); } metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY + "=" + groupKey); metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH + "=" + PluginContextAware.getContextPath(environment)); try { ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); if (applicationInfoAdapter != null) { metadata.add(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID + "=" + applicationInfoAdapter.getAppId()); } } catch (Exception e) { } for (Map.Entry<String, String> entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isNotEmpty(value)) { metadata.add(key + "=" + value); } } MetadataUtil.filter(metadata, environment); return bean; } else { return bean; }
61
1,271
1,332
<methods>public non-sealed void <init>() ,public int getOrder() ,public void initialize(ConfigurableApplicationContext) <variables>private static final Logger LOG
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-consul/src/main/java/com/nepxion/discovery/plugin/registercenter/consul/decorator/ConsulServiceRegistryDecorator.java
ConsulServiceRegistryDecorator
setStatus
class ConsulServiceRegistryDecorator extends ConsulServiceRegistry { // private static final Logger LOG = LoggerFactory.getLogger(ConsulServiceRegistryDecorator.class); private ConsulServiceRegistry serviceRegistry; private ConfigurableApplicationContext applicationContext; public ConsulServiceRegistryDecorator(ConsulServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { super(null, null, null, null); this.serviceRegistry = serviceRegistry; this.applicationContext = applicationContext; } @Override public void register(ConsulRegistration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onRegister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.register(registration); } @Override public void deregister(ConsulRegistration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onDeregister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.deregister(registration); } @Override public void setStatus(ConsulRegistration registration, String status) {<FILL_FUNCTION_BODY>} @Override public Object getStatus(ConsulRegistration registration) { return serviceRegistry.getStatus(registration); } @Override public void close() { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onClose(); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.close(); } }
try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onSetStatus(registration, status); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.setStatus(registration, status);
501
92
593
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/adapter/EurekaAdapter.java
EurekaAdapter
getServerMetadata
class EurekaAdapter extends AbstractPluginAdapter { @Override public Map<String, String> getServerMetadata(Server server) {<FILL_FUNCTION_BODY>} }
if (server instanceof DiscoveryEnabledServer) { DiscoveryEnabledServer discoveryEnabledServer = (DiscoveryEnabledServer) server; return discoveryEnabledServer.getInstanceInfo().getMetadata(); } return emptyMetadata; // throw new DiscoveryException("Server instance isn't the type of DiscoveryEnabledServer");
46
80
126
<methods>public non-sealed void <init>() ,public void clearDynamicGlobalRule() ,public void clearDynamicPartialRule() ,public void clearDynamicVersion() ,public java.lang.String getContextPath() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicGlobalRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicPartialRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicRule() ,public java.lang.String getDynamicVersion() ,public java.lang.String getEnvironment() ,public java.lang.String getFormatContextPath() ,public java.lang.String getGroup() ,public java.lang.String getGroupKey() ,public java.lang.String getHost() ,public java.lang.String getInstanceContextPath(ServiceInstance) ,public java.lang.String getInstanceEnvironment(ServiceInstance) ,public java.lang.String getInstanceFormatContextPath(ServiceInstance) ,public java.lang.String getInstanceGroup(ServiceInstance) ,public java.lang.String getInstanceGroupKey(ServiceInstance) ,public Map<java.lang.String,java.lang.String> getInstanceMetadata(ServiceInstance) ,public java.lang.String getInstancePlugin(ServiceInstance) ,public java.lang.String getInstanceProtocol(ServiceInstance) ,public java.lang.String getInstanceRegion(ServiceInstance) ,public java.lang.String getInstanceServiceAppId(ServiceInstance) ,public java.lang.String getInstanceServiceId(ServiceInstance) ,public java.lang.String getInstanceServiceType(ServiceInstance) ,public java.lang.String getInstanceServiceUUId(ServiceInstance) ,public java.lang.String getInstanceVersion(ServiceInstance) ,public java.lang.String getInstanceZone(ServiceInstance) ,public com.nepxion.discovery.common.entity.RuleEntity getLocalRule() ,public java.lang.String getLocalVersion() ,public Map<java.lang.String,java.lang.String> getMetadata() ,public java.lang.String getPlugin() ,public java.lang.String getPluginInfo(java.lang.String) ,public int getPort() ,public java.lang.String getProtocol() ,public java.lang.String getRegion() ,public com.nepxion.discovery.common.entity.RuleEntity getRule() ,public java.lang.String getServerContextPath(Server) ,public java.lang.String getServerEnvironment(Server) ,public java.lang.String getServerFormatContextPath(Server) ,public java.lang.String getServerGroup(Server) ,public java.lang.String getServerGroupKey(Server) ,public java.lang.String getServerPlugin(Server) ,public java.lang.String getServerProtocol(Server) ,public java.lang.String getServerRegion(Server) ,public java.lang.String getServerServiceAppId(Server) ,public java.lang.String getServerServiceId(Server) ,public java.lang.String getServerServiceType(Server) ,public java.lang.String getServerServiceUUId(Server) ,public java.lang.String getServerVersion(Server) ,public java.lang.String getServerZone(Server) ,public java.lang.String getServiceAppId() ,public java.lang.String getServiceId() ,public java.lang.String getServiceType() ,public java.lang.String getServiceUUId() ,public java.lang.String getVersion() ,public java.lang.String getZone() ,public boolean isActive() ,public boolean isInstanceActive(ServiceInstance) ,public boolean isServerActive(Server) ,public void setDynamicGlobalRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicPartialRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicVersion(java.lang.String) ,public void setLocalRule(com.nepxion.discovery.common.entity.RuleEntity) <variables>private java.lang.String applicationType,protected Map<java.lang.String,java.lang.String> emptyMetadata,private java.lang.String groupKey,protected com.nepxion.discovery.plugin.framework.cache.PluginCache pluginCache,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected Registration registration,protected com.nepxion.discovery.plugin.framework.cache.RuleCache ruleCache
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/configuration/EurekaLoadBalanceConfiguration.java
EurekaLoadBalanceConfiguration
ribbonServerList
class EurekaLoadBalanceConfiguration { @Value("${ribbon.eureka.approximateZoneFromHostname:false}") private boolean approximateZoneFromHostname = false; @RibbonClientName private String serviceId = "client"; @Autowired private PropertiesFactory propertiesFactory; @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @Bean public ServerList<?> ribbonServerList(IClientConfig config, Provider<EurekaClient> eurekaClientProvider) {<FILL_FUNCTION_BODY>} }
if (this.propertiesFactory.isSet(ServerList.class, serviceId)) { return this.propertiesFactory.get(ServerList.class, config, serviceId); } DiscoveryEnabledNIWSServerList discoveryServerList = new DiscoveryEnabledNIWSServerList(config, eurekaClientProvider); EurekaServerListDecorator serverList = new EurekaServerListDecorator(discoveryServerList, config, this.approximateZoneFromHostname); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); serverList.setServiceId(config.getClientName()); return serverList;
152
160
312
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/context/EurekaApplicationContextInitializer.java
EurekaApplicationContextInitializer
afterInitialization
class EurekaApplicationContextInitializer extends PluginApplicationContextInitializer { @Override protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof EurekaServiceRegistry) { EurekaServiceRegistry eurekaServiceRegistry = (EurekaServiceRegistry) bean; return new EurekaServiceRegistryDecorator(eurekaServiceRegistry, applicationContext); } else if (bean instanceof EurekaInstanceConfigBean) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); EurekaInstanceConfigBean eurekaInstanceConfig = (EurekaInstanceConfigBean) bean; eurekaInstanceConfig.setPreferIpAddress(true); Map<String, String> metadata = eurekaInstanceConfig.getMetadataMap(); String groupKey = PluginContextAware.getGroupKey(environment); /*if (!metadata.containsKey(groupKey)) { metadata.put(groupKey, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.VERSION)) { metadata.put(DiscoveryConstant.VERSION, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.REGION)) { metadata.put(DiscoveryConstant.REGION, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ENVIRONMENT)) { metadata.put(DiscoveryConstant.ENVIRONMENT, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ZONE)) { metadata.put(DiscoveryConstant.ZONE, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ACTIVE)) { metadata.put(DiscoveryConstant.ACTIVE, "false"); }*/ String prefixGroup = getPrefixGroup(applicationContext); if (StringUtils.isNotEmpty(prefixGroup)) { metadata.put(groupKey, prefixGroup); } String gitVersion = getGitVersion(applicationContext); if (StringUtils.isNotEmpty(gitVersion)) { metadata.put(DiscoveryConstant.VERSION, gitVersion); } metadata.put(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION, SpringBootVersion.getVersion()); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); if (StringUtils.isNotEmpty(applicationGatewayType)) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE, applicationGatewayType); } metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL, PluginContextAware.getApplicationProtocol(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID, PluginContextAware.getApplicationUUId(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, DiscoveryType.EUREKA.toString()); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); if (StringUtils.isNotEmpty(agentVersion)) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, agentVersion); } metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY, groupKey); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); try { ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); if (applicationInfoAdapter != null) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID, applicationInfoAdapter.getAppId()); } } catch (Exception e) { } for (Map.Entry<String, String> entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isNotEmpty(value)) { metadata.put(key, value); } } MetadataUtil.filter(metadata, environment); return bean; } else { return bean; }
62
1,159
1,221
<methods>public non-sealed void <init>() ,public int getOrder() ,public void initialize(ConfigurableApplicationContext) <variables>private static final Logger LOG
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-eureka/src/main/java/com/nepxion/discovery/plugin/registercenter/eureka/decorator/EurekaServiceRegistryDecorator.java
EurekaServiceRegistryDecorator
close
class EurekaServiceRegistryDecorator extends EurekaServiceRegistry { // private static final Logger LOG = LoggerFactory.getLogger(EurekaServiceRegistryDecorator.class); private EurekaServiceRegistry serviceRegistry; private ConfigurableApplicationContext applicationContext; public EurekaServiceRegistryDecorator(EurekaServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { this.serviceRegistry = serviceRegistry; this.applicationContext = applicationContext; } @Override public void register(EurekaRegistration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onRegister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.register(registration); } @Override public void deregister(EurekaRegistration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onDeregister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.deregister(registration); } @Override public void setStatus(EurekaRegistration registration, String status) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onSetStatus(registration, status); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.setStatus(registration, status); } @Override public Object getStatus(EurekaRegistration registration) { return serviceRegistry.getStatus(registration); } @Override public void close() {<FILL_FUNCTION_BODY>} }
try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onClose(); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.close();
510
80
590
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/adapter/NacosAdapter.java
NacosAdapter
getServerMetadata
class NacosAdapter extends AbstractPluginAdapter { @Value("${" + NacosConstant.SPRING_APPLICATION_NACOS_SERVICE_ID_FILTER_ENABLED + ":true}") protected Boolean nacosServiceIdFilterEnabled; public static final String SEPARATE = "@@"; @Override public Map<String, String> getServerMetadata(Server server) {<FILL_FUNCTION_BODY>} @Override public String getServiceId() { String serviceId = super.getServiceId(); return filterServiceId(serviceId); } @Override public String getServerServiceId(Server server) { String serverServiceId = super.getServerServiceId(server); return filterServiceId(serverServiceId); } @Override public String getInstanceServiceId(ServiceInstance instance) { String instanceServiceId = super.getInstanceServiceId(instance); return filterServiceId(instanceServiceId); } // 由于Nacos注册中心会自动把服务名处理成GROUP@@SERVICE_ID的格式,导致根据服务名去获取元数据的时候会找不到,通过如下方式过滤掉GROUP前缀 private String filterServiceId(String serviceId) { if (nacosServiceIdFilterEnabled && StringUtils.contains(serviceId, SEPARATE)) { serviceId = serviceId.substring(serviceId.indexOf(SEPARATE) + SEPARATE.length(), serviceId.length()); } return serviceId; } }
if (server instanceof NacosServer) { NacosServer nacosServer = (NacosServer) server; return nacosServer.getMetadata(); } return emptyMetadata; // throw new DiscoveryException("Server instance isn't the type of NacosServer");
387
79
466
<methods>public non-sealed void <init>() ,public void clearDynamicGlobalRule() ,public void clearDynamicPartialRule() ,public void clearDynamicVersion() ,public java.lang.String getContextPath() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicGlobalRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicPartialRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicRule() ,public java.lang.String getDynamicVersion() ,public java.lang.String getEnvironment() ,public java.lang.String getFormatContextPath() ,public java.lang.String getGroup() ,public java.lang.String getGroupKey() ,public java.lang.String getHost() ,public java.lang.String getInstanceContextPath(ServiceInstance) ,public java.lang.String getInstanceEnvironment(ServiceInstance) ,public java.lang.String getInstanceFormatContextPath(ServiceInstance) ,public java.lang.String getInstanceGroup(ServiceInstance) ,public java.lang.String getInstanceGroupKey(ServiceInstance) ,public Map<java.lang.String,java.lang.String> getInstanceMetadata(ServiceInstance) ,public java.lang.String getInstancePlugin(ServiceInstance) ,public java.lang.String getInstanceProtocol(ServiceInstance) ,public java.lang.String getInstanceRegion(ServiceInstance) ,public java.lang.String getInstanceServiceAppId(ServiceInstance) ,public java.lang.String getInstanceServiceId(ServiceInstance) ,public java.lang.String getInstanceServiceType(ServiceInstance) ,public java.lang.String getInstanceServiceUUId(ServiceInstance) ,public java.lang.String getInstanceVersion(ServiceInstance) ,public java.lang.String getInstanceZone(ServiceInstance) ,public com.nepxion.discovery.common.entity.RuleEntity getLocalRule() ,public java.lang.String getLocalVersion() ,public Map<java.lang.String,java.lang.String> getMetadata() ,public java.lang.String getPlugin() ,public java.lang.String getPluginInfo(java.lang.String) ,public int getPort() ,public java.lang.String getProtocol() ,public java.lang.String getRegion() ,public com.nepxion.discovery.common.entity.RuleEntity getRule() ,public java.lang.String getServerContextPath(Server) ,public java.lang.String getServerEnvironment(Server) ,public java.lang.String getServerFormatContextPath(Server) ,public java.lang.String getServerGroup(Server) ,public java.lang.String getServerGroupKey(Server) ,public java.lang.String getServerPlugin(Server) ,public java.lang.String getServerProtocol(Server) ,public java.lang.String getServerRegion(Server) ,public java.lang.String getServerServiceAppId(Server) ,public java.lang.String getServerServiceId(Server) ,public java.lang.String getServerServiceType(Server) ,public java.lang.String getServerServiceUUId(Server) ,public java.lang.String getServerVersion(Server) ,public java.lang.String getServerZone(Server) ,public java.lang.String getServiceAppId() ,public java.lang.String getServiceId() ,public java.lang.String getServiceType() ,public java.lang.String getServiceUUId() ,public java.lang.String getVersion() ,public java.lang.String getZone() ,public boolean isActive() ,public boolean isInstanceActive(ServiceInstance) ,public boolean isServerActive(Server) ,public void setDynamicGlobalRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicPartialRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicVersion(java.lang.String) ,public void setLocalRule(com.nepxion.discovery.common.entity.RuleEntity) <variables>private java.lang.String applicationType,protected Map<java.lang.String,java.lang.String> emptyMetadata,private java.lang.String groupKey,protected com.nepxion.discovery.plugin.framework.cache.PluginCache pluginCache,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected Registration registration,protected com.nepxion.discovery.plugin.framework.cache.RuleCache ruleCache
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/configuration/NacosLoadBalanceConfiguration.java
NacosLoadBalanceConfiguration
ribbonServerList
class NacosLoadBalanceConfiguration { @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @Bean public ServerList<?> ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) {<FILL_FUNCTION_BODY>} }
NacosServerListDecorator serverList = new NacosServerListDecorator(nacosDiscoveryProperties); serverList.initWithNiwsConfig(config); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); return serverList;
80
72
152
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/context/NacosApplicationContextInitializer.java
NacosApplicationContextInitializer
afterInitialization
class NacosApplicationContextInitializer extends PluginApplicationContextInitializer { @Override protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof NacosServiceRegistry) { NacosServiceRegistry nacosServiceRegistry = (NacosServiceRegistry) bean; NacosServiceManager nacosServiceManager = applicationContext.getBean(NacosServiceManager.class); NacosDiscoveryProperties nacosDiscoveryProperties = applicationContext.getBean(NacosDiscoveryProperties.class); return new NacosServiceRegistryDecorator(nacosServiceManager, nacosDiscoveryProperties, nacosServiceRegistry, applicationContext); } else if (bean instanceof NacosDiscoveryProperties) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); NacosDiscoveryProperties nacosDiscoveryProperties = (NacosDiscoveryProperties) bean; Map<String, String> metadata = nacosDiscoveryProperties.getMetadata(); String groupKey = PluginContextAware.getGroupKey(environment); /*if (!metadata.containsKey(groupKey)) { metadata.put(groupKey, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.VERSION)) { metadata.put(DiscoveryConstant.VERSION, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.REGION)) { metadata.put(DiscoveryConstant.REGION, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ENVIRONMENT)) { metadata.put(DiscoveryConstant.ENVIRONMENT, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ZONE)) { metadata.put(DiscoveryConstant.ZONE, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ACTIVE)) { metadata.put(DiscoveryConstant.ACTIVE, "false"); }*/ String prefixGroup = getPrefixGroup(applicationContext); if (StringUtils.isNotEmpty(prefixGroup)) { metadata.put(groupKey, prefixGroup); } String gitVersion = getGitVersion(applicationContext); if (StringUtils.isNotEmpty(gitVersion)) { metadata.put(DiscoveryConstant.VERSION, gitVersion); } metadata.put(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION, SpringBootVersion.getVersion()); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); if (StringUtils.isNotEmpty(applicationGatewayType)) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE, applicationGatewayType); } metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL, PluginContextAware.getApplicationProtocol(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID, PluginContextAware.getApplicationUUId(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, DiscoveryType.NACOS.toString()); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); if (StringUtils.isNotEmpty(agentVersion)) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, agentVersion); } metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY, groupKey); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); try { ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); if (applicationInfoAdapter != null) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID, applicationInfoAdapter.getAppId()); } } catch (Exception e) { } for (Map.Entry<String, String> entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isNotEmpty(value)) { metadata.put(key, value); } } MetadataUtil.filter(metadata, environment); return bean; } else { return bean; }
62
1,213
1,275
<methods>public non-sealed void <init>() ,public int getOrder() ,public void initialize(ConfigurableApplicationContext) <variables>private static final Logger LOG
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-nacos/src/main/java/com/nepxion/discovery/plugin/registercenter/nacos/decorator/NacosServiceRegistryDecorator.java
NacosServiceRegistryDecorator
setStatus
class NacosServiceRegistryDecorator extends NacosServiceRegistry { // private static final Logger LOG = LoggerFactory.getLogger(NacosServiceRegistryDecorator.class); private NacosServiceRegistry serviceRegistry; private ConfigurableApplicationContext applicationContext; public NacosServiceRegistryDecorator(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties, NacosServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { super(nacosServiceManager, nacosDiscoveryProperties); this.serviceRegistry = serviceRegistry; this.applicationContext = applicationContext; } @Override public void register(Registration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onRegister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.register(registration); } @Override public void deregister(Registration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onDeregister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.deregister(registration); } @Override public void setStatus(Registration registration, String status) {<FILL_FUNCTION_BODY>} @Override public Object getStatus(Registration registration) { return serviceRegistry.getStatus(registration); } @Override public void close() { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onClose(); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.close(); } }
try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onSetStatus(registration, status); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.setStatus(registration, status);
528
92
620
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/adapter/ZookeeperAdapter.java
ZookeeperAdapter
getServerMetadata
class ZookeeperAdapter extends AbstractPluginAdapter { // Zookeeper比较特殊,getServiceInstance是Lazy Initialize模式 @PostConstruct public void initialize() { if (registration instanceof ZookeeperRegistration) { ZookeeperRegistration zookeeperRegistration = (ZookeeperRegistration) registration; zookeeperRegistration.getServiceInstance(); return; } throw new DiscoveryException("Registration isn't the type of ZookeeperRegistration"); } @Override public Map<String, String> getServerMetadata(Server server) {<FILL_FUNCTION_BODY>} }
if (server instanceof ZookeeperServer) { ZookeeperServer zookeeperServer = (ZookeeperServer) server; return zookeeperServer.getInstance().getPayload().getMetadata(); } return emptyMetadata; // throw new DiscoveryException("Server instance isn't the type of ZookeeperServer");
168
91
259
<methods>public non-sealed void <init>() ,public void clearDynamicGlobalRule() ,public void clearDynamicPartialRule() ,public void clearDynamicVersion() ,public java.lang.String getContextPath() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicGlobalRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicPartialRule() ,public com.nepxion.discovery.common.entity.RuleEntity getDynamicRule() ,public java.lang.String getDynamicVersion() ,public java.lang.String getEnvironment() ,public java.lang.String getFormatContextPath() ,public java.lang.String getGroup() ,public java.lang.String getGroupKey() ,public java.lang.String getHost() ,public java.lang.String getInstanceContextPath(ServiceInstance) ,public java.lang.String getInstanceEnvironment(ServiceInstance) ,public java.lang.String getInstanceFormatContextPath(ServiceInstance) ,public java.lang.String getInstanceGroup(ServiceInstance) ,public java.lang.String getInstanceGroupKey(ServiceInstance) ,public Map<java.lang.String,java.lang.String> getInstanceMetadata(ServiceInstance) ,public java.lang.String getInstancePlugin(ServiceInstance) ,public java.lang.String getInstanceProtocol(ServiceInstance) ,public java.lang.String getInstanceRegion(ServiceInstance) ,public java.lang.String getInstanceServiceAppId(ServiceInstance) ,public java.lang.String getInstanceServiceId(ServiceInstance) ,public java.lang.String getInstanceServiceType(ServiceInstance) ,public java.lang.String getInstanceServiceUUId(ServiceInstance) ,public java.lang.String getInstanceVersion(ServiceInstance) ,public java.lang.String getInstanceZone(ServiceInstance) ,public com.nepxion.discovery.common.entity.RuleEntity getLocalRule() ,public java.lang.String getLocalVersion() ,public Map<java.lang.String,java.lang.String> getMetadata() ,public java.lang.String getPlugin() ,public java.lang.String getPluginInfo(java.lang.String) ,public int getPort() ,public java.lang.String getProtocol() ,public java.lang.String getRegion() ,public com.nepxion.discovery.common.entity.RuleEntity getRule() ,public java.lang.String getServerContextPath(Server) ,public java.lang.String getServerEnvironment(Server) ,public java.lang.String getServerFormatContextPath(Server) ,public java.lang.String getServerGroup(Server) ,public java.lang.String getServerGroupKey(Server) ,public java.lang.String getServerPlugin(Server) ,public java.lang.String getServerProtocol(Server) ,public java.lang.String getServerRegion(Server) ,public java.lang.String getServerServiceAppId(Server) ,public java.lang.String getServerServiceId(Server) ,public java.lang.String getServerServiceType(Server) ,public java.lang.String getServerServiceUUId(Server) ,public java.lang.String getServerVersion(Server) ,public java.lang.String getServerZone(Server) ,public java.lang.String getServiceAppId() ,public java.lang.String getServiceId() ,public java.lang.String getServiceType() ,public java.lang.String getServiceUUId() ,public java.lang.String getVersion() ,public java.lang.String getZone() ,public boolean isActive() ,public boolean isInstanceActive(ServiceInstance) ,public boolean isServerActive(Server) ,public void setDynamicGlobalRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicPartialRule(com.nepxion.discovery.common.entity.RuleEntity) ,public void setDynamicVersion(java.lang.String) ,public void setLocalRule(com.nepxion.discovery.common.entity.RuleEntity) <variables>private java.lang.String applicationType,protected Map<java.lang.String,java.lang.String> emptyMetadata,private java.lang.String groupKey,protected com.nepxion.discovery.plugin.framework.cache.PluginCache pluginCache,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected Registration registration,protected com.nepxion.discovery.plugin.framework.cache.RuleCache ruleCache
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/configuration/ZookeeperLoadBalanceConfiguration.java
ZookeeperLoadBalanceConfiguration
ribbonServerListFromDependencies
class ZookeeperLoadBalanceConfiguration { @Autowired private LoadBalanceListenerExecutor loadBalanceListenerExecutor; @Bean @ConditionalOnDependenciesPassed public ServerList<?> ribbonServerListFromDependencies(IClientConfig config, ZookeeperDependencies zookeeperDependencies, ServiceDiscovery<ZookeeperInstance> serviceDiscovery) {<FILL_FUNCTION_BODY>} @Bean @ConditionalOnDependenciesNotPassed public ServerList<?> ribbonServerList(IClientConfig config, ServiceDiscovery<ZookeeperInstance> serviceDiscovery) { ZookeeperServerListDecorator serverList = new ZookeeperServerListDecorator(serviceDiscovery); serverList.initWithNiwsConfig(config); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); serverList.setServiceId(config.getClientName()); return serverList; } }
ZookeeperServerListDecorator serverList = new ZookeeperServerListDecorator(serviceDiscovery); serverList.initFromDependencies(config, zookeeperDependencies); serverList.setLoadBalanceListenerExecutor(loadBalanceListenerExecutor); serverList.setServiceId(config.getClientName()); return serverList;
242
91
333
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/context/ZookeeperApplicationContextInitializer.java
ZookeeperApplicationContextInitializer
afterInitialization
class ZookeeperApplicationContextInitializer extends PluginApplicationContextInitializer { @Override protected Object afterInitialization(ConfigurableApplicationContext applicationContext, Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof ZookeeperServiceRegistry) { ZookeeperServiceRegistry zookeeperServiceRegistry = (ZookeeperServiceRegistry) bean; return new ZookeeperServiceRegistryDecorator(zookeeperServiceRegistry, applicationContext); } else if (bean instanceof ZookeeperDiscoveryProperties) { ConfigurableEnvironment environment = applicationContext.getEnvironment(); ZookeeperDiscoveryProperties zookeeperDiscoveryProperties = (ZookeeperDiscoveryProperties) bean; zookeeperDiscoveryProperties.setPreferIpAddress(true); Map<String, String> metadata = zookeeperDiscoveryProperties.getMetadata(); String groupKey = PluginContextAware.getGroupKey(environment); /*if (!metadata.containsKey(groupKey)) { metadata.put(groupKey, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.VERSION)) { metadata.put(DiscoveryConstant.VERSION, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.REGION)) { metadata.put(DiscoveryConstant.REGION, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ENVIRONMENT)) { metadata.put(DiscoveryConstant.ENVIRONMENT, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ZONE)) { metadata.put(DiscoveryConstant.ZONE, DiscoveryConstant.DEFAULT); } if (!metadata.containsKey(DiscoveryConstant.ACTIVE)) { metadata.put(DiscoveryConstant.ACTIVE, "false"); }*/ String prefixGroup = getPrefixGroup(applicationContext); if (StringUtils.isNotEmpty(prefixGroup)) { metadata.put(groupKey, prefixGroup); } String gitVersion = getGitVersion(applicationContext); if (StringUtils.isNotEmpty(gitVersion)) { metadata.put(DiscoveryConstant.VERSION, gitVersion); } metadata.put(DiscoveryMetaDataConstant.SPRING_BOOT_VERSION, SpringBootVersion.getVersion()); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_NAME, PluginContextAware.getApplicationName(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_TYPE, PluginContextAware.getApplicationType(environment)); String applicationGatewayType = PluginContextAware.getApplicationGatewayType(environment); if (StringUtils.isNotEmpty(applicationGatewayType)) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GATEWAY_TYPE, applicationGatewayType); } metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_PROTOCOL, PluginContextAware.getApplicationProtocol(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_UUID, PluginContextAware.getApplicationUUId(environment)); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_PLUGIN, DiscoveryType.ZOOKEEPER.toString()); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_VERSION, DiscoveryConstant.DISCOVERY_VERSION); String agentVersion = System.getProperty(DiscoveryConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION); if (StringUtils.isNotEmpty(agentVersion)) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_DISCOVERY_AGENT_VERSION, agentVersion); } metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_GROUP_KEY, groupKey); metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_CONTEXT_PATH, PluginContextAware.getContextPath(environment)); try { ApplicationInfoAdapter applicationInfoAdapter = applicationContext.getBean(ApplicationInfoAdapter.class); if (applicationInfoAdapter != null) { metadata.put(DiscoveryMetaDataConstant.SPRING_APPLICATION_APP_ID, applicationInfoAdapter.getAppId()); } } catch (Exception e) { } for (Map.Entry<String, String> entry : DiscoveryMetaDataPreInstallation.getMetadata().entrySet()) { String key = entry.getKey(); String value = entry.getValue(); if (StringUtils.isNotEmpty(value)) { metadata.put(key, value); } } MetadataUtil.filter(metadata, environment); return bean; } else { return bean; }
63
1,173
1,236
<methods>public non-sealed void <init>() ,public int getOrder() ,public void initialize(ConfigurableApplicationContext) <variables>private static final Logger LOG
Nepxion_Discovery
Discovery/discovery-plugin-register-center/discovery-plugin-register-center-starter-zookeeper/src/main/java/com/nepxion/discovery/plugin/registercenter/zookeeper/decorator/ZookeeperServiceRegistryDecorator.java
ZookeeperServiceRegistryDecorator
deregister
class ZookeeperServiceRegistryDecorator extends ZookeeperServiceRegistry { // private static final Logger LOG = LoggerFactory.getLogger(ZookeeperServiceRegistryDecorator.class); private ZookeeperServiceRegistry serviceRegistry; private ConfigurableApplicationContext applicationContext; public ZookeeperServiceRegistryDecorator(ZookeeperServiceRegistry serviceRegistry, ConfigurableApplicationContext applicationContext) { super(null); this.serviceRegistry = serviceRegistry; this.applicationContext = applicationContext; } @Override public void register(ZookeeperRegistration registration) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onRegister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.register(registration); } @Override public void deregister(ZookeeperRegistration registration) {<FILL_FUNCTION_BODY>} @Override public void setStatus(ZookeeperRegistration registration, String status) { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onSetStatus(registration, status); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.setStatus(registration, status); } @Override public Object getStatus(ZookeeperRegistration registration) { return serviceRegistry.getStatus(registration); } @Override public void close() { try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onClose(); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.close(); } @Override public void afterSingletonsInstantiated() { serviceRegistry.afterSingletonsInstantiated(); } }
try { RegisterListenerExecutor registerListenerExecutor = applicationContext.getBean(RegisterListenerExecutor.class); registerListenerExecutor.onDeregister(registration); } catch (BeansException e) { // LOG.warn("Get bean for RegisterListenerExecutor failed, ignore to executor listener"); } serviceRegistry.deregister(registration);
551
90
641
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/configuration/GatewayStrategyAutoConfiguration.java
SkywalkingStrategyConfiguration
skyWalkingGatewayStrategyFilter
class SkywalkingStrategyConfiguration { @Autowired private ConfigurableEnvironment environment; @Bean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) public SkyWalkingGatewayStrategyFilter skyWalkingGatewayStrategyFilter() {<FILL_FUNCTION_BODY>} }
Boolean skywalkingTraceIdEnabled = environment.getProperty(GatewayStrategyConstant.SPRING_APPLICATION_STRATEGY_GATEWAY_SKYWALKING_TRACEID_ENABLED, Boolean.class, Boolean.TRUE); if (skywalkingTraceIdEnabled) { return new SkyWalkingGatewayStrategyFilter(); } return null;
103
98
201
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextHolder.java
GatewayStrategyContextHolder
getServerHttpRequest
class GatewayStrategyContextHolder extends AbstractStrategyContextHolder { public ServerWebExchange getExchange() { return GatewayStrategyContext.getCurrentContext().getExchange(); } public ServerHttpRequest getServerHttpRequest() {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getHeaderNames() { ServerHttpRequest request = getServerHttpRequest(); if (request == null) { return null; } Set<String> headerNameSet = request.getHeaders().keySet(); return Collections.enumeration(headerNameSet); } @Override public String getHeader(String name) { ServerHttpRequest request = getServerHttpRequest(); if (request == null) { return null; } return request.getHeaders().getFirst(name); } @Override public String getParameter(String name) { ServerHttpRequest request = getServerHttpRequest(); if (request == null) { return null; } return request.getQueryParams().getFirst(name); } public HttpCookie getHttpCookie(String name) { ServerHttpRequest request = getServerHttpRequest(); if (request == null) { return null; } return request.getCookies().getFirst(name); } @Override public String getCookie(String name) { HttpCookie cookie = getHttpCookie(name); if (cookie != null) { return cookie.getValue(); } return null; } public URI getURI() { ServerHttpRequest request = getServerHttpRequest(); if (request == null) { return null; } return request.getURI(); } }
ServerWebExchange exchange = getExchange(); if (exchange == null) { // LOG.warn("The ServerWebExchange object is lost for thread switched, or it is got before context filter probably"); return null; } ServerHttpRequest request = exchange.getRequest(); if (request == null) { // LOG.warn("The ServerHttpRequest object is lost for thread switched, or it is got before context filter probably"); return null; } return request;
455
126
581
<methods>public non-sealed void <init>() ,public java.lang.String getContext(java.lang.String) ,public java.lang.String getContextRouteAddress() ,public java.lang.String getContextRouteAddressBlacklist() ,public java.lang.String getContextRouteAddressFailover() ,public java.lang.String getContextRouteEnvironment() ,public java.lang.String getContextRouteEnvironmentFailover() ,public java.lang.String getContextRouteIdBlacklist() ,public java.lang.String getContextRouteRegion() ,public java.lang.String getContextRouteRegionFailover() ,public java.lang.String getContextRouteRegionTransfer() ,public java.lang.String getContextRouteRegionWeight() ,public java.lang.String getContextRouteVersion() ,public java.lang.String getContextRouteVersionFailover() ,public java.lang.String getContextRouteVersionPrefer() ,public java.lang.String getContextRouteVersionWeight() ,public java.lang.String getContextRouteZoneFailover() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public java.lang.String getRouteAddress() ,public java.lang.String getRouteAddressBlacklist() ,public java.lang.String getRouteAddressFailover() ,public java.lang.String getRouteEnvironment() ,public java.lang.String getRouteEnvironmentFailover() ,public java.lang.String getRouteIdBlacklist() ,public java.lang.String getRouteRegion() ,public java.lang.String getRouteRegionFailover() ,public java.lang.String getRouteRegionTransfer() ,public java.lang.String getRouteRegionWeight() ,public java.lang.String getRouteVersion() ,public java.lang.String getRouteVersionFailover() ,public java.lang.String getRouteVersionPrefer() ,public java.lang.String getRouteVersionWeight() ,public java.lang.String getRouteZoneFailover() ,public java.lang.String getSpanId() ,public com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper getStrategyWrapper() ,public java.lang.String getTraceId() <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext strategyMonitorContext,protected com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper strategyWrapper
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/context/GatewayStrategyContextListener.java
GatewayStrategyContextListener
onApplicationEvent
class GatewayStrategyContextListener implements ApplicationListener<ContextRefreshedEvent> { private static final Logger LOG = LoggerFactory.getLogger(GatewayStrategyContextListener.class); @Override public void onApplicationEvent(ContextRefreshedEvent event) {<FILL_FUNCTION_BODY>} }
// 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 LOG.info("Initialize Gateway Strategy Context after Application started..."); GatewayStrategyContext.getCurrentContext();
78
54
132
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/DefaultGatewayStrategyClearFilter.java
DefaultGatewayStrategyClearFilter
filter
class DefaultGatewayStrategyClearFilter implements GatewayStrategyClearFilter { @Autowired(required = false) protected GatewayStrategyMonitor gatewayStrategyMonitor; @Override public int getOrder() { return Ordered.LOWEST_PRECEDENCE - 1; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>} }
GatewayStrategyContext.clearCurrentContext(); // 调用链释放 if (gatewayStrategyMonitor != null) { gatewayStrategyMonitor.release(exchange); } return chain.filter(exchange);
115
61
176
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/GatewayStrategyFilterResolver.java
GatewayStrategyFilterResolver
setHeader
class GatewayStrategyFilterResolver { public static void setHeader(ServerHttpRequest request, ServerHttpRequest.Builder requestBuilder, String headerName, String headerValue, Boolean gatewayHeaderPriority) {<FILL_FUNCTION_BODY>} public static void ignoreHeader(ServerHttpRequest.Builder requestBuilder, String headerName, Boolean gatewayHeaderPriority, Boolean gatewayOriginalHeaderIgnored) { if (gatewayHeaderPriority && gatewayOriginalHeaderIgnored) { ignoreHeader(requestBuilder, headerName); } } public static void ignoreHeader(ServerHttpRequest.Builder requestBuilder, String headerName) { // 需要把外界的Header清除 requestBuilder.headers(headers -> headers.remove(headerName)); } }
if (StringUtils.isEmpty(headerValue)) { return; } if (gatewayHeaderPriority) { // 需要把外界的Header清除 requestBuilder.headers(headers -> headers.remove(headerName)); // 需要把内置的Header加入 requestBuilder.headers(headers -> headers.add(headerName, headerValue)); } else { // 非网关优先条件下,判断外界请求是否含有Header // 如果含有,则不加入内置的Header if (!request.getHeaders().containsKey(headerName)) { requestBuilder.headers(headers -> headers.add(headerName, headerValue)); } }
178
174
352
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/filter/SkyWalkingGatewayStrategyFilter.java
SkyWalkingGatewayStrategyFilter
filter
class SkyWalkingGatewayStrategyFilter implements GatewayStrategyFilter { public static final String SKYWALING_SPAN = "SKYWALING_SPAN"; public static final String OWNER = "owner"; @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {<FILL_FUNCTION_BODY>} private String getTraceId(AbstractTracingSpan tracingSpan) throws Exception { if (tracingSpan == null) { return null; } Object owner = ReflectionUtil.getValue(AbstractTracingSpan.class, tracingSpan, OWNER); if (owner instanceof TracingContext) { TracingContext tracingContext = (TracingContext) owner; return tracingContext.getReadablePrimaryTraceId(); } return null; } }
String traceId = null; try { EntrySpan entrySpan = exchange.getAttribute(SKYWALING_SPAN); traceId = getTraceId(entrySpan); } catch (Exception e) { } StrategySpan strategySpan = new StrategySpan(); strategySpan.setTraceId(traceId != null ? traceId : DiscoveryConstant.IGNORED); strategySpan.setSpanId(DiscoveryConstant.IGNORED); StrategyTracerContext.getCurrentContext().setSpan(strategySpan); return chain.filter(exchange);
249
151
400
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-gateway/src/main/java/com/nepxion/discovery/plugin/strategy/gateway/wrapper/DefaultGatewayStrategyCallableWrapper.java
DefaultGatewayStrategyCallableWrapper
wrapCallable
class DefaultGatewayStrategyCallableWrapper implements GatewayStrategyCallableWrapper { @Override public <T> Callable<T> wrapCallable(Callable<T> callable) {<FILL_FUNCTION_BODY>} }
ServerWebExchange exchange = GatewayStrategyContext.getCurrentContext().getExchange(); Object span = StrategyTracerContext.getCurrentContext().getSpan(); return new Callable<T>() { @Override public T call() throws Exception { try { GatewayStrategyContext.getCurrentContext().setExchange(exchange); StrategyTracerContext.getCurrentContext().setSpan(span); return callable.call(); } finally { GatewayStrategyContext.clearCurrentContext(); StrategyTracerContext.clearCurrentContext(); } } };
60
155
215
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/opentelemetry/monitor/OpenTelemetryStrategyTracer.java
OpenTelemetryStrategyTracer
errorSpan
class OpenTelemetryStrategyTracer extends AbstractStrategyTracer<Span> { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") protected Boolean tracerExceptionDetailOutputEnabled; @Autowired private Tracer tracer; @Override protected Span buildSpan() { return tracer.spanBuilder(tracerSpanValue).startSpan(); } @Override protected void outputSpan(Span span, String key, String value) { span.setAttribute(key, value); } @Override protected void errorSpan(Span span, Throwable e) {<FILL_FUNCTION_BODY>} @Override protected void finishSpan(Span span) { span.end(); } // Never used probably @Override protected Span getActiveSpan() { return null; } @Override protected String toTraceId(Span span) { return span.getSpanContext().getTraceId(); } @Override protected String toSpanId(Span span) { return span.getSpanContext().getSpanId(); } }
span.setAttribute(DiscoveryConstant.EVENT, DiscoveryConstant.ERROR); if (tracerExceptionDetailOutputEnabled) { span.setAttribute(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); } else { span.recordException(e); }
318
76
394
<methods>public non-sealed void <init>() ,public java.lang.String getSpanId() ,public java.lang.String getTraceId() ,public void spanBuild() ,public void spanError(java.lang.Throwable) ,public void spanFinish() ,public void spanOutput(Map<java.lang.String,java.lang.String>) <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext strategyMonitorContext,protected java.lang.Boolean tracerEnabled,protected java.lang.Boolean tracerRuleOutputEnabled,protected java.lang.Boolean tracerSeparateSpanEnabled,protected java.lang.String tracerSpanPluginValue,protected java.lang.String tracerSpanValue
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-opentracing/src/main/java/com/nepxion/discovery/plugin/strategy/opentracing/monitor/OpenTracingStrategyTracer.java
OpenTracingStrategyTracer
errorSpan
class OpenTracingStrategyTracer extends AbstractStrategyTracer<Span> { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") protected Boolean tracerExceptionDetailOutputEnabled; @Autowired private Tracer tracer; @Override protected Span buildSpan() { return tracer.buildSpan(tracerSpanValue).start(); } @Override protected void outputSpan(Span span, String key, String value) { span.setTag(key, value); } @Override protected void errorSpan(Span span, Throwable e) {<FILL_FUNCTION_BODY>} @Override protected void finishSpan(Span span) { span.finish(); } @Override protected Span getActiveSpan() { return tracer.activeSpan(); } @Override protected String toTraceId(Span span) { return span.context().toTraceId(); } @Override protected String toSpanId(Span span) { return span.context().toSpanId(); } }
Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put(DiscoveryConstant.EVENT, DiscoveryConstant.ERROR); if (tracerExceptionDetailOutputEnabled) { map.put(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); } else { map.put(DiscoveryConstant.ERROR_OBJECT, e); } span.log(map);
310
110
420
<methods>public non-sealed void <init>() ,public java.lang.String getSpanId() ,public java.lang.String getTraceId() ,public void spanBuild() ,public void spanError(java.lang.Throwable) ,public void spanFinish() ,public void spanOutput(Map<java.lang.String,java.lang.String>) <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext strategyMonitorContext,protected java.lang.Boolean tracerEnabled,protected java.lang.Boolean tracerRuleOutputEnabled,protected java.lang.Boolean tracerSeparateSpanEnabled,protected java.lang.String tracerSpanPluginValue,protected java.lang.String tracerSpanValue
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-datasource/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/datasource/loader/SentinelStrategyRuleLoader.java
SentinelStrategyRuleLoader
loadFileRules
class SentinelStrategyRuleLoader { private static final Logger LOG = LoggerFactory.getLogger(SentinelStrategyRuleLoader.class); @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_FLOW_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_FLOW_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") private String sentinelStrategyFlowPath; @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_DEGRADE_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_DEGRADE_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") private String sentinelStrategyDegradePath; @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_AUTHORITY_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_AUTHORITY_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") private String sentinelStrategyAuthorityPath; @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_SYSTEM_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_SYSTEM_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") private String sentinelStrategySystemPath; @Value("${" + SentinelStrategyDataSourceConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_PARAM_FLOW_PATH + ":" + DiscoveryConstant.PREFIX_CLASSPATH + DiscoveryConstant.SENTINEL_PARAM_FLOW_KEY + "." + DiscoveryConstant.JSON_FORMAT + "}") private String sentinelStrategyParamFlowPath; @Autowired private SentinelStrategyFlowRuleParser sentinelStrategyFlowRuleParser; @Autowired private SentinelStrategyDegradeRuleParser sentinelStrategyDegradeRuleParser; @Autowired private SentinelStrategyAuthorityRuleParser sentinelStrategyAuthorityRuleParser; @Autowired private SentinelStrategySystemRuleParser sentinelStrategySystemRuleParser; @Autowired private SentinelStrategyParamFlowRuleParser sentinelStrategyParamFlowRuleParser; @Autowired private ApplicationContext applicationContext; private boolean sentinelStrategyFlowRuleRetrieved = false; private boolean sentinelStrategyDegradeRuleRetrieved = false; private boolean sentinelStrategyAuthorityRuleRetrieved = false; private boolean sentinelStrategySystemRuleRetrieved = false; private boolean sentinelStrategyParamFlowRuleRetrieved = false; public void loadFileRules(SentinelRuleType sentinelRuleType) {<FILL_FUNCTION_BODY>} public void loadRules(SentinelRuleType sentinelRuleType, String sentinelStrategyRule) { if (StringUtils.isBlank(sentinelStrategyRule)) { sentinelStrategyRule = DiscoveryConstant.EMPTY_JSON_RULE_MULTIPLE; } String ruleTypeDescription = sentinelRuleType.getDescription(); switch (sentinelRuleType) { case FLOW: FlowRuleManager.loadRules(sentinelStrategyFlowRuleParser.convert(sentinelStrategyRule)); sentinelStrategyFlowRuleRetrieved = true; LOG.info("Loaded {} count={}", ruleTypeDescription, FlowRuleManager.getRules().size()); break; case DEGRADE: DegradeRuleManager.loadRules(sentinelStrategyDegradeRuleParser.convert(sentinelStrategyRule)); sentinelStrategyDegradeRuleRetrieved = true; LOG.info("Loaded {} count={}", ruleTypeDescription, DegradeRuleManager.getRules().size()); break; case AUTHORITY: AuthorityRuleManager.loadRules(sentinelStrategyAuthorityRuleParser.convert(sentinelStrategyRule)); sentinelStrategyAuthorityRuleRetrieved = true; LOG.info("Loaded {} count={}", ruleTypeDescription, AuthorityRuleManager.getRules().size()); break; case SYSTEM: SystemRuleManager.loadRules(sentinelStrategySystemRuleParser.convert(sentinelStrategyRule)); sentinelStrategySystemRuleRetrieved = true; LOG.info("Loaded {} count={}", ruleTypeDescription, SystemRuleManager.getRules().size()); break; case PARAM_FLOW: ParamFlowRuleManager.loadRules(sentinelStrategyParamFlowRuleParser.convert(sentinelStrategyRule)); sentinelStrategyParamFlowRuleRetrieved = true; LOG.info("Loaded {} count={}", ruleTypeDescription, ParamFlowRuleManager.getRules().size()); break; } } public String getRules(String path) { return FileUtil.getText(applicationContext, path); } }
String ruleTypeDescription = sentinelRuleType.getDescription(); switch (sentinelRuleType) { case FLOW: if (!sentinelStrategyFlowRuleRetrieved) { String sentinelStrategyRule = getRules(sentinelStrategyFlowPath); if (StringUtils.isNotBlank(sentinelStrategyRule)) { loadRules(sentinelRuleType, sentinelStrategyRule); } } else { LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); } break; case DEGRADE: if (!sentinelStrategyDegradeRuleRetrieved) { String sentinelStrategyRule = getRules(sentinelStrategyDegradePath); if (StringUtils.isNotBlank(sentinelStrategyRule)) { loadRules(sentinelRuleType, sentinelStrategyRule); } } else { LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); } break; case AUTHORITY: if (!sentinelStrategyAuthorityRuleRetrieved) { String sentinelStrategyRule = getRules(sentinelStrategyAuthorityPath); if (StringUtils.isNotBlank(sentinelStrategyRule)) { loadRules(sentinelRuleType, sentinelStrategyRule); } } else { LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); } break; case SYSTEM: if (!sentinelStrategySystemRuleRetrieved) { String sentinelStrategyRule = getRules(sentinelStrategySystemPath); if (StringUtils.isNotBlank(sentinelStrategyRule)) { loadRules(sentinelRuleType, sentinelStrategyRule); } } else { LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); } break; case PARAM_FLOW: if (!sentinelStrategyParamFlowRuleRetrieved) { String sentinelStrategyRule = getRules(sentinelStrategyParamFlowPath); if (StringUtils.isNotBlank(sentinelStrategyRule)) { loadRules(sentinelRuleType, sentinelStrategyRule); } } else { LOG.info("{} is retrieved from remote config, ignore to load from file...", ruleTypeDescription); } break; }
1,328
634
1,962
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-limiter/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/limiter/parser/SentinelStrategyRequestOriginParser.java
SentinelStrategyRequestOriginParser
parseOrigin
class SentinelStrategyRequestOriginParser implements RequestOriginParser { @Value("${" + SentinelStrategyLimiterConstant.SPRING_APPLICATION_STRATEGY_SENTINEL_REQUEST_ORIGIN_KEY + ":" + DiscoveryConstant.N_D_SERVICE_ID + "}") protected String requestOriginKey; @Autowired(required = false) protected SentinelStrategyRequestOriginAdapter sentinelStrategyRequestOriginAdapter; public SentinelStrategyRequestOriginParser() { WebCallbackManager.setRequestOriginParser(this); } @Override public String parseOrigin(HttpServletRequest request) {<FILL_FUNCTION_BODY>} }
if (sentinelStrategyRequestOriginAdapter != null) { return sentinelStrategyRequestOriginAdapter.parseOrigin(request); } else { String requestOriginValue = request.getHeader(requestOriginKey); return StringUtils.isNotEmpty(requestOriginValue) ? requestOriginValue : DiscoveryConstant.UNKNOWN; }
175
88
263
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricExtension.java
SentinelMicrometerMetricExtension
addBlock
class SentinelMicrometerMetricExtension implements MetricExtension { @Override public void addPass(String resource, int n, Object... args) { Environment environment = PluginContextAware.getStaticEnvironment(); Boolean metricSentinelPassQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_PASS_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); if (metricSentinelPassQpsOutputEnabled) { Metrics.counter(SentinelMetricType.PASS_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); } } @Override public void addBlock(String resource, int n, String origin, BlockException blockException, Object... args) {<FILL_FUNCTION_BODY>} @Override public void addSuccess(String resource, int n, Object... args) { Environment environment = PluginContextAware.getStaticEnvironment(); Boolean metricSentinelSuccessQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_SUCCESS_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); if (metricSentinelSuccessQpsOutputEnabled) { Metrics.counter(SentinelMetricType.SUCCESS_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); } } @Override public void addException(String resource, int n, Throwable throwable) { Environment environment = PluginContextAware.getStaticEnvironment(); Boolean metricSentinelExceptionQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_EXCEPTION_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); if (metricSentinelExceptionQpsOutputEnabled) { Metrics.counter(SentinelMetricType.EXCEPTION_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); } } @Override public void addRt(String resource, long rt, Object... args) { } @Override public void increaseThreadNum(String resource, Object... args) { } @Override public void decreaseThreadNum(String resource, Object... args) { } }
Environment environment = PluginContextAware.getStaticEnvironment(); Boolean metricSentinelBlockQpsOutputEnabled = environment.getProperty(SentinelMicrometerMetricConstant.SPRING_APPLICATION_STRATEGY_METRIC_SENTINEL_BLOCK_QPS_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); if (metricSentinelBlockQpsOutputEnabled) { Metrics.counter(SentinelMetricType.BLOCK_QPS.toString(), SentinelMicrometerMetricConstant.RESOURCE, resource).increment(n); }
669
152
821
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-micrometer/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/micrometer/monitor/metric/SentinelMicrometerMetricInitializer.java
SentinelMicrometerMetricInitializer
initialize
class SentinelMicrometerMetricInitializer { @Autowired private MeterRegistry registry; @PostConstruct public void initialize() {<FILL_FUNCTION_BODY>} }
for (SentinelMetricType sentinelMetricType : SentinelMetricType.values()) { Counter.builder(sentinelMetricType.toString()).tag(SentinelMicrometerMetricConstant.RESOURCE, StringUtils.EMPTY).register(registry); }
55
78
133
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-monitor/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/monitor/callback/SentinelTracerProcessorSlotEntryCallback.java
SentinelTracerProcessorSlotEntryCallback
onBlocked
class SentinelTracerProcessorSlotEntryCallback<S> implements ProcessorSlotEntryCallback<DefaultNode> { @Override public void onPass(Context context, ResourceWrapper resourceWrapper, DefaultNode param, int count, Object... args) throws Exception { } @Override public void onBlocked(BlockException e, Context context, ResourceWrapper resourceWrapper, DefaultNode param, int count, Object... args) {<FILL_FUNCTION_BODY>} protected abstract S buildSpan(); protected abstract void outputSpan(S span, String key, String value); protected abstract void finishSpan(S span); }
S span = buildSpan(); ApplicationContext applicationContext = PluginContextAware.getStaticApplicationContext(); PluginAdapter pluginAdapter = applicationContext.getBean(PluginAdapter.class); Environment staticEnvironment = PluginContextAware.getStaticEnvironment(); Boolean tracerSentinelRuleOutputEnabled = staticEnvironment.getProperty(SentinelStrategyMonitorConstant.SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_RULE_OUTPUT_ENABLED, Boolean.class, Boolean.TRUE); Boolean tracerSentinelArgsOutputEnabled = staticEnvironment.getProperty(SentinelStrategyMonitorConstant.SPRING_APPLICATION_STRATEGY_TRACER_SENTINEL_ARGS_OUTPUT_ENABLED, Boolean.class, Boolean.FALSE); outputSpan(span, DiscoveryConstant.SPAN_TAG_PLUGIN_NAME, context.getName()); outputSpan(span, DiscoveryConstant.N_D_SERVICE_GROUP, pluginAdapter.getGroup()); outputSpan(span, DiscoveryConstant.N_D_SERVICE_TYPE, pluginAdapter.getServiceType()); String serviceAppId = pluginAdapter.getServiceAppId(); if (StringUtils.isNotEmpty(serviceAppId)) { outputSpan(span, DiscoveryConstant.N_D_SERVICE_APP_ID, serviceAppId); } outputSpan(span, DiscoveryConstant.N_D_SERVICE_ID, pluginAdapter.getServiceId()); outputSpan(span, DiscoveryConstant.N_D_SERVICE_ADDRESS, pluginAdapter.getHost() + ":" + pluginAdapter.getPort()); String version = pluginAdapter.getVersion(); if (StringUtils.isNotEmpty(version) && !StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { outputSpan(span, DiscoveryConstant.N_D_SERVICE_VERSION, version); } String region = pluginAdapter.getRegion(); if (StringUtils.isNotEmpty(region) && !StringUtils.equals(region, DiscoveryConstant.DEFAULT)) { outputSpan(span, DiscoveryConstant.N_D_SERVICE_REGION, region); } String environment = pluginAdapter.getEnvironment(); if (StringUtils.isNotEmpty(environment) && !StringUtils.equals(environment, DiscoveryConstant.DEFAULT)) { outputSpan(span, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT, environment); } String zone = pluginAdapter.getZone(); if (StringUtils.isNotEmpty(zone) && !StringUtils.equals(zone, DiscoveryConstant.DEFAULT)) { outputSpan(span, DiscoveryConstant.N_D_SERVICE_ZONE, zone); } outputSpan(span, SentinelStrategyMonitorConstant.ORIGIN, context.getOrigin()); outputSpan(span, SentinelStrategyMonitorConstant.ASYNC, String.valueOf(context.isAsync())); outputSpan(span, SentinelStrategyMonitorConstant.RESOURCE_NAME, resourceWrapper.getName()); outputSpan(span, SentinelStrategyMonitorConstant.RESOURCE_SHOW_NAME, resourceWrapper.getShowName()); outputSpan(span, SentinelStrategyMonitorConstant.RESOURCE_TYPE, String.valueOf(resourceWrapper.getResourceType())); outputSpan(span, SentinelStrategyMonitorConstant.ENTRY_TYPE, resourceWrapper.getEntryType().toString()); outputSpan(span, SentinelStrategyMonitorConstant.RULE_LIMIT_APP, e.getRuleLimitApp()); if (tracerSentinelRuleOutputEnabled) { outputSpan(span, SentinelStrategyMonitorConstant.RULE, e.getRule() != null ? e.getRule().toString() : StringUtils.EMPTY); } outputSpan(span, SentinelStrategyMonitorConstant.CAUSE, e.getClass().getName()); outputSpan(span, SentinelStrategyMonitorConstant.BLOCK_EXCEPTION, e.getMessage()); outputSpan(span, SentinelStrategyMonitorConstant.COUNT, String.valueOf(count)); if (tracerSentinelArgsOutputEnabled) { outputSpan(span, SentinelStrategyMonitorConstant.ARGS, JSON.toJSONString(args)); } finishSpan(span);
154
1,039
1,193
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-sentinel-opentelemetry/src/main/java/com/nepxion/discovery/plugin/strategy/sentinel/opentelemetry/monitor/SentinelOpenTelemetryProcessorSlotEntryCallback.java
SentinelOpenTelemetryProcessorSlotEntryCallback
buildSpan
class SentinelOpenTelemetryProcessorSlotEntryCallback extends SentinelTracerProcessorSlotEntryCallback<Span> { public static final String INSTRUMENTATION_NAME = "opentelemetry.trace.tracer.name"; @Override protected Span buildSpan() {<FILL_FUNCTION_BODY>} @Override protected void outputSpan(Span span, String key, String value) { span.setAttribute(key, value); } @Override protected void finishSpan(Span span) { span.end(); } }
Environment environment = PluginContextAware.getStaticEnvironment(); String instrumentationName = environment.getProperty(INSTRUMENTATION_NAME, String.class, SentinelStrategyMonitorConstant.TRACER_NAME); return GlobalOpenTelemetry.getTracer(instrumentationName).spanBuilder(SentinelStrategyMonitorConstant.SPAN_NAME).startSpan();
146
92
238
<methods>public non-sealed void <init>() ,public transient void onBlocked(BlockException, Context, ResourceWrapper, DefaultNode, int, java.lang.Object[]) ,public transient void onPass(Context, ResourceWrapper, DefaultNode, int, java.lang.Object[]) throws java.lang.Exception<variables>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/configuration/ServiceStrategyAutoConfiguration.java
ServiceStrategyAutoConfiguration
getInjectorScanPackages
class ServiceStrategyAutoConfiguration { @Autowired private ConfigurableEnvironment environment; @Autowired private StrategyPackagesExtractor strategyPackagesExtractor; @Autowired(required = false) private List<StrategyPackagesInjector> strategyPackagesInjectorList; @Bean @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED, matchIfMissing = false) public ServiceRpcStrategyAutoScanProxy serviceRpcStrategyAutoScanProxy() { String scanPackages = getConfigScanPackages(); scanPackages = getInjectorScanPackages(scanPackages, PackagesInjectorType.RPC); if (StringUtils.isEmpty(scanPackages)) { throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); } return new ServiceRpcStrategyAutoScanProxy(scanPackages); } @Bean @ConditionalOnProperty(value = ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_RPC_INTERCEPT_ENABLED, matchIfMissing = false) public ServiceRpcStrategyInterceptor serviceRpcStrategyInterceptor() { return new ServiceRpcStrategyInterceptor(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, matchIfMissing = false) public ServiceProviderIsolationStrategyAutoScanProxy serviceProviderIsolationStrategyAutoScanProxy() { String scanPackages = getConfigScanPackages(); scanPackages = getInjectorScanPackages(scanPackages, PackagesInjectorType.PROVIDER_ISOLATION); if (StringUtils.isEmpty(scanPackages)) { throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); } return new ServiceProviderIsolationStrategyAutoScanProxy(scanPackages); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_PROVIDER_ISOLATION_ENABLED, matchIfMissing = false) public ServiceProviderIsolationStrategyInterceptor serviceProviderIsolationStrategyInterceptor() { return new ServiceProviderIsolationStrategyInterceptor(); } @Bean @ConditionalOnMissingBean public ServiceStrategyRouteFilter serviceStrategyRouteFilter() { return new DefaultServiceStrategyRouteFilter(); } @Bean @ConditionalOnMissingBean public ServiceStrategyFilterExclusion serviceStrategyFilterExclusion() { return new DefaultServiceStrategyFilterExclusion(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) public ServiceStrategyMonitor serviceStrategyMonitor() { return new DefaultServiceStrategyMonitor(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) public ServiceStrategyMonitorAutoScanProxy serviceStrategyMonitorAutoScanProxy() { String scanPackages = getConfigScanPackages(); scanPackages = getInjectorScanPackages(scanPackages, PackagesInjectorType.TRACER); scanPackages = getEndpointScanPackages(scanPackages); if (StringUtils.isEmpty(scanPackages)) { throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't be empty"); } return new ServiceStrategyMonitorAutoScanProxy(scanPackages); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_MONITOR_ENABLED, matchIfMissing = false) public ServiceStrategyMonitorInterceptor serviceStrategyMonitorInterceptor() { return new ServiceStrategyMonitorInterceptor(); } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(value = StrategyConstant.SPRING_APPLICATION_STRATEGY_HYSTRIX_THREADLOCAL_SUPPORTED, matchIfMissing = false) public ServiceStrategyCallableWrapper serviceStrategyCallableWrapper() { return new DefaultServiceStrategyCallableWrapper(); } @Bean public ServiceStrategyContextListener serviceStrategyContextListener() { return new ServiceStrategyContextListener(); } public String getConfigScanPackages() { String scanPackages = environment.getProperty(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES, StringUtils.EMPTY); if (StringUtils.isNotEmpty(scanPackages)) { if (scanPackages.endsWith(DiscoveryConstant.SEPARATE)) { throw new DiscoveryException(ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SCAN_PACKAGES + "'s value can't end with '" + DiscoveryConstant.SEPARATE + "'"); } } else { scanPackages = strategyPackagesExtractor.getAllPackages(); } return scanPackages; } public String getInjectorScanPackages(String scanPackages, PackagesInjectorType packagesInjectorType) {<FILL_FUNCTION_BODY>} public String getEndpointScanPackages(String scanPackages) { List<String> scanPackageList = new ArrayList<String>(StringUtil.splitToList(scanPackages)); if (!scanPackageList.contains(DiscoveryConstant.ENDPOINT_SCAN_PACKAGES)) { scanPackageList.add(DiscoveryConstant.ENDPOINT_SCAN_PACKAGES); } return StringUtil.convertToString(scanPackageList); } }
List<String> scanPackageList = new ArrayList<String>(StringUtil.splitToList(scanPackages)); List<String> packageList = StrategyPackagesResolver.getInjectedPackages(strategyPackagesInjectorList, packagesInjectorType); if (CollectionUtils.isNotEmpty(packageList)) { for (String pkg : packageList) { if (!scanPackageList.contains(pkg)) { scanPackageList.add(pkg); } } } return StringUtil.convertToString(scanPackageList);
1,552
140
1,692
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextHolder.java
ServiceStrategyContextHolder
getHttpCookie
class ServiceStrategyContextHolder extends AbstractStrategyContextHolder { // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以服务设置为优先,否则以外界传值为优先 @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_SERVICE_HEADER_PRIORITY + ":true}") protected Boolean serviceHeaderPriority; public ServletRequestAttributes getRestAttributes() { RequestAttributes requestAttributes = RestStrategyContext.getCurrentContext().getRequestAttributes(); if (requestAttributes == null) { requestAttributes = RequestContextHolder.getRequestAttributes(); } return (ServletRequestAttributes) requestAttributes; } public Map<String, Object> getRpcAttributes() { return RpcStrategyContext.getCurrentContext().getAttributes(); } public HttpServletRequest getHttpServletRequest() { ServletRequestAttributes attributes = getRestAttributes(); if (attributes == null) { // LOG.warn("The ServletRequestAttributes object is lost for thread switched probably"); return null; } HttpServletRequest request = attributes.getRequest(); if (request == null) { // LOG.warn("The HttpServletRequest object is lost for thread switched probably"); return null; } return request; } @Override public Enumeration<String> getHeaderNames() { HttpServletRequest request = getHttpServletRequest(); if (request == null) { return null; } Enumeration<String> headerNames = request.getHeaderNames(); Map<String, String> headerMap = strategyWrapper.getHeaderMap(); if (MapUtils.isNotEmpty(headerMap)) { List<String> headerNameList = Collections.list(headerNames); for (Map.Entry<String, String> entry : headerMap.entrySet()) { String headerName = entry.getKey(); if (!headerNameList.contains(headerName)) { headerNameList.add(headerName); } } return Collections.enumeration(headerNameList); } return headerNames; } @Override public String getHeader(String name) { if (serviceHeaderPriority) { String header = strategyWrapper.getHeader(name); if (StringUtils.isEmpty(header)) { HttpServletRequest request = getHttpServletRequest(); if (request != null) { header = request.getHeader(name); } } return header; } else { String header = null; HttpServletRequest request = getHttpServletRequest(); if (request != null) { header = request.getHeader(name); } if (StringUtils.isEmpty(header)) { header = strategyWrapper.getHeader(name); } return header; } } @Override public String getParameter(String name) { HttpServletRequest request = getHttpServletRequest(); if (request == null) { return null; } return request.getParameter(name); } public Cookie getHttpCookie(String name) {<FILL_FUNCTION_BODY>} @Override public String getCookie(String name) { Cookie cookie = getHttpCookie(name); if (cookie != null) { return cookie.getValue(); } return null; } public String getRequestURL() { HttpServletRequest request = getHttpServletRequest(); if (request == null) { return null; } return request.getRequestURL().toString(); } public String getRequestURI() { HttpServletRequest request = getHttpServletRequest(); if (request == null) { return null; } return request.getRequestURI(); } }
HttpServletRequest request = getHttpServletRequest(); if (request == null) { return null; } Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String cookieName = cookie.getName(); if (StringUtils.equals(cookieName, name)) { return cookie; } } return null;
984
137
1,121
<methods>public non-sealed void <init>() ,public java.lang.String getContext(java.lang.String) ,public java.lang.String getContextRouteAddress() ,public java.lang.String getContextRouteAddressBlacklist() ,public java.lang.String getContextRouteAddressFailover() ,public java.lang.String getContextRouteEnvironment() ,public java.lang.String getContextRouteEnvironmentFailover() ,public java.lang.String getContextRouteIdBlacklist() ,public java.lang.String getContextRouteRegion() ,public java.lang.String getContextRouteRegionFailover() ,public java.lang.String getContextRouteRegionTransfer() ,public java.lang.String getContextRouteRegionWeight() ,public java.lang.String getContextRouteVersion() ,public java.lang.String getContextRouteVersionFailover() ,public java.lang.String getContextRouteVersionPrefer() ,public java.lang.String getContextRouteVersionWeight() ,public java.lang.String getContextRouteZoneFailover() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public java.lang.String getRouteAddress() ,public java.lang.String getRouteAddressBlacklist() ,public java.lang.String getRouteAddressFailover() ,public java.lang.String getRouteEnvironment() ,public java.lang.String getRouteEnvironmentFailover() ,public java.lang.String getRouteIdBlacklist() ,public java.lang.String getRouteRegion() ,public java.lang.String getRouteRegionFailover() ,public java.lang.String getRouteRegionTransfer() ,public java.lang.String getRouteRegionWeight() ,public java.lang.String getRouteVersion() ,public java.lang.String getRouteVersionFailover() ,public java.lang.String getRouteVersionPrefer() ,public java.lang.String getRouteVersionWeight() ,public java.lang.String getRouteZoneFailover() ,public java.lang.String getSpanId() ,public com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper getStrategyWrapper() ,public java.lang.String getTraceId() <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext strategyMonitorContext,protected com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper strategyWrapper
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/context/ServiceStrategyContextListener.java
ServiceStrategyContextListener
onApplicationEvent
class ServiceStrategyContextListener implements ApplicationListener<ContextRefreshedEvent> { private static final Logger LOG = LoggerFactory.getLogger(ServiceStrategyContextListener.class); @Override public void onApplicationEvent(ContextRefreshedEvent event) {<FILL_FUNCTION_BODY>} }
// 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 LOG.info("Initialize Service Strategy Context after Application started..."); RestStrategyContext.getCurrentContext(); RpcStrategyContext.getCurrentContext();
75
63
138
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecorator.java
ServiceStrategyRequestDecorator
getHeaders
class ServiceStrategyRequestDecorator extends HttpServletRequestWrapper { private Map<String, List<String>> headers; public ServiceStrategyRequestDecorator(HttpServletRequest request) { super(request); headers = initializeHeaders(request); } private Map<String, List<String>> initializeHeaders(HttpServletRequest request) { // 不区分大小写Key的Map用于适配不同的Web容器对于大小写Header的不同处理逻辑 Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<List<String>>(); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); if (headerName != null) { headers.put(headerName, Collections.list(request.getHeaders(headerName))); } } return headers; } @Override public String getHeader(String name) { List<String> headerValues = headers.get(name); return CollectionUtils.isEmpty(headerValues) ? null : headerValues.get(0); } @Override public Enumeration<String> getHeaders(String name) {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(headers.keySet()); } }
List<String> headerValues = headers.get(name); return Collections.enumeration(headerValues != null ? headerValues : Collections.emptySet());
352
44
396
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/decorator/ServiceStrategyRequestDecoratorFactory.java
ServiceStrategyRequestDecoratorFactory
decorateRequestAttributes
class ServiceStrategyRequestDecoratorFactory { public static RequestAttributes decorateRequestAttributes(RequestAttributes requestAttributes) {<FILL_FUNCTION_BODY>} }
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); return new ServletRequestAttributes(new ServiceStrategyRequestDecorator(request));
41
41
82
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/DefaultServiceStrategyFilterExclusion.java
DefaultServiceStrategyFilterExclusion
isExclusion
class DefaultServiceStrategyFilterExclusion implements ServiceStrategyFilterExclusion { @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_URI_FILTER_EXCLUSION + ":/actuator/}") protected String uriFilterExclusion; protected List<String> uriFilterExclusionList = new ArrayList<String>(); @PostConstruct public void initialize() { if (StringUtils.isNotEmpty(uriFilterExclusion)) { uriFilterExclusionList = StringUtil.splitToList(uriFilterExclusion); } } @Override public boolean isExclusion(HttpServletRequest request, HttpServletResponse response) {<FILL_FUNCTION_BODY>} }
String requestURI = request.getRequestURI(); for (String uriFilterExclusionValue : uriFilterExclusionList) { if (requestURI.contains(uriFilterExclusionValue)) { return true; } } return false;
182
67
249
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyFilterResolver.java
ServiceStrategyFilterResolver
setHeader
class ServiceStrategyFilterResolver { public static void setHeader(ServiceStrategyRouteFilterRequest serviceStrategyRouteFilterRequest, String headerName, String headerValue, Boolean serviceHeaderPriority) {<FILL_FUNCTION_BODY>} }
if (StringUtils.isEmpty(headerValue)) { return; } // 内置策略,例如,AbstractServiceStrategyRouteFilter中String routeVersion = getRouteVersion();是从strategyWrapper.getRouteVersion()获取 // 服务设置为优先的时候,直接把内置策略加入。在负载均衡前,通过OncePerRequestFilter装饰方式代替掉外界的Header if (serviceHeaderPriority) { serviceStrategyRouteFilterRequest.addHeader(headerName, headerValue); } else { // 外界传值为优先的时候,外界已传值,则返回;外界未传值,则需要把内置策略加入 String originalHeaderValue = serviceStrategyRouteFilterRequest.getOriginalRequest().getHeader(headerName); if (StringUtils.isEmpty(originalHeaderValue)) { serviceStrategyRouteFilterRequest.addHeader(headerName, headerValue); } }
54
223
277
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/filter/ServiceStrategyRouteFilterRequest.java
ServiceStrategyRouteFilterRequest
getHeaderNames
class ServiceStrategyRouteFilterRequest extends HttpServletRequestWrapper { private HttpServletRequest originalRequest; private Map<String, String> headers; public ServiceStrategyRouteFilterRequest(HttpServletRequest request) { super(request); this.originalRequest = request; // 不区分大小写Key的Map用于适配不同的Web容器对于大小写Header的不同处理逻辑 headers = new LinkedCaseInsensitiveMap<String>(); } public void addHeader(String name, String value) { headers.put(name, value); } @Override public String getHeader(String name) { if (headers.containsKey(name)) { return headers.get(name); } return super.getHeader(name); } @Override public Enumeration<String> getHeaderNames() {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getHeaders(String name) { if (headers.containsKey(name)) { List<String> values = Arrays.asList(headers.get(name)); return Collections.enumeration(values); } return super.getHeaders(name); } public HttpServletRequest getOriginalRequest() { return originalRequest; } }
if (MapUtils.isNotEmpty(headers)) { List<String> names = Collections.list(super.getHeaderNames()); for (String name : headers.keySet()) { if (!names.contains(name)) { names.add(name); } } return Collections.enumeration(names); } return super.getHeaderNames();
330
100
430
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyAutoScanProxy.java
ServiceProviderIsolationStrategyAutoScanProxy
getCommonInterceptorNames
class ServiceProviderIsolationStrategyAutoScanProxy extends DefaultAutoScanProxy { private static final long serialVersionUID = 6147822053647878553L; private String[] commonInterceptorNames; @SuppressWarnings("rawtypes") private Class[] classAnnotations; public ServiceProviderIsolationStrategyAutoScanProxy(String scanPackages) { super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); } @Override protected String[] getCommonInterceptorNames() {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") @Override protected Class<? extends Annotation>[] getClassAnnotations() { if (classAnnotations == null) { classAnnotations = new Class[] { RestController.class, ServiceStrategy.class }; } return classAnnotations; } }
if (commonInterceptorNames == null) { commonInterceptorNames = new String[] { "serviceProviderIsolationStrategyInterceptor" }; } return commonInterceptorNames;
251
52
303
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/isolation/ServiceProviderIsolationStrategyInterceptor.java
ServiceProviderIsolationStrategyInterceptor
invoke
class ServiceProviderIsolationStrategyInterceptor extends AbstractInterceptor { @Autowired protected PluginAdapter pluginAdapter; @Autowired protected ServiceStrategyContextHolder serviceStrategyContextHolder; @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
boolean hasInitBinderAnnotation = getMethod(invocation).isAnnotationPresent(InitBinder.class); if (hasInitBinderAnnotation) { return invocation.proceed(); } // N_D_SERVICE_GROUP的Header属于上游服务传入 String groupHeader = serviceStrategyContextHolder.getHeader(DiscoveryConstant.N_D_SERVICE_GROUP); if (StringUtils.isEmpty(groupHeader)) { // N_D_GROUP的Header属于外部URL调用传入 groupHeader = serviceStrategyContextHolder.getHeader(DiscoveryConstant.N_D_GROUP); } String group = pluginAdapter.getGroup(); String serviceId = pluginAdapter.getServiceId(); if (!StringUtils.equals(groupHeader, group)) { throw new DiscoveryException("Reject to invoke because of isolation with different group for serviceId=" + serviceId); } return invocation.proceed();
86
234
320
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/DefaultServiceStrategyMonitor.java
DefaultServiceStrategyMonitor
createContextMap
class DefaultServiceStrategyMonitor extends StrategyMonitor implements ServiceStrategyMonitor { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_ENABLED + ":false}") protected Boolean tracerEnabled; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_METHOD_CONTEXT_OUTPUT_ENABLED + ":false}") protected Boolean tracerMethodContextOutputEnabled; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ALARM_ENABLED + ":false}") protected Boolean alarmEnabled; @Autowired(required = false) protected List<ServiceStrategyMonitorAdapter> serviceStrategyMonitorAdapterList; @Override public void monitor(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation) { spanBuild(); loggerOutput(); loggerDebug(); alarm(createContextMap(interceptor, invocation)); } @Override public void monitor(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Object returnValue) { spanOutput(createContextMap(interceptor, invocation, returnValue)); } @Override public void error(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Throwable e) { spanError(e); } @Override public void release(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation) { loggerClear(); spanFinish(); } private Map<String, String> createContextMap(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation) { if (!alarmEnabled) { return null; } Map<String, String> contextMap = new LinkedHashMap<String, String>(); String className = interceptor.getMethod(invocation).getDeclaringClass().getName(); String methodName = interceptor.getMethodName(invocation); contextMap.put(DiscoveryConstant.CLASS, className); contextMap.put(DiscoveryConstant.METHOD, methodName); return contextMap; } private Map<String, String> createContextMap(ServiceStrategyMonitorInterceptor interceptor, MethodInvocation invocation, Object returnValue) {<FILL_FUNCTION_BODY>} }
if (!tracerEnabled) { return null; } Map<String, String> contextMap = new LinkedHashMap<String, String>(); String className = interceptor.getMethod(invocation).getDeclaringClass().getName(); String methodName = interceptor.getMethodName(invocation); contextMap.put("* " + DiscoveryConstant.CLASS, className); contextMap.put("* " + DiscoveryConstant.METHOD, methodName); if (tracerMethodContextOutputEnabled) { String[] methodParameterNames = interceptor.getMethodParameterNames(invocation); Object[] arguments = interceptor.getArguments(invocation); Map<String, Object> parameterMap = ClassUtil.getParameterMap(methodParameterNames, arguments); if (CollectionUtils.isNotEmpty(serviceStrategyMonitorAdapterList)) { for (ServiceStrategyMonitorAdapter serviceStrategyMonitorAdapter : serviceStrategyMonitorAdapterList) { Map<String, String> customizationMap = serviceStrategyMonitorAdapter.getCustomizationMap(interceptor, invocation, parameterMap, returnValue); for (Map.Entry<String, String> entry : customizationMap.entrySet()) { contextMap.put("* " + entry.getKey(), entry.getValue()); } } } } return contextMap;
593
325
918
<methods>public non-sealed void <init>() ,public void alarm(Map<java.lang.String,java.lang.String>) ,public com.nepxion.discovery.plugin.strategy.monitor.StrategyAlarm getStrategyAlarm() ,public com.nepxion.discovery.plugin.strategy.monitor.StrategyLogger getStrategyLogger() ,public com.nepxion.discovery.plugin.strategy.monitor.StrategyTracer getStrategyTracer() ,public void loggerClear() ,public void loggerDebug() ,public void loggerOutput() ,public void spanBuild() ,public void spanError(java.lang.Throwable) ,public void spanFinish() ,public void spanOutput(Map<java.lang.String,java.lang.String>) <variables>protected com.nepxion.discovery.plugin.strategy.monitor.StrategyAlarm strategyAlarm,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyLogger strategyLogger,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyTracer strategyTracer
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorAutoScanProxy.java
ServiceStrategyMonitorAutoScanProxy
getCommonInterceptorNames
class ServiceStrategyMonitorAutoScanProxy extends DefaultAutoScanProxy { private static final long serialVersionUID = 2204522253627697121L; private String[] commonInterceptorNames; @SuppressWarnings("rawtypes") private Class[] classAnnotations; public ServiceStrategyMonitorAutoScanProxy(String scanPackages) { super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); } @Override protected String[] getCommonInterceptorNames() {<FILL_FUNCTION_BODY>} @SuppressWarnings("unchecked") @Override protected Class<? extends Annotation>[] getClassAnnotations() { if (classAnnotations == null) { classAnnotations = new Class[] { RestController.class, ServiceStrategy.class }; } return classAnnotations; } }
if (commonInterceptorNames == null) { commonInterceptorNames = new String[] { "serviceStrategyMonitorInterceptor" }; } return commonInterceptorNames;
247
50
297
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/monitor/ServiceStrategyMonitorInterceptor.java
ServiceStrategyMonitorInterceptor
invoke
class ServiceStrategyMonitorInterceptor extends AbstractInterceptor { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_METHOD_CONTEXT_OUTPUT_ENABLED + ":false}") protected Boolean tracerMethodContextOutputEnabled; @Autowired protected ServiceStrategyMonitor serviceStrategyMonitor; @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
boolean hasInitBinderAnnotation = getMethod(invocation).isAnnotationPresent(InitBinder.class); if (hasInitBinderAnnotation) { return invocation.proceed(); } String className = getMethod(invocation).getDeclaringClass().getName(); String methodName = getMethodName(invocation); boolean isMonitorIgnored = false; boolean isMonitored = false; boolean isMethodContextMonitored = false; try { // 拦截侦测请求 if (StringUtils.equals(className, DiscoveryConstant.INSPECTOR_ENDPOINT_CLASS_NAME) && StringUtils.equals(methodName, DiscoveryConstant.INSPECTOR_ENDPOINT_METHOD_NAME)) { // 埋点创建、日志输出、告警输出 serviceStrategyMonitor.monitor(this, invocation); isMonitored = true; // 埋点输出 serviceStrategyMonitor.monitor(this, invocation, "* " + DiscoveryConstant.IGNORED); isMethodContextMonitored = true; return invocation.proceed(); } else { isMonitorIgnored = getMethod(invocation).isAnnotationPresent(ServiceMonitorIgnore.class); if (isMonitorIgnored) { return invocation.proceed(); } // 埋点创建、日志输出、告警输出 serviceStrategyMonitor.monitor(this, invocation); isMonitored = true; if (tracerMethodContextOutputEnabled) { // 先执行调用,根据调用结果再输出返回值的埋点 Object returnValue = invocation.proceed(); // 埋点输出 serviceStrategyMonitor.monitor(this, invocation, returnValue); isMethodContextMonitored = true; return returnValue; } else { // 埋点方法上下文输出 serviceStrategyMonitor.monitor(this, invocation, null); isMethodContextMonitored = true; return invocation.proceed(); } } } catch (Throwable e) { if (!isMonitorIgnored) { if (!isMonitored) { // 埋点创建、日志输出、告警输出 serviceStrategyMonitor.monitor(this, invocation); isMonitored = true; } if (!isMethodContextMonitored) { // 埋点输出 serviceStrategyMonitor.monitor(this, invocation, null); isMethodContextMonitored = true; } // 埋点异常输出 serviceStrategyMonitor.error(this, invocation, e); } throw e; } finally { if (!isMonitorIgnored && isMonitored && isMethodContextMonitored) { // 埋点提交、日志清除 serviceStrategyMonitor.release(this, invocation); } }
123
716
839
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyAutoScanProxy.java
ServiceRpcStrategyAutoScanProxy
getClassAnnotations
class ServiceRpcStrategyAutoScanProxy extends DefaultAutoScanProxy { private static final long serialVersionUID = 8436914718400274011L; private String[] commonInterceptorNames; @SuppressWarnings("rawtypes") private Class[] classAnnotations; public ServiceRpcStrategyAutoScanProxy(String scanPackages) { super(scanPackages, ProxyMode.BY_CLASS_ANNOTATION_ONLY, ScanMode.FOR_CLASS_ANNOTATION_ONLY); } @Override protected String[] getCommonInterceptorNames() { if (commonInterceptorNames == null) { commonInterceptorNames = new String[] { "serviceRpcStrategyInterceptor" }; } return commonInterceptorNames; } @SuppressWarnings("unchecked") @Override protected Class<? extends Annotation>[] getClassAnnotations() {<FILL_FUNCTION_BODY>} }
if (classAnnotations == null) { classAnnotations = new Class[] { RestController.class, ServiceStrategy.class }; } return classAnnotations;
255
45
300
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/rpc/ServiceRpcStrategyInterceptor.java
ServiceRpcStrategyInterceptor
invoke
class ServiceRpcStrategyInterceptor extends AbstractInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
boolean hasInitBinderAnnotation = getMethod(invocation).isAnnotationPresent(InitBinder.class); if (hasInitBinderAnnotation) { return invocation.proceed(); } Class<?> clazz = getMethod(invocation).getDeclaringClass(); String methodName = getMethodName(invocation); String[] methodParameterNames = getMethodParameterNames(invocation); Object[] arguments = getArguments(invocation); Map<String, Object> parameterMap = ClassUtil.getParameterMap(methodParameterNames, arguments); RpcStrategyContext context = RpcStrategyContext.getCurrentContext(); context.add(DiscoveryConstant.CLASS, clazz); context.add(DiscoveryConstant.METHOD, methodName); context.add(DiscoveryConstant.PARAMETER_MAP, parameterMap); try { return invocation.proceed(); } finally { RpcStrategyContext.clearCurrentContext(); }
50
237
287
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-service/src/main/java/com/nepxion/discovery/plugin/strategy/service/wrapper/DefaultServiceStrategyCallableWrapper.java
DefaultServiceStrategyCallableWrapper
call
class DefaultServiceStrategyCallableWrapper implements ServiceStrategyCallableWrapper { @Value("${" + ServiceStrategyConstant.SPRING_APPLICATION_STRATEGY_REST_REQUEST_DECORATOR_ENABLED + ":true}") protected Boolean requestDecoratorEnabled; @Override public <T> Callable<T> wrapCallable(Callable<T> callable) { RequestAttributes originRequestAttributes = RequestContextHolder.getRequestAttributes(); if (requestDecoratorEnabled) { if (originRequestAttributes != null) { originRequestAttributes = ServiceStrategyRequestDecoratorFactory.decorateRequestAttributes(originRequestAttributes); } } RequestAttributes requestAttributes = originRequestAttributes; Map<String, Object> attributes = RpcStrategyContext.getCurrentContext().getAttributes(); Object span = StrategyTracerContext.getCurrentContext().getSpan(); return new Callable<T>() { @Override public T call() throws Exception {<FILL_FUNCTION_BODY>} }; } }
try { RequestContextHolder.setRequestAttributes(requestAttributes); RestStrategyContext.getCurrentContext().setRequestAttributes(requestAttributes); RpcStrategyContext.getCurrentContext().setAttributes(attributes); StrategyTracerContext.getCurrentContext().setSpan(span); return callable.call(); } finally { RequestContextHolder.resetRequestAttributes(); RestStrategyContext.clearCurrentContext(); RpcStrategyContext.clearCurrentContext(); StrategyTracerContext.clearCurrentContext(); }
264
132
396
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategySpan.java
SkyWalkingStrategySpan
createTraceId
class SkyWalkingStrategySpan implements Span { private Span span; private String traceId; private String spanId; public SkyWalkingStrategySpan(Span span) { this.span = span; this.traceId = createTraceId(); this.spanId = createSpanId(); } @Override public Span setOperationName(String operationName) { return span.setOperationName(operationName); } @Override public Span log(long timestampMicroseconds, Map<String, ?> fields) { return span.log(timestampMicroseconds, fields); } @Override public void finish(long finishMicros) { span.finish(finishMicros); } @Override public Span log(long timestampMicroseconds, String event) { return span.log(timestampMicroseconds, event); } @Override public void finish() { span.finish(); } @Override public SpanContext context() { return span.context(); } @Override public Span setTag(String key, String value) { return span.setTag(key, value); } @Override public Span setTag(String key, boolean value) { return span.setTag(key, value); } @Override public Span setTag(String key, Number value) { return span.setTag(key, value); } @Override public Span log(Map<String, ?> fields) { return span.log(fields); } @Override public Span log(String event) { return span.log(event); } @Override public Span setBaggageItem(String key, String value) { return span.setBaggageItem(key, value); } @Override public String getBaggageItem(String key) { return span.getBaggageItem(key); } @Deprecated @Override public Span log(String eventName, Object payload) { return span.log(eventName, payload); } @Deprecated @Override public Span log(long timestampMicroseconds, String eventName, Object payload) { return span.log(timestampMicroseconds, eventName, payload); } public String toTraceId() { return traceId; } public String toSpanId() { return spanId; } private String createTraceId() {<FILL_FUNCTION_BODY>} private String createSpanId() { try { return DiscoveryConstant.IGNORED; } catch (Exception e) { return null; } } }
try { Object span = StrategyTracerContext.getCurrentContext().getSpan(); if (span != null) { // 该方式适用在WebFlux模式下 StrategySpan strategySpan = (StrategySpan) span; return strategySpan.getTraceId(); } else { // 该方式适用在WebMvc模式下 return TraceContext.traceId(); } } catch (Exception e) { return null; }
716
121
837
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-skywalking/src/main/java/com/nepxion/discovery/plugin/strategy/skywalking/monitor/SkyWalkingStrategyTracer.java
SkyWalkingStrategyTracer
errorSpan
class SkyWalkingStrategyTracer extends AbstractStrategyTracer<SkyWalkingStrategySpan> { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_TRACER_EXCEPTION_DETAIL_OUTPUT_ENABLED + ":false}") protected Boolean tracerExceptionDetailOutputEnabled; private Tracer tracer = new SkywalkingTracer(); @Override protected SkyWalkingStrategySpan buildSpan() { return new SkyWalkingStrategySpan(tracer.buildSpan(tracerSpanValue).startManual()); } @Override protected void outputSpan(SkyWalkingStrategySpan span, String key, String value) { span.setTag(key, value); } @Override protected void errorSpan(SkyWalkingStrategySpan span, Throwable e) {<FILL_FUNCTION_BODY>} @Override protected void finishSpan(SkyWalkingStrategySpan span) { span.finish(); } // Never used probably @Override protected SkyWalkingStrategySpan getActiveSpan() { return null; } @Override protected String toTraceId(SkyWalkingStrategySpan span) { return span.toTraceId(); } @Override protected String toSpanId(SkyWalkingStrategySpan span) { return span.toSpanId(); } }
if (tracerExceptionDetailOutputEnabled) { span.setTag(DiscoveryConstant.ERROR_OBJECT, ExceptionUtils.getStackTrace(e)); } else { span.setTag(DiscoveryConstant.ERROR_OBJECT, e.getMessage()); }
355
68
423
<methods>public non-sealed void <init>() ,public java.lang.String getSpanId() ,public java.lang.String getTraceId() ,public void spanBuild() ,public void spanError(java.lang.Throwable) ,public void spanFinish() ,public void spanOutput(Map<java.lang.String,java.lang.String>) <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext strategyMonitorContext,protected java.lang.Boolean tracerEnabled,protected java.lang.Boolean tracerRuleOutputEnabled,protected java.lang.Boolean tracerSeparateSpanEnabled,protected java.lang.String tracerSpanPluginValue,protected java.lang.String tracerSpanValue
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextHolder.java
ZuulStrategyContextHolder
getZuulRequestHeaders
class ZuulStrategyContextHolder extends AbstractStrategyContextHolder { // 如果外界也传了相同的Header,例如,从Postman传递过来的Header,当下面的变量为true,以网关设置为优先,否则以外界传值为优先 @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_HEADER_PRIORITY + ":true}") protected Boolean zuulHeaderPriority; // 当以网关设置为优先的时候,网关未配置Header,而外界配置了Header,仍旧忽略外界的Header @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_ORIGINAL_HEADER_IGNORED + ":true}") protected Boolean zuulOriginalHeaderIgnored; // Zuul上核心策略Header是否传递。当全局订阅启动时,可以关闭核心策略Header传递,这样可以节省传递数据的大小,一定程度上可以提升性能 // 核心策略Header指n-d-开头的Header(不包括n-d-env,因为环境路由隔离,必须传递该Header),不包括n-d-service开头的Header @Value("${" + ZuulStrategyConstant.SPRING_APPLICATION_STRATEGY_ZUUL_CORE_HEADER_TRANSMISSION_ENABLED + ":true}") protected Boolean zuulCoreHeaderTransmissionEnabled; public HttpServletRequest getRequest() { HttpServletRequest request = ZuulStrategyContext.getCurrentContext().getRequest(); if (request == null) { request = RequestContext.getCurrentContext().getRequest(); } if (request == null) { // LOG.warn("The HttpServletRequest object is lost for thread switched, or it is got before context filter probably"); return null; } return request; } public Map<String, String> getZuulRequestHeaders() {<FILL_FUNCTION_BODY>} @Override public Enumeration<String> getHeaderNames() { HttpServletRequest request = getRequest(); if (request == null) { return null; } Enumeration<String> headerNames = request.getHeaderNames(); Map<String, String> headers = getZuulRequestHeaders(); if (MapUtils.isNotEmpty(headers)) { List<String> headerNameList = Collections.list(headerNames); for (Map.Entry<String, String> entry : headers.entrySet()) { String headerName = entry.getKey(); if (!headerNameList.contains(headerName)) { headerNameList.add(headerName); } } return Collections.enumeration(headerNameList); } return headerNames; } @Override public String getHeader(String name) { HttpServletRequest request = getRequest(); if (request == null) { return null; } if (!zuulCoreHeaderTransmissionEnabled) { boolean isCoreHeaderContains = StrategyUtil.isCoreHeaderContains(name); if (isCoreHeaderContains) { return null; } } if (zuulHeaderPriority) { // 来自于Zuul Filter的Header Map<String, String> headers = getZuulRequestHeaders(); String header = null; if (MapUtils.isNotEmpty(headers)) { header = headers.get(name); } if (StringUtils.isEmpty(header)) { if (StrategyUtil.isCoreHeaderContains(name) && zuulOriginalHeaderIgnored) { header = null; } else { // 来自于外界的Header header = request.getHeader(name); } } return header; } else { // 来自于外界的Header String header = request.getHeader(name); if (StringUtils.isEmpty(header)) { // 来自于Zuul Filter的Header Map<String, String> headers = getZuulRequestHeaders(); if (MapUtils.isNotEmpty(headers)) { header = headers.get(name); } } return header; } } @Override public String getParameter(String name) { HttpServletRequest request = getRequest(); if (request == null) { return null; } return request.getParameter(name); } public Cookie getHttpCookie(String name) { HttpServletRequest request = getRequest(); if (request == null) { return null; } Cookie[] cookies = request.getCookies(); if (cookies == null) { return null; } for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; String cookieName = cookie.getName(); if (StringUtils.equals(cookieName, name)) { return cookie; } } return null; } @Override public String getCookie(String name) { Cookie cookie = getHttpCookie(name); if (cookie != null) { return cookie.getValue(); } return null; } public String getRequestURL() { HttpServletRequest request = getRequest(); if (request == null) { return null; } return request.getRequestURL().toString(); } public String getRequestURI() { HttpServletRequest request = getRequest(); if (request == null) { return null; } return request.getRequestURI(); } }
Map<String, String> headers = ZuulStrategyContext.getCurrentContext().getHeaders(); if (headers == null) { headers = RequestContext.getCurrentContext().getZuulRequestHeaders(); } if (headers == null) { // LOG.warn("The Headers object is lost for thread switched, or it is got before context filter probably"); return null; } return headers;
1,453
107
1,560
<methods>public non-sealed void <init>() ,public java.lang.String getContext(java.lang.String) ,public java.lang.String getContextRouteAddress() ,public java.lang.String getContextRouteAddressBlacklist() ,public java.lang.String getContextRouteAddressFailover() ,public java.lang.String getContextRouteEnvironment() ,public java.lang.String getContextRouteEnvironmentFailover() ,public java.lang.String getContextRouteIdBlacklist() ,public java.lang.String getContextRouteRegion() ,public java.lang.String getContextRouteRegionFailover() ,public java.lang.String getContextRouteRegionTransfer() ,public java.lang.String getContextRouteRegionWeight() ,public java.lang.String getContextRouteVersion() ,public java.lang.String getContextRouteVersionFailover() ,public java.lang.String getContextRouteVersionPrefer() ,public java.lang.String getContextRouteVersionWeight() ,public java.lang.String getContextRouteZoneFailover() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public java.lang.String getRouteAddress() ,public java.lang.String getRouteAddressBlacklist() ,public java.lang.String getRouteAddressFailover() ,public java.lang.String getRouteEnvironment() ,public java.lang.String getRouteEnvironmentFailover() ,public java.lang.String getRouteIdBlacklist() ,public java.lang.String getRouteRegion() ,public java.lang.String getRouteRegionFailover() ,public java.lang.String getRouteRegionTransfer() ,public java.lang.String getRouteRegionWeight() ,public java.lang.String getRouteVersion() ,public java.lang.String getRouteVersionFailover() ,public java.lang.String getRouteVersionPrefer() ,public java.lang.String getRouteVersionWeight() ,public java.lang.String getRouteZoneFailover() ,public java.lang.String getSpanId() ,public com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper getStrategyWrapper() ,public java.lang.String getTraceId() <variables>protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.strategy.monitor.StrategyMonitorContext strategyMonitorContext,protected com.nepxion.discovery.plugin.strategy.wrapper.StrategyWrapper strategyWrapper
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/context/ZuulStrategyContextListener.java
ZuulStrategyContextListener
onApplicationEvent
class ZuulStrategyContextListener implements ApplicationListener<ContextRefreshedEvent> { private static final Logger LOG = LoggerFactory.getLogger(ZuulStrategyContextListener.class); @Override public void onApplicationEvent(ContextRefreshedEvent event) {<FILL_FUNCTION_BODY>} }
// 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 LOG.info("Initialize Zuul Strategy Context after Application started..."); ZuulStrategyContext.getCurrentContext();
79
56
135
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/DefaultZuulStrategyClearFilter.java
DefaultZuulStrategyClearFilter
run
class DefaultZuulStrategyClearFilter extends ZuulStrategyClearFilter { @Autowired(required = false) protected ZuulStrategyMonitor zuulStrategyMonitor; @Override public String filterType() { return FilterConstants.POST_TYPE; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() {<FILL_FUNCTION_BODY>} }
// 调用链释放 RequestContext context = RequestContext.getCurrentContext(); if (zuulStrategyMonitor != null) { zuulStrategyMonitor.release(context); } return null;
137
59
196
<methods>public non-sealed void <init>() <variables>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/filter/ZuulStrategyFilterResolver.java
ZuulStrategyFilterResolver
setHeader
class ZuulStrategyFilterResolver { public static void setHeader(RequestContext context, String headerName, String headerValue, Boolean zuulHeaderPriority) {<FILL_FUNCTION_BODY>} public static void ignoreHeader(RequestContext context, String headerName, Boolean zuulHeaderPriority, Boolean zuulOriginalHeaderIgnored) { if (zuulHeaderPriority && zuulOriginalHeaderIgnored) { ignoreHeader(context, headerName); } } public static void ignoreHeader(RequestContext context, String headerName) { String header = context.getRequest().getHeader(headerName); if (StringUtils.isNotEmpty(header)) { // 通过Zuul Filter的Header直接把外界的Header替换成空字符串 context.addZuulRequestHeader(headerName, StringUtils.EMPTY); } } }
if (StringUtils.isEmpty(headerValue)) { return; } if (zuulHeaderPriority) { // 通过Zuul Filter的Header直接把外界的Header替换掉,并传递 context.addZuulRequestHeader(headerName, headerValue); } else { // 在外界的Header不存在的前提下,通过Zuul Filter的Header传递 String header = context.getRequest().getHeader(headerName); if (StringUtils.isEmpty(header)) { context.addZuulRequestHeader(headerName, headerValue); } }
219
155
374
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter-zuul/src/main/java/com/nepxion/discovery/plugin/strategy/zuul/wrapper/DefaultZuulStrategyCallableWrapper.java
DefaultZuulStrategyCallableWrapper
wrapCallable
class DefaultZuulStrategyCallableWrapper implements ZuulStrategyCallableWrapper { @Override public <T> Callable<T> wrapCallable(Callable<T> callable) {<FILL_FUNCTION_BODY>} }
HttpServletRequest request = RequestContext.getCurrentContext().getRequest(); Map<String, String> headers = RequestContext.getCurrentContext().getZuulRequestHeaders(); Object span = StrategyTracerContext.getCurrentContext().getSpan(); return new Callable<T>() { @Override public T call() throws Exception { try { ZuulStrategyContext.getCurrentContext().setRequest(request); ZuulStrategyContext.getCurrentContext().setHeaders(headers); StrategyTracerContext.getCurrentContext().setSpan(span); return callable.call(); } finally { ZuulStrategyContext.clearCurrentContext(); StrategyTracerContext.clearCurrentContext(); } } };
61
192
253
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/adapter/DefaultDiscoveryEnabledAdapter.java
DefaultDiscoveryEnabledAdapter
apply
class DefaultDiscoveryEnabledAdapter implements DiscoveryEnabledAdapter { @Autowired protected List<StrategyEnabledFilter> strategyEnabledFilterList; @Autowired(required = false) protected List<DiscoveryEnabledStrategy> discoveryEnabledStrategyList; @Override public void filter(List<? extends Server> servers) { for (StrategyEnabledFilter strategyEnabledFilter : strategyEnabledFilterList) { strategyEnabledFilter.filter(servers); } } @Override public boolean apply(Server server) {<FILL_FUNCTION_BODY>} }
if (CollectionUtils.isEmpty(discoveryEnabledStrategyList)) { return true; } for (DiscoveryEnabledStrategy discoveryEnabledStrategy : discoveryEnabledStrategyList) { boolean enabled = discoveryEnabledStrategy.apply(server); if (!enabled) { return false; } } return true;
142
83
225
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/AbstractStrategyInterceptor.java
AbstractStrategyInterceptor
interceptInputHeader
class AbstractStrategyInterceptor { private static final Logger LOG = LoggerFactory.getLogger(AbstractStrategyInterceptor.class); @Autowired protected PluginAdapter pluginAdapter; @Autowired protected StrategyContextHolder strategyContextHolder; @Autowired protected StrategyHeaderContext strategyHeaderContext; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REST_INTERCEPT_DEBUG_ENABLED + ":false}") protected Boolean interceptDebugEnabled; protected List<String> requestHeaderNameList; @PostConstruct public void initialize() { requestHeaderNameList = strategyHeaderContext.getRequestHeaderNameList(); InterceptorType interceptorType = getInterceptorType(); LOG.info("--------- Strategy Intercept Information ---------"); LOG.info("{} desires to intercept customer headers are {}", interceptorType, requestHeaderNameList); LOG.info("--------------------------------------------------"); } protected void interceptInputHeader() {<FILL_FUNCTION_BODY>} protected boolean isHeaderContains(String headerName) { return headerName.startsWith(DiscoveryConstant.N_D_PREFIX) || requestHeaderNameList.contains(headerName); } protected boolean isHeaderContainsExcludeInner(String headerName) { return isHeaderContains(headerName) && !StrategyUtil.isInnerHeaderContains(headerName); // return isHeaderContains(headerName) && !headerName.startsWith(DiscoveryConstant.N_D_SERVICE_PREFIX); } protected abstract InterceptorType getInterceptorType(); protected abstract Logger getInterceptorLogger(); }
if (!interceptDebugEnabled) { return; } Enumeration<String> headerNames = strategyContextHolder.getHeaderNames(); if (headerNames != null) { InterceptorType interceptorType = getInterceptorType(); Logger log = getInterceptorLogger(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("\n"); switch (interceptorType) { case FEIGN: stringBuilder.append("--------- Feign Intercept Input Header Information ---------").append("\n"); break; case REST_TEMPLATE: stringBuilder.append("----- RestTemplate Intercept Input Header Information ------").append("\n"); break; case WEB_CLIENT: stringBuilder.append("------- WebClient Intercept Input Header Information -------").append("\n"); break; } while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); boolean isHeaderContains = isHeaderContains(headerName.toLowerCase()); if (isHeaderContains) { String headerValue = strategyContextHolder.getHeader(headerName); stringBuilder.append(headerName + "=" + headerValue).append("\n"); } } stringBuilder.append("------------------------------------------------------------"); log.info(stringBuilder.toString()); }
430
339
769
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/RestTemplateStrategyBeanPostProcessor.java
RestTemplateStrategyBeanPostProcessor
postProcessAfterInitialization
class RestTemplateStrategyBeanPostProcessor implements BeanPostProcessor { @Autowired protected RestTemplateStrategyInterceptor restTemplateStrategyInterceptor; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof RestTemplate) { RestTemplate restTemplate = (RestTemplate) bean; restTemplate.getInterceptors().add(restTemplateStrategyInterceptor); } return bean;
112
54
166
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/aop/WebClientStrategyBeanPostProcessor.java
WebClientStrategyBeanPostProcessor
postProcessAfterInitialization
class WebClientStrategyBeanPostProcessor implements BeanPostProcessor { @Autowired protected WebClientStrategyInterceptor webClientStrategyInterceptor; @Override public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { return bean; } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {<FILL_FUNCTION_BODY>} }
if (bean instanceof WebClient.Builder) { WebClient.Builder webClientBuilder = (WebClient.Builder) bean; webClientBuilder.filter(webClientStrategyInterceptor); } return bean;
112
58
170
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/condition/ExpressionStrategyCondition.java
ExpressionStrategyCondition
createMap
class ExpressionStrategyCondition extends AbstractStrategyCondition { @Autowired private StrategyWrapper strategyWrapper; @Override public boolean isTriggered(StrategyConditionEntity strategyConditionEntity) { Map<String, String> map = createMap(strategyConditionEntity); return isTriggered(strategyConditionEntity, map); } private Map<String, String> createMap(StrategyConditionEntity strategyConditionEntity) {<FILL_FUNCTION_BODY>} @Override public boolean isTriggered(StrategyConditionEntity strategyConditionEntity, Map<String, String> map) { String expression = strategyConditionEntity.getExpression(); return DiscoveryExpressionResolver.eval(expression, DiscoveryConstant.EXPRESSION_PREFIX, map, strategyTypeComparator); } }
String expression = strategyConditionEntity.getExpression(); if (StringUtils.isEmpty(expression)) { return null; } Map<String, String> map = new HashMap<String, String>(); List<String> list = DiscoveryExpressionResolver.extractList(expression); for (String name : list) { String value = null; // 从外置Parameter获取 if (StringUtils.isBlank(value)) { value = strategyContextHolder.getParameter(name); } // 从外置Cookie获取 if (StringUtils.isBlank(value)) { value = strategyContextHolder.getCookie(name); } // 从外置Header获取 if (StringUtils.isBlank(value)) { value = strategyContextHolder.getHeader(name); } // 从内置Header获取 if (StringUtils.isBlank(value)) { value = strategyWrapper.getHeader(name); } if (StringUtils.isNotBlank(value)) { map.put(name, value); } } return map;
197
291
488
<methods>public non-sealed void <init>() ,public com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder getStrategyContextHolder() ,public TypeComparator getStrategyTypeComparator() <variables>protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder,protected TypeComparator strategyTypeComparator
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/configuration/StrategyLoadBalanceConfiguration.java
StrategyLoadBalanceConfiguration
ribbonRule
class StrategyLoadBalanceConfiguration { @Autowired private ConfigurableEnvironment environment; @RibbonClientName private String serviceId = "client"; @Autowired private PropertiesFactory propertiesFactory; @Autowired private PluginAdapter pluginAdapter; @Autowired(required = false) private DiscoveryEnabledAdapter discoveryEnabledAdapter; @Bean public IRule ribbonRule(IClientConfig config) {<FILL_FUNCTION_BODY>} }
if (this.propertiesFactory.isSet(IRule.class, serviceId)) { return this.propertiesFactory.get(IRule.class, config, serviceId); } boolean zoneAvoidanceRuleEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_AVOIDANCE_RULE_ENABLED, Boolean.class, Boolean.TRUE); if (zoneAvoidanceRuleEnabled) { DiscoveryEnabledZoneAvoidanceRule discoveryEnabledRule = new DiscoveryEnabledZoneAvoidanceRule(); discoveryEnabledRule.initWithNiwsConfig(config); DiscoveryEnabledZoneAvoidancePredicate discoveryEnabledPredicate = discoveryEnabledRule.getDiscoveryEnabledPredicate(); discoveryEnabledPredicate.setPluginAdapter(pluginAdapter); discoveryEnabledPredicate.setDiscoveryEnabledAdapter(discoveryEnabledAdapter); return discoveryEnabledRule; } else { DiscoveryEnabledBaseRule discoveryEnabledRule = new DiscoveryEnabledBaseRule(); DiscoveryEnabledBasePredicate discoveryEnabledPredicate = discoveryEnabledRule.getDiscoveryEnabledPredicate(); discoveryEnabledPredicate.setPluginAdapter(pluginAdapter); discoveryEnabledPredicate.setDiscoveryEnabledAdapter(discoveryEnabledAdapter); return discoveryEnabledRule; }
129
311
440
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/AbstractStrategyContextHolder.java
AbstractStrategyContextHolder
getContextRouteRegion
class AbstractStrategyContextHolder implements PluginContextHolder, StrategyContextHolder { @Autowired protected PluginAdapter pluginAdapter; @Autowired protected StrategyWrapper strategyWrapper; @Autowired(required = false) protected StrategyMonitorContext strategyMonitorContext; @Override public String getContext(String name) { return getHeader(name); } @Override public String getContextRouteVersion() { String versionValue = getContext(DiscoveryConstant.N_D_VERSION); if (StringUtils.isEmpty(versionValue)) { versionValue = getRouteVersion(); } return versionValue; } @Override public String getContextRouteRegion() {<FILL_FUNCTION_BODY>} @Override public String getContextRouteEnvironment() { String environmentValue = getContext(DiscoveryConstant.N_D_ENVIRONMENT); if (StringUtils.isEmpty(environmentValue)) { environmentValue = getRouteEnvironment(); } return environmentValue; } @Override public String getContextRouteAddress() { String addressValue = getContext(DiscoveryConstant.N_D_ADDRESS); if (StringUtils.isEmpty(addressValue)) { addressValue = getRouteAddress(); } return addressValue; } @Override public String getContextRouteVersionWeight() { String versionWeightValue = getContext(DiscoveryConstant.N_D_VERSION_WEIGHT); if (StringUtils.isEmpty(versionWeightValue)) { versionWeightValue = getRouteVersionWeight(); } return versionWeightValue; } @Override public String getContextRouteRegionWeight() { String regionWeightValue = getContext(DiscoveryConstant.N_D_REGION_WEIGHT); if (StringUtils.isEmpty(regionWeightValue)) { regionWeightValue = getRouteRegionWeight(); } return regionWeightValue; } @Override public String getContextRouteVersionPrefer() { String versionPreferValue = getContext(DiscoveryConstant.N_D_VERSION_PREFER); if (StringUtils.isEmpty(versionPreferValue)) { versionPreferValue = getRouteVersionPrefer(); } return versionPreferValue; } @Override public String getContextRouteVersionFailover() { String versionFailoverValue = getContext(DiscoveryConstant.N_D_VERSION_FAILOVER); if (StringUtils.isEmpty(versionFailoverValue)) { versionFailoverValue = getRouteVersionFailover(); } return versionFailoverValue; } @Override public String getContextRouteRegionTransfer() { String regionTransferValue = getContext(DiscoveryConstant.N_D_REGION_TRANSFER); if (StringUtils.isEmpty(regionTransferValue)) { regionTransferValue = getRouteRegionTransfer(); } return regionTransferValue; } @Override public String getContextRouteRegionFailover() { String regionFailoverValue = getContext(DiscoveryConstant.N_D_REGION_FAILOVER); if (StringUtils.isEmpty(regionFailoverValue)) { regionFailoverValue = getRouteRegionFailover(); } return regionFailoverValue; } @Override public String getContextRouteEnvironmentFailover() { String environmentFailoverValue = getContext(DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER); if (StringUtils.isEmpty(environmentFailoverValue)) { environmentFailoverValue = getRouteEnvironmentFailover(); } return environmentFailoverValue; } @Override public String getContextRouteZoneFailover() { String zoneFailoverValue = getContext(DiscoveryConstant.N_D_ZONE_FAILOVER); if (StringUtils.isEmpty(zoneFailoverValue)) { zoneFailoverValue = getRouteZoneFailover(); } return zoneFailoverValue; } @Override public String getContextRouteAddressFailover() { String addressFailoverValue = getContext(DiscoveryConstant.N_D_ADDRESS_FAILOVER); if (StringUtils.isEmpty(addressFailoverValue)) { addressFailoverValue = getRouteAddressFailover(); } return addressFailoverValue; } @Override public String getContextRouteIdBlacklist() { String idBlacklistValue = getContext(DiscoveryConstant.N_D_ID_BLACKLIST); if (StringUtils.isEmpty(idBlacklistValue)) { idBlacklistValue = getRouteIdBlacklist(); } return idBlacklistValue; } @Override public String getContextRouteAddressBlacklist() { String addressBlacklistValue = getContext(DiscoveryConstant.N_D_ADDRESS_BLACKLIST); if (StringUtils.isEmpty(addressBlacklistValue)) { addressBlacklistValue = getRouteAddressBlacklist(); } return addressBlacklistValue; } @Override public String getRouteVersion() { return strategyWrapper.getRouteVersion(); } @Override public String getRouteRegion() { return strategyWrapper.getRouteRegion(); } @Override public String getRouteEnvironment() { return null; } @Override public String getRouteAddress() { return strategyWrapper.getRouteAddress(); } @Override public String getRouteVersionWeight() { return strategyWrapper.getRouteVersionWeight(); } @Override public String getRouteRegionWeight() { return strategyWrapper.getRouteRegionWeight(); } @Override public String getRouteVersionPrefer() { return strategyWrapper.getRouteVersionPrefer(); } @Override public String getRouteVersionFailover() { return strategyWrapper.getRouteVersionFailover(); } @Override public String getRouteRegionTransfer() { return strategyWrapper.getRouteRegionTransfer(); } @Override public String getRouteRegionFailover() { return strategyWrapper.getRouteRegionFailover(); } @Override public String getRouteEnvironmentFailover() { return strategyWrapper.getRouteEnvironmentFailover(); } @Override public String getRouteZoneFailover() { return strategyWrapper.getRouteZoneFailover(); } @Override public String getRouteAddressFailover() { return strategyWrapper.getRouteAddressFailover(); } @Override public String getRouteIdBlacklist() { return strategyWrapper.getRouteIdBlacklist(); } @Override public String getRouteAddressBlacklist() { return strategyWrapper.getRouteAddressBlacklist(); } @Override public String getTraceId() { if (strategyMonitorContext != null) { return strategyMonitorContext.getTraceId(); } return null; } @Override public String getSpanId() { if (strategyMonitorContext != null) { return strategyMonitorContext.getSpanId(); } return null; } public PluginAdapter getPluginAdapter() { return pluginAdapter; } public StrategyWrapper getStrategyWrapper() { return strategyWrapper; } }
String regionValue = getContext(DiscoveryConstant.N_D_REGION); if (StringUtils.isEmpty(regionValue)) { regionValue = getRouteRegion(); } return regionValue;
1,856
55
1,911
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/context/StrategyHeaderContext.java
StrategyHeaderContext
initialize
class StrategyHeaderContext { @Autowired private ConfigurableEnvironment environment; @Autowired(required = false) private List<StrategyHeadersInjector> strategyHeadersInjectorList; private List<String> requestHeaderNameList; @PostConstruct public void initialize() {<FILL_FUNCTION_BODY>} public List<String> getRequestHeaderNameList() { return requestHeaderNameList; } }
requestHeaderNameList = new ArrayList<String>(); String contextRequestHeaders = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_CONTEXT_REQUEST_HEADERS); String businessRequestHeaders = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_BUSINESS_REQUEST_HEADERS); List<String> injectorRequestHeaders = StrategyHeadersResolver.getInjectedHeaders(strategyHeadersInjectorList, HeadersInjectorType.TRANSMISSION); if (StringUtils.isNotEmpty(contextRequestHeaders)) { requestHeaderNameList.addAll(StringUtil.splitToList(contextRequestHeaders.toLowerCase())); } if (StringUtils.isNotEmpty(businessRequestHeaders)) { requestHeaderNameList.addAll(StringUtil.splitToList(businessRequestHeaders.toLowerCase())); } if (CollectionUtils.isNotEmpty(injectorRequestHeaders)) { requestHeaderNameList.addAll(injectorRequestHeaders); }
117
258
375
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/extractor/StrategyPackagesExtractor.java
StrategyPackagesExtractor
getComponentScanningPackages
class StrategyPackagesExtractor implements BeanDefinitionRegistryPostProcessor, ApplicationContextAware { private static final Logger LOG = LoggerFactory.getLogger(StrategyPackagesExtractor.class); private ApplicationContext applicationContext; private Environment environment; private List<String> basePackagesList; private List<String> scanningPackagesList; private Set<String> scanningPackagesSet; private List<String> allPackagesList; private String basePackages; private String scanningPackages; private String allPackages; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; this.environment = applicationContext.getEnvironment(); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { Boolean autoScanPackagesEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_AUTO_SCAN_PACKAGES_ENABLED, Boolean.class, Boolean.TRUE); if (!autoScanPackagesEnabled) { return; } try { allPackagesList = new ArrayList<String>(); basePackagesList = getComponentBasePackages(); if (CollectionUtils.isNotEmpty(basePackagesList)) { basePackages = StringUtil.convertToString(basePackagesList); for (String pkg : basePackagesList) { if (!allPackagesList.contains(pkg)) { allPackagesList.add(pkg); } } } scanningPackagesSet = getComponentScanningPackages(registry, basePackagesList); if (CollectionUtils.isNotEmpty(scanningPackagesSet)) { scanningPackagesList = new ArrayList<String>(scanningPackagesSet); scanningPackages = StringUtil.convertToString(scanningPackagesList); for (String pkg : scanningPackagesList) { if (!allPackagesList.contains(pkg)) { allPackagesList.add(pkg); } } } if (CollectionUtils.isNotEmpty(allPackagesList)) { allPackages = StringUtil.convertToString(allPackagesList); } LOG.info("--------- Auto Scan Packages Information ---------"); LOG.info("Base packages is {}", basePackagesList); LOG.info("Scanning packages is {}", scanningPackagesList); LOG.info("All packages is {}", allPackagesList); LOG.info("--------------------------------------------------"); } catch (Exception e) { LOG.warn("Get base and scanning packages failed, skip it..."); } } public List<String> getBasePackagesList() { return basePackagesList; } public List<String> getScanningPackagesList() { return scanningPackagesList; } public List<String> getAllPackagesList() { return allPackagesList; } public String getBasePackages() { return basePackages; } public String getScanningPackages() { return scanningPackages; } public String getAllPackages() { return allPackages; } protected List<String> getComponentBasePackages() { return AutoConfigurationPackages.get(applicationContext); } protected Set<String> getComponentScanningPackages(BeanDefinitionRegistry registry, List<String> basePackages) {<FILL_FUNCTION_BODY>} private void addComponentScanningPackages(Set<String> packages, AnnotationMetadata metadata) { AnnotationAttributes attributes = AnnotationAttributes .fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true)); if (attributes != null) { addPackages(packages, attributes.getStringArray("value")); addPackages(packages, attributes.getStringArray("basePackages")); addClasses(packages, attributes.getStringArray("basePackageClasses")); if (packages.isEmpty()) { packages.add(ClassUtils.getPackageName(metadata.getClassName())); } } } private void addPackages(Set<String> packages, String[] values) { if (values != null) { Collections.addAll(packages, values); } } private void addClasses(Set<String> packages, String[] values) { if (values != null) { for (String value : values) { packages.add(ClassUtils.getPackageName(value)); } } } }
if (CollectionUtils.isEmpty(basePackages)) { return null; } Boolean autoScanRecursionEnabled = environment.getProperty(StrategyConstant.SPRING_APPLICATION_STRATEGY_AUTO_SCAN_RECURSION_ENABLED, Boolean.class, Boolean.FALSE); Set<String> packages = new LinkedHashSet<>(); String[] names = registry.getBeanDefinitionNames(); for (String name : names) { BeanDefinition definition = registry.getBeanDefinition(name); String beanClassName = definition.getBeanClassName(); if (definition instanceof AnnotatedBeanDefinition && beanClassName != null) { String beanPackage = ClassUtils.getPackageName(beanClassName); for (String pkg : basePackages) { if (beanPackage.equals(pkg) || beanPackage.startsWith(pkg + '.')) { AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); break; } } if (autoScanRecursionEnabled) { for (String pkg : packages) { if (beanPackage.equals(pkg) || beanPackage.startsWith(pkg + '.')) { AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition; addComponentScanningPackages(packages, annotatedDefinition.getMetadata()); break; } } } } } return packages;
1,172
382
1,554
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/AbstractStrategyEnabledFilter.java
AbstractStrategyEnabledFilter
matchByRegion
class AbstractStrategyEnabledFilter implements StrategyEnabledFilter { @Autowired protected DiscoveryMatcher discoveryMatcher; @Autowired protected PluginAdapter pluginAdapter; @Autowired protected PluginContextHolder pluginContextHolder; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_SORT_TYPE + ":" + DiscoveryConstant.SORT_BY_VERSION + "}") protected String sortType; @Override public void filter(List<? extends Server> servers) { Iterator<? extends Server> iterator = servers.iterator(); while (iterator.hasNext()) { Server server = iterator.next(); boolean enabled = apply(servers, server); if (!enabled) { iterator.remove(); } } } public boolean findByGroup(List<? extends Server> servers, String group) { for (Server server : servers) { String serverGroup = pluginAdapter.getServerGroup(server); if (StringUtils.equals(group, serverGroup)) { return true; } } return false; } public boolean findByVersion(List<? extends Server> servers, String version) { for (Server server : servers) { String serverVersion = pluginAdapter.getServerVersion(server); if (StringUtils.equals(version, serverVersion)) { return true; } } return false; } public boolean findByRegion(List<? extends Server> servers, String region) { for (Server server : servers) { String serverRegion = pluginAdapter.getServerRegion(server); if (StringUtils.equals(region, serverRegion)) { return true; } } return false; } public boolean findByEnvironment(List<? extends Server> servers, String environment) { for (Server server : servers) { String serverEnvironment = pluginAdapter.getServerEnvironment(server); if (StringUtils.equals(environment, serverEnvironment)) { return true; } } return false; } public boolean findByZone(List<? extends Server> servers, String zone) { for (Server server : servers) { String serverZone = pluginAdapter.getServerZone(server); if (StringUtils.equals(zone, serverZone)) { return true; } } return false; } public boolean matchByVersion(List<? extends Server> servers, String versions) { for (Server server : servers) { String serverVersion = pluginAdapter.getServerVersion(server); if (discoveryMatcher.match(versions, serverVersion, true)) { return true; } } return false; } public boolean matchByRegion(List<? extends Server> servers, String regions) {<FILL_FUNCTION_BODY>} public boolean matchByAddress(List<? extends Server> servers, String addresses) { for (Server server : servers) { String serverHost = server.getHost(); int serverPort = server.getPort(); if (discoveryMatcher.matchAddress(addresses, serverHost, serverPort, true)) { return true; } } return false; } public List<String> assembleVersionList(List<? extends Server> servers) { List<VersionSortEntity> versionSortEntityList = new ArrayList<VersionSortEntity>(); for (Server server : servers) { String serverVersion = pluginAdapter.getServerVersion(server); String serverServiceUUId = pluginAdapter.getServerServiceUUId(server); VersionSortEntity versionSortEntity = new VersionSortEntity(); versionSortEntity.setVersion(serverVersion); versionSortEntity.setServiceUUId(serverServiceUUId); versionSortEntityList.add(versionSortEntity); } VersionSortType versionSortType = VersionSortType.fromString(sortType); return VersionSortUtil.getVersionList(versionSortEntityList, versionSortType); } public DiscoveryMatcher getDiscoveryMatcher() { return discoveryMatcher; } public PluginAdapter getPluginAdapter() { return pluginAdapter; } public PluginContextHolder getPluginContextHolder() { return pluginContextHolder; } }
for (Server server : servers) { String serverRegion = pluginAdapter.getServerRegion(server); if (discoveryMatcher.match(regions, serverRegion, true)) { return true; } } return false;
1,098
65
1,163
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressBlacklistEnabledFilter.java
StrategyAddressBlacklistEnabledFilter
apply
class StrategyAddressBlacklistEnabledFilter extends AbstractStrategyEnabledFilter { @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE + 1; } }
String serviceId = pluginAdapter.getServerServiceId(server); String addresses = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteAddressBlacklist(), serviceId); if (StringUtils.isEmpty(addresses)) { return true; } return discoveryMatcher.matchAddress(addresses, server.getHost(), server.getPort(), false);
82
93
175
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyAddressEnabledFilter.java
StrategyAddressEnabledFilter
apply
class StrategyAddressEnabledFilter extends AbstractStrategyEnabledFilter { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ADDRESS_FAILOVER_ENABLED + ":false}") protected Boolean addressFailoverEnabled; @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE + 5; } }
String serviceId = pluginAdapter.getServerServiceId(server); String addresses = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteAddress(), serviceId); if (StringUtils.isEmpty(addresses)) { return true; } if (addressFailoverEnabled) { boolean matched = matchByAddress(servers, addresses); if (!matched) { String addressFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteAddressFailover(), serviceId); if (StringUtils.isEmpty(addressFailovers)) { return true; } else { return discoveryMatcher.matchAddress(addressFailovers, server.getHost(), server.getPort(), true); } } } return discoveryMatcher.matchAddress(addresses, server.getHost(), server.getPort(), true);
131
210
341
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyEnvironmentEnabledFilter.java
StrategyEnvironmentEnabledFilter
apply
class StrategyEnvironmentEnabledFilter extends AbstractStrategyEnabledFilter { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ENVIRONMENT_FAILOVER_ENABLED + ":false}") protected Boolean environmentFailoverEnabled; @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE + 3; } }
String environment = pluginContextHolder.getContextRouteEnvironment(); if (StringUtils.isEmpty(environment)) { return true; } String serverEnvironment = pluginAdapter.getServerEnvironment(server); boolean found = findByEnvironment(servers, environment); if (found) { // 匹配到传递过来的环境Header的服务实例,返回匹配的环境的服务实例 return StringUtils.equals(serverEnvironment, environment); } else { if (environmentFailoverEnabled) { String serviceId = pluginAdapter.getServerServiceId(server); // 没有匹配上,则寻址Common环境,返回Common环境的服务实例 String environmentFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteEnvironmentFailover(), serviceId); if (StringUtils.isEmpty(environmentFailovers)) { environmentFailovers = StrategyConstant.SPRING_APPLICATION_STRATEGY_ENVIRONMENT_FAILOVER_VALUE; } return discoveryMatcher.match(environmentFailovers, serverEnvironment, true); } } return StringUtils.equals(serverEnvironment, environment);
133
289
422
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyGroupEnabledFilter.java
StrategyGroupEnabledFilter
apply
class StrategyGroupEnabledFilter extends AbstractStrategyEnabledFilter { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_CONSUMER_ISOLATION_ENABLED + ":false}") protected Boolean consumerIsolationEnabled; @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE + 2; } }
if (!consumerIsolationEnabled) { return true; } String serverServiceType = pluginAdapter.getServerServiceType(server); if (StringUtils.equals(serverServiceType, ServiceType.GATEWAY.toString())) { return true; } String serverGroup = pluginAdapter.getServerGroup(server); String group = pluginAdapter.getGroup(); return StringUtils.equals(serverGroup, group);
132
113
245
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyIdBlacklistEnabledFilter.java
StrategyIdBlacklistEnabledFilter
apply
class StrategyIdBlacklistEnabledFilter extends AbstractStrategyEnabledFilter { @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE; } }
String serviceId = pluginAdapter.getServerServiceId(server); String ids = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteIdBlacklist(), serviceId); if (StringUtils.isEmpty(ids)) { return true; } String id = pluginAdapter.getServerServiceUUId(server); return discoveryMatcher.match(ids, id, false);
80
101
181
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyRegionEnabledFilter.java
StrategyRegionEnabledFilter
apply
class StrategyRegionEnabledFilter extends AbstractStrategyEnabledFilter { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REGION_TRANSFER_ENABLED + ":false}") protected Boolean regionTransferEnabled; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_REGION_FAILOVER_ENABLED + ":false}") protected Boolean regionFailoverEnabled; @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE + 6; } }
String serviceId = pluginAdapter.getServerServiceId(server); String region = pluginAdapter.getServerRegion(server); String regions = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteRegion(), serviceId); if (StringUtils.isEmpty(regions)) { // 流量路由到指定的区域下。当未对服务指定访问区域的时候,路由到事先指定的区域 // 使用场景示例: // 开发环境(个人电脑环境)在测试环境(线上环境)进行联调 // 访问路径为A服务 -> B服务 -> C服务,A服务和B服务在开发环境上,C服务在测试环境上 // 调用时候,在最前端传入的Header(n-d-region)指定为B的开发环境区域(用来保证A服务和B服务只在开发环境调用),而B服务会自动路由调用到测试环境上的C服务实例,但不会路由到其它个人电脑的C服务实例 // 该功能的意义,个人电脑环境可以接入到测试环境联调,当多套个人环境接入时候,可以保护不同的个人环境间不会彼此调用 if (regionTransferEnabled) { String regionTransfers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteRegionTransfer(), serviceId); if (StringUtils.isEmpty(regionTransfers)) { throw new DiscoveryException("The Region Transfer value is missing"); } return discoveryMatcher.match(regionTransfers, region, true); } else { return true; } } if (regionFailoverEnabled) { boolean matched = matchByRegion(servers, regions); if (!matched) { // 判断提供端服务的元数据多活标记 boolean isServerActive = pluginAdapter.isServerActive(server); // 如果提供端为多活服务,消费端不执行故障转移 if (isServerActive) { return false; } String regionFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteRegionFailover(), serviceId); if (StringUtils.isEmpty(regionFailovers)) { return true; } else { return discoveryMatcher.match(regionFailovers, region, true); } } } return discoveryMatcher.match(regions, region, true);
181
599
780
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyVersionEnabledFilter.java
StrategyVersionEnabledFilter
apply
class StrategyVersionEnabledFilter extends AbstractStrategyEnabledFilter { @Autowired protected StrategyVersionFilterAdapter strategyVersionFilterAdapter; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_FAILOVER_ENABLED + ":false}") protected Boolean versionFailoverEnabled; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_FAILOVER_STABLE_ENABLED + ":false}") protected Boolean versionFailoverStableEnabled; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_VERSION_PREFER_ENABLED + ":false}") protected Boolean versionPreferEnabled; @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} public boolean containVersion(List<? extends Server> servers, Server server) { String version = pluginAdapter.getServerVersion(server); // 当服务未接入本框架或者版本号未设置(表现出来的值为DiscoveryConstant.DEFAULT),则不过滤,返回 if (StringUtils.equals(version, DiscoveryConstant.DEFAULT)) { return true; } List<String> versionList = assembleVersionList(servers); if (versionList.size() <= 1) { return true; } // 过滤出老的稳定版的版本号列表,一般来说,老的稳定版的版本号只有一个,为了增加扩展性,支持多个 List<String> filterVersionList = strategyVersionFilterAdapter.filter(versionList); return filterVersionList.contains(version); } @Override public int getOrder() { return HIGHEST_PRECEDENCE + 7; } }
String serviceId = pluginAdapter.getServerServiceId(server); String version = pluginAdapter.getServerVersion(server); String versions = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteVersion(), serviceId); if (StringUtils.isEmpty(versions)) { // 版本偏好,即非蓝绿灰度发布场景下,路由到老的稳定版本的实例,或者指定版本的实例 if (versionPreferEnabled) { // 版本列表排序策略的(取最老的稳定版本的实例)偏好,即不管存在多少版本,直接路由到最老的稳定版本的实例 String versionPrefers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteVersionPrefer(), serviceId); if (StringUtils.isEmpty(versionPrefers)) { return containVersion(servers, server); } else { // 指定版本的偏好,即不管存在多少版本,直接路由到该版本实例 return discoveryMatcher.match(versionPrefers, version, true); } } else { return true; } } else { // 版本故障转移,即无法找到相应版本的服务实例,路由到老的稳定版本的实例,或者指定版本的实例,或者执行负载均衡 if (versionFailoverEnabled) { boolean matched = matchByVersion(servers, versions); if (!matched) { String versionFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteVersionFailover(), serviceId); if (StringUtils.isEmpty(versionFailovers)) { if (versionFailoverStableEnabled) { // 版本列表排序策略的(取最老的稳定版本的实例)故障转移,即找不到实例的时候,直接路由到最老的稳定版本的实例 return containVersion(servers, server); } else { // 负载均衡策略的故障转移,即找不到实例的时候,执行负载均衡策略 return true; } } else { // 指定版本的故障转移,即找不到实例的时候,直接路由到该版本实例 return discoveryMatcher.match(versionFailovers, version, true); } } } } return discoveryMatcher.match(versions, version, true);
463
585
1,048
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/filter/StrategyZoneEnabledFilter.java
StrategyZoneEnabledFilter
apply
class StrategyZoneEnabledFilter extends AbstractStrategyEnabledFilter { @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_AFFINITY_ENABLED + ":false}") protected Boolean zoneAffinityEnabled; @Value("${" + StrategyConstant.SPRING_APPLICATION_STRATEGY_ZONE_FAILOVER_ENABLED + ":false}") protected Boolean zoneFailoverEnabled; @Override public boolean apply(List<? extends Server> servers, Server server) {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return HIGHEST_PRECEDENCE + 4; } }
if (!zoneAffinityEnabled) { return true; } String zone = pluginAdapter.getZone(); String serverZone = pluginAdapter.getServerZone(server); boolean found = findByZone(servers, zone); if (found) { // 可用区存在:执行可用区亲和性,即调用端实例和提供端实例的元数据Metadata的zone配置值相等才能调用 return StringUtils.equals(serverZone, zone); } else { // 可用区不存在:路由开关打开,可路由到其它指定可用区;路由开关关闭,不可路由到其它可用区或者不归属任何可用区 if (zoneFailoverEnabled) { String serviceId = pluginAdapter.getServerServiceId(server); String zoneFailovers = JsonUtil.fromJsonMap(pluginContextHolder.getContextRouteZoneFailover(), serviceId); if (StringUtils.isEmpty(zoneFailovers)) { return true; } else { return discoveryMatcher.match(zoneFailovers, serverZone, true); } } } return StringUtils.equals(serverZone, zone);
183
302
485
<methods>public non-sealed void <init>() ,public List<java.lang.String> assembleVersionList(List<? extends Server>) ,public void filter(List<? extends Server>) ,public boolean findByEnvironment(List<? extends Server>, java.lang.String) ,public boolean findByGroup(List<? extends Server>, java.lang.String) ,public boolean findByRegion(List<? extends Server>, java.lang.String) ,public boolean findByVersion(List<? extends Server>, java.lang.String) ,public boolean findByZone(List<? extends Server>, java.lang.String) ,public com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher getDiscoveryMatcher() ,public com.nepxion.discovery.plugin.framework.adapter.PluginAdapter getPluginAdapter() ,public com.nepxion.discovery.plugin.framework.context.PluginContextHolder getPluginContextHolder() ,public boolean matchByAddress(List<? extends Server>, java.lang.String) ,public boolean matchByRegion(List<? extends Server>, java.lang.String) ,public boolean matchByVersion(List<? extends Server>, java.lang.String) <variables>protected com.nepxion.discovery.plugin.strategy.matcher.DiscoveryMatcher discoveryMatcher,protected com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter,protected com.nepxion.discovery.plugin.framework.context.PluginContextHolder pluginContextHolder,protected java.lang.String sortType
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyHeadersResolver.java
StrategyHeadersResolver
getInjectedHeaders
class StrategyHeadersResolver { public static List<String> getInjectedHeaders(List<StrategyHeadersInjector> strategyHeadersInjectorList, HeadersInjectorType headersInjectorType) {<FILL_FUNCTION_BODY>} }
List<String> headerList = null; if (CollectionUtils.isNotEmpty(strategyHeadersInjectorList)) { headerList = new ArrayList<String>(); for (StrategyHeadersInjector strategyHeadersInjector : strategyHeadersInjectorList) { List<HeadersInjectorEntity> headersInjectorEntityList = strategyHeadersInjector.getHeadersInjectorEntityList(); if (CollectionUtils.isNotEmpty(headersInjectorEntityList)) { for (HeadersInjectorEntity headersInjectorEntity : headersInjectorEntityList) { HeadersInjectorType injectorType = headersInjectorEntity.getHeadersInjectorType(); List<String> headers = headersInjectorEntity.getHeaders(); if (injectorType == headersInjectorType || injectorType == HeadersInjectorType.ALL) { if (CollectionUtils.isNotEmpty(headers)) { for (String header : headers) { if (!headerList.contains(header)) { headerList.add(header); } } } } } } } } return headerList;
62
288
350
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/injector/StrategyPackagesResolver.java
StrategyPackagesResolver
getInjectedPackages
class StrategyPackagesResolver { public static List<String> getInjectedPackages(List<StrategyPackagesInjector> strategyPackagesInjectorList, PackagesInjectorType packagesInjectorType) {<FILL_FUNCTION_BODY>} }
List<String> packageList = null; if (CollectionUtils.isNotEmpty(strategyPackagesInjectorList)) { packageList = new ArrayList<String>(); for (StrategyPackagesInjector strategyPackagesInjector : strategyPackagesInjectorList) { List<PackagesInjectorEntity> packagesInjectorEntityList = strategyPackagesInjector.getPackagesInjectorEntityList(); if (CollectionUtils.isNotEmpty(packagesInjectorEntityList)) { for (PackagesInjectorEntity packagesInjectorEntity : packagesInjectorEntityList) { PackagesInjectorType injectorType = packagesInjectorEntity.getPackagesInjectorType(); List<String> packages = packagesInjectorEntity.getPackages(); if (injectorType == packagesInjectorType || injectorType == PackagesInjectorType.ALL) { if (CollectionUtils.isNotEmpty(packages)) { for (String pkg : packages) { if (!packageList.contains(pkg)) { packageList.add(pkg); } } } } } } } } return packageList;
65
297
362
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/matcher/DiscoveryMatcher.java
DiscoveryMatcher
match
class DiscoveryMatcher { @Autowired protected DiscoveryMatcherStrategy discoveryMatcherStrategy; public boolean match(String targetValues, String value, boolean returnValue) {<FILL_FUNCTION_BODY>} public boolean matchAddress(String addresses, String host, int port, boolean returnValue) { List<String> addressList = StringUtil.splitToList(addresses); // 如果精确匹配不满足,尝试用通配符匹配 if (addressList.contains(host + ":" + port) || addressList.contains(host) || addressList.contains(String.valueOf(port))) { return returnValue; } // 通配符匹配。前者是通配表达式,后者是具体值 for (String addressPattern : addressList) { if (discoveryMatcherStrategy.match(addressPattern, host + ":" + port) || discoveryMatcherStrategy.match(addressPattern, host) || discoveryMatcherStrategy.match(addressPattern, String.valueOf(port))) { return returnValue; } } return !returnValue; } }
List<String> targetValueList = StringUtil.splitToList(targetValues); // 如果精确匹配不满足,尝试用通配符匹配 if (targetValueList.contains(value)) { return returnValue; } // 通配符匹配。前者是通配表达式,后者是具体值 for (String targetValuePattern : targetValueList) { if (discoveryMatcherStrategy.match(targetValuePattern, value)) { return returnValue; } } return !returnValue;
280
142
422
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyMonitorContext.java
StrategyMonitorContext
getTracerCustomizationMap
class StrategyMonitorContext { @Autowired(required = false) protected StrategyTracer strategyTracer; @Autowired(required = false) protected StrategyTracerAdapter strategyTracerAdapter; @Autowired(required = false) protected List<StrategyHeadersInjector> strategyHeadersInjectorList; protected List<String> tracerInjectorHeaderNameList; @PostConstruct public void initialize() { tracerInjectorHeaderNameList = StrategyHeadersResolver.getInjectedHeaders(strategyHeadersInjectorList, HeadersInjectorType.TRACER); } public String getTraceId() { if (strategyTracer != null) { return strategyTracer.getTraceId(); } if (strategyTracerAdapter != null) { return strategyTracerAdapter.getTraceId(); } return null; } public String getSpanId() { if (strategyTracer != null) { return strategyTracer.getSpanId(); } if (strategyTracerAdapter != null) { return strategyTracerAdapter.getSpanId(); } return null; } public List<String> getTracerInjectorHeaderNameList() { return tracerInjectorHeaderNameList; } public Map<String, String> getTracerCustomizationMap() {<FILL_FUNCTION_BODY>} }
if (strategyTracerAdapter != null) { return strategyTracerAdapter.getCustomizationMap(); } return null;
375
39
414
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContext.java
StrategyTracerContext
clearCurrentContext
class StrategyTracerContext { private static final ThreadLocal<StrategyTracerContext> THREAD_LOCAL = new ThreadLocal<StrategyTracerContext>() { @Override protected StrategyTracerContext initialValue() { return new StrategyTracerContext(); } }; private LinkedList<Object> spanList = new LinkedList<Object>(); public static StrategyTracerContext getCurrentContext() { return THREAD_LOCAL.get(); } public static void clearCurrentContext() {<FILL_FUNCTION_BODY>} public Object getSpan() { if (spanList.isEmpty()) { return null; } return spanList.getLast(); } public void setSpan(Object span) { spanList.addLast(span); } private LinkedList<Object> getSpanList() { return spanList; } @Override public int hashCode() { return HashCodeBuilder.reflectionHashCode(this); } @Override public boolean equals(Object object) { return EqualsBuilder.reflectionEquals(this, object); } @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } }
StrategyTracerContext strategyTracerContext = THREAD_LOCAL.get(); if (strategyTracerContext == null) { return; } LinkedList<Object> spanList = strategyTracerContext.getSpanList(); if (!spanList.isEmpty()) { spanList.removeLast(); } if (spanList.isEmpty()) { THREAD_LOCAL.remove(); }
337
108
445
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/monitor/StrategyTracerContextListener.java
StrategyTracerContextListener
onApplicationEvent
class StrategyTracerContextListener implements ApplicationListener<ContextRefreshedEvent> { private static final Logger LOG = LoggerFactory.getLogger(StrategyTracerContextListener.class); @Override public void onApplicationEvent(ContextRefreshedEvent event) {<FILL_FUNCTION_BODY>} }
// 异步调用下,第一次启动在某些情况下可能存在丢失上下文的问题 LOG.info("Initialize Strategy Tracer Context after Application started..."); StrategyTracerContext.getCurrentContext();
78
55
133
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledBasePredicate.java
DiscoveryEnabledBasePredicate
apply
class DiscoveryEnabledBasePredicate extends AbstractServerPredicate { protected PluginAdapter pluginAdapter; protected DiscoveryEnabledAdapter discoveryEnabledAdapter; @Override public boolean apply(PredicateKey input) { return input != null && apply(input.getServer()); } protected boolean apply(Server server) {<FILL_FUNCTION_BODY>} public void setPluginAdapter(PluginAdapter pluginAdapter) { this.pluginAdapter = pluginAdapter; } public void setDiscoveryEnabledAdapter(DiscoveryEnabledAdapter discoveryEnabledAdapter) { this.discoveryEnabledAdapter = discoveryEnabledAdapter; } }
if (discoveryEnabledAdapter == null) { return true; } return discoveryEnabledAdapter.apply(server);
158
35
193
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidancePredicate.java
DiscoveryEnabledZoneAvoidancePredicate
apply
class DiscoveryEnabledZoneAvoidancePredicate extends ZoneAvoidancePredicate { protected PluginAdapter pluginAdapter; protected DiscoveryEnabledAdapter discoveryEnabledAdapter; public DiscoveryEnabledZoneAvoidancePredicate(IRule rule, IClientConfig clientConfig) { super(rule, clientConfig); } public DiscoveryEnabledZoneAvoidancePredicate(LoadBalancerStats lbStats, IClientConfig clientConfig) { super(lbStats, clientConfig); } @Override public boolean apply(PredicateKey input) { boolean enabled = super.apply(input); if (!enabled) { return false; } return apply(input.getServer()); } protected boolean apply(Server server) {<FILL_FUNCTION_BODY>} public void setPluginAdapter(PluginAdapter pluginAdapter) { this.pluginAdapter = pluginAdapter; } public void setDiscoveryEnabledAdapter(DiscoveryEnabledAdapter discoveryEnabledAdapter) { this.discoveryEnabledAdapter = discoveryEnabledAdapter; } }
if (discoveryEnabledAdapter == null) { return true; } return discoveryEnabledAdapter.apply(server);
264
35
299
<no_super_class>
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/rule/DiscoveryEnabledZoneAvoidanceRule.java
DiscoveryEnabledZoneAvoidanceRule
initWithNiwsConfig
class DiscoveryEnabledZoneAvoidanceRule extends ZoneAvoidanceRuleDecorator { private CompositePredicate compositePredicate; private DiscoveryEnabledZoneAvoidancePredicate discoveryEnabledPredicate; public DiscoveryEnabledZoneAvoidanceRule() { super(); discoveryEnabledPredicate = new DiscoveryEnabledZoneAvoidancePredicate(this, null); AvailabilityPredicate availabilityPredicate = new AvailabilityPredicate(this, null); compositePredicate = createCompositePredicate(discoveryEnabledPredicate, availabilityPredicate); } private CompositePredicate createCompositePredicate(DiscoveryEnabledZoneAvoidancePredicate discoveryEnabledPredicate, AvailabilityPredicate availabilityPredicate) { return CompositePredicate.withPredicates(discoveryEnabledPredicate, availabilityPredicate) // .addFallbackPredicate(availabilityPredicate) // .addFallbackPredicate(AbstractServerPredicate.alwaysTrue()) .build(); } @Override public void initWithNiwsConfig(IClientConfig clientConfig) {<FILL_FUNCTION_BODY>} @Override public AbstractServerPredicate getPredicate() { return compositePredicate; } public DiscoveryEnabledZoneAvoidancePredicate getDiscoveryEnabledPredicate() { return discoveryEnabledPredicate; } }
discoveryEnabledPredicate = new DiscoveryEnabledZoneAvoidancePredicate(this, clientConfig); AvailabilityPredicate availabilityPredicate = new AvailabilityPredicate(this, clientConfig); compositePredicate = createCompositePredicate(discoveryEnabledPredicate, availabilityPredicate);
332
69
401
<methods>public non-sealed void <init>() ,public Server choose(java.lang.Object) ,public Server filterChoose(java.lang.Object) <variables>private com.nepxion.discovery.plugin.framework.loadbalance.DiscoveryEnabledLoadBalance discoveryEnabledLoadBalance,private RuleWeightRandomLoadBalance<com.nepxion.discovery.common.entity.WeightFilterEntity> ruleWeightRandomLoadBalance,private StrategyWeightRandomLoadBalance<com.nepxion.discovery.common.entity.WeightFilterEntity> strategyWeightRandomLoadBalance
Nepxion_Discovery
Discovery/discovery-plugin-strategy/discovery-plugin-strategy-starter/src/main/java/com/nepxion/discovery/plugin/strategy/util/StrategyUtil.java
StrategyUtil
isCoreHeaderContains
class StrategyUtil { public static boolean isCoreHeaderContains(String headerName) {<FILL_FUNCTION_BODY>} public static boolean isInnerHeaderContains(String headerName) { return StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_GROUP) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_TYPE) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_APP_ID) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ID) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ADDRESS) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_VERSION) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_REGION) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ENVIRONMENT) || StringUtils.equals(headerName, DiscoveryConstant.N_D_SERVICE_ZONE); } }
return StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION) || StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION) || StringUtils.equals(headerName, DiscoveryConstant.N_D_ADDRESS) || StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION_WEIGHT) || StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION_WEIGHT) || StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION_PREFER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_VERSION_FAILOVER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION_TRANSFER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_REGION_FAILOVER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_ENVIRONMENT_FAILOVER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_ZONE_FAILOVER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_ADDRESS_FAILOVER) || StringUtils.equals(headerName, DiscoveryConstant.N_D_ID_BLACKLIST) || StringUtils.equals(headerName, DiscoveryConstant.N_D_ADDRESS_BLACKLIST);
278
355
633
<no_super_class>