proj_name
stringclasses 131
values | relative_path
stringlengths 30
228
| class_name
stringlengths 1
68
| func_name
stringlengths 1
48
| masked_class
stringlengths 78
9.82k
| func_body
stringlengths 46
9.61k
| len_input
int64 29
2.01k
| len_output
int64 14
1.94k
| total
int64 55
2.05k
| relevant_context
stringlengths 0
38.4k
|
---|---|---|---|---|---|---|---|---|---|
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>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryEnabledStrategy.java
|
MyDiscoveryEnabledStrategy
|
applyFromHeader
|
class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class);
@Autowired
private GatewayStrategyContextHolder gatewayStrategyContextHolder;
@Autowired
private PluginAdapter pluginAdapter;
@Override
public boolean apply(Server server) {
// 对Rest调用传来的Header参数(例如:mobile)做策略
return applyFromHeader(server);
}
// 根据REST调用传来的Header参数(例如:mobile),选取执行调用请求的服务实例
private boolean applyFromHeader(Server server) {<FILL_FUNCTION_BODY>}
}
|
String mobile = gatewayStrategyContextHolder.getHeader("mobile");
String serviceId = pluginAdapter.getServerServiceId(server);
String version = pluginAdapter.getServerVersion(server);
String region = pluginAdapter.getServerRegion(server);
String environment = pluginAdapter.getServerEnvironment(server);
String address = server.getHost() + ":" + server.getPort();
LOG.info("负载均衡用户定制触发:mobile={}, serviceId={}, version={}, region={}, env={}, address={}", mobile, serviceId, version, region, environment, address);
if (StringUtils.isNotEmpty(mobile)) {
// 手机号以移动138开头,路由到1.0版本的服务上
if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) {
return true;
// 手机号以联通133开头,路由到1.1版本的服务上
} else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) {
return true;
} else {
// 其它情况,实例被过滤掉
return false;
}
}
// 无手机号,实例不被过滤掉
return true;
| 181 | 332 | 513 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyDiscoveryListener.java
|
MyDiscoveryListener
|
onGetInstances
|
class MyDiscoveryListener extends AbstractDiscoveryListener {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryListener.class);
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE - 500;
}
}
|
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance instance = iterator.next();
String group = pluginAdapter.getInstanceGroup(instance);
if (StringUtils.equals(group, "mygroup2")) {
iterator.remove();
LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现");
}
}
| 132 | 115 | 247 |
<methods>public non-sealed void <init>() ,public DiscoveryClient getDiscoveryClient() <variables>protected DiscoveryClient discoveryClient
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyLoadBalanceListener.java
|
MyLoadBalanceListener
|
onGetServers
|
class MyLoadBalanceListener extends AbstractLoadBalanceListener {
private static final Logger LOG = LoggerFactory.getLogger(MyLoadBalanceListener.class);
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE - 500;
}
}
|
Iterator<? extends Server> iterator = servers.iterator();
while (iterator.hasNext()) {
Server server = iterator.next();
String group = pluginAdapter.getServerGroup(server);
if (StringUtils.equals(group, "mygroup3")) {
iterator.remove();
LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡");
}
}
| 112 | 119 | 231 |
<methods>public non-sealed void <init>() <variables>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRegisterListener.java
|
MyRegisterListener
|
onRegister
|
class MyRegisterListener extends AbstractRegisterListener {
@Override
public void onRegister(Registration registration) {<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() {
return LOWEST_PRECEDENCE - 500;
}
}
|
String serviceId = pluginAdapter.getServiceId();
String group = pluginAdapter.getGroup();
if (StringUtils.equals(group, "mygroup1")) {
throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心");
}
| 139 | 82 | 221 |
<methods>public non-sealed void <init>() ,public ServiceRegistry<?> getServiceRegistry() <variables>protected ServiceRegistry<?> serviceRegistry
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MyRouteFilter.java
|
MyRouteFilter
|
getRouteVersion
|
class MyRouteFilter extends DefaultGatewayStrategyRouteFilter {
private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}";
private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}";
@Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}")
private String aRouteVersion;
@Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}")
private String bRouteVersion;
@Override
public String getRouteVersion() {<FILL_FUNCTION_BODY>}
}
|
String user = strategyContextHolder.getHeader("user");
if (StringUtils.equals(user, "zhangsan")) {
return aRouteVersion;
} else if (StringUtils.equals(user, "lisi")) {
return bRouteVersion;
}
return super.getRouteVersion();
| 256 | 81 | 337 |
<methods>public non-sealed void <init>() ,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 com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder getStrategyContextHolder() <variables>protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-gateway/src/main/java/com/nepxion/discovery/plugin/example/gateway/impl/MySubscriber.java
|
MySubscriber
|
onParameterChanged
|
class MySubscriber {
private static final Logger LOG = LoggerFactory.getLogger(MySubscriber.class);
@Autowired
private PluginAdapter pluginAdapter;
@Subscribe
public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) {
LOG.info("规则执行更新, rule=" + ruleUpdatedEvent.getRule());
}
@Subscribe
public void onRuleCleared(RuleClearedEvent ruleClearedEvent) {
LOG.info("规则执行清空");
}
@Subscribe
public void onRuleRuleFailure(RuleFailureEvent ruleFailureEvent) {
LOG.info("规则更新失败, rule=" + ruleFailureEvent.getRule() + ", exception=" + ruleFailureEvent.getException());
}
@Subscribe
public void onParameterChanged(ParameterChangedEvent parameterChangedEvent) {<FILL_FUNCTION_BODY>}
@Subscribe
public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) {
LOG.info("注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort());
}
@Subscribe
public void onAlarm(StrategyAlarmEvent strategyAlarmEvent) {
LOG.info("告警类型=" + strategyAlarmEvent.getAlarmType());
LOG.info("告警内容=" + strategyAlarmEvent.getAlarmMap());
}
}
|
ParameterEntity parameterEntity = parameterChangedEvent.getParameterEntity();
String serviceId = pluginAdapter.getServiceId();
List<ParameterServiceEntity> parameterServiceEntityList = null;
if (parameterEntity != null) {
Map<String, List<ParameterServiceEntity>> parameterServiceMap = parameterEntity.getParameterServiceMap();
parameterServiceEntityList = parameterServiceMap.get(serviceId);
}
LOG.info("获取动态参数, serviceId=" + serviceId + ", parameterServiceEntityList=" + parameterServiceEntityList);
| 401 | 132 | 533 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/context/MyApplicationContextInitializer.java
|
MyApplicationContextInitializer
|
initialize
|
class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {<FILL_FUNCTION_BODY>}
}
|
if (applicationContext instanceof AnnotationConfigApplicationContext) {
return;
}
// System.setProperty("ext.group", "myGroup");
// System.setProperty("ext.version", "8888");
// System.setProperty("ext.region", "myRegion");
| 51 | 75 | 126 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/AFeignImpl.java
|
AFeignImpl
|
invoke
|
class AFeignImpl extends AbstractFeignImpl implements AFeign {
private static final Logger LOG = LoggerFactory.getLogger(AFeignImpl.class);
@Autowired
private BFeign bFeign;
@Override
public String invoke(@RequestBody String value) {<FILL_FUNCTION_BODY>}
}
|
value = doInvoke(value);
value = bFeign.invoke(value);
LOG.info("调用路径:{}", value);
return value;
| 87 | 48 | 135 |
<methods>public non-sealed void <init>() ,public java.lang.String doInvoke(java.lang.String) <variables>private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/feign/BFeignImpl.java
|
BFeignImpl
|
invoke
|
class BFeignImpl extends AbstractFeignImpl implements BFeign {
private static final Logger LOG = LoggerFactory.getLogger(BFeignImpl.class);
@Autowired
private CFeign cFeign;
@Override
public String invoke(@RequestBody String value) {<FILL_FUNCTION_BODY>}
}
|
value = doInvoke(value);
value = cFeign.invoke(value);
LOG.info("调用路径:{}", value);
return value;
| 87 | 48 | 135 |
<methods>public non-sealed void <init>() ,public java.lang.String doInvoke(java.lang.String) <variables>private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryEnabledStrategy.java
|
MyDiscoveryEnabledStrategy
|
applyFromHeader
|
class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class);
@Autowired
private PluginAdapter pluginAdapter;
@Autowired
private ServiceStrategyContextHolder serviceStrategyContextHolder;
@Override
public boolean apply(Server server) {
// 对Rest调用传来的Header参数(例如:token)做策略
boolean enabled = applyFromHeader(server);
if (!enabled) {
return false;
}
// 对RPC调用传来的方法参数做策略
return applyFromMethod(server);
}
// 根据REST调用传来的Header参数(例如:token),选取执行调用请求的服务实例
private boolean applyFromHeader(Server server) {<FILL_FUNCTION_BODY>}
// 根据RPC调用传来的方法参数(例如接口名、方法名、参数名或参数值等),选取执行调用请求的服务实例
@SuppressWarnings("unchecked")
private boolean applyFromMethod(Server server) {
Map<String, Object> attributes = serviceStrategyContextHolder.getRpcAttributes();
String serviceId = pluginAdapter.getServerServiceId(server);
String version = pluginAdapter.getServerVersion(server);
String region = pluginAdapter.getServerRegion(server);
String environment = pluginAdapter.getServerEnvironment(server);
String address = server.getHost() + ":" + server.getPort();
LOG.info("负载均衡用户定制触发:attributes={}, serviceId={}, version={}, region={}, env={}, address={}", attributes, serviceId, version, region, environment, address);
String filterServiceId = "discovery-springcloud-example-b";
String filterVersion = "1.0";
String filterBusinessValue = "abc";
if (StringUtils.equals(serviceId, filterServiceId) && StringUtils.equals(version, filterVersion)) {
if (attributes.containsKey(DiscoveryConstant.PARAMETER_MAP)) {
Map<String, Object> parameterMap = (Map<String, Object>) attributes.get(DiscoveryConstant.PARAMETER_MAP);
String value = parameterMap.get("value").toString();
if (StringUtils.isNotEmpty(value) && value.contains(filterBusinessValue)) {
LOG.info("过滤条件:当serviceId={} && version={} && 业务参数含有'{}'的时候,不能被负载均衡到", filterServiceId, filterVersion, filterBusinessValue);
return false;
}
}
}
return true;
}
}
|
String token = serviceStrategyContextHolder.getHeader("token");
String serviceId = pluginAdapter.getServerServiceId(server);
String version = pluginAdapter.getServerVersion(server);
String region = pluginAdapter.getServerRegion(server);
String environment = pluginAdapter.getServerEnvironment(server);
String address = server.getHost() + ":" + server.getPort();
LOG.info("负载均衡用户定制触发:token={}, serviceId={}, version={}, region={}, env={}, address={}", token, serviceId, version, region, environment, address);
String filterServiceId = "discovery-springcloud-example-c";
String filterToken = "123";
if (StringUtils.equals(serviceId, filterServiceId) && StringUtils.isNotEmpty(token) && token.contains(filterToken)) {
LOG.info("过滤条件:当serviceId={} && Token含有'{}'的时候,不能被负载均衡到", filterServiceId, filterToken);
return false;
}
return true;
| 670 | 270 | 940 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyDiscoveryListener.java
|
MyDiscoveryListener
|
onGetInstances
|
class MyDiscoveryListener extends AbstractDiscoveryListener {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryListener.class);
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE - 500;
}
}
|
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance instance = iterator.next();
String group = pluginAdapter.getInstanceGroup(instance);
if (StringUtils.equals(group, "mygroup2")) {
iterator.remove();
LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现");
}
}
| 132 | 115 | 247 |
<methods>public non-sealed void <init>() ,public DiscoveryClient getDiscoveryClient() <variables>protected DiscoveryClient discoveryClient
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyLoadBalanceListener.java
|
MyLoadBalanceListener
|
onGetServers
|
class MyLoadBalanceListener extends AbstractLoadBalanceListener {
private static final Logger LOG = LoggerFactory.getLogger(MyLoadBalanceListener.class);
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE - 500;
}
}
|
Iterator<? extends Server> iterator = servers.iterator();
while (iterator.hasNext()) {
Server server = iterator.next();
String group = pluginAdapter.getServerGroup(server);
if (StringUtils.equals(group, "mygroup3")) {
iterator.remove();
LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡");
}
}
| 112 | 119 | 231 |
<methods>public non-sealed void <init>() <variables>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRegisterListener.java
|
MyRegisterListener
|
onRegister
|
class MyRegisterListener extends AbstractRegisterListener {
@Override
public void onRegister(Registration registration) {<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() {
return LOWEST_PRECEDENCE - 500;
}
}
|
String serviceId = pluginAdapter.getServiceId();
String group = pluginAdapter.getGroup();
if (StringUtils.equals(group, "mygroup1")) {
throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心");
}
| 139 | 82 | 221 |
<methods>public non-sealed void <init>() ,public ServiceRegistry<?> getServiceRegistry() <variables>protected ServiceRegistry<?> serviceRegistry
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MyRouteFilter.java
|
MyRouteFilter
|
getRouteVersion
|
class MyRouteFilter extends DefaultServiceStrategyRouteFilter {
private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}";
private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}";
@Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}")
private String aRouteVersion;
@Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}")
private String bRouteVersion;
@Override
public String getRouteVersion() {<FILL_FUNCTION_BODY>}
}
|
String user = strategyContextHolder.getHeader("user");
if (StringUtils.equals(user, "zhangsan")) {
return aRouteVersion;
} else if (StringUtils.equals(user, "lisi")) {
return bRouteVersion;
}
return super.getRouteVersion();
| 254 | 81 | 335 |
<methods>public non-sealed void <init>() ,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 com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder getStrategyContextHolder() <variables>protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/impl/MySubscriber.java
|
MySubscriber
|
onParameterChanged
|
class MySubscriber {
private static final Logger LOG = LoggerFactory.getLogger(MySubscriber.class);
@Autowired
private PluginAdapter pluginAdapter;
@Subscribe
public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) {
LOG.info("规则执行更新, rule=" + ruleUpdatedEvent.getRule());
}
@Subscribe
public void onRuleCleared(RuleClearedEvent ruleClearedEvent) {
LOG.info("规则执行清空");
}
@Subscribe
public void onRuleRuleFailure(RuleFailureEvent ruleFailureEvent) {
LOG.info("规则更新失败, rule=" + ruleFailureEvent.getRule() + ", exception=" + ruleFailureEvent.getException());
}
@Subscribe
public void onParameterChanged(ParameterChangedEvent parameterChangedEvent) {<FILL_FUNCTION_BODY>}
@Subscribe
public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) {
LOG.info("注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort());
}
@Subscribe
public void onAlarm(StrategyAlarmEvent strategyAlarmEvent) {
LOG.info("告警类型=" + strategyAlarmEvent.getAlarmType());
LOG.info("告警内容=" + strategyAlarmEvent.getAlarmMap());
}
}
|
ParameterEntity parameterEntity = parameterChangedEvent.getParameterEntity();
String serviceId = pluginAdapter.getServiceId();
List<ParameterServiceEntity> parameterServiceEntityList = null;
if (parameterEntity != null) {
Map<String, List<ParameterServiceEntity>> parameterServiceMap = parameterEntity.getParameterServiceMap();
parameterServiceEntityList = parameterServiceMap.get(serviceId);
}
LOG.info("获取动态参数, serviceId=" + serviceId + ", parameterServiceEntityList=" + parameterServiceEntityList);
| 401 | 132 | 533 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/ARestImpl.java
|
ARestImpl
|
rest
|
class ARestImpl extends AbstractRestImpl {
private static final Logger LOG = LoggerFactory.getLogger(ARestImpl.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private ServiceStrategyContextHolder serviceStrategyContextHolder;
@RequestMapping(path = "/rest", method = RequestMethod.POST)
@SentinelResource(value = "sentinel-resource", blockHandler = "handleBlock", fallback = "handleFallback")
public String rest(@RequestBody String value) {<FILL_FUNCTION_BODY>}
@RequestMapping(path = "/test", method = RequestMethod.POST)
public String test(@RequestBody String value) {
try {
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
public String handleBlock(String value, BlockException e) {
return "A server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp() + ", value=" + value;
}
public String handleFallback(String value) {
return "A server sentinel fallback, value=" + value;
}
}
|
value = doRest(value);
// Just for testing
ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes();
Enumeration<String> headerNames = attributes.getRequest().getHeaderNames();
LOG.info("Header name list:");
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
LOG.info("* " + headerName);
}
String token = attributes.getRequest().getHeader("token");
LOG.info("Old token=" + token);
LOG.info("New token=Token-A");
HttpHeaders headers = new HttpHeaders();
headers.set("token", "Token-A");
HttpEntity<String> entity = new HttpEntity<String>(value, headers);
value = restTemplate.postForEntity("http://discovery-springcloud-example-b/rest", entity, String.class).getBody();
LOG.info("调用路径:{}", value);
return value;
| 328 | 252 | 580 |
<methods>public non-sealed void <init>() ,public java.lang.String doRest(java.lang.String) <variables>private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/BRestImpl.java
|
BRestImpl
|
handleBlock
|
class BRestImpl extends AbstractRestImpl {
private static final Logger LOG = LoggerFactory.getLogger(BRestImpl.class);
@Autowired
private RestTemplate restTemplate;
@Autowired
private ServiceStrategyContextHolder serviceStrategyContextHolder;
@RequestMapping(path = "/rest", method = RequestMethod.POST)
@SentinelResource(value = "sentinel-resource", blockHandler = "handleBlock", fallback = "handleFallback")
public String rest(@RequestBody String value) {
value = doRest(value);
// Just for testing
ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes();
Enumeration<String> headerNames = attributes.getRequest().getHeaderNames();
LOG.info("Header name list:");
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
LOG.info("* " + headerName);
}
String token = attributes.getRequest().getHeader("token");
LOG.info("Old token=" + token);
LOG.info("New token=Token-B");
HttpHeaders headers = new HttpHeaders();
headers.set("token", "Token-B");
HttpEntity<String> entity = new HttpEntity<String>(value, headers);
value = restTemplate.postForEntity("http://discovery-springcloud-example-c/rest", entity, String.class).getBody();
LOG.info("调用路径:{}", value);
return value;
}
@RequestMapping(path = "/test", method = RequestMethod.POST)
public String test(@RequestBody String value) {
return value;
}
public String handleBlock(String value, BlockException e) {<FILL_FUNCTION_BODY>}
public String handleFallback(String value) {
return "B server sentinel fallback, value=" + value;
}
}
|
return "B server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp() + ", value=" + value;
| 486 | 58 | 544 |
<methods>public non-sealed void <init>() ,public java.lang.String doRest(java.lang.String) <variables>private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/rest/CRestImpl.java
|
CRestImpl
|
handleBlock
|
class CRestImpl extends AbstractRestImpl {
private static final Logger LOG = LoggerFactory.getLogger(CRestImpl.class);
@Autowired
private ServiceStrategyContextHolder serviceStrategyContextHolder;
@RequestMapping(path = "/rest", method = RequestMethod.POST)
@SentinelResource(value = "sentinel-resource", blockHandler = "handleBlock", fallback = "handleFallback")
public String rest(@RequestBody String value) {
value = doRest(value);
// Just for testing
ServletRequestAttributes attributes = serviceStrategyContextHolder.getRestAttributes();
Enumeration<String> headerNames = attributes.getRequest().getHeaderNames();
LOG.info("Header name list:");
while (headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
LOG.info("* " + headerName);
}
String token = attributes.getRequest().getHeader("token");
LOG.info("Token=" + token);
LOG.info("调用路径:{}", value);
return value;
}
@RequestMapping(path = "/test", method = RequestMethod.POST)
public String test(@RequestBody String value) {
return value;
}
public String handleBlock(String value, BlockException e) {<FILL_FUNCTION_BODY>}
public String handleFallback(String value) {
return "C server sentinel fallback, value=" + value;
}
}
|
return "C server sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp() + ", value=" + value;
| 377 | 58 | 435 |
<methods>public non-sealed void <init>() ,public java.lang.String doRest(java.lang.String) <variables>private com.nepxion.discovery.plugin.framework.adapter.PluginAdapter pluginAdapter
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyAFeignFallbackHandler.java
|
MyAFeignFallbackHandler
|
invoke
|
class MyAFeignFallbackHandler implements AFeign {
@Override
public String invoke(String value) {<FILL_FUNCTION_BODY>}
}
|
return value + " -> A Feign client sentinel fallback";
| 43 | 21 | 64 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyBFeignFallbackHandler.java
|
MyBFeignFallbackHandler
|
invoke
|
class MyBFeignFallbackHandler implements BFeign {
@Override
public String invoke(String value) {<FILL_FUNCTION_BODY>}
}
|
return value + " -> B Feign client sentinel fallback";
| 43 | 21 | 64 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyCFeignFallbackHandler.java
|
MyCFeignFallbackHandler
|
invoke
|
class MyCFeignFallbackHandler implements CFeign {
@Override
public String invoke(String value) {<FILL_FUNCTION_BODY>}
}
|
return value + " -> C Feign client sentinel fallback";
| 43 | 21 | 64 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateBlockHandler.java
|
MyRestTemplateBlockHandler
|
handleBlock
|
class MyRestTemplateBlockHandler {
public static SentinelClientHttpResponse handleBlock(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException e) {<FILL_FUNCTION_BODY>}
}
|
return new SentinelClientHttpResponse("RestTemplate client sentinel block, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp());
| 54 | 58 | 112 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-service/src/main/java/com/nepxion/discovery/plugin/example/service/sentinel/MyRestTemplateFallbackHandler.java
|
MyRestTemplateFallbackHandler
|
handleFallback
|
class MyRestTemplateFallbackHandler {
public static SentinelClientHttpResponse handleFallback(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException e) {<FILL_FUNCTION_BODY>}
}
|
return new SentinelClientHttpResponse("RestTemplate client sentinel fallback, cause=" + e.getClass().getName() + ", rule=" + e.getRule() + ", limitApp=" + e.getRuleLimitApp());
| 58 | 59 | 117 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryEnabledStrategy.java
|
MyDiscoveryEnabledStrategy
|
applyFromHeader
|
class MyDiscoveryEnabledStrategy implements DiscoveryEnabledStrategy {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryEnabledStrategy.class);
@Autowired
private ZuulStrategyContextHolder zuulStrategyContextHolder;
@Autowired
private PluginAdapter pluginAdapter;
@Override
public boolean apply(Server server) {
// 对Rest调用传来的Header参数(例如:mobile)做策略
return applyFromHeader(server);
}
// 根据REST调用传来的Header参数(例如:mobile),选取执行调用请求的服务实例
private boolean applyFromHeader(Server server) {<FILL_FUNCTION_BODY>}
}
|
String mobile = zuulStrategyContextHolder.getHeader("mobile");
String serviceId = pluginAdapter.getServerServiceId(server);
String version = pluginAdapter.getServerVersion(server);
String region = pluginAdapter.getServerRegion(server);
String environment = pluginAdapter.getServerEnvironment(server);
String address = server.getHost() + ":" + server.getPort();
LOG.info("负载均衡用户定制触发:mobile={}, serviceId={}, version={}, region={}, env={}, address={}", mobile, serviceId, version, region, environment, address);
if (StringUtils.isNotEmpty(mobile)) {
// 手机号以移动138开头,路由到1.0版本的服务上
if (mobile.startsWith("138") && StringUtils.equals(version, "1.0")) {
return true;
// 手机号以联通133开头,路由到1.1版本的服务上
} else if (mobile.startsWith("133") && StringUtils.equals(version, "1.1")) {
return true;
} else {
// 其它情况,实例被过滤掉
return false;
}
}
// 无手机号,实例不被过滤掉
return true;
| 184 | 334 | 518 |
<no_super_class>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyDiscoveryListener.java
|
MyDiscoveryListener
|
onGetInstances
|
class MyDiscoveryListener extends AbstractDiscoveryListener {
private static final Logger LOG = LoggerFactory.getLogger(MyDiscoveryListener.class);
@Override
public void onGetInstances(String serviceId, List<ServiceInstance> instances) {<FILL_FUNCTION_BODY>}
@Override
public void onGetServices(List<String> services) {
}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE - 500;
}
}
|
Iterator<ServiceInstance> iterator = instances.iterator();
while (iterator.hasNext()) {
ServiceInstance instance = iterator.next();
String group = pluginAdapter.getInstanceGroup(instance);
if (StringUtils.equals(group, "mygroup2")) {
iterator.remove();
LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务发现");
}
}
| 132 | 115 | 247 |
<methods>public non-sealed void <init>() ,public DiscoveryClient getDiscoveryClient() <variables>protected DiscoveryClient discoveryClient
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyLoadBalanceListener.java
|
MyLoadBalanceListener
|
onGetServers
|
class MyLoadBalanceListener extends AbstractLoadBalanceListener {
private static final Logger LOG = LoggerFactory.getLogger(MyLoadBalanceListener.class);
@Override
public void onGetServers(String serviceId, List<? extends Server> servers) {<FILL_FUNCTION_BODY>}
@Override
public int getOrder() {
return LOWEST_PRECEDENCE - 500;
}
}
|
Iterator<? extends Server> iterator = servers.iterator();
while (iterator.hasNext()) {
Server server = iterator.next();
String group = pluginAdapter.getServerGroup(server);
if (StringUtils.equals(group, "mygroup3")) {
iterator.remove();
LOG.info("服务名=" + serviceId + ",组名=" + group + "的服务禁止被本服务负载均衡");
}
}
| 112 | 119 | 231 |
<methods>public non-sealed void <init>() <variables>
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRegisterListener.java
|
MyRegisterListener
|
onRegister
|
class MyRegisterListener extends AbstractRegisterListener {
@Override
public void onRegister(Registration registration) {<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() {
return LOWEST_PRECEDENCE - 500;
}
}
|
String serviceId = pluginAdapter.getServiceId();
String group = pluginAdapter.getGroup();
if (StringUtils.equals(group, "mygroup1")) {
throw new DiscoveryException("服务名=" + serviceId + ",组名=" + group + "的服务禁止被注册到注册中心");
}
| 139 | 82 | 221 |
<methods>public non-sealed void <init>() ,public ServiceRegistry<?> getServiceRegistry() <variables>protected ServiceRegistry<?> serviceRegistry
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MyRouteFilter.java
|
MyRouteFilter
|
getRouteVersion
|
class MyRouteFilter extends DefaultZuulStrategyRouteFilter {
private static final String DEFAULT_A_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.0\", \"discovery-springcloud-example-b\":\"1.0\", \"discovery-springcloud-example-c\":\"1.0\"}";
private static final String DEFAULT_B_ROUTE_VERSION = "{\"discovery-springcloud-example-a\":\"1.1\", \"discovery-springcloud-example-b\":\"1.1\", \"discovery-springcloud-example-c\":\"1.1\"}";
@Value("${a.route.version:" + DEFAULT_A_ROUTE_VERSION + "}")
private String aRouteVersion;
@Value("${b.route.version:" + DEFAULT_B_ROUTE_VERSION + "}")
private String bRouteVersion;
@Override
public String getRouteVersion() {<FILL_FUNCTION_BODY>}
}
|
String user = strategyContextHolder.getHeader("user");
if (StringUtils.equals(user, "zhangsan")) {
return aRouteVersion;
} else if (StringUtils.equals(user, "lisi")) {
return bRouteVersion;
}
return super.getRouteVersion();
| 256 | 81 | 337 |
<methods>public non-sealed void <init>() ,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 com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder getStrategyContextHolder() <variables>protected com.nepxion.discovery.plugin.strategy.context.StrategyContextHolder strategyContextHolder
|
Nepxion_Discovery
|
Discovery/discovery-springcloud-examples/discovery-springcloud-example-zuul/src/main/java/com/nepxion/discovery/plugin/example/zuul/impl/MySubscriber.java
|
MySubscriber
|
onRegisterFailure
|
class MySubscriber {
private static final Logger LOG = LoggerFactory.getLogger(MySubscriber.class);
@Autowired
private PluginAdapter pluginAdapter;
@Subscribe
public void onRuleUpdated(RuleUpdatedEvent ruleUpdatedEvent) {
LOG.info("规则执行更新, rule=" + ruleUpdatedEvent.getRule());
}
@Subscribe
public void onRuleCleared(RuleClearedEvent ruleClearedEvent) {
LOG.info("规则执行清空");
}
@Subscribe
public void onRuleRuleFailure(RuleFailureEvent ruleFailureEvent) {
LOG.info("规则更新失败, rule=" + ruleFailureEvent.getRule() + ", exception=" + ruleFailureEvent.getException());
}
@Subscribe
public void onParameterChanged(ParameterChangedEvent parameterChangedEvent) {
ParameterEntity parameterEntity = parameterChangedEvent.getParameterEntity();
String serviceId = pluginAdapter.getServiceId();
List<ParameterServiceEntity> parameterServiceEntityList = null;
if (parameterEntity != null) {
Map<String, List<ParameterServiceEntity>> parameterServiceMap = parameterEntity.getParameterServiceMap();
parameterServiceEntityList = parameterServiceMap.get(serviceId);
}
LOG.info("获取动态参数, serviceId=" + serviceId + ", parameterServiceEntityList=" + parameterServiceEntityList);
}
@Subscribe
public void onRegisterFailure(RegisterFailureEvent registerFailureEvent) {<FILL_FUNCTION_BODY>}
@Subscribe
public void onAlarm(StrategyAlarmEvent strategyAlarmEvent) {
LOG.info("告警类型=" + strategyAlarmEvent.getAlarmType());
LOG.info("告警内容=" + strategyAlarmEvent.getAlarmMap());
}
}
|
LOG.info("注册失败, eventType=" + registerFailureEvent.getEventType() + ", eventDescription=" + registerFailureEvent.getEventDescription() + ", serviceId=" + registerFailureEvent.getServiceId() + ", host=" + registerFailureEvent.getHost() + ", port=" + registerFailureEvent.getPort());
| 452 | 81 | 533 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/AbstractHistogramIterator.java
|
AbstractHistogramIterator
|
next
|
class AbstractHistogramIterator implements Iterator<HistogramIterationValue> {
AbstractHistogram histogram;
long arrayTotalCount;
int currentIndex;
long currentValueAtIndex;
long nextValueAtIndex;
long prevValueIteratedTo;
long totalCountToPrevIndex;
long totalCountToCurrentIndex;
long totalValueToCurrentIndex;
long countAtThisValue;
private boolean freshSubBucket;
final HistogramIterationValue currentIterationValue = new HistogramIterationValue();
private double integerToDoubleValueConversionRatio;
void resetIterator(final AbstractHistogram histogram) {
this.histogram = histogram;
this.arrayTotalCount = histogram.getTotalCount();
this.integerToDoubleValueConversionRatio = histogram.getIntegerToDoubleValueConversionRatio();
this.currentIndex = 0;
this.currentValueAtIndex = 0;
this.nextValueAtIndex = 1 << histogram.unitMagnitude;
this.prevValueIteratedTo = 0;
this.totalCountToPrevIndex = 0;
this.totalCountToCurrentIndex = 0;
this.totalValueToCurrentIndex = 0;
this.countAtThisValue = 0;
this.freshSubBucket = true;
currentIterationValue.reset();
}
/**
* Returns true if the iteration has more elements. (In other words, returns true if next would return an
* element rather than throwing an exception.)
*
* @return true if the iterator has more elements.
*/
@Override
public boolean hasNext() {
if (histogram.getTotalCount() != arrayTotalCount) {
throw new ConcurrentModificationException();
}
return (totalCountToCurrentIndex < arrayTotalCount);
}
/**
* Returns the next element in the iteration.
*
* @return the {@link HistogramIterationValue} associated with the next element in the iteration.
*/
@Override
public HistogramIterationValue next() {<FILL_FUNCTION_BODY>}
/**
* Not supported. Will throw an {@link UnsupportedOperationException}.
*/
@Override
public void remove() {
throw new UnsupportedOperationException();
}
abstract void incrementIterationLevel();
/**
* @return true if the current position's data should be emitted by the iterator
*/
abstract boolean reachedIterationLevel();
double getPercentileIteratedTo() {
return (100.0 * (double) totalCountToCurrentIndex) / arrayTotalCount;
}
double getPercentileIteratedFrom() {
return (100.0 * (double) totalCountToPrevIndex) / arrayTotalCount;
}
long getValueIteratedTo() {
return histogram.highestEquivalentValue(currentValueAtIndex);
}
private boolean exhaustedSubBuckets() {
return (currentIndex >= histogram.countsArrayLength);
}
void incrementSubBucket() {
freshSubBucket = true;
// Take on the next index:
currentIndex++;
currentValueAtIndex = histogram.valueFromIndex(currentIndex);
// Figure out the value at the next index (used by some iterators):
nextValueAtIndex = histogram.valueFromIndex(currentIndex + 1);
}
}
|
// Move through the sub buckets and buckets until we hit the next reporting level:
while (!exhaustedSubBuckets()) {
countAtThisValue = histogram.getCountAtIndex(currentIndex);
if (freshSubBucket) { // Don't add unless we've incremented since last bucket...
totalCountToCurrentIndex += countAtThisValue;
totalValueToCurrentIndex += countAtThisValue * histogram.highestEquivalentValue(currentValueAtIndex);
freshSubBucket = false;
}
if (reachedIterationLevel()) {
long valueIteratedTo = getValueIteratedTo();
currentIterationValue.set(valueIteratedTo, prevValueIteratedTo, countAtThisValue,
(totalCountToCurrentIndex - totalCountToPrevIndex), totalCountToCurrentIndex,
totalValueToCurrentIndex, ((100.0 * totalCountToCurrentIndex) / arrayTotalCount),
getPercentileIteratedTo(), integerToDoubleValueConversionRatio);
prevValueIteratedTo = valueIteratedTo;
totalCountToPrevIndex = totalCountToCurrentIndex;
// move the next iteration level forward:
incrementIterationLevel();
if (histogram.getTotalCount() != arrayTotalCount) {
throw new ConcurrentModificationException();
}
return currentIterationValue;
}
incrementSubBucket();
}
// Should not reach here. But possible for concurrent modification or overflowed histograms
// under certain conditions
if ((histogram.getTotalCount() != arrayTotalCount) ||
(totalCountToCurrentIndex > arrayTotalCount)) {
throw new ConcurrentModificationException();
}
throw new NoSuchElementException();
| 851 | 424 | 1,275 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/AllValuesIterator.java
|
AllValuesIterator
|
hasNext
|
class AllValuesIterator extends AbstractHistogramIterator implements Iterator<HistogramIterationValue> {
int visitedIndex;
/**
* Reset iterator for re-use in a fresh iteration over the same histogram data set.
*/
public void reset() {
reset(histogram);
}
private void reset(final AbstractHistogram histogram) {
super.resetIterator(histogram);
visitedIndex = -1;
}
/**
* @param histogram The histogram this iterator will operate on
*/
public AllValuesIterator(final AbstractHistogram histogram) {
reset(histogram);
}
@Override
void incrementIterationLevel() {
visitedIndex = currentIndex;
}
@Override
boolean reachedIterationLevel() {
return (visitedIndex != currentIndex);
}
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
}
|
if (histogram.getTotalCount() != arrayTotalCount) {
throw new ConcurrentModificationException();
}
// Unlike other iterators AllValuesIterator is only done when we've exhausted the indices:
return (currentIndex < (histogram.countsArrayLength - 1));
| 239 | 74 | 313 |
<methods>public boolean hasNext() ,public org.HdrHistogram.HistogramIterationValue next() ,public void remove() <variables>long arrayTotalCount,long countAtThisValue,int currentIndex,final org.HdrHistogram.HistogramIterationValue currentIterationValue,long currentValueAtIndex,private boolean freshSubBucket,org.HdrHistogram.AbstractHistogram histogram,private double integerToDoubleValueConversionRatio,long nextValueAtIndex,long prevValueIteratedTo,long totalCountToCurrentIndex,long totalCountToPrevIndex,long totalValueToCurrentIndex
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/Base64Helper.java
|
Base64Helper
|
printBase64Binary
|
class Base64Helper {
/**
* Converts an array of bytes into a Base64 string.
*
* @param binaryArray A binary encoded input array
* @return a String containing the Base64 encoded equivalent of the binary input
*/
static String printBase64Binary(byte [] binaryArray) {<FILL_FUNCTION_BODY>}
/**
* Converts a Base64 encoded String to a byte array
*
* @param base64input A base64-encoded input String
* @return a byte array containing the binary representation equivalent of the Base64 encoded input
*/
static byte[] parseBase64Binary(String base64input) {
try {
return (byte []) decodeMethod.invoke(decoderObj, base64input);
} catch (Throwable e) {
throw new UnsupportedOperationException("Failed to use platform's base64 decode method");
}
}
private static Method decodeMethod;
private static Method encodeMethod;
// encoderObj and decoderObj are used in non-static method forms, and
// irrelevant for static method forms:
private static Object decoderObj;
private static Object encoderObj;
static {
try {
Class<?> javaUtilBase64Class = Class.forName("java.util.Base64");
Method getDecoderMethod = javaUtilBase64Class.getMethod("getDecoder");
decoderObj = getDecoderMethod.invoke(null);
decodeMethod = decoderObj.getClass().getMethod("decode", String.class);
Method getEncoderMethod = javaUtilBase64Class.getMethod("getEncoder");
encoderObj = getEncoderMethod.invoke(null);
encodeMethod = encoderObj.getClass().getMethod("encodeToString", byte[].class);
} catch (Throwable e) {
decodeMethod = null;
encodeMethod = null;
}
if (encodeMethod == null) {
decoderObj = null;
encoderObj = null;
try {
Class<?> javaxXmlBindDatatypeConverterClass = Class.forName("javax.xml.bind.DatatypeConverter");
decodeMethod = javaxXmlBindDatatypeConverterClass.getMethod("parseBase64Binary", String.class);
encodeMethod = javaxXmlBindDatatypeConverterClass.getMethod("printBase64Binary", byte[].class);
} catch (Throwable e) {
decodeMethod = null;
encodeMethod = null;
}
}
}
}
|
try {
return (String) encodeMethod.invoke(encoderObj, binaryArray);
} catch (Throwable e) {
throw new UnsupportedOperationException("Failed to use platform's base64 encode method");
}
| 640 | 59 | 699 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/ConcurrentDoubleHistogram.java
|
ConcurrentDoubleHistogram
|
decodeFromByteBuffer
|
class ConcurrentDoubleHistogram extends DoubleHistogram {
/**
* Construct a new auto-resizing DoubleHistogram using a precision stated as a number of significant decimal
* digits.
*
* @param numberOfSignificantValueDigits Specifies the precision to use. This is the number of significant decimal
* digits to which the histogram will maintain value resolution and
* separation. Must be a non-negative integer between 0 and 5.
*/
public ConcurrentDoubleHistogram(final int numberOfSignificantValueDigits) {
this(2, numberOfSignificantValueDigits);
setAutoResize(true);
}
/**
* Construct a new DoubleHistogram with the specified dynamic range (provided in {@code highestToLowestValueRatio})
* and using a precision stated as a number of significant decimal digits.
*
* @param highestToLowestValueRatio specifies the dynamic range to use
* @param numberOfSignificantValueDigits Specifies the precision to use. This is the number of significant decimal
* digits to which the histogram will maintain value resolution and
* separation. Must be a non-negative integer between 0 and 5.
*/
public ConcurrentDoubleHistogram(final long highestToLowestValueRatio, final int numberOfSignificantValueDigits) {
this(highestToLowestValueRatio, numberOfSignificantValueDigits, ConcurrentHistogram.class);
}
/**
* Construct a {@link ConcurrentDoubleHistogram} with the same range settings as a given source,
* duplicating the source's start/end timestamps (but NOT it's contents)
* @param source The source histogram to duplicate
*/
public ConcurrentDoubleHistogram(final DoubleHistogram source) {
super(source);
}
ConcurrentDoubleHistogram(final long highestToLowestValueRatio,
final int numberOfSignificantValueDigits,
final Class<? extends AbstractHistogram> internalCountsHistogramClass) {
super(highestToLowestValueRatio, numberOfSignificantValueDigits, internalCountsHistogramClass);
}
ConcurrentDoubleHistogram(final long highestToLowestValueRatio,
final int numberOfSignificantValueDigits,
final Class<? extends AbstractHistogram> internalCountsHistogramClass,
AbstractHistogram internalCountsHistogram) {
super(
highestToLowestValueRatio,
numberOfSignificantValueDigits,
internalCountsHistogramClass,
internalCountsHistogram
);
}
/**
* Construct a new ConcurrentDoubleHistogram by decoding it from a ByteBuffer.
* @param buffer The buffer to decode from
* @param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
* @return The newly constructed ConcurrentDoubleHistogram
*/
public static ConcurrentDoubleHistogram decodeFromByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) {<FILL_FUNCTION_BODY>}
/**
* Construct a new ConcurrentDoubleHistogram by decoding it from a compressed form in a ByteBuffer.
* @param buffer The buffer to decode from
* @param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
* @return The newly constructed ConcurrentDoubleHistogram
* @throws DataFormatException on error parsing/decompressing the buffer
*/
public static ConcurrentDoubleHistogram decodeFromCompressedByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) throws DataFormatException {
int cookie = buffer.getInt();
if (!isCompressedDoubleHistogramCookie(cookie)) {
throw new IllegalArgumentException("The buffer does not contain a compressed DoubleHistogram");
}
ConcurrentDoubleHistogram histogram = constructHistogramFromBuffer(cookie, buffer,
ConcurrentDoubleHistogram.class, ConcurrentHistogram.class,
minBarForHighestToLowestValueRatio);
return histogram;
}
}
|
try {
int cookie = buffer.getInt();
if (!isNonCompressedDoubleHistogramCookie(cookie)) {
throw new IllegalArgumentException("The buffer does not contain a DoubleHistogram");
}
ConcurrentDoubleHistogram histogram = constructHistogramFromBuffer(cookie, buffer,
ConcurrentDoubleHistogram.class, ConcurrentHistogram.class,
minBarForHighestToLowestValueRatio);
return histogram;
} catch (DataFormatException ex) {
throw new RuntimeException(ex);
}
| 1,029 | 137 | 1,166 |
<methods>public void <init>(int) ,public void <init>(int, Class<? extends org.HdrHistogram.AbstractHistogram>) ,public void <init>(long, int) ,public void <init>(org.HdrHistogram.DoubleHistogram) ,public void add(org.HdrHistogram.DoubleHistogram) throws java.lang.ArrayIndexOutOfBoundsException,public void addWhileCorrectingForCoordinatedOmission(org.HdrHistogram.DoubleHistogram, double) ,public org.HdrHistogram.DoubleHistogram.AllValues allValues() ,public org.HdrHistogram.DoubleHistogram copy() ,public org.HdrHistogram.DoubleHistogram copyCorrectedForCoordinatedOmission(double) ,public void copyInto(org.HdrHistogram.DoubleHistogram) ,public void copyIntoCorrectedForCoordinatedOmission(org.HdrHistogram.DoubleHistogram, double) ,public static org.HdrHistogram.DoubleHistogram decodeFromByteBuffer(java.nio.ByteBuffer, long) ,public static org.HdrHistogram.DoubleHistogram decodeFromByteBuffer(java.nio.ByteBuffer, Class<? extends org.HdrHistogram.AbstractHistogram>, long) ,public static org.HdrHistogram.DoubleHistogram decodeFromCompressedByteBuffer(java.nio.ByteBuffer, long) throws java.util.zip.DataFormatException,public static org.HdrHistogram.DoubleHistogram decodeFromCompressedByteBuffer(java.nio.ByteBuffer, Class<? extends org.HdrHistogram.AbstractHistogram>, long) throws java.util.zip.DataFormatException,public synchronized int encodeIntoByteBuffer(java.nio.ByteBuffer) ,public synchronized int encodeIntoCompressedByteBuffer(java.nio.ByteBuffer, int) ,public int encodeIntoCompressedByteBuffer(java.nio.ByteBuffer) ,public boolean equals(java.lang.Object) ,public static org.HdrHistogram.DoubleHistogram fromString(java.lang.String) throws java.util.zip.DataFormatException,public long getCountAtValue(double) throws java.lang.ArrayIndexOutOfBoundsException,public double getCountBetweenValues(double, double) throws java.lang.ArrayIndexOutOfBoundsException,public long getEndTimeStamp() ,public int getEstimatedFootprintInBytes() ,public long getHighestToLowestValueRatio() ,public double getIntegerToDoubleValueConversionRatio() ,public double getMaxValue() ,public double getMaxValueAsDouble() ,public double getMean() ,public double getMinNonZeroValue() ,public double getMinValue() ,public int getNeededByteBufferCapacity() ,public int getNumberOfSignificantValueDigits() ,public double getPercentileAtOrBelowValue(double) ,public long getStartTimeStamp() ,public double getStdDeviation() ,public java.lang.String getTag() ,public long getTotalCount() ,public double getValueAtPercentile(double) ,public int hashCode() ,public double highestEquivalentValue(double) ,public boolean isAutoResize() ,public org.HdrHistogram.DoubleHistogram.LinearBucketValues linearBucketValues(double) ,public org.HdrHistogram.DoubleHistogram.LogarithmicBucketValues logarithmicBucketValues(double, double) ,public double lowestEquivalentValue(double) ,public double medianEquivalentValue(double) ,public double nextNonEquivalentValue(double) ,public void outputPercentileDistribution(java.io.PrintStream, java.lang.Double) ,public void outputPercentileDistribution(java.io.PrintStream, int, java.lang.Double) ,public void outputPercentileDistribution(java.io.PrintStream, int, java.lang.Double, boolean) ,public org.HdrHistogram.DoubleHistogram.Percentiles percentiles(int) ,public void recordValue(double) throws java.lang.ArrayIndexOutOfBoundsException,public void recordValueWithCount(double, long) throws java.lang.ArrayIndexOutOfBoundsException,public void recordValueWithExpectedInterval(double, double) throws java.lang.ArrayIndexOutOfBoundsException,public org.HdrHistogram.DoubleHistogram.RecordedValues recordedValues() ,public void reset() ,public void setAutoResize(boolean) ,public void setEndTimeStamp(long) ,public void setStartTimeStamp(long) ,public void setTag(java.lang.String) ,public double sizeOfEquivalentValueRange(double) ,public void subtract(org.HdrHistogram.DoubleHistogram) ,public boolean valuesAreEquivalent(double, double) <variables>private static final int DHIST_compressedEncodingCookie,private static final int DHIST_encodingCookie,private boolean autoResize,private long configuredHighestToLowestValueRatio,private static final Class#RAW[] constructorArgTypes,private volatile double currentHighestValueLimitInAutoRange,private volatile double currentLowestValueInAutoRange,private static final non-sealed double highestAllowedValueEver,org.HdrHistogram.AbstractHistogram integerValuesHistogram,private static final long serialVersionUID
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/DoubleHistogramIterationValue.java
|
DoubleHistogramIterationValue
|
toString
|
class DoubleHistogramIterationValue {
private final HistogramIterationValue integerHistogramIterationValue;
void reset() {
integerHistogramIterationValue.reset();
}
DoubleHistogramIterationValue(HistogramIterationValue integerHistogramIterationValue) {
this.integerHistogramIterationValue = integerHistogramIterationValue;
}
public String toString() {<FILL_FUNCTION_BODY>}
public double getValueIteratedTo() {
return integerHistogramIterationValue.getValueIteratedTo() *
integerHistogramIterationValue.getIntegerToDoubleValueConversionRatio();
}
public double getValueIteratedFrom() {
return integerHistogramIterationValue.getValueIteratedFrom() *
integerHistogramIterationValue.getIntegerToDoubleValueConversionRatio();
}
public long getCountAtValueIteratedTo() {
return integerHistogramIterationValue.getCountAtValueIteratedTo();
}
public long getCountAddedInThisIterationStep() {
return integerHistogramIterationValue.getCountAddedInThisIterationStep();
}
public long getTotalCountToThisValue() {
return integerHistogramIterationValue.getTotalCountToThisValue();
}
public double getTotalValueToThisValue() {
return integerHistogramIterationValue.getTotalValueToThisValue() *
integerHistogramIterationValue.getIntegerToDoubleValueConversionRatio();
}
public double getPercentile() {
return integerHistogramIterationValue.getPercentile();
}
public double getPercentileLevelIteratedTo() {
return integerHistogramIterationValue.getPercentileLevelIteratedTo();
}
public HistogramIterationValue getIntegerHistogramIterationValue() {
return integerHistogramIterationValue;
}
}
|
return "valueIteratedTo:" + getValueIteratedTo() +
", prevValueIteratedTo:" + getValueIteratedFrom() +
", countAtValueIteratedTo:" + getCountAtValueIteratedTo() +
", countAddedInThisIterationStep:" + getCountAddedInThisIterationStep() +
", totalCountToThisValue:" + getTotalCountToThisValue() +
", totalValueToThisValue:" + getTotalValueToThisValue() +
", percentile:" + getPercentile() +
", percentileLevelIteratedTo:" + getPercentileLevelIteratedTo();
| 468 | 149 | 617 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/EncodableHistogram.java
|
EncodableHistogram
|
decodeFromCompressedByteBuffer
|
class EncodableHistogram {
public abstract int getNeededByteBufferCapacity();
public abstract int encodeIntoCompressedByteBuffer(final ByteBuffer targetBuffer, int compressionLevel);
public abstract long getStartTimeStamp();
public abstract void setStartTimeStamp(long startTimeStamp);
public abstract long getEndTimeStamp();
public abstract void setEndTimeStamp(long endTimestamp);
public abstract String getTag();
public abstract void setTag(String tag);
public abstract double getMaxValueAsDouble();
/**
* Decode a {@link EncodableHistogram} from a compressed byte buffer. Will return either a
* {@link org.HdrHistogram.Histogram} or {@link org.HdrHistogram.DoubleHistogram} depending
* on the format found in the supplied buffer.
*
* @param buffer The input buffer to decode from.
* @param minBarForHighestTrackableValue A lower bound either on the highestTrackableValue of
* the created Histogram, or on the HighestToLowestValueRatio
* of the created DoubleHistogram.
* @return The decoded {@link org.HdrHistogram.Histogram} or {@link org.HdrHistogram.DoubleHistogram}
* @throws DataFormatException on errors in decoding the buffer compression.
*/
static EncodableHistogram decodeFromCompressedByteBuffer(
ByteBuffer buffer,
final long minBarForHighestTrackableValue) throws DataFormatException {<FILL_FUNCTION_BODY>}
}
|
// Peek iun buffer to see the cookie:
int cookie = buffer.getInt(buffer.position());
if (DoubleHistogram.isDoubleHistogramCookie(cookie)) {
return DoubleHistogram.decodeFromCompressedByteBuffer(buffer, minBarForHighestTrackableValue);
} else {
return Histogram.decodeFromCompressedByteBuffer(buffer, minBarForHighestTrackableValue);
}
| 389 | 108 | 497 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/HistogramIterationValue.java
|
HistogramIterationValue
|
set
|
class HistogramIterationValue {
private long valueIteratedTo;
private long valueIteratedFrom;
private long countAtValueIteratedTo;
private long countAddedInThisIterationStep;
private long totalCountToThisValue;
private long totalValueToThisValue;
private double percentile;
private double percentileLevelIteratedTo;
private double integerToDoubleValueConversionRatio;
// Set is all-or-nothing to avoid the potential for accidental omission of some values...
void set(final long valueIteratedTo, final long valueIteratedFrom, final long countAtValueIteratedTo,
final long countInThisIterationStep, final long totalCountToThisValue, final long totalValueToThisValue,
final double percentile, final double percentileLevelIteratedTo, double integerToDoubleValueConversionRatio) {<FILL_FUNCTION_BODY>}
void reset() {
this.valueIteratedTo = 0;
this.valueIteratedFrom = 0;
this.countAtValueIteratedTo = 0;
this.countAddedInThisIterationStep = 0;
this.totalCountToThisValue = 0;
this.totalValueToThisValue = 0;
this.percentile = 0.0;
this.percentileLevelIteratedTo = 0.0;
}
HistogramIterationValue() {
}
public String toString() {
return "valueIteratedTo:" + valueIteratedTo +
", prevValueIteratedTo:" + valueIteratedFrom +
", countAtValueIteratedTo:" + countAtValueIteratedTo +
", countAddedInThisIterationStep:" + countAddedInThisIterationStep +
", totalCountToThisValue:" + totalCountToThisValue +
", totalValueToThisValue:" + totalValueToThisValue +
", percentile:" + percentile +
", percentileLevelIteratedTo:" + percentileLevelIteratedTo;
}
public long getValueIteratedTo() {
return valueIteratedTo;
}
public double getDoubleValueIteratedTo() {
return valueIteratedTo * integerToDoubleValueConversionRatio;
}
public long getValueIteratedFrom() {
return valueIteratedFrom;
}
public double getDoubleValueIteratedFrom() {
return valueIteratedFrom * integerToDoubleValueConversionRatio;
}
public long getCountAtValueIteratedTo() {
return countAtValueIteratedTo;
}
public long getCountAddedInThisIterationStep() {
return countAddedInThisIterationStep;
}
public long getTotalCountToThisValue() {
return totalCountToThisValue;
}
public long getTotalValueToThisValue() {
return totalValueToThisValue;
}
public double getPercentile() {
return percentile;
}
public double getPercentileLevelIteratedTo() {
return percentileLevelIteratedTo;
}
public double getIntegerToDoubleValueConversionRatio() { return integerToDoubleValueConversionRatio; }
}
|
this.valueIteratedTo = valueIteratedTo;
this.valueIteratedFrom = valueIteratedFrom;
this.countAtValueIteratedTo = countAtValueIteratedTo;
this.countAddedInThisIterationStep = countInThisIterationStep;
this.totalCountToThisValue = totalCountToThisValue;
this.totalValueToThisValue = totalValueToThisValue;
this.percentile = percentile;
this.percentileLevelIteratedTo = percentileLevelIteratedTo;
this.integerToDoubleValueConversionRatio = integerToDoubleValueConversionRatio;
| 776 | 150 | 926 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/HistogramLogScanner.java
|
LazyHistogramReader
|
process
|
class LazyHistogramReader implements EncodableHistogramSupplier {
private final Scanner scanner;
private boolean gotIt = true;
private LazyHistogramReader(Scanner scanner)
{
this.scanner = scanner;
}
private void allowGet()
{
gotIt = false;
}
@Override
public EncodableHistogram read() throws DataFormatException
{
// prevent double calls to this method
if (gotIt) {
throw new IllegalStateException();
}
gotIt = true;
final String compressedPayloadString = scanner.next();
final ByteBuffer buffer = ByteBuffer.wrap(Base64Helper.parseBase64Binary(compressedPayloadString));
EncodableHistogram histogram = EncodableHistogram.decodeFromCompressedByteBuffer(buffer, 0);
return histogram;
}
}
private final LazyHistogramReader lazyReader;
protected final Scanner scanner;
/**
* Constructs a new HistogramLogReader that produces intervals read from the specified file name.
* @param inputFileName The name of the file to read from
* @throws java.io.FileNotFoundException when unable to find inputFileName
*/
public HistogramLogScanner(final String inputFileName) throws FileNotFoundException {
this(new Scanner(new File(inputFileName)));
}
/**
* Constructs a new HistogramLogReader that produces intervals read from the specified InputStream. Note that
* log readers constructed through this constructor do not assume ownership of stream and will not close it on
* {@link #close()}.
*
* @param inputStream The InputStream to read from
*/
public HistogramLogScanner(final InputStream inputStream) {
this(new Scanner(inputStream));
}
/**
* Constructs a new HistogramLogReader that produces intervals read from the specified file.
* @param inputFile The File to read from
* @throws java.io.FileNotFoundException when unable to find inputFile
*/
public HistogramLogScanner(final File inputFile) throws FileNotFoundException {
this(new Scanner(inputFile));
}
private HistogramLogScanner(Scanner scanner)
{
this.scanner = scanner;
this.lazyReader = new LazyHistogramReader(scanner);
initScanner();
}
private void initScanner() {
scanner.useLocale(Locale.US);
scanner.useDelimiter("[ ,\\r\\n]");
}
/**
* Close underlying scanner.
*/
@Override
public void close()
{
scanner.close();
}
public void process(EventHandler handler) {<FILL_FUNCTION_BODY>
|
while (scanner.hasNextLine()) {
try {
if (scanner.hasNext("\\#.*")) {
// comment line.
// Look for explicit start time or base time notes in comments:
if (scanner.hasNext("#\\[StartTime:")) {
scanner.next("#\\[StartTime:");
if (scanner.hasNextDouble()) {
double startTimeSec = scanner.nextDouble(); // start time represented as seconds since epoch
if (handler.onStartTime(startTimeSec)) {
return;
}
}
} else if (scanner.hasNext("#\\[BaseTime:")) {
scanner.next("#\\[BaseTime:");
if (scanner.hasNextDouble()) {
double baseTimeSec = scanner.nextDouble(); // base time represented as seconds since epoch
if (handler.onBaseTime(baseTimeSec))
{
return;
}
}
} else if (handler.onComment(scanner.next("\\#.*"))) {
return;
}
continue;
}
if (scanner.hasNext("\"StartTimestamp\".*")) {
// Legend line
continue;
}
String tagString = null;
if (scanner.hasNext("Tag\\=.*")) {
tagString = scanner.next("Tag\\=.*").substring(4);
}
// Decode: startTimestamp, intervalLength, maxTime, histogramPayload
final double logTimeStampInSec = scanner.nextDouble(); // Timestamp is expected to be in seconds
final double intervalLengthSec = scanner.nextDouble(); // Timestamp length is expect to be in seconds
scanner.nextDouble(); // Skip maxTime field, as max time can be deduced from the histogram.
lazyReader.allowGet();
if (handler.onHistogram(tagString, logTimeStampInSec, intervalLengthSec, lazyReader)) {
return;
}
} catch (Throwable ex) {
if (handler.onException(ex)) {
return;
}
} finally {
scanner.nextLine(); // Move to next line.
}
}
| 711 | 548 | 1,259 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/LinearIterator.java
|
LinearIterator
|
hasNext
|
class LinearIterator extends AbstractHistogramIterator implements Iterator<HistogramIterationValue> {
private long valueUnitsPerBucket;
private long currentStepHighestValueReportingLevel;
private long currentStepLowestValueReportingLevel;
/**
* Reset iterator for re-use in a fresh iteration over the same histogram data set.
* @param valueUnitsPerBucket The size (in value units) of each bucket iteration.
*/
public void reset(final long valueUnitsPerBucket) {
reset(histogram, valueUnitsPerBucket);
}
private void reset(final AbstractHistogram histogram, final long valueUnitsPerBucket) {
super.resetIterator(histogram);
this.valueUnitsPerBucket = valueUnitsPerBucket;
this.currentStepHighestValueReportingLevel = valueUnitsPerBucket - 1;
this.currentStepLowestValueReportingLevel = histogram.lowestEquivalentValue(currentStepHighestValueReportingLevel);
}
/**
* @param histogram The histogram this iterator will operate on
* @param valueUnitsPerBucket The size (in value units) of each bucket iteration.
*/
public LinearIterator(final AbstractHistogram histogram, final long valueUnitsPerBucket) {
reset(histogram, valueUnitsPerBucket);
}
@Override
public boolean hasNext() {<FILL_FUNCTION_BODY>}
@Override
void incrementIterationLevel() {
currentStepHighestValueReportingLevel += valueUnitsPerBucket;
currentStepLowestValueReportingLevel = histogram.lowestEquivalentValue(currentStepHighestValueReportingLevel);
}
@Override
long getValueIteratedTo() {
return currentStepHighestValueReportingLevel;
}
@Override
boolean reachedIterationLevel() {
return ((currentValueAtIndex >= currentStepLowestValueReportingLevel) ||
(currentIndex >= histogram.countsArrayLength - 1)) ;
}
}
|
if (super.hasNext()) {
return true;
}
// If the next iteration will not move to the next sub bucket index (which is empty if
// if we reached this point), then we are not yet done iterating (we want to iterate
// until we are no longer on a value that has a count, rather than util we first reach
// the last value that has a count. The difference is subtle but important)...
// When this is called, we're about to begin the "next" iteration, so
// currentStepHighestValueReportingLevel has already been incremented, and we use it
// without incrementing its value.
return (currentStepHighestValueReportingLevel < nextValueAtIndex);
| 521 | 177 | 698 |
<methods>public boolean hasNext() ,public org.HdrHistogram.HistogramIterationValue next() ,public void remove() <variables>long arrayTotalCount,long countAtThisValue,int currentIndex,final org.HdrHistogram.HistogramIterationValue currentIterationValue,long currentValueAtIndex,private boolean freshSubBucket,org.HdrHistogram.AbstractHistogram histogram,private double integerToDoubleValueConversionRatio,long nextValueAtIndex,long prevValueIteratedTo,long totalCountToCurrentIndex,long totalCountToPrevIndex,long totalValueToCurrentIndex
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/LogarithmicIterator.java
|
LogarithmicIterator
|
incrementIterationLevel
|
class LogarithmicIterator extends AbstractHistogramIterator implements Iterator<HistogramIterationValue> {
long valueUnitsInFirstBucket;
double logBase;
double nextValueReportingLevel;
long currentStepHighestValueReportingLevel;
long currentStepLowestValueReportingLevel;
/**
* Reset iterator for re-use in a fresh iteration over the same histogram data set.
* @param valueUnitsInFirstBucket the size (in value units) of the first value bucket step
* @param logBase the multiplier by which the bucket size is expanded in each iteration step.
*/
public void reset(final long valueUnitsInFirstBucket, final double logBase) {
reset(histogram, valueUnitsInFirstBucket, logBase);
}
private void reset(final AbstractHistogram histogram, final long valueUnitsInFirstBucket, final double logBase) {
super.resetIterator(histogram);
this.logBase = logBase;
this.valueUnitsInFirstBucket = valueUnitsInFirstBucket;
nextValueReportingLevel = valueUnitsInFirstBucket;
this.currentStepHighestValueReportingLevel = ((long) nextValueReportingLevel) - 1;
this.currentStepLowestValueReportingLevel = histogram.lowestEquivalentValue(currentStepHighestValueReportingLevel);
}
/**
* @param histogram The histogram this iterator will operate on
* @param valueUnitsInFirstBucket the size (in value units) of the first value bucket step
* @param logBase the multiplier by which the bucket size is expanded in each iteration step.
*/
public LogarithmicIterator(final AbstractHistogram histogram, final long valueUnitsInFirstBucket, final double logBase) {
reset(histogram, valueUnitsInFirstBucket, logBase);
}
@Override
public boolean hasNext() {
if (super.hasNext()) {
return true;
}
// If the next iterate will not move to the next sub bucket index (which is empty if
// if we reached this point), then we are not yet done iterating (we want to iterate
// until we are no longer on a value that has a count, rather than util we first reach
// the last value that has a count. The difference is subtle but important)...
return (histogram.lowestEquivalentValue((long) nextValueReportingLevel) < nextValueAtIndex);
}
@Override
void incrementIterationLevel() {<FILL_FUNCTION_BODY>}
@Override
long getValueIteratedTo() {
return currentStepHighestValueReportingLevel;
}
@Override
boolean reachedIterationLevel() {
return ((currentValueAtIndex >= currentStepLowestValueReportingLevel) ||
(currentIndex >= histogram.countsArrayLength - 1)) ;
}
}
|
nextValueReportingLevel *= logBase;
this.currentStepHighestValueReportingLevel = ((long)nextValueReportingLevel) - 1;
currentStepLowestValueReportingLevel = histogram.lowestEquivalentValue(currentStepHighestValueReportingLevel);
| 723 | 72 | 795 |
<methods>public boolean hasNext() ,public org.HdrHistogram.HistogramIterationValue next() ,public void remove() <variables>long arrayTotalCount,long countAtThisValue,int currentIndex,final org.HdrHistogram.HistogramIterationValue currentIterationValue,long currentValueAtIndex,private boolean freshSubBucket,org.HdrHistogram.AbstractHistogram histogram,private double integerToDoubleValueConversionRatio,long nextValueAtIndex,long prevValueIteratedTo,long totalCountToCurrentIndex,long totalCountToPrevIndex,long totalValueToCurrentIndex
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/PackedConcurrentDoubleHistogram.java
|
PackedConcurrentDoubleHistogram
|
decodeFromByteBuffer
|
class PackedConcurrentDoubleHistogram extends ConcurrentDoubleHistogram {
/**
* Construct a new auto-resizing DoubleHistogram using a precision stated as a number of significant decimal
* digits.
*
* @param numberOfSignificantValueDigits Specifies the precision to use. This is the number of significant decimal
* digits to which the histogram will maintain value resolution and
* separation. Must be a non-negative integer between 0 and 5.
*/
public PackedConcurrentDoubleHistogram(final int numberOfSignificantValueDigits) {
this(2, numberOfSignificantValueDigits);
setAutoResize(true);
}
/**
* Construct a new DoubleHistogram with the specified dynamic range (provided in {@code highestToLowestValueRatio})
* and using a precision stated as a number of significant decimal digits.
*
* @param highestToLowestValueRatio specifies the dynamic range to use
* @param numberOfSignificantValueDigits Specifies the precision to use. This is the number of significant decimal
* digits to which the histogram will maintain value resolution and
* separation. Must be a non-negative integer between 0 and 5.
*/
public PackedConcurrentDoubleHistogram(final long highestToLowestValueRatio, final int numberOfSignificantValueDigits) {
this(highestToLowestValueRatio, numberOfSignificantValueDigits, PackedConcurrentHistogram.class);
}
/**
* Construct a {@link PackedConcurrentDoubleHistogram} with the same range settings as a given source,
* duplicating the source's start/end timestamps (but NOT it's contents)
* @param source The source histogram to duplicate
*/
public PackedConcurrentDoubleHistogram(final DoubleHistogram source) {
super(source);
}
PackedConcurrentDoubleHistogram(final long highestToLowestValueRatio,
final int numberOfSignificantValueDigits,
final Class<? extends AbstractHistogram> internalCountsHistogramClass) {
super(highestToLowestValueRatio, numberOfSignificantValueDigits, internalCountsHistogramClass);
}
PackedConcurrentDoubleHistogram(final long highestToLowestValueRatio,
final int numberOfSignificantValueDigits,
final Class<? extends AbstractHistogram> internalCountsHistogramClass,
AbstractHistogram internalCountsHistogram) {
super(
highestToLowestValueRatio,
numberOfSignificantValueDigits,
internalCountsHistogramClass,
internalCountsHistogram
);
}
/**
* Construct a new ConcurrentDoubleHistogram by decoding it from a ByteBuffer.
* @param buffer The buffer to decode from
* @param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
* @return The newly constructed ConcurrentDoubleHistogram
*/
public static PackedConcurrentDoubleHistogram decodeFromByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) {<FILL_FUNCTION_BODY>}
/**
* Construct a new ConcurrentDoubleHistogram by decoding it from a compressed form in a ByteBuffer.
* @param buffer The buffer to decode from
* @param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
* @return The newly constructed ConcurrentDoubleHistogram
* @throws DataFormatException on error parsing/decompressing the buffer
*/
public static PackedConcurrentDoubleHistogram decodeFromCompressedByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) throws DataFormatException {
int cookie = buffer.getInt();
if (!isCompressedDoubleHistogramCookie(cookie)) {
throw new IllegalArgumentException("The buffer does not contain a compressed DoubleHistogram");
}
PackedConcurrentDoubleHistogram histogram = constructHistogramFromBuffer(cookie, buffer,
PackedConcurrentDoubleHistogram.class, PackedConcurrentHistogram.class,
minBarForHighestToLowestValueRatio);
return histogram;
}
}
|
try {
int cookie = buffer.getInt();
if (!isNonCompressedDoubleHistogramCookie(cookie)) {
throw new IllegalArgumentException("The buffer does not contain a DoubleHistogram");
}
PackedConcurrentDoubleHistogram histogram = constructHistogramFromBuffer(cookie, buffer,
PackedConcurrentDoubleHistogram.class, PackedConcurrentHistogram.class,
minBarForHighestToLowestValueRatio);
return histogram;
} catch (DataFormatException ex) {
throw new RuntimeException(ex);
}
| 1,057 | 143 | 1,200 |
<methods>public void <init>(int) ,public void <init>(long, int) ,public void <init>(org.HdrHistogram.DoubleHistogram) ,public static org.HdrHistogram.ConcurrentDoubleHistogram decodeFromByteBuffer(java.nio.ByteBuffer, long) ,public static org.HdrHistogram.ConcurrentDoubleHistogram decodeFromCompressedByteBuffer(java.nio.ByteBuffer, long) throws java.util.zip.DataFormatException<variables>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/PackedDoubleHistogram.java
|
PackedDoubleHistogram
|
decodeFromByteBuffer
|
class PackedDoubleHistogram extends DoubleHistogram {
/**
* Construct a new auto-resizing DoubleHistogram using a precision stated as a number of significant decimal
* digits.
*
* @param numberOfSignificantValueDigits Specifies the precision to use. This is the number of significant decimal
* digits to which the histogram will maintain value resolution and
* separation. Must be a non-negative integer between 0 and 5.
*/
public PackedDoubleHistogram(final int numberOfSignificantValueDigits) {
this(2, numberOfSignificantValueDigits);
setAutoResize(true);
}
/**
* Construct a new DoubleHistogram with the specified dynamic range (provided in {@code highestToLowestValueRatio})
* and using a precision stated as a number of significant decimal digits.
*
* @param highestToLowestValueRatio specifies the dynamic range to use
* @param numberOfSignificantValueDigits Specifies the precision to use. This is the number of significant decimal
* digits to which the histogram will maintain value resolution and
* separation. Must be a non-negative integer between 0 and 5.
*/
public PackedDoubleHistogram(final long highestToLowestValueRatio, final int numberOfSignificantValueDigits) {
this(highestToLowestValueRatio, numberOfSignificantValueDigits, PackedHistogram.class);
}
/**
* Construct a {@link PackedDoubleHistogram} with the same range settings as a given source,
* duplicating the source's start/end timestamps (but NOT it's contents)
* @param source The source histogram to duplicate
*/
public PackedDoubleHistogram(final DoubleHistogram source) {
super(source);
}
PackedDoubleHistogram(final long highestToLowestValueRatio,
final int numberOfSignificantValueDigits,
final Class<? extends AbstractHistogram> internalCountsHistogramClass) {
super(highestToLowestValueRatio, numberOfSignificantValueDigits, internalCountsHistogramClass);
}
PackedDoubleHistogram(final long highestToLowestValueRatio,
final int numberOfSignificantValueDigits,
final Class<? extends AbstractHistogram> internalCountsHistogramClass,
AbstractHistogram internalCountsHistogram) {
super(
highestToLowestValueRatio,
numberOfSignificantValueDigits,
internalCountsHistogramClass,
internalCountsHistogram
);
}
/**
* Construct a new ConcurrentDoubleHistogram by decoding it from a ByteBuffer.
* @param buffer The buffer to decode from
* @param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
* @return The newly constructed ConcurrentDoubleHistogram
*/
public static PackedDoubleHistogram decodeFromByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) {<FILL_FUNCTION_BODY>}
/**
* Construct a new ConcurrentDoubleHistogram by decoding it from a compressed form in a ByteBuffer.
* @param buffer The buffer to decode from
* @param minBarForHighestToLowestValueRatio Force highestTrackableValue to be set at least this high
* @return The newly constructed ConcurrentDoubleHistogram
* @throws DataFormatException on error parsing/decompressing the buffer
*/
public static PackedDoubleHistogram decodeFromCompressedByteBuffer(
final ByteBuffer buffer,
final long minBarForHighestToLowestValueRatio) throws DataFormatException {
int cookie = buffer.getInt();
if (!isCompressedDoubleHistogramCookie(cookie)) {
throw new IllegalArgumentException("The buffer does not contain a compressed DoubleHistogram");
}
PackedDoubleHistogram histogram = constructHistogramFromBuffer(cookie, buffer,
PackedDoubleHistogram.class, PackedHistogram.class,
minBarForHighestToLowestValueRatio);
return histogram;
}
}
|
try {
int cookie = buffer.getInt();
if (!isNonCompressedDoubleHistogramCookie(cookie)) {
throw new IllegalArgumentException("The buffer does not contain a DoubleHistogram");
}
PackedDoubleHistogram histogram = constructHistogramFromBuffer(cookie, buffer,
PackedDoubleHistogram.class, PackedHistogram.class,
minBarForHighestToLowestValueRatio);
return histogram;
} catch (DataFormatException ex) {
throw new RuntimeException(ex);
}
| 1,029 | 137 | 1,166 |
<methods>public void <init>(int) ,public void <init>(int, Class<? extends org.HdrHistogram.AbstractHistogram>) ,public void <init>(long, int) ,public void <init>(org.HdrHistogram.DoubleHistogram) ,public void add(org.HdrHistogram.DoubleHistogram) throws java.lang.ArrayIndexOutOfBoundsException,public void addWhileCorrectingForCoordinatedOmission(org.HdrHistogram.DoubleHistogram, double) ,public org.HdrHistogram.DoubleHistogram.AllValues allValues() ,public org.HdrHistogram.DoubleHistogram copy() ,public org.HdrHistogram.DoubleHistogram copyCorrectedForCoordinatedOmission(double) ,public void copyInto(org.HdrHistogram.DoubleHistogram) ,public void copyIntoCorrectedForCoordinatedOmission(org.HdrHistogram.DoubleHistogram, double) ,public static org.HdrHistogram.DoubleHistogram decodeFromByteBuffer(java.nio.ByteBuffer, long) ,public static org.HdrHistogram.DoubleHistogram decodeFromByteBuffer(java.nio.ByteBuffer, Class<? extends org.HdrHistogram.AbstractHistogram>, long) ,public static org.HdrHistogram.DoubleHistogram decodeFromCompressedByteBuffer(java.nio.ByteBuffer, long) throws java.util.zip.DataFormatException,public static org.HdrHistogram.DoubleHistogram decodeFromCompressedByteBuffer(java.nio.ByteBuffer, Class<? extends org.HdrHistogram.AbstractHistogram>, long) throws java.util.zip.DataFormatException,public synchronized int encodeIntoByteBuffer(java.nio.ByteBuffer) ,public synchronized int encodeIntoCompressedByteBuffer(java.nio.ByteBuffer, int) ,public int encodeIntoCompressedByteBuffer(java.nio.ByteBuffer) ,public boolean equals(java.lang.Object) ,public static org.HdrHistogram.DoubleHistogram fromString(java.lang.String) throws java.util.zip.DataFormatException,public long getCountAtValue(double) throws java.lang.ArrayIndexOutOfBoundsException,public double getCountBetweenValues(double, double) throws java.lang.ArrayIndexOutOfBoundsException,public long getEndTimeStamp() ,public int getEstimatedFootprintInBytes() ,public long getHighestToLowestValueRatio() ,public double getIntegerToDoubleValueConversionRatio() ,public double getMaxValue() ,public double getMaxValueAsDouble() ,public double getMean() ,public double getMinNonZeroValue() ,public double getMinValue() ,public int getNeededByteBufferCapacity() ,public int getNumberOfSignificantValueDigits() ,public double getPercentileAtOrBelowValue(double) ,public long getStartTimeStamp() ,public double getStdDeviation() ,public java.lang.String getTag() ,public long getTotalCount() ,public double getValueAtPercentile(double) ,public int hashCode() ,public double highestEquivalentValue(double) ,public boolean isAutoResize() ,public org.HdrHistogram.DoubleHistogram.LinearBucketValues linearBucketValues(double) ,public org.HdrHistogram.DoubleHistogram.LogarithmicBucketValues logarithmicBucketValues(double, double) ,public double lowestEquivalentValue(double) ,public double medianEquivalentValue(double) ,public double nextNonEquivalentValue(double) ,public void outputPercentileDistribution(java.io.PrintStream, java.lang.Double) ,public void outputPercentileDistribution(java.io.PrintStream, int, java.lang.Double) ,public void outputPercentileDistribution(java.io.PrintStream, int, java.lang.Double, boolean) ,public org.HdrHistogram.DoubleHistogram.Percentiles percentiles(int) ,public void recordValue(double) throws java.lang.ArrayIndexOutOfBoundsException,public void recordValueWithCount(double, long) throws java.lang.ArrayIndexOutOfBoundsException,public void recordValueWithExpectedInterval(double, double) throws java.lang.ArrayIndexOutOfBoundsException,public org.HdrHistogram.DoubleHistogram.RecordedValues recordedValues() ,public void reset() ,public void setAutoResize(boolean) ,public void setEndTimeStamp(long) ,public void setStartTimeStamp(long) ,public void setTag(java.lang.String) ,public double sizeOfEquivalentValueRange(double) ,public void subtract(org.HdrHistogram.DoubleHistogram) ,public boolean valuesAreEquivalent(double, double) <variables>private static final int DHIST_compressedEncodingCookie,private static final int DHIST_encodingCookie,private boolean autoResize,private long configuredHighestToLowestValueRatio,private static final Class#RAW[] constructorArgTypes,private volatile double currentHighestValueLimitInAutoRange,private volatile double currentLowestValueInAutoRange,private static final non-sealed double highestAllowedValueEver,org.HdrHistogram.AbstractHistogram integerValuesHistogram,private static final long serialVersionUID
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/PercentileIterator.java
|
PercentileIterator
|
reachedIterationLevel
|
class PercentileIterator extends AbstractHistogramIterator implements Iterator<HistogramIterationValue> {
int percentileTicksPerHalfDistance;
double percentileLevelToIterateTo;
double percentileLevelToIterateFrom;
boolean reachedLastRecordedValue;
/**
* Reset iterator for re-use in a fresh iteration over the same histogram data set.
*
* @param percentileTicksPerHalfDistance The number of iteration steps per half-distance to 100%.
*/
public void reset(final int percentileTicksPerHalfDistance) {
reset(histogram, percentileTicksPerHalfDistance);
}
private void reset(final AbstractHistogram histogram, final int percentileTicksPerHalfDistance) {
super.resetIterator(histogram);
this.percentileTicksPerHalfDistance = percentileTicksPerHalfDistance;
this.percentileLevelToIterateTo = 0.0;
this.percentileLevelToIterateFrom = 0.0;
this.reachedLastRecordedValue = false;
}
/**
* @param histogram The histogram this iterator will operate on
* @param percentileTicksPerHalfDistance The number of equal-sized iteration steps per half-distance to 100%.
*/
public PercentileIterator(final AbstractHistogram histogram, final int percentileTicksPerHalfDistance) {
reset(histogram, percentileTicksPerHalfDistance);
}
@Override
public boolean hasNext() {
if (super.hasNext())
return true;
// We want one additional last step to 100%
if (!reachedLastRecordedValue && (arrayTotalCount > 0)) {
percentileLevelToIterateTo = 100.0;
reachedLastRecordedValue = true;
return true;
}
return false;
}
@Override
void incrementIterationLevel() {
percentileLevelToIterateFrom = percentileLevelToIterateTo;
// The choice to maintain fixed-sized "ticks" in each half-distance to 100% [starting
// from 0%], as opposed to a "tick" size that varies with each interval, was made to
// make the steps easily comprehensible and readable to humans. The resulting percentile
// steps are much easier to browse through in a percentile distribution output, for example.
//
// We calculate the number of equal-sized "ticks" that the 0-100 range will be divided
// by at the current scale. The scale is determined by the percentile level we are
// iterating to. The following math determines the tick size for the current scale,
// and maintain a fixed tick size for the remaining "half the distance to 100%"
// [from either 0% or from the previous half-distance]. When that half-distance is
// crossed, the scale changes and the tick size is effectively cut in half.
long percentileReportingTicks =
percentileTicksPerHalfDistance *
(long) Math.pow(2,
(long) (Math.log(100.0 / (100.0 - (percentileLevelToIterateTo))) / Math.log(2)) + 1);
percentileLevelToIterateTo += 100.0 / percentileReportingTicks;
}
@Override
boolean reachedIterationLevel() {<FILL_FUNCTION_BODY>}
@Override
double getPercentileIteratedTo() {
return percentileLevelToIterateTo;
}
@Override
double getPercentileIteratedFrom() {
return percentileLevelToIterateFrom;
}
}
|
if (countAtThisValue == 0)
return false;
double currentPercentile = (100.0 * (double) totalCountToCurrentIndex) / arrayTotalCount;
return (currentPercentile >= percentileLevelToIterateTo);
| 921 | 65 | 986 |
<methods>public boolean hasNext() ,public org.HdrHistogram.HistogramIterationValue next() ,public void remove() <variables>long arrayTotalCount,long countAtThisValue,int currentIndex,final org.HdrHistogram.HistogramIterationValue currentIterationValue,long currentValueAtIndex,private boolean freshSubBucket,org.HdrHistogram.AbstractHistogram histogram,private double integerToDoubleValueConversionRatio,long nextValueAtIndex,long prevValueIteratedTo,long totalCountToCurrentIndex,long totalCountToPrevIndex,long totalValueToCurrentIndex
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/RecordedValuesIterator.java
|
RecordedValuesIterator
|
reachedIterationLevel
|
class RecordedValuesIterator extends AbstractHistogramIterator implements Iterator<HistogramIterationValue> {
int visitedIndex;
/**
* Reset iterator for re-use in a fresh iteration over the same histogram data set.
*/
public void reset() {
reset(histogram);
}
private void reset(final AbstractHistogram histogram) {
super.resetIterator(histogram);
visitedIndex = -1;
}
/**
* @param histogram The histogram this iterator will operate on
*/
public RecordedValuesIterator(final AbstractHistogram histogram) {
reset(histogram);
}
@Override
void incrementIterationLevel() {
visitedIndex = currentIndex;
}
@Override
boolean reachedIterationLevel() {<FILL_FUNCTION_BODY>}
}
|
long currentCount = histogram.getCountAtIndex(currentIndex);
return (currentCount != 0) && (visitedIndex != currentIndex);
| 213 | 40 | 253 |
<methods>public boolean hasNext() ,public org.HdrHistogram.HistogramIterationValue next() ,public void remove() <variables>long arrayTotalCount,long countAtThisValue,int currentIndex,final org.HdrHistogram.HistogramIterationValue currentIterationValue,long currentValueAtIndex,private boolean freshSubBucket,org.HdrHistogram.AbstractHistogram histogram,private double integerToDoubleValueConversionRatio,long nextValueAtIndex,long prevValueIteratedTo,long totalCountToCurrentIndex,long totalCountToPrevIndex,long totalValueToCurrentIndex
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/SingleWriterDoubleRecorder.java
|
PackedInternalDoubleHistogram
|
validateFitAsReplacementHistogram
|
class PackedInternalDoubleHistogram extends PackedDoubleHistogram {
private final long containingInstanceId;
private PackedInternalDoubleHistogram(long id, int numberOfSignificantValueDigits) {
super(numberOfSignificantValueDigits);
this.containingInstanceId = id;
}
}
private void validateFitAsReplacementHistogram(DoubleHistogram replacementHistogram,
boolean enforceContainingInstance) {<FILL_FUNCTION_BODY>
|
boolean bad = true;
if (replacementHistogram == null) {
bad = false;
} else if ((replacementHistogram instanceof InternalDoubleHistogram)
&&
((!enforceContainingInstance) ||
(((InternalDoubleHistogram) replacementHistogram).containingInstanceId ==
((InternalDoubleHistogram)activeHistogram).containingInstanceId)
)) {
bad = false;
} else if ((replacementHistogram instanceof PackedInternalDoubleHistogram)
&&
((!enforceContainingInstance) ||
(((PackedInternalDoubleHistogram) replacementHistogram).containingInstanceId ==
((PackedInternalDoubleHistogram)activeHistogram).containingInstanceId)
)) {
bad = false;
}
if (bad) {
throw new IllegalArgumentException("replacement histogram must have been obtained via a previous " +
"getIntervalHistogram() call from this " + this.getClass().getName() +" instance");
}
| 119 | 244 | 363 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/WriterReaderPhaser.java
|
WriterReaderPhaser
|
flipPhase
|
class WriterReaderPhaser {
private volatile long startEpoch = 0;
private volatile long evenEndEpoch = 0;
private volatile long oddEndEpoch = Long.MIN_VALUE;
private final ReentrantLock readerLock = new ReentrantLock();
private static final AtomicLongFieldUpdater<WriterReaderPhaser> startEpochUpdater =
AtomicLongFieldUpdater.newUpdater(WriterReaderPhaser.class, "startEpoch");
private static final AtomicLongFieldUpdater<WriterReaderPhaser> evenEndEpochUpdater =
AtomicLongFieldUpdater.newUpdater(WriterReaderPhaser.class, "evenEndEpoch");
private static final AtomicLongFieldUpdater<WriterReaderPhaser> oddEndEpochUpdater =
AtomicLongFieldUpdater.newUpdater(WriterReaderPhaser.class, "oddEndEpoch");
/**
* Indicate entry to a critical section containing a write operation.
* <p>
* This call is wait-free on architectures that support wait free atomic increment operations,
* and is lock-free on architectures that do not.
* <p>
* {@code writerCriticalSectionEnter()} must be matched with a subsequent
* {@link WriterReaderPhaser#writerCriticalSectionExit(long)} in order for CriticalSectionPhaser
* synchronization to function properly.
*
* @return an (opaque) value associated with the critical section entry, which MUST be provided
* to the matching {@link WriterReaderPhaser#writerCriticalSectionExit} call.
*/
public long writerCriticalSectionEnter() {
return startEpochUpdater.getAndIncrement(this);
}
/**
* Indicate exit from a critical section containing a write operation.
* <p>
* This call is wait-free on architectures that support wait free atomic increment operations,
* and is lock-free on architectures that do not.
* <p>
* {@code writerCriticalSectionExit(long)} must be matched with a preceding
* {@link WriterReaderPhaser#writerCriticalSectionEnter()} call, and must be provided with the
* matching {@link WriterReaderPhaser#writerCriticalSectionEnter()} call's return value, in
* order for CriticalSectionPhaser synchronization to function properly.
*
* @param criticalValueAtEnter the (opaque) value returned from the matching
* {@link WriterReaderPhaser#writerCriticalSectionEnter()} call.
*/
public void writerCriticalSectionExit(long criticalValueAtEnter) {
(criticalValueAtEnter < 0 ? oddEndEpochUpdater : evenEndEpochUpdater).getAndIncrement(this);
}
/**
* Enter to a critical section containing a read operation (reentrant, mutually excludes against
* {@link WriterReaderPhaser#readerLock} calls by other threads).
* <p>
* {@link WriterReaderPhaser#readerLock} DOES NOT provide synchronization
* against {@link WriterReaderPhaser#writerCriticalSectionEnter()} calls. Use {@link WriterReaderPhaser#flipPhase()}
* to synchronize reads against writers.
*/
public void readerLock() {
readerLock.lock();
}
/**
* Exit from a critical section containing a read operation (relinquishes mutual exclusion against other
* {@link WriterReaderPhaser#readerLock} calls).
*/
public void readerUnlock() {
readerLock.unlock();
}
/**
* Flip a phase in the {@link WriterReaderPhaser} instance, {@link WriterReaderPhaser#flipPhase()}
* can only be called while holding the {@link WriterReaderPhaser#readerLock() readerLock}.
* {@link WriterReaderPhaser#flipPhase()} will return only after all writer critical sections (protected by
* {@link WriterReaderPhaser#writerCriticalSectionEnter() writerCriticalSectionEnter} and
* {@link WriterReaderPhaser#writerCriticalSectionExit writerCriticalSectionEnter}) that may have been
* in flight when the {@link WriterReaderPhaser#flipPhase()} call were made had completed.
* <p>
* No actual writer critical section activity is required for {@link WriterReaderPhaser#flipPhase()} to
* succeed.
* <p>
* However, {@link WriterReaderPhaser#flipPhase()} is lock-free with respect to calls to
* {@link WriterReaderPhaser#writerCriticalSectionEnter()} and
* {@link WriterReaderPhaser#writerCriticalSectionExit writerCriticalSectionExit()}. It may spin-wait
* or for active writer critical section code to complete.
*
* @param yieldTimeNsec The amount of time (in nanoseconds) to sleep in each yield if yield loop is needed.
*/
public void flipPhase(long yieldTimeNsec) {<FILL_FUNCTION_BODY>}
/**
* Flip a phase in the {@link WriterReaderPhaser} instance, {@code flipPhase()}
* can only be called while holding the {@link WriterReaderPhaser#readerLock() readerLock}.
* {@code flipPhase()} will return only after all writer critical sections (protected by
* {@link WriterReaderPhaser#writerCriticalSectionEnter() writerCriticalSectionEnter} and
* {@link WriterReaderPhaser#writerCriticalSectionExit writerCriticalSectionEnter}) that may have been
* in flight when the {@code flipPhase()} call were made had completed.
* <p>
* No actual writer critical section activity is required for {@code flipPhase()} to
* succeed.
* <p>
* However, {@code flipPhase()} is lock-free with respect to calls to
* {@link WriterReaderPhaser#writerCriticalSectionEnter()} and
* {@link WriterReaderPhaser#writerCriticalSectionExit writerCriticalSectionExit()}. It may spin-wait
* or for active writer critical section code to complete.
*/
public void flipPhase() {
flipPhase(0);
}
}
|
if (!readerLock.isHeldByCurrentThread()) {
throw new IllegalStateException("flipPhase() can only be called while holding the readerLock()");
}
// Read the volatile 'startEpoch' exactly once
boolean nextPhaseIsEven = (startEpoch < 0); // Current phase is odd...
// First, clear currently unused [next] phase end epoch (to proper initial value for phase):
long initialStartValue = nextPhaseIsEven ? 0 : Long.MIN_VALUE;
(nextPhaseIsEven ? evenEndEpochUpdater : oddEndEpochUpdater).lazySet(this, initialStartValue);
// Next, reset start value, indicating new phase, and retain value at flip:
long startValueAtFlip = startEpochUpdater.getAndSet(this, initialStartValue);
// Now, spin until previous phase end value catches up with start value at flip:
while((nextPhaseIsEven ? oddEndEpoch : evenEndEpoch) != startValueAtFlip) {
if (yieldTimeNsec == 0) {
Thread.yield();
} else {
try {
TimeUnit.NANOSECONDS.sleep(yieldTimeNsec);
} catch (InterruptedException ex) {
// nothing to do here, we just woke up earlier that expected.
}
}
}
| 1,534 | 344 | 1,878 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/ZigZagEncoding.java
|
ZigZagEncoding
|
putLong
|
class ZigZagEncoding {
/**
* Writes a long value to the given buffer in LEB128 ZigZag encoded format
* @param buffer the buffer to write to
* @param value the value to write to the buffer
*/
static void putLong(ByteBuffer buffer, long value) {<FILL_FUNCTION_BODY>}
/**
* Writes an int value to the given buffer in LEB128-64b9B ZigZag encoded format
* @param buffer the buffer to write to
* @param value the value to write to the buffer
*/
static void putInt(ByteBuffer buffer, int value) {
value = (value << 1) ^ (value >> 31);
if (value >>> 7 == 0) {
buffer.put((byte) value);
} else {
buffer.put((byte) ((value & 0x7F) | 0x80));
if (value >>> 14 == 0) {
buffer.put((byte) (value >>> 7));
} else {
buffer.put((byte) (value >>> 7 | 0x80));
if (value >>> 21 == 0) {
buffer.put((byte) (value >>> 14));
} else {
buffer.put((byte) (value >>> 14 | 0x80));
if (value >>> 28 == 0) {
buffer.put((byte) (value >>> 21));
} else {
buffer.put((byte) (value >>> 21 | 0x80));
buffer.put((byte) (value >>> 28));
}
}
}
}
}
/**
* Read an LEB128-64b9B ZigZag encoded long value from the given buffer
* @param buffer the buffer to read from
* @return the value read from the buffer
*/
static long getLong(ByteBuffer buffer) {
long v = buffer.get();
long value = v & 0x7F;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 7;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 14;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 21;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 28;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 35;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 42;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 49;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= v << 56;
}
}
}
}
}
}
}
}
value = (value >>> 1) ^ (-(value & 1));
return value;
}
/**
* Read an LEB128-64b9B ZigZag encoded int value from the given buffer
* @param buffer the buffer to read from
* @return the value read from the buffer
*/
static int getInt (ByteBuffer buffer) {
int v = buffer.get();
int value = v & 0x7F;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 7;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 14;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 21;
if ((v & 0x80) != 0) {
v = buffer.get();
value |= (v & 0x7F) << 28;
}
}
}
}
value = (value >>> 1) ^ (-(value & 1));
return value;
}
}
|
value = (value << 1) ^ (value >> 63);
if (value >>> 7 == 0) {
buffer.put((byte) value);
} else {
buffer.put((byte) ((value & 0x7F) | 0x80));
if (value >>> 14 == 0) {
buffer.put((byte) (value >>> 7));
} else {
buffer.put((byte) (value >>> 7 | 0x80));
if (value >>> 21 == 0) {
buffer.put((byte) (value >>> 14));
} else {
buffer.put((byte) (value >>> 14 | 0x80));
if (value >>> 28 == 0) {
buffer.put((byte) (value >>> 21));
} else {
buffer.put((byte) (value >>> 21 | 0x80));
if (value >>> 35 == 0) {
buffer.put((byte) (value >>> 28));
} else {
buffer.put((byte) (value >>> 28 | 0x80));
if (value >>> 42 == 0) {
buffer.put((byte) (value >>> 35));
} else {
buffer.put((byte) (value >>> 35 | 0x80));
if (value >>> 49 == 0) {
buffer.put((byte) (value >>> 42));
} else {
buffer.put((byte) (value >>> 42 | 0x80));
if (value >>> 56 == 0) {
buffer.put((byte) (value >>> 49));
} else {
buffer.put((byte) (value >>> 49 | 0x80));
buffer.put((byte) (value >>> 56));
}
}
}
}
}
}
}
}
| 1,199 | 501 | 1,700 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/packedarray/ConcurrentPackedArrayContext.java
|
ConcurrentPackedArrayContext
|
resizeArray
|
class ConcurrentPackedArrayContext extends PackedArrayContext {
ConcurrentPackedArrayContext(final int virtualLength,
final int initialPhysicalLength,
final boolean allocateArray) {
super(virtualLength, initialPhysicalLength, false);
if (allocateArray) {
array = new AtomicLongArray(getPhysicalLength());
init(virtualLength);
}
}
ConcurrentPackedArrayContext(final int virtualLength,
final int initialPhysicalLength) {
this(virtualLength, initialPhysicalLength, true);
}
ConcurrentPackedArrayContext(final int newVirtualCountsArraySize,
final AbstractPackedArrayContext from,
final int arrayLength) {
this(newVirtualCountsArraySize, arrayLength);
if (isPacked()) {
populateEquivalentEntriesWithZerosFromOther(from);
}
}
private AtomicLongArray array;
private volatile int populatedShortLength;
private static final AtomicIntegerFieldUpdater<ConcurrentPackedArrayContext> populatedShortLengthUpdater =
AtomicIntegerFieldUpdater.newUpdater(ConcurrentPackedArrayContext.class, "populatedShortLength");
@Override
int length() {
return array.length();
}
@Override
int getPopulatedShortLength() {
return populatedShortLength;
}
@Override
boolean casPopulatedShortLength(final int expectedPopulatedShortLength, final int newPopulatedShortLength) {
return populatedShortLengthUpdater.compareAndSet(this, expectedPopulatedShortLength, newPopulatedShortLength);
}
@Override
boolean casPopulatedLongLength(final int expectedPopulatedLongLength, final int newPopulatedLongLength) {
int existingShortLength = getPopulatedShortLength();
int existingLongLength = (existingShortLength + 3) >> 2;
if (existingLongLength != expectedPopulatedLongLength) return false;
return casPopulatedShortLength(existingShortLength, newPopulatedLongLength << 2);
}
@Override
long getAtLongIndex(final int longIndex) {
return array.get(longIndex);
}
@Override
boolean casAtLongIndex(final int longIndex, final long expectedValue, final long newValue) {
return array.compareAndSet(longIndex, expectedValue, newValue);
}
@Override
void lazySetAtLongIndex(final int longIndex, final long newValue) {
array.lazySet(longIndex, newValue);
}
@Override
void clearContents() {
for (int i = 0; i < array.length(); i++) {
array.lazySet(i, 0);
}
init(getVirtualLength());
}
@Override
void resizeArray(final int newLength) {<FILL_FUNCTION_BODY>}
@Override
long getAtUnpackedIndex(final int index) {
return array.get(index);
}
@Override
void setAtUnpackedIndex(final int index, final long newValue) {
array.set(index, newValue);
}
@Override
void lazySetAtUnpackedIndex(final int index, final long newValue) {
array.lazySet(index, newValue);
}
@Override
long incrementAndGetAtUnpackedIndex(final int index) {
return array.incrementAndGet(index);
}
@Override
long addAndGetAtUnpackedIndex(final int index, final long valueToAdd) {
return array.addAndGet(index, valueToAdd);
}
@Override
String unpackedToString() {
return array.toString();
}
}
|
final AtomicLongArray newArray = new AtomicLongArray(newLength);
int copyLength = Math.min(array.length(), newLength);
for (int i = 0; i < copyLength; i++) {
newArray.lazySet(i, array.get(i));
}
array = newArray;
| 950 | 84 | 1,034 |
<methods><variables>private long[] array,private int populatedShortLength
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/packedarray/ConcurrentPackedLongArray.java
|
ConcurrentPackedLongArray
|
setVirtualLength
|
class ConcurrentPackedLongArray extends PackedLongArray {
public ConcurrentPackedLongArray(final int virtualLength) {
this(virtualLength, AbstractPackedArrayContext.MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY);
}
public ConcurrentPackedLongArray(final int virtualLength, final int initialPhysicalLength) {
super();
setArrayContext(new ConcurrentPackedArrayContext(virtualLength, initialPhysicalLength));
}
transient WriterReaderPhaser wrp = new WriterReaderPhaser();
@Override
void resizeStorageArray(final int newPhysicalLengthInLongs) {
AbstractPackedArrayContext inactiveArrayContext;
try {
wrp.readerLock();
// Create a new array context, mimicking the structure of the currently active
// context, but without actually populating any values.
ConcurrentPackedArrayContext newArrayContext =
new ConcurrentPackedArrayContext(
getArrayContext().getVirtualLength(),
getArrayContext(), newPhysicalLengthInLongs
);
// Flip the current live array context and the newly created one:
inactiveArrayContext = getArrayContext();
setArrayContext(newArrayContext);
wrp.flipPhase();
// The now inactive array context is stable, and the new array context is active.
// We don't want to try to record values from the inactive into the new array context
// here (under the wrp reader lock) because we could deadlock if resizing is needed.
// Instead, value recording will be done after we release the read lock.
} finally {
wrp.readerUnlock();
}
// Record all contents from the now inactive array to new live one:
for (IterationValue v : inactiveArrayContext.nonZeroValues()) {
add(v.getIndex(), v.getValue());
}
// inactive array contents is fully committed into the newly resized live array. It can now die in peace.
}
@Override
public void setVirtualLength(final int newVirtualArrayLength) {<FILL_FUNCTION_BODY>}
@Override
public ConcurrentPackedLongArray copy() {
ConcurrentPackedLongArray copy = new ConcurrentPackedLongArray(this.length(), this.getPhysicalLength());
copy.add(this);
return copy;
}
@Override
void clearContents() {
try {
wrp.readerLock();
getArrayContext().clearContents();
} finally {
wrp.readerUnlock();
}
}
@Override
long criticalSectionEnter() {
return wrp.writerCriticalSectionEnter();
}
@Override
void criticalSectionExit(long criticalValueAtEnter) {
wrp.writerCriticalSectionExit(criticalValueAtEnter);
}
@Override
public String toString() {
try {
wrp.readerLock();
return super.toString();
} finally {
wrp.readerUnlock();
}
}
@Override
public void clear() {
try {
wrp.readerLock();
super.clear();
} finally {
wrp.readerUnlock();
}
}
private void readObject(final ObjectInputStream o)
throws IOException, ClassNotFoundException {
o.defaultReadObject();
wrp = new WriterReaderPhaser();
}
}
|
if (newVirtualArrayLength < length()) {
throw new IllegalArgumentException(
"Cannot set virtual length, as requested length " + newVirtualArrayLength +
" is smaller than the current virtual length " + length());
}
AbstractPackedArrayContext inactiveArrayContext;
try {
wrp.readerLock();
AbstractPackedArrayContext currentArrayContext = getArrayContext();
if (currentArrayContext.isPacked() &&
(currentArrayContext.determineTopLevelShiftForVirtualLength(newVirtualArrayLength) ==
currentArrayContext.getTopLevelShift())) {
// No changes to the array context contents is needed. Just change the virtual length.
currentArrayContext.setVirtualLength(newVirtualArrayLength);
return;
}
inactiveArrayContext = currentArrayContext;
setArrayContext(
new ConcurrentPackedArrayContext(
newVirtualArrayLength,
inactiveArrayContext,
inactiveArrayContext.length()
));
wrp.flipPhase();
// The now inactive array context is stable, and the new array context is active.
// We don't want to try to record values from the inactive into the new array context
// here (under the wrp reader lock) because we could deadlock if resizing is needed.
// Instead, value recording will be done after we release the read lock.
} finally {
wrp.readerUnlock();
}
for (IterationValue v : inactiveArrayContext.nonZeroValues()) {
add(v.getIndex(), v.getValue());
}
| 861 | 386 | 1,247 |
<methods>public void <init>(int) ,public void <init>(int, int) ,public org.HdrHistogram.packedarray.PackedLongArray copy() ,public void setVirtualLength(int) <variables>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/packedarray/PackedArrayContext.java
|
PackedArrayContext
|
casPopulatedShortLength
|
class PackedArrayContext extends AbstractPackedArrayContext {
PackedArrayContext(final int virtualLength,
final int initialPhysicalLength,
final boolean allocateArray) {
super(virtualLength, initialPhysicalLength);
if (allocateArray) {
array = new long[getPhysicalLength()];
init(virtualLength);
}
}
PackedArrayContext(final int virtualLength,
final int initialPhysicalLength) {
this(virtualLength, initialPhysicalLength, true);
}
PackedArrayContext(final int virtualLength,
final AbstractPackedArrayContext from,
final int newPhysicalArrayLength) {
this(virtualLength, newPhysicalArrayLength);
if (isPacked()) {
populateEquivalentEntriesWithZerosFromOther(from);
}
}
private long[] array;
private int populatedShortLength = 0;
@Override
int length() {
return array.length;
}
@Override
int getPopulatedShortLength() {
return populatedShortLength;
}
@Override
boolean casPopulatedShortLength(final int expectedPopulatedShortLength, final int newPopulatedShortLength) {<FILL_FUNCTION_BODY>}
@Override
boolean casPopulatedLongLength(final int expectedPopulatedLongLength, final int newPopulatedLongLength) {
if (getPopulatedLongLength() != expectedPopulatedLongLength) return false;
return casPopulatedShortLength(populatedShortLength, newPopulatedLongLength << 2);
}
@Override
long getAtLongIndex(final int longIndex) {
return array[longIndex];
}
@Override
boolean casAtLongIndex(final int longIndex, final long expectedValue, final long newValue) {
if (array[longIndex] != expectedValue) return false;
array[longIndex] = newValue;
return true;
}
@Override
void lazySetAtLongIndex(final int longIndex, final long newValue) {
array[longIndex] = newValue;
}
@Override
void clearContents() {
java.util.Arrays.fill(array, 0);
init(getVirtualLength());
}
@Override
void resizeArray(final int newLength) {
array = Arrays.copyOf(array, newLength);
}
@Override
long getAtUnpackedIndex(final int index) {
return array[index];
}
@Override
void setAtUnpackedIndex(final int index, final long newValue) {
array[index] = newValue;
}
@Override
void lazySetAtUnpackedIndex(final int index, final long newValue) {
array[index] = newValue;
}
@Override
long incrementAndGetAtUnpackedIndex(final int index) {
array[index]++;
return array[index];
}
@Override
long addAndGetAtUnpackedIndex(final int index, final long valueToAdd) {
array[index] += valueToAdd;
return array[index];
}
@Override
String unpackedToString() {
return Arrays.toString(array);
}
}
|
if (this.populatedShortLength != expectedPopulatedShortLength) return false;
this.populatedShortLength = newPopulatedShortLength;
return true;
| 827 | 44 | 871 |
<methods>public java.lang.String toString() <variables>private static final int LEAF_LEVEL_SHIFT,static final int MAX_SUPPORTED_PACKED_COUNTS_ARRAY_LENGTH,static final int MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY,private static final int NON_LEAF_ENTRY_HEADER_SIZE_IN_SHORTS,private static final int NON_LEAF_ENTRY_PREVIOUS_VERSION_OFFSET,private static final int NON_LEAF_ENTRY_SLOT_INDICATORS_OFFSET,private static final int NUMBER_OF_SETS,private static final int PACKED_ARRAY_GROWTH_FRACTION_POW2,private static final int PACKED_ARRAY_GROWTH_INCREMENT,private static final int SET_0_START_INDEX,private final non-sealed boolean isPacked,private int physicalLength,private int topLevelShift,private int virtualLength
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/packedarray/PackedArraySingleWriterRecorder.java
|
InternalPackedLongArray
|
validateFitAsReplacementArray
|
class InternalPackedLongArray extends PackedLongArray {
private final long containingInstanceId;
private InternalPackedLongArray(final long id, int virtualLength, final int initialPhysicalLength) {
super(virtualLength, initialPhysicalLength);
this.containingInstanceId = id;
}
private InternalPackedLongArray(final long id, final int virtualLength) {
super(virtualLength);
this.containingInstanceId = id;
}
}
private void validateFitAsReplacementArray(final PackedLongArray replacementArray,
final boolean enforceContainingInstance) {<FILL_FUNCTION_BODY>
|
boolean bad = true;
if (replacementArray == null) {
bad = false;
} else if (replacementArray instanceof InternalPackedLongArray) {
if ((activeArray instanceof InternalPackedLongArray)
&&
((!enforceContainingInstance) ||
(((InternalPackedLongArray)replacementArray).containingInstanceId ==
((InternalPackedLongArray) activeArray).containingInstanceId)
)) {
bad = false;
}
}
if (bad) {
throw new IllegalArgumentException("replacement array must have been obtained via a previous" +
" getIntervalArray() call from this " + this.getClass().getName() +
(enforceContainingInstance ? " instance" : " class"));
}
| 161 | 189 | 350 |
<no_super_class>
|
HdrHistogram_HdrHistogram
|
HdrHistogram/src/main/java/org/HdrHistogram/packedarray/PackedLongArray.java
|
PackedLongArray
|
setVirtualLength
|
class PackedLongArray extends AbstractPackedLongArray {
PackedLongArray() {}
public PackedLongArray(final int virtualLength) {
this(virtualLength, AbstractPackedArrayContext.MINIMUM_INITIAL_PACKED_ARRAY_CAPACITY);
}
public PackedLongArray(final int virtualLength, final int initialPhysicalLength) {
setArrayContext(new PackedArrayContext(virtualLength, initialPhysicalLength));
}
@Override
void resizeStorageArray(final int newPhysicalLengthInLongs) {
AbstractPackedArrayContext oldArrayContext = getArrayContext();
PackedArrayContext newArrayContext =
new PackedArrayContext(oldArrayContext.getVirtualLength(), oldArrayContext, newPhysicalLengthInLongs);
setArrayContext(newArrayContext);
for (IterationValue v : oldArrayContext.nonZeroValues()) {
set(v.getIndex(), v.getValue());
}
}
@Override
public void setVirtualLength(final int newVirtualArrayLength) {<FILL_FUNCTION_BODY>}
@Override
public PackedLongArray copy() {
PackedLongArray copy = new PackedLongArray(this.length(), this.getPhysicalLength());
copy.add(this);
return copy;
}
@Override
void clearContents() {
getArrayContext().clearContents();
}
@Override
long criticalSectionEnter() {
return 0;
}
@Override
void criticalSectionExit(final long criticalValueAtEnter) {
}
}
|
if (newVirtualArrayLength < length()) {
throw new IllegalArgumentException(
"Cannot set virtual length, as requested length " + newVirtualArrayLength +
" is smaller than the current virtual length " + length());
}
AbstractPackedArrayContext currentArrayContext = getArrayContext();
if (currentArrayContext.isPacked() &&
(currentArrayContext.determineTopLevelShiftForVirtualLength(newVirtualArrayLength) ==
currentArrayContext.getTopLevelShift())) {
// No changes to the array context contents is needed. Just change the virtual length.
currentArrayContext.setVirtualLength(newVirtualArrayLength);
return;
}
AbstractPackedArrayContext oldArrayContext = currentArrayContext;
setArrayContext(new PackedArrayContext(newVirtualArrayLength, oldArrayContext, oldArrayContext.length()));
for (IterationValue v : oldArrayContext.nonZeroValues()) {
set(v.getIndex(), v.getValue());
}
| 400 | 236 | 636 |
<methods>public void add(int, long) ,public void add(org.HdrHistogram.packedarray.AbstractPackedLongArray) ,public void clear() ,public abstract org.HdrHistogram.packedarray.AbstractPackedLongArray copy() ,public boolean equals(java.lang.Object) ,public long get(int) ,public long getEndTimeStamp() ,public int getPhysicalLength() ,public long getStartTimeStamp() ,public int hashCode() ,public void increment(int) ,public Iterator<java.lang.Long> iterator() ,public int length() ,public Iterable<org.HdrHistogram.packedarray.IterationValue> nonZeroValues() ,public void set(int, long) ,public void setEndTimeStamp(long) ,public void setStartTimeStamp(long) ,public abstract void setVirtualLength(int) ,public java.lang.String toString() <variables>static final int NUMBER_OF_NON_ZEROS_TO_HASH,private static final int NUMBER_OF_SETS,private org.HdrHistogram.packedarray.AbstractPackedArrayContext arrayContext,private long endTimeStampMsec,private long startTimeStampMsec
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/HotswapAgent.java
|
HotswapAgent
|
parseArgs
|
class HotswapAgent {
private static AgentLogger LOGGER = AgentLogger.getLogger(HotswapAgent.class);
/**
* Force disable plugin, this plugin is skipped during scanning process.
* <p/>
* Plugin might be disabled in hotswap-agent.properties for application classloaders as well.
*/
private static Set<String> disabledPlugins = new HashSet<>();
/**
* Default value for autoHotswap property.
*/
private static boolean autoHotswap = false;
/**
* Path for an external properties file `hotswap-agent.properties`
*/
private static String propertiesFilePath;
public static void agentmain(String args, Instrumentation inst) {
premain(args, inst);
}
public static void premain(String args, Instrumentation inst) {
LOGGER.info("Loading Hotswap agent {{}} - unlimited runtime class redefinition.", Version.version());
parseArgs(args);
fixJboss7Modules();
PluginManager.getInstance().init(inst);
LOGGER.debug("Hotswap agent initialized.");
}
public static void parseArgs(String args) {<FILL_FUNCTION_BODY>}
/**
* @return the path for the hotswap-agent.properties external file
*/
public static String getExternalPropertiesFile() {
return propertiesFilePath;
}
/**
* Checks if the plugin is disabled (by name).
*
* @param pluginName plugin name (e.g. Tomcat, Spring, ...)
* @return true if the plugin is disabled
*/
public static boolean isPluginDisabled(String pluginName) {
return disabledPlugins.contains(pluginName.toLowerCase());
}
/**
* Default autoHotswap property value.
*
* @return true if autoHotswap=true command line option was specified
*/
public static boolean isAutoHotswap() {
return autoHotswap;
}
/**
* JBoss 7 use OSGI classloading and hence agent core classes are not available from application classloader
* (this is not the case with standard classloaders with parent delgation).
*
* Wee need to simulate command line attribute -Djboss.modules.system.pkgs=org.hotswap.agent to allow any
* classloader to access agent libraries (OSGI default export). This method does it on behalf of the user.
*
* It is not possible to add whole org.hotswap.agent package, because it includes all subpackages and
* examples will fail (org.hotswap.agent.example will become system package).
*
* See similar problem description https://issues.jboss.org/browse/WFLY-895.
*/
private static void fixJboss7Modules() {
String JBOSS_SYSTEM_MODULES_KEY = "jboss.modules.system.pkgs";
String oldValue = System.getProperty(JBOSS_SYSTEM_MODULES_KEY, null);
System.setProperty(JBOSS_SYSTEM_MODULES_KEY, oldValue == null ? HOTSWAP_AGENT_EXPORT_PACKAGES : oldValue + "," + HOTSWAP_AGENT_EXPORT_PACKAGES);
}
public static final String HOTSWAP_AGENT_EXPORT_PACKAGES = //
"org.hotswap.agent.annotation,"//
+ "org.hotswap.agent.command," //
+ "org.hotswap.agent.config," //
+ "org.hotswap.agent.logging,"
+ "org.hotswap.agent.plugin," //
+ "org.hotswap.agent.util," //
+ "org.hotswap.agent.watch," //
+ "org.hotswap.agent.versions," //
+ "org.hotswap.agent.javassist";
}
|
if (args == null)
return;
for (String arg : args.split(",")) {
String[] val = arg.split("=");
if (val.length != 2) {
LOGGER.warning("Invalid javaagent command line argument '{}'. Argument is ignored.", arg);
}
String option = val[0];
String optionValue = val[1];
if ("disablePlugin".equals(option)) {
disabledPlugins.add(optionValue.toLowerCase());
} else if ("autoHotswap".equals(option)) {
autoHotswap = Boolean.valueOf(optionValue);
} else if ("propertiesFilePath".equals(option)) {
propertiesFilePath = optionValue;
} else {
LOGGER.warning("Invalid javaagent option '{}'. Argument '{}' is ignored.", option, arg);
}
}
| 1,024 | 223 | 1,247 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/AnnotationProcessor.java
|
AnnotationProcessor
|
processFieldAnnotations
|
class AnnotationProcessor {
private static AgentLogger LOGGER = AgentLogger.getLogger(AnnotationProcessor.class);
protected PluginManager pluginManager;
public AnnotationProcessor(PluginManager pluginManager) {
this.pluginManager = pluginManager;
init(pluginManager);
}
protected Map<Class<? extends Annotation>, PluginHandler> handlers =
new HashMap<Class<? extends Annotation>, PluginHandler>();
public void init(PluginManager pluginManager) {
addAnnotationHandler(Init.class, new InitHandler(pluginManager));
addAnnotationHandler(OnClassLoadEvent.class, new OnClassLoadedHandler(pluginManager));
addAnnotationHandler(OnClassFileEvent.class, new WatchHandler(pluginManager));
addAnnotationHandler(OnResourceFileEvent.class, new WatchHandler(pluginManager));
}
public void addAnnotationHandler(Class<? extends Annotation> annotation, PluginHandler handler) {
handlers.put(annotation, handler);
}
/**
* Process annotations on the plugin class - only static methods, methods to hook plugin initialization.
*
* @param processClass class to process annotation
* @param pluginClass main plugin class (annotated with @Plugin)
* @return true if success
*/
public boolean processAnnotations(Class processClass, Class pluginClass) {
try {
for (Field field : processClass.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers()))
if (!processFieldAnnotations(null, field, pluginClass))
return false;
}
for (Method method : processClass.getDeclaredMethods()) {
if (Modifier.isStatic(method.getModifiers()))
if (!processMethodAnnotations(null, method, pluginClass))
return false;
}
// process annotations on all supporting classes in addition to the plugin itself
for (Annotation annotation : processClass.getDeclaredAnnotations()) {
if (annotation instanceof Plugin) {
for (Class supportClass : ((Plugin) annotation).supportClass()) {
processAnnotations(supportClass, pluginClass);
}
}
}
return true;
} catch (Throwable e) {
LOGGER.error("Unable to process plugin annotations '{}'", e, pluginClass);
return false;
}
}
/**
* Process annotations on a plugin - non static fields and methods.
*
* @param plugin plugin object
* @return true if success
*/
public boolean processAnnotations(Object plugin) {
LOGGER.debug("Processing annotations for plugin '" + plugin + "'.");
Class pluginClass = plugin.getClass();
for (Field field : pluginClass.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers()))
if (!processFieldAnnotations(plugin, field, pluginClass))
return false;
}
for (Method method : pluginClass.getDeclaredMethods()) {
if (!Modifier.isStatic(method.getModifiers()))
if (!processMethodAnnotations(plugin, method, pluginClass))
return false;
}
return true;
}
@SuppressWarnings("unchecked")
private boolean processFieldAnnotations(Object plugin, Field field, Class pluginClass) {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
private boolean processMethodAnnotations(Object plugin, Method method, Class pluginClass) {
// for all methods and all handlers
for (Annotation annotation : method.getDeclaredAnnotations()) {
for (Class<? extends Annotation> handlerAnnotation : handlers.keySet()) {
if (annotation.annotationType().equals(handlerAnnotation)) {
// initialize
PluginAnnotation<?> pluginAnnotation = new PluginAnnotation<>(pluginClass, plugin, annotation, method);
if (!handlers.get(handlerAnnotation).initMethod(pluginAnnotation)) {
return false;
}
}
}
}
return true;
}
}
|
// for all fields and all handlers
for (Annotation annotation : field.getDeclaredAnnotations()) {
for (Class<? extends Annotation> handlerAnnotation : handlers.keySet()) {
if (annotation.annotationType().equals(handlerAnnotation)) {
// initialize
PluginAnnotation<?> pluginAnnotation = new PluginAnnotation<>(pluginClass, plugin, annotation, field);
if (!handlers.get(handlerAnnotation).initField(pluginAnnotation)) {
return false;
}
}
}
}
return true;
| 1,006 | 136 | 1,142 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/InitHandler.java
|
InitHandler
|
resolveType
|
class InitHandler implements PluginHandler<Init> {
private static AgentLogger LOGGER = AgentLogger.getLogger(InitHandler.class);
protected PluginManager pluginManager;
public InitHandler(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
@Override
public boolean initField(PluginAnnotation pluginAnnotation) {
Field field = pluginAnnotation.getField();
// if plugin not set, it is static method on plugin registration, use agent classloader
ClassLoader appClassLoader = pluginAnnotation.getPlugin() == null ? getClass().getClassLoader() :
pluginManager.getPluginRegistry().getAppClassLoader(pluginAnnotation.getPlugin());
Object value = resolveType(appClassLoader, pluginAnnotation.getPluginClass(), field.getType());
field.setAccessible(true);
try {
field.set(pluginAnnotation.getPlugin(), value);
} catch (IllegalAccessException e) {
LOGGER.error("Unable to set plugin field '{}' to value '{}' on plugin '{}'",
e, field.getName(), value, pluginAnnotation.getPluginClass());
return false;
}
return true;
}
// Main plugin initialization via @Init method.
// If static, just register callback, otherwise the method is immediately invoked.
@Override
public boolean initMethod(PluginAnnotation pluginAnnotation) {
Object plugin = pluginAnnotation.getPlugin();
if (plugin == null) {
// special case - static method - register callback
if (Modifier.isStatic(pluginAnnotation.getMethod().getModifiers()))
return registerClassLoaderInit(pluginAnnotation);
else
return true;
} else {
if (!Modifier.isStatic(pluginAnnotation.getMethod().getModifiers())) {
ClassLoader appClassLoader = pluginManager.getPluginRegistry().getAppClassLoader(plugin);
return invokeInitMethod(pluginAnnotation, plugin, appClassLoader);
} else
return true;
}
}
// resolve all method parameter types to actual values and invoke the plugin method (both static and non static)
private boolean invokeInitMethod(PluginAnnotation pluginAnnotation, Object plugin, ClassLoader classLoader) {
List<Object> args = new ArrayList<>();
for (Class type : pluginAnnotation.getMethod().getParameterTypes()) {
args.add(resolveType(classLoader, pluginAnnotation.getPluginClass(), type));
}
try {
pluginAnnotation.getMethod().invoke(plugin, args.toArray());
return true;
} catch (IllegalAccessException e) {
LOGGER.error("IllegalAccessException in init method on plugin {}.", e, pluginAnnotation.getPluginClass());
return false;
} catch (InvocationTargetException e) {
LOGGER.error("InvocationTargetException in init method on plugin {}.", e, pluginAnnotation.getPluginClass());
return false;
}
}
/**
* Register on classloader init event - call the @Init static method.
*
* @param pluginAnnotation description of plugin method to call
* @return true if ok
*/
protected boolean registerClassLoaderInit(final PluginAnnotation pluginAnnotation) {
LOGGER.debug("Registering ClassLoaderInitListener on {}", pluginAnnotation.getPluginClass());
pluginManager.registerClassLoaderInitListener(new ClassLoaderInitListener() {
@Override
public void onInit(ClassLoader classLoader) {
// call the init method
LOGGER.debug("Init plugin {} at classloader {}.", pluginAnnotation.getPluginClass(), classLoader);
invokeInitMethod(pluginAnnotation, null, classLoader);
}
});
return true;
}
/**
* Support for autowiring of agent services - resolve instance by class.
*
* @param classLoader application classloader
* @param pluginClass used only for debugging messages
* @param type requested type
* @return resolved instance or null (error is logged)
*/
@SuppressWarnings("unchecked")
protected Object resolveType(ClassLoader classLoader, Class pluginClass, Class type) {<FILL_FUNCTION_BODY>}
}
|
if (type.isAssignableFrom(PluginManager.class)) {
return pluginManager;
} else if (type.isAssignableFrom(Watcher.class)) {
return pluginManager.getWatcher();
} else if (type.isAssignableFrom(Scheduler.class)) {
return pluginManager.getScheduler();
} else if (type.isAssignableFrom(HotswapTransformer.class)) {
return pluginManager.getHotswapTransformer();
} else if (type.isAssignableFrom(PluginConfiguration.class)) {
return pluginManager.getPluginConfiguration(classLoader);
} else if (type.isAssignableFrom(ClassLoader.class)) {
return classLoader;
} else if (type.isAssignableFrom(Instrumentation.class)) {
return pluginManager.getInstrumentation();
} else {
LOGGER.error("Unable process @Init on plugin '{}'." +
" Type '" + type + "' is not recognized for @Init annotation.", pluginClass);
return null;
}
| 1,008 | 271 | 1,279 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/OnClassLoadedHandler.java
|
OnClassLoadedHandler
|
initMethod
|
class OnClassLoadedHandler implements PluginHandler<OnClassLoadEvent> {
protected static AgentLogger LOGGER = AgentLogger.getLogger(OnClassLoadedHandler.class);
protected PluginManager pluginManager;
protected HotswapTransformer hotswapTransformer;
public OnClassLoadedHandler(PluginManager pluginManager) {
this.pluginManager = pluginManager;
this.hotswapTransformer = pluginManager.getHotswapTransformer();
if (hotswapTransformer == null) {
throw new IllegalArgumentException("Error instantiating OnClassLoadedHandler. Hotswap transformer is missing in PluginManager.");
}
}
@Override
public boolean initField(PluginAnnotation<OnClassLoadEvent> pluginAnnotation) {
throw new IllegalAccessError("@OnClassLoadEvent annotation not allowed on fields.");
}
@Override
public boolean initMethod(final PluginAnnotation<OnClassLoadEvent> pluginAnnotation) {<FILL_FUNCTION_BODY>}
}
|
LOGGER.debug("Init for method " + pluginAnnotation.getMethod());
if (hotswapTransformer == null) {
LOGGER.error("Error in init for method " + pluginAnnotation.getMethod() + ". Hotswap transformer is missing.");
return false;
}
final OnClassLoadEvent annot = pluginAnnotation.getAnnotation();
if (annot == null) {
LOGGER.error("Error in init for method " + pluginAnnotation.getMethod() + ". Annotation missing.");
return false;
}
ClassLoader appClassLoader = null;
if (pluginAnnotation.getPlugin() != null){
appClassLoader = pluginManager.getPluginRegistry().getAppClassLoader(pluginAnnotation.getPlugin());
}
hotswapTransformer.registerTransformer(appClassLoader, annot.classNameRegexp(), new PluginClassFileTransformer(pluginManager, pluginAnnotation));
return true;
| 251 | 231 | 482 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/PluginAnnotation.java
|
PluginAnnotation
|
hashCode
|
class PluginAnnotation<T extends Annotation> {
private static AgentLogger LOGGER = AgentLogger.getLogger(PluginAnnotation.class);
// the main plugin class
Class<?> pluginClass;
// target plugin object
Object plugin;
// the annotation to process
T annotation;
// annotation is on a field (and method property is empty)
Field field;
// annotation is on a method (and field property is empty)
Method method;
// plugin matcher
final PluginMatcher pluginMatcher;
// Method matcher
final MethodMatcher methodMatcher;
// plugin group (elresolver etc..)
final String group;
// Falback plugin - plugin is used if no other plugin in the group version matches
final boolean fallback;
public PluginAnnotation(Class<?> pluginClass, Object plugin, T annotation, Method method) {
this.pluginClass = pluginClass;
this.plugin = plugin;
this.annotation = annotation;
this.method = method;
Plugin pluginAnnotation = pluginClass.getAnnotation(Plugin.class);
this.group = (pluginAnnotation.group() != null && !pluginAnnotation.group().isEmpty()) ? pluginAnnotation.group() : null;
this.fallback = pluginAnnotation.fallback();
if(method != null && (Modifier.isStatic(method.getModifiers()))) {
this.pluginMatcher = new PluginMatcher(pluginClass);
this.methodMatcher= new MethodMatcher(method);
} else {
this.pluginMatcher = null;
this.methodMatcher = null;
}
}
public PluginAnnotation(Class<?> pluginClass, Object plugin, T annotation, Field field) {
this.pluginClass = pluginClass;
this.plugin = plugin;
this.annotation = annotation;
this.field = field;
this.pluginMatcher = null;
this.methodMatcher = null;
this.fallback = false;
this.group = null;
}
/**
* Return plugin class (the plugin to which this annotation belongs - not necessarily declaring class.
*/
public Class<?> getPluginClass() {
return pluginClass;
}
public Object getPlugin() {
return plugin;
}
public T getAnnotation() {
return annotation;
}
public Method getMethod() {
return method;
}
public Field getField() {
return field;
}
public boolean shouldCheckVersion() {
return //
(this.plugin == null)//
&& //
(//
(pluginMatcher != null && pluginMatcher.isApply()) //
|| //
(methodMatcher != null && methodMatcher.isApply())//
);//
}
/**
* @return true, if plugin is fallback
*/
public boolean isFallBack() {
return fallback;
}
/**
* @return the plugin group
*/
public String getGroup() {
return group;
}
/**
* Matches.
*
* @param deploymentInfo the deployment info
* @return true, if successful
*/
public boolean matches(DeploymentInfo deploymentInfo){
if(deploymentInfo == null || (pluginMatcher == null && methodMatcher == null)) {
LOGGER.debug("No matchers, apply");
return true;
}
if(pluginMatcher != null && pluginMatcher.isApply()) {
if(VersionMatchResult.REJECTED.equals(pluginMatcher.matches(deploymentInfo))){
LOGGER.debug("Plugin matcher rejected");
return false;
}
}
if(methodMatcher != null && methodMatcher.isApply()) {
if(VersionMatchResult.REJECTED.equals(methodMatcher.matches(deploymentInfo))){
LOGGER.debug("Method matcher rejected");
return false;
}
}
return true;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PluginAnnotation<?> that = (PluginAnnotation<?>) o;
if (!annotation.equals(that.annotation)) return false;
if (field != null ? !field.equals(that.field) : that.field != null) return false;
if (method != null ? !method.equals(that.method) : that.method != null) return false;
if (!plugin.equals(that.plugin)) return false;
return true;
}
@Override
public int hashCode() {<FILL_FUNCTION_BODY>}
@Override
public String toString() {
return "PluginAnnotation{" +
"plugin=" + plugin +
", annotation=" + annotation +
", field=" + field +
", method=" + method +
'}';
}
}
|
int result = plugin.hashCode();
result = 31 * result + annotation.hashCode();
result = 31 * result + (field != null ? field.hashCode() : 0);
result = 31 * result + (method != null ? method.hashCode() : 0);
return result;
| 1,266 | 80 | 1,346 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/WatchEventCommand.java
|
WatchEventCommand
|
equals
|
class WatchEventCommand<T extends Annotation> extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(WatchEventCommand.class);
private final PluginAnnotation<T> pluginAnnotation;
private final WatchEventDTO watchEventDTO;
private final WatchFileEvent event;
private final ClassLoader classLoader;
public static <T extends Annotation> WatchEventCommand<T> createCmdForEvent(PluginAnnotation<T> pluginAnnotation,
WatchFileEvent event, ClassLoader classLoader) {
WatchEventDTO watchEventDTO = WatchEventDTO.parse(pluginAnnotation.getAnnotation());
// Watch event is not supported.
if (!watchEventDTO.accept(event)) {
return null;
}
// regular files filter
if (watchEventDTO.isOnlyRegularFiles() && !event.isFile()) {
LOGGER.trace("Skipping URI {} because it is not a regular file.", event.getURI());
return null;
}
// watch type filter
if (!Arrays.asList(watchEventDTO.getEvents()).contains(event.getEventType())) {
LOGGER.trace("Skipping URI {} because it is not a requested event.", event.getURI());
return null;
}
// resource name filter regexp
if (watchEventDTO.getFilter() != null && watchEventDTO.getFilter().length() > 0) {
if (!event.getURI().toString().matches(watchEventDTO.getFilter())) {
LOGGER.trace("Skipping URI {} because it does not match filter.", event.getURI(), watchEventDTO.getFilter());
return null;
}
}
return new WatchEventCommand<>(pluginAnnotation, event, classLoader, watchEventDTO);
}
private WatchEventCommand(PluginAnnotation<T> pluginAnnotation, WatchFileEvent event, ClassLoader classLoader, WatchEventDTO watchEventDTO) {
this.pluginAnnotation = pluginAnnotation;
this.event = event;
this.classLoader = classLoader;
this.watchEventDTO = watchEventDTO;
}
@Override
public void executeCommand() {
LOGGER.trace("Executing for pluginAnnotation={}, event={} at classloader {}", pluginAnnotation, event, classLoader);
onWatchEvent(pluginAnnotation, event, classLoader);
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = pluginAnnotation != null ? pluginAnnotation.hashCode() : 0;
result = 31 * result + (event != null ? event.hashCode() : 0);
result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "WatchEventCommand{" +
"pluginAnnotation=" + pluginAnnotation +
", event=" + event +
", classLoader=" + classLoader +
'}';
}
/**
* Run plugin the method.
*/
public void onWatchEvent(PluginAnnotation<T> pluginAnnotation, WatchFileEvent event, ClassLoader classLoader) {
final T annot = pluginAnnotation.getAnnotation();
Object plugin = pluginAnnotation.getPlugin();
//we may need to crate CtClass on behalf of the client and close it after invocation.
CtClass ctClass = null;
// class file regexp
if (watchEventDTO.isClassFileEvent()) {
try {
// TODO creating class only to check name may slow down if lot of handlers is in use.
ctClass = createCtClass(event.getURI(), classLoader);
} catch (Exception e) {
LOGGER.error("Unable create CtClass for URI '{}'.", e, event.getURI());
return;
}
// unable to create CtClass or it's name does not match
if (ctClass == null || !ctClass.getName().matches(watchEventDTO.getClassNameRegexp()))
return;
}
LOGGER.debug("Executing resource changed method {} on class {} for event {}",
pluginAnnotation.getMethod().getName(), plugin.getClass().getName(), event);
List<Object> args = new ArrayList<>();
for (Class<?> type : pluginAnnotation.getMethod().getParameterTypes()) {
if (type.isAssignableFrom(ClassLoader.class)) {
args.add(classLoader);
} else if (type.isAssignableFrom(URI.class)) {
args.add(event.getURI());
} else if (type.isAssignableFrom(URL.class)) {
try {
args.add(event.getURI().toURL());
} catch (MalformedURLException e) {
LOGGER.error("Unable to convert URI '{}' to URL.", e, event.getURI());
return;
}
} else if (type.isAssignableFrom(ClassPool.class)) {
args.add(ClassPool.getDefault());
} else if (type.isAssignableFrom(FileEvent.class)) {
args.add(event.getEventType());
} else if (watchEventDTO.isClassFileEvent() && type.isAssignableFrom(CtClass.class)) {
args.add(ctClass);
} else if (watchEventDTO.isClassFileEvent() && type.isAssignableFrom(String.class)) {
args.add(ctClass != null ? ctClass.getName() : null);
} else {
LOGGER.error("Unable to call method {} on plugin {}. Method parameter type {} is not recognized.",
pluginAnnotation.getMethod().getName(), plugin.getClass().getName(), type);
return;
}
}
try {
pluginAnnotation.getMethod().invoke(plugin, args.toArray());
// close CtClass if created from here
if (ctClass != null) {
ctClass.detach();
}
} catch (IllegalAccessException e) {
LOGGER.error("IllegalAccessException in method '{}' class '{}' classLoader '{}' on plugin '{}'",
e, pluginAnnotation.getMethod().getName(), ctClass != null ? ctClass.getName() : "",
classLoader != null ? classLoader.getClass().getName() : "", plugin.getClass().getName());
} catch (InvocationTargetException e) {
LOGGER.error("InvocationTargetException in method '{}' class '{}' classLoader '{}' on plugin '{}'",
e, pluginAnnotation.getMethod().getName(), ctClass != null ? ctClass.getName() : "",
classLoader != null ? classLoader.getClass().getName() : "", plugin.getClass().getName());
}
}
/**
* Creats javaassist CtClass for bytecode manipulation. Add default classloader.
*
* @param uri uri
* @param classLoader loader
* @return created class
* @throws org.hotswap.agent.javassist.NotFoundException
*/
private CtClass createCtClass(URI uri, ClassLoader classLoader) throws NotFoundException, IOException {
File file = new File(uri);
if (file.exists()) {
ClassPool cp = new ClassPool();
cp.appendClassPath(new LoaderClassPath(classLoader));
return cp.makeClass(new ByteArrayInputStream(IOUtils.toByteArray(uri)));
}
return null;
}
}
|
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
WatchEventCommand that = (WatchEventCommand) o;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (event != null ? !event.equals(that.event) : that.event != null) return false;
if (pluginAnnotation != null ? !pluginAnnotation.equals(that.pluginAnnotation) : that.pluginAnnotation != null)
return false;
return true;
| 1,891 | 154 | 2,045 |
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/WatchEventDTO.java
|
WatchEventDTO
|
accept
|
class WatchEventDTO {
private final boolean classFileEvent;
private final int timeout;
private final FileEvent[] events;
private final String classNameRegexp;
private final String filter;
private final String path;
private final boolean onlyRegularFiles;
/**
* Parse the annotation to fill in the container.
*/
public static <T extends Annotation> WatchEventDTO parse(T annotation) {
if (annotation instanceof OnClassFileEvent)
return new WatchEventDTO((OnClassFileEvent)annotation);
else if (annotation instanceof OnResourceFileEvent)
return new WatchEventDTO((OnResourceFileEvent)annotation);
else
throw new IllegalArgumentException("Invalid annotation type " + annotation);
}
public WatchEventDTO(OnClassFileEvent annotation) {
classFileEvent = true;
timeout = annotation.timeout();
classNameRegexp = annotation.classNameRegexp();
events = annotation.events();
onlyRegularFiles = true;
filter = null;
path = null;
}
public WatchEventDTO(OnResourceFileEvent annotation) {
classFileEvent = false;
timeout = annotation.timeout();
filter = annotation.filter();
path = annotation.path();
events = annotation.events();
onlyRegularFiles = annotation.onlyRegularFiles();
classNameRegexp = null;
}
public boolean isClassFileEvent() {
return classFileEvent;
}
public int getTimeout() {
return timeout;
}
public FileEvent[] getEvents() {
return events;
}
public String getClassNameRegexp() {
return classNameRegexp;
}
public String getFilter() {
return filter;
}
public String getPath() {
return path;
}
public boolean isOnlyRegularFiles() {
return onlyRegularFiles;
}
/**
* Check if this handler supports actual event.
* @param event file event fired by filesystem
* @return true if supports - should continue handling
*/
public boolean accept(WatchFileEvent event) {<FILL_FUNCTION_BODY>}
}
|
// all handlers currently support only files
if (!event.isFile()) {
return false;
}
// load class files only from files named ".class"
// Don't treat _jsp.class as a class file. JSP class files are compiled by application server, compilation
// has two phases that cause many problems with HA. Look at JSR45
if (isClassFileEvent() && (!event.getURI().toString().endsWith(".class") || event.getURI().toString().endsWith("_jsp.class"))) {
return false;
}
return true;
| 546 | 152 | 698 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/annotation/handler/WatchHandler.java
|
WatchHandler
|
registerResourceListener
|
class WatchHandler<T extends Annotation> implements PluginHandler<T> {
private static AgentLogger LOGGER = AgentLogger.getLogger(WatchHandler.class);
protected PluginManager pluginManager;
public WatchHandler(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
@Override
public boolean initField(PluginAnnotation<T> pluginAnnotation) {
throw new IllegalAccessError("@OnResourceFileEvent annotation not allowed on fields.");
}
@Override
public boolean initMethod(final PluginAnnotation<T> pluginAnnotation) {
LOGGER.debug("Init for method " + pluginAnnotation.getMethod());
ClassLoader classLoader = pluginManager.getPluginRegistry().getAppClassLoader(pluginAnnotation.getPlugin());
try {
registerResources(pluginAnnotation, classLoader);
} catch (IOException e) {
LOGGER.error("Unable to register resources for annotation {} on method {} class {}", e,
pluginAnnotation.getAnnotation(),
pluginAnnotation.getMethod().getName(),
pluginAnnotation.getMethod().getDeclaringClass().getName());
return false;
}
return true;
}
/**
* Register resource change listener on URI:
* - classpath (already should contain extraClasspath)
* - plugin configuration - watchResources property
*/
private void registerResources(final PluginAnnotation<T> pluginAnnotation, final ClassLoader classLoader) throws IOException {
final T annot = pluginAnnotation.getAnnotation();
WatchEventDTO watchEventDTO = WatchEventDTO.parse(annot);
String path = watchEventDTO.getPath();
// normalize
if (path == null || path.equals(".") || path.equals("/"))
path = "";
if (path.endsWith("/"))
path = path.substring(0, path.length() - 2);
// classpath resources (already should contain extraClasspath)
Enumeration<URL> en = classLoader.getResources(path);
while (en.hasMoreElements()) {
try {
URI uri = en.nextElement().toURI();
// check that this is a local accessible file (not vfs inside JAR etc.)
try {
new File(uri);
} catch (Exception e) {
LOGGER.trace("Skipping uri {}, not a local file.", uri);
continue;
}
LOGGER.debug("Registering resource listener on classpath URI {}", uri);
registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, uri);
} catch (URISyntaxException e) {
LOGGER.error("Unable convert root resource path URL to URI", e);
}
}
// add extra directories for watchResources property
if (!watchEventDTO.isClassFileEvent()) {
for (URL url : pluginManager.getPluginConfiguration(classLoader).getWatchResources()) {
try {
Path watchResourcePath = Paths.get(url.toURI());
Path pathInWatchResource = watchResourcePath.resolve(path);
if (pathInWatchResource.toFile().exists()) {
LOGGER.debug("Registering resource listener on watchResources URI {}", pathInWatchResource.toUri());
registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, pathInWatchResource.toUri());
}
} catch (URISyntaxException e) {
LOGGER.error("Unable convert watch resource path URL {} to URI", e, url);
}
}
}
}
/**
* Using pluginManager.registerResourceListener() add new listener on URI.
* <p/>
* There might be several same events for a resource change (either from filesystem or when IDE clears and reloads
* a class multiple time on rebuild). Use command scheduler to group same events into single invocation.
*/
private void registerResourceListener(final PluginAnnotation<T> pluginAnnotation, final WatchEventDTO watchEventDTO,
final ClassLoader classLoader, URI uri) throws IOException {<FILL_FUNCTION_BODY>}
}
|
pluginManager.getWatcher().addEventListener(classLoader, uri, new WatchEventListener() {
@Override
public void onEvent(WatchFileEvent event) {
WatchEventCommand<T> command = WatchEventCommand.createCmdForEvent(pluginAnnotation, event, classLoader);
if (command != null) {
pluginManager.getScheduler().scheduleCommand(command, watchEventDTO.getTimeout());
LOGGER.trace("Resource changed {}", event);
}
}
});
| 998 | 124 | 1,122 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/command/ReflectionCommand.java
|
ReflectionCommand
|
equals
|
class ReflectionCommand extends MergeableCommand {
private static AgentLogger LOGGER = AgentLogger.getLogger(ReflectionCommand.class);
/**
* Run the method on target object.
*/
private Object target;
/**
* Run a method in the class - if null, run a method on this object, otherwise create new instance of className.
*/
private String className;
/**
* Method name to run.
*/
private String methodName;
/**
* Method actual parameters value. These parameter types must be known to the target classloader.
* For norma use (call application classloader from plugin class) this means that you can use only
* Java default types.
*/
private List<Object> params = new ArrayList<>();
/**
* Plugin object to resolve target classloader (if not set directly). May be null.
*/
private Object plugin;
/**
* Classloader application classloader to run the command in. If null, use agent classloader.
*/
private ClassLoader targetClassLoader;
/**
* Register a listener after the command is executed to obtain method invocation result.
*/
private CommandExecutionListener commandExecutionListener;
/**
* Define a command.
*/
public ReflectionCommand(Object plugin, String className, String methodName, ClassLoader targetClassLoader, Object... params) {
this.plugin = plugin;
this.className = className;
this.methodName = methodName;
this.targetClassLoader = targetClassLoader;
this.params = Arrays.asList(params);
}
/**
* Predefine a command. The params and/or target classloader will be set by setter.
*/
public ReflectionCommand(Object plugin, String className, String methodName) {
this.plugin = plugin;
this.className = className;
this.methodName = methodName;
}
/**
* Define a command on target object.
*/
public ReflectionCommand(Object target, String methodName, Object... params) {
this.target = target;
this.className = target == null ? "NULL" : target.getClass().getName();
this.methodName = methodName;
this.params = Arrays.asList(params);
}
@Override
public String toString() {
return "Command{" +
"class='" + getClassName() + '\'' +
", methodName='" + getMethodName() + '\'' +
'}';
}
public String getClassName() {
if (className == null && target != null)
className = target.getClass().getName();
return className;
}
public String getMethodName() {
return methodName;
}
public List<Object> getParams() {
return params;
}
public ClassLoader getTargetClassLoader() {
if (targetClassLoader == null) {
if (target != null)
targetClassLoader = target.getClass().getClassLoader();
else
targetClassLoader = PluginManager.getInstance().getPluginRegistry().getAppClassLoader(plugin);
}
return targetClassLoader;
}
public void setTargetClassLoader(ClassLoader targetClassLoader) {
this.targetClassLoader = targetClassLoader;
}
public CommandExecutionListener getCommandExecutionListener() {
return commandExecutionListener;
}
public void setCommandExecutionListener(CommandExecutionListener commandExecutionListener) {
this.commandExecutionListener = commandExecutionListener;
}
/**
* Execute the command.
*/
public void executeCommand() {
// replace context classloader with application classloader
if (getTargetClassLoader() != null)
Thread.currentThread().setContextClassLoader(getTargetClassLoader());
ClassLoader targetClassLoader = Thread.currentThread().getContextClassLoader();
String className = getClassName();
String method = getMethodName();
List<Object> params = getParams();
Object result = null;
try {
result = doExecuteReflectionCommand(targetClassLoader, className, target, method, params);
} catch (ClassNotFoundException e) {
LOGGER.error("Class {} not found in classloader {}", e, className, targetClassLoader);
} catch (NoClassDefFoundError e) {
LOGGER.error("NoClassDefFoundError for class {} in classloader {}", e, className, targetClassLoader);
} catch (InstantiationException e) {
LOGGER.error("Unable instantiate class {} in classloader {}", e, className, targetClassLoader);
} catch (IllegalAccessException e) {
LOGGER.error("Method {} not public in class {}", e, method, className);
} catch (NoSuchMethodException e) {
LOGGER.error("Method {} not found in class {}", e, method, className);
} catch (InvocationTargetException e) {
LOGGER.error("Error executin method {} in class {}", e, method, className);
}
// notify lilstener
CommandExecutionListener listener = getCommandExecutionListener();
if (listener != null)
listener.commandExecuted(result);
}
protected Object doExecuteReflectionCommand(ClassLoader targetClassLoader, String className, Object target, String method, List<Object> params) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<?> classInAppClassLoader = Class.forName(className, true, targetClassLoader);
LOGGER.trace("Executing command: requestedClassLoader={}, resolvedClassLoader={}, class={}, method={}, params={}",
targetClassLoader, classInAppClassLoader.getClassLoader(), classInAppClassLoader, method, params);
Class[] paramTypes = new Class[params.size()];
int i = 0;
for (Object param : params) {
if (param == null)
throw new IllegalArgumentException("Cannot execute for null parameter value");
else {
paramTypes[i++] = param.getClass();
}
}
Method m = classInAppClassLoader.getDeclaredMethod(method, paramTypes);
return m.invoke(target, params.toArray());
}
@Override
public boolean equals(Object o) {<FILL_FUNCTION_BODY>}
@Override
public int hashCode() {
int result = target != null ? target.hashCode() : 0;
result = 31 * result + (className != null ? className.hashCode() : 0);
result = 31 * result + (methodName != null ? methodName.hashCode() : 0);
result = 31 * result + (params != null ? params.hashCode() : 0);
result = 31 * result + (plugin != null ? plugin.hashCode() : 0);
result = 31 * result + (targetClassLoader != null ? targetClassLoader.hashCode() : 0);
return result;
}
}
|
if (this == o) return true;
if (!(o instanceof ReflectionCommand)) return false;
ReflectionCommand that = (ReflectionCommand) o;
if (!className.equals(that.className)) return false;
if (!methodName.equals(that.methodName)) return false;
if (!params.equals(that.params)) return false;
if (plugin != null ? !plugin.equals(that.plugin) : that.plugin != null) return false;
if (target != null ? !target.equals(that.target) : that.target != null) return false;
if (targetClassLoader != null ? !targetClassLoader.equals(that.targetClassLoader) : that.targetClassLoader != null) return false;
return true;
| 1,742 | 192 | 1,934 |
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/command/impl/CommandExecutor.java
|
CommandExecutor
|
run
|
class CommandExecutor extends Thread {
private static AgentLogger LOGGER = AgentLogger.getLogger(CommandExecutor.class);
final Command command;
public CommandExecutor(Command command) {
this.command = command;
setDaemon(true);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
/**
* Method template to register finish event
*/
public void finished() {
}
}
|
try {
LOGGER.trace("Executing command {}", command);
command.executeCommand();
} finally {
finished();
}
| 117 | 40 | 157 |
<methods>public void <init>() ,public void <init>(java.lang.Runnable) ,public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public void <init>(java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long) ,public void <init>(java.lang.ThreadGroup, java.lang.Runnable, java.lang.String, long, boolean) ,public static int activeCount() ,public final void checkAccess() ,public int countStackFrames() ,public static native java.lang.Thread currentThread() ,public static void dumpStack() ,public static int enumerate(java.lang.Thread[]) ,public static Map<java.lang.Thread,java.lang.StackTraceElement[]> getAllStackTraces() ,public java.lang.ClassLoader getContextClassLoader() ,public static java.lang.Thread.UncaughtExceptionHandler getDefaultUncaughtExceptionHandler() ,public long getId() ,public final java.lang.String getName() ,public final int getPriority() ,public java.lang.StackTraceElement[] getStackTrace() ,public java.lang.Thread.State getState() ,public final java.lang.ThreadGroup getThreadGroup() ,public java.lang.Thread.UncaughtExceptionHandler getUncaughtExceptionHandler() ,public static native boolean holdsLock(java.lang.Object) ,public void interrupt() ,public static boolean interrupted() ,public final boolean isAlive() ,public final boolean isDaemon() ,public boolean isInterrupted() ,public final void join() throws java.lang.InterruptedException,public final synchronized void join(long) throws java.lang.InterruptedException,public final synchronized void join(long, int) throws java.lang.InterruptedException,public static void onSpinWait() ,public final void resume() ,public void run() ,public void setContextClassLoader(java.lang.ClassLoader) ,public final void setDaemon(boolean) ,public static void setDefaultUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public final synchronized void setName(java.lang.String) ,public final void setPriority(int) ,public void setUncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) ,public static native void sleep(long) throws java.lang.InterruptedException,public static void sleep(long, int) throws java.lang.InterruptedException,public synchronized void start() ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public static native void yield() <variables>private static final java.lang.StackTraceElement[] EMPTY_STACK_TRACE,public static final int MAX_PRIORITY,public static final int MIN_PRIORITY,public static final int NORM_PRIORITY,private volatile sun.nio.ch.Interruptible blocker,private final java.lang.Object blockerLock,private java.lang.ClassLoader contextClassLoader,private boolean daemon,private static volatile java.lang.Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler,private volatile long eetop,private java.lang.ThreadGroup group,java.lang.ThreadLocal.ThreadLocalMap inheritableThreadLocals,private java.security.AccessControlContext inheritedAccessControlContext,private volatile boolean interrupted,private volatile java.lang.String name,volatile java.lang.Object parkBlocker,private int priority,private final long stackSize,private boolean stillborn,private java.lang.Runnable target,private static int threadInitNumber,int threadLocalRandomProbe,int threadLocalRandomSecondarySeed,long threadLocalRandomSeed,java.lang.ThreadLocal.ThreadLocalMap threadLocals,private static long threadSeqNumber,private volatile int threadStatus,private final long tid,private volatile java.lang.Thread.UncaughtExceptionHandler uncaughtExceptionHandler
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/command/impl/SchedulerImpl.java
|
SchedulerImpl
|
run
|
class SchedulerImpl implements Scheduler {
private static AgentLogger LOGGER = AgentLogger.getLogger(SchedulerImpl.class);
int DEFAULT_SCHEDULING_TIMEOUT = 100;
// TODO : Some commands must be executed in the order in which they are put to scheduler. Therefore
// there could be a LinkedHashMap and CommandExecutor should be singleton for commands that
// must be executed in order. There is an issue related to this problem
// https://github.com/HotswapProjects/HotswapAgent/issues/39 which requires concurrent using
final Map<Command, DuplicateScheduleConfig> scheduledCommands = new ConcurrentHashMap<>();
final Set<Command> runningCommands = Collections.synchronizedSet(new HashSet<Command>());
Thread runner;
boolean stopped;
@Override
public void scheduleCommand(Command command) {
scheduleCommand(command, DEFAULT_SCHEDULING_TIMEOUT);
}
@Override
public void scheduleCommand(Command command, int timeout) {
scheduleCommand(command, timeout, DuplicateSheduleBehaviour.WAIT_AND_RUN_AFTER);
}
@Override
public void scheduleCommand(Command command, int timeout, DuplicateSheduleBehaviour behaviour) {
synchronized (scheduledCommands) {
Command targetCommand = command;
if (scheduledCommands.containsKey(command) && (command instanceof MergeableCommand)) {
// get existing equals command and merge it
for (Command scheduledCommand : scheduledCommands.keySet()) {
if (command.equals(scheduledCommand)) {
targetCommand = ((MergeableCommand) scheduledCommand).merge(command);
break;
}
}
}
// map may already contain equals command, put will replace it and reset timer
scheduledCommands.put(targetCommand, new DuplicateScheduleConfig(System.currentTimeMillis() + timeout, behaviour));
LOGGER.trace("{} scheduled for execution in {}ms", targetCommand, timeout);
}
}
/**
* One cycle of the scheduler agent. Process all commands which are not currently
* running and time lower than current milliseconds.
*
* @return true if the agent should continue (false for fatal error)
*/
private boolean processCommands() {
Long currentTime = System.currentTimeMillis();
synchronized (scheduledCommands) {
for (Iterator<Map.Entry<Command, DuplicateScheduleConfig>> it = scheduledCommands.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<Command, DuplicateScheduleConfig> entry = it.next();
DuplicateScheduleConfig config = entry.getValue();
Command command = entry.getKey();
// if timeout
if (config.getTime() < currentTime) {
// command is currently running
if (runningCommands.contains(command)) {
if (config.getBehaviour().equals(DuplicateSheduleBehaviour.SKIP)) {
LOGGER.debug("Skipping duplicate running command {}", command);
it.remove();
} else if (config.getBehaviour().equals(DuplicateSheduleBehaviour.RUN_DUPLICATE)) {
executeCommand(command);
it.remove();
}
} else {
executeCommand(command);
it.remove();
}
}
}
}
return true;
}
/**
* Execute this command in a separate thread.
*
* @param command the command to execute
*/
private void executeCommand(Command command) {
if (command instanceof WatchEventCommand)
LOGGER.trace("Executing {}", command); // too much output for debug
else
LOGGER.debug("Executing {}", command);
runningCommands.add(command);
new CommandExecutor(command) {
@Override
public void finished() {
runningCommands.remove(command);
}
}.start();
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
@Override
public void stop() {
stopped = true;
}
private static class DuplicateScheduleConfig {
// time when to run
long time;
// behaviour in case of conflict (running same command in progress)
DuplicateSheduleBehaviour behaviour;
private DuplicateScheduleConfig(long time, DuplicateSheduleBehaviour behaviour) {
this.time = time;
this.behaviour = behaviour;
}
public long getTime() {
return time;
}
public DuplicateSheduleBehaviour getBehaviour() {
return behaviour;
}
}
}
|
runner = new Thread() {
@Override
public void run() {
for (; ; ) {
if (stopped || !processCommands())
break;
// wait for 100 ms
try {
sleep(100);
} catch (InterruptedException e) {
break;
}
}
}
};
runner.setDaemon(true);
runner.start();
| 1,180 | 113 | 1,293 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/config/LogConfigurationHelper.java
|
LogConfigurationHelper
|
configureLog
|
class LogConfigurationHelper {
private static AgentLogger LOGGER = AgentLogger.getLogger(LogConfigurationHelper.class);
public static final String LOGGER_PREFIX = "LOGGER";
public static final String DATETIME_FORMAT = "LOGGER_DATETIME_FORMAT";
private static final String LOGFILE = "LOGFILE";
private static final String LOGFILE_APPEND = "LOGFILE.append";
/**
* Search properties for prefix LOGGER and set level for package in format:
* LOGGER.my.package=LEVEL
*
* @param properties properties
*/
public static void configureLog(Properties properties) {<FILL_FUNCTION_BODY>}
// resolve level from enum
private static AgentLogger.Level getLevel(String property, String levelName) {
try {
return AgentLogger.Level.valueOf(levelName.toUpperCase(Locale.ENGLISH));
} catch (IllegalArgumentException e) {
LOGGER.warning("Invalid configuration value for property '{}'. Unknown LOG level '{}'.", property, levelName);
return null;
}
}
// get package name from logger
private static String getClassPrefix(String property) {
if (property.equals(LOGGER_PREFIX)) {
return null;
} else {
return property.substring(LOGGER_PREFIX.length() + 1);
}
}
}
|
for (String property : properties.stringPropertyNames()) {
if (property.startsWith(LOGGER_PREFIX)) {
if (property.startsWith(DATETIME_FORMAT)) {
String dateTimeFormat = properties.getProperty(DATETIME_FORMAT);
if (dateTimeFormat != null && !dateTimeFormat.isEmpty()) {
AgentLogger.setDateTimeFormat(dateTimeFormat);
}
} else {
String classPrefix = getClassPrefix(property);
AgentLogger.Level level = getLevel(property, properties.getProperty(property));
if (level != null) {
if (classPrefix == null)
AgentLogger.setLevel(level);
else
AgentLogger.setLevel(classPrefix, level);
}
}
} else if (property.equals(LOGFILE)) {
String logfile = properties.getProperty(LOGFILE);
boolean append = parseBoolean(properties.getProperty(LOGFILE_APPEND, "false"));
try {
PrintStream ps = new PrintStream(new FileOutputStream(new File(logfile), append));
AgentLogger.getHandler().setPrintStream(ps);
} catch (FileNotFoundException e) {
LOGGER.error("Invalid configuration property {} value '{}'. Unable to create/open the file.",
e, LOGFILE, logfile);
}
}
}
| 349 | 338 | 687 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/config/ScheduledHotswapCommand.java
|
ScheduledHotswapCommand
|
merge
|
class ScheduledHotswapCommand extends MergeableCommand {
private Map<Class<?>, byte[]> reloadMap;
public ScheduledHotswapCommand(Map<Class<?>, byte[]> reloadMap) {
this.reloadMap = new HashMap<>();
for (Class<?> key: reloadMap.keySet()) {
this.reloadMap.put(key, reloadMap.get(key));
}
}
public Command merge(Command other) {<FILL_FUNCTION_BODY>}
@Override
public void executeCommand() {
PluginManager.getInstance().hotswap(reloadMap);
}
@Override
public boolean equals(Object o) {
if (this == o || getClass() == o.getClass()) return true;
return false;
}
@Override
public int hashCode() {
return 31;
}
}
|
if (other instanceof ScheduledHotswapCommand) {
ScheduledHotswapCommand scheduledHotswapCommand = (ScheduledHotswapCommand) other;
for (Class<?> key: scheduledHotswapCommand.reloadMap.keySet()) {
this.reloadMap.put(key, scheduledHotswapCommand.reloadMap.get(key));
}
}
return this;
| 242 | 110 | 352 |
<methods>public non-sealed void <init>() ,public List<org.hotswap.agent.command.Command> getMergedCommands() ,public org.hotswap.agent.command.Command merge(org.hotswap.agent.command.Command) ,public List<org.hotswap.agent.command.Command> popMergedCommands() <variables>List<org.hotswap.agent.command.Command> mergedCommands
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/ByteArrayClassPath.java
|
ByteArrayClassPath
|
find
|
class ByteArrayClassPath implements ClassPath {
protected String classname;
protected byte[] classfile;
/*
* Creates a <code>ByteArrayClassPath</code> containing the given
* bytes.
*
* @param name a fully qualified class name
* @param classfile the contents of a class file.
*/
public ByteArrayClassPath(String name, byte[] classfile) {
this.classname = name;
this.classfile = classfile;
}
@Override
public String toString() {
return "byte[]:" + classname;
}
/**
* Opens the class file.
*/
@Override
public InputStream openClassfile(String classname) {
if(this.classname.equals(classname))
return new ByteArrayInputStream(classfile);
return null;
}
/**
* Obtains the URL.
*/
@Override
public URL find(String classname) {<FILL_FUNCTION_BODY>}
private class BytecodeURLStreamHandler extends URLStreamHandler {
protected URLConnection openConnection(final URL u) {
return new BytecodeURLConnection(u);
}
}
private class BytecodeURLConnection extends URLConnection {
protected BytecodeURLConnection(URL url) {
super(url);
}
public void connect() throws IOException {
}
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(classfile);
}
public int getContentLength() {
return classfile.length;
}
}
}
|
if(this.classname.equals(classname)) {
String cname = classname.replace('.', '/') + ".class";
try {
return new URL(null, "file:/ByteArrayClassPath/" + cname, new BytecodeURLStreamHandler());
}
catch (MalformedURLException e) {}
}
return null;
| 407 | 90 | 497 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/ClassClassPath.java
|
ClassClassPath
|
openClassfile
|
class ClassClassPath implements ClassPath {
private Class<?> thisClass;
/** Creates a search path.
*
* @param c the <code>Class</code> object used to obtain a class
* file. <code>getResourceAsStream()</code> is called on
* this object.
*/
public ClassClassPath(Class<?> c) {
thisClass = c;
}
ClassClassPath() {
/* The value of thisClass was this.getClass() in early versions:
*
* thisClass = this.getClass();
*
* However, this made openClassfile() not search all the system
* class paths if javassist.jar is put in jre/lib/ext/
* (with JDK1.4).
*/
this(java.lang.Object.class);
}
/**
* Obtains a class file by <code>getResourceAsStream()</code>.
*/
@Override
public InputStream openClassfile(String classname) throws NotFoundException {<FILL_FUNCTION_BODY>}
/**
* Obtains the URL of the specified class file.
*
* @return null if the class file could not be found.
*/
@Override
public URL find(String classname) {
String filename = '/' + classname.replace('.', '/') + ".class";
return thisClass.getResource(filename);
}
@Override
public String toString() {
return thisClass.getName() + ".class";
}
}
|
String filename = '/' + classname.replace('.', '/') + ".class";
return thisClass.getResourceAsStream(filename);
| 401 | 36 | 437 |
<no_super_class>
|
HotswapProjects_HotswapAgent
|
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/ClassMap.java
|
ClassMap
|
put
|
class ClassMap extends HashMap<String,String> {
/** default serialVersionUID */
private static final long serialVersionUID = 1L;
private ClassMap parent;
/**
* Constructs a hash table.
*/
public ClassMap() { parent = null; }
ClassMap(ClassMap map) { parent = map; }
/**
* Maps a class name to another name in this hashtable.
* The names are obtained with calling <code>Class.getName()</code>.
* This method translates the given class names into the
* internal form used in the JVM before putting it in
* the hashtable.
*
* @param oldname the original class name
* @param newname the substituted class name.
*/
public void put(CtClass oldname, CtClass newname) {
put(oldname.getName(), newname.getName());
}
/**
* Maps a class name to another name in this hashtable.
* If the hashtable contains another mapping from the same
* class name, the old mapping is replaced.
* This method translates the given class names into the
* internal form used in the JVM before putting it in
* the hashtable.
*
* <p>If <code>oldname</code> is identical to
* <code>newname</code>, then this method does not
* perform anything; it does not record the mapping from
* <code>oldname</code> to <code>newname</code>. See
* <code>fix</code> method.
*
* @param oldname the original class name.
* @param newname the substituted class name.
* @see #fix(String)
*/
@Override
public String put(String oldname, String newname) {<FILL_FUNCTION_BODY>}
/**
* Is equivalent to <code>put()</code> except that
* the given mapping is not recorded into the hashtable
* if another mapping from <code>oldname</code> is
* already included.
*
* @param oldname the original class name.
* @param newname the substituted class name.
*/
public void putIfNone(String oldname, String newname) {
if (oldname == newname)
return;
String oldname2 = toJvmName(oldname);
String s = get(oldname2);
if (s == null)
super.put(oldname2, toJvmName(newname));
}
protected final String put0(String oldname, String newname) {
return super.put(oldname, newname);
}
/**
* Returns the class name to wihch the given <code>jvmClassName</code>
* is mapped. A subclass of this class should override this method.
*
* <p>This method receives and returns the internal representation of
* class name used in the JVM.
*
* @see #toJvmName(String)
* @see #toJavaName(String)
*/
@Override
public String get(Object jvmClassName) {
String found = super.get(jvmClassName);
if (found == null && parent != null)
return parent.get(jvmClassName);
return found;
}
/**
* Prevents a mapping from the specified class name to another name.
*/
public void fix(CtClass clazz) {
fix(clazz.getName());
}
/**
* Prevents a mapping from the specified class name to another name.
*/
public void fix(String name) {
String name2 = toJvmName(name);
super.put(name2, name2);
}
/**
* Converts a class name into the internal representation used in
* the JVM.
*/
public static String toJvmName(String classname) {
return Descriptor.toJvmName(classname);
}
/**
* Converts a class name from the internal representation used in
* the JVM to the normal one used in Java.
*/
public static String toJavaName(String classname) {
return Descriptor.toJavaName(classname);
}
}
|
if (oldname == newname)
return oldname;
String oldname2 = toJvmName(oldname);
String s = get(oldname2);
if (s == null || !s.equals(oldname2))
return super.put(oldname2, toJvmName(newname));
return s;
| 1,101 | 88 | 1,189 |
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.String>) ,public void <init>(int, float) ,public void clear() ,public java.lang.Object clone() ,public java.lang.String compute(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public java.lang.String computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends java.lang.String>) ,public java.lang.String computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lang.String>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.String>) ,public java.lang.String get(java.lang.Object) ,public java.lang.String getOrDefault(java.lang.Object, java.lang.String) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public java.lang.String merge(java.lang.String, java.lang.String, BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public java.lang.String put(java.lang.String, java.lang.String) ,public void putAll(Map<? extends java.lang.String,? extends java.lang.String>) ,public java.lang.String putIfAbsent(java.lang.String, java.lang.String) ,public java.lang.String remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public java.lang.String replace(java.lang.String, java.lang.String) ,public boolean replace(java.lang.String, java.lang.String, java.lang.String) ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.String,? extends java.lang.String>) ,public int size() ,public Collection<java.lang.String> values() <variables>static final int DEFAULT_INITIAL_CAPACITY,static final float DEFAULT_LOAD_FACTOR,static final int MAXIMUM_CAPACITY,static final int MIN_TREEIFY_CAPACITY,static final int TREEIFY_THRESHOLD,static final int UNTREEIFY_THRESHOLD,transient Set<Entry<java.lang.String,java.lang.String>> entrySet,final float loadFactor,transient int modCount,private static final long serialVersionUID,transient int size,transient Node<java.lang.String,java.lang.String>[] table,int threshold
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.