index
int64
0
990
proj_name
stringclasses
162 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
49
masked_class
stringlengths
68
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
27
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
601
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
602
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
603
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
604
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
605
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
606
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
607
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
608
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
609
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
610
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
611
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
612
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
613
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
614
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
615
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
616
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
617
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
618
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
619
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
620
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
621
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
622
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
623
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
624
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
625
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
626
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
627
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
628
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
629
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
630
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
631
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
632
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
633
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
634
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
635
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
636
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
637
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
638
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
639
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
640
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
641
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
642
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
643
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
644
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
645
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
646
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
647
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
648
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
649
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
650
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
651
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
652
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
653
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
654
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
655
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
656
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
657
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
658
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
659
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
660
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
661
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
662
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
663
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
664
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
665
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
666
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
667
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
668
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/ClassPoolTail.java
ClassPoolTail
appendClassPath
class ClassPoolTail { protected ClassPathList pathList; public ClassPoolTail() { pathList = null; } @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("[class path: "); ClassPathList list = pathList; while (list != null) { buf.append(list.path.toString()); buf.append(File.pathSeparatorChar); list = list.next; } buf.append(']'); return buf.toString(); } public synchronized ClassPath insertClassPath(ClassPath cp) { pathList = new ClassPathList(cp, pathList); return cp; } public synchronized ClassPath appendClassPath(ClassPath cp) {<FILL_FUNCTION_BODY>} public synchronized void removeClassPath(ClassPath cp) { ClassPathList list = pathList; if (list != null) if (list.path == cp) pathList = list.next; else { while (list.next != null) if (list.next.path == cp) list.next = list.next.next; else list = list.next; } } public ClassPath appendSystemPath() { if (org.hotswap.agent.javassist.bytecode.ClassFile.MAJOR_VERSION < org.hotswap.agent.javassist.bytecode.ClassFile.JAVA_9) return appendClassPath(new ClassClassPath()); ClassLoader cl = Thread.currentThread().getContextClassLoader(); return appendClassPath(new LoaderClassPath(cl)); } public ClassPath insertClassPath(String pathname) throws NotFoundException { return insertClassPath(makePathObject(pathname)); } public ClassPath appendClassPath(String pathname) throws NotFoundException { return appendClassPath(makePathObject(pathname)); } private static ClassPath makePathObject(String pathname) throws NotFoundException { String lower = pathname.toLowerCase(); if (lower.endsWith(".jar") || lower.endsWith(".zip")) return new JarClassPath(pathname); int len = pathname.length(); if (len > 2 && pathname.charAt(len - 1) == '*' && (pathname.charAt(len - 2) == '/' || pathname.charAt(len - 2) == File.separatorChar)) { String dir = pathname.substring(0, len - 2); return new JarDirClassPath(dir); } return new DirClassPath(pathname); } /** * This method does not close the output stream. */ void writeClassfile(String classname, OutputStream out) throws NotFoundException, IOException, CannotCompileException { InputStream fin = openClassfile(classname); if (fin == null) throw new NotFoundException(classname); try { copyStream(fin, out); } finally { fin.close(); } } /* -- faster version -- void checkClassName(String classname) throws NotFoundException { if (find(classname) == null) throw new NotFoundException(classname); } -- slower version -- void checkClassName(String classname) throws NotFoundException { InputStream fin = openClassfile(classname); try { fin.close(); } catch (IOException e) {} } */ /** * Opens the class file for the class specified by * <code>classname</code>. * * @param classname a fully-qualified class name * @return null if the file has not been found. * @throws NotFoundException if any error is reported by ClassPath. */ InputStream openClassfile(String classname) throws NotFoundException { ClassPathList list = pathList; InputStream ins = null; NotFoundException error = null; while (list != null) { try { ins = list.path.openClassfile(classname); } catch (NotFoundException e) { if (error == null) error = e; } if (ins == null) list = list.next; else return ins; } if (error != null) throw error; return null; // not found } /** * Searches the class path to obtain the URL of the class file * specified by classname. It is also used to determine whether * the class file exists. * * @param classname a fully-qualified class name. * @return null if the class file could not be found. */ public URL find(String classname) { ClassPathList list = pathList; URL url = null; while (list != null) { url = list.path.find(classname); if (url == null) list = list.next; else return url; } return null; } /** * Reads from an input stream until it reaches the end. * * @return the contents of that input stream */ public static byte[] readStream(InputStream fin) throws IOException { byte[][] bufs = new byte[8][]; int bufsize = 4096; for (int i = 0; i < 8; ++i) { bufs[i] = new byte[bufsize]; int size = 0; int len = 0; do { len = fin.read(bufs[i], size, bufsize - size); if (len >= 0) size += len; else { byte[] result = new byte[bufsize - 4096 + size]; int s = 0; for (int j = 0; j < i; ++j) { System.arraycopy(bufs[j], 0, result, s, s + 4096); s = s + s + 4096; } System.arraycopy(bufs[i], 0, result, s, size); return result; } } while (size < bufsize); bufsize *= 2; } throw new IOException("too much data"); } /** * Reads from an input stream and write to an output stream * until it reaches the end. This method does not close the * streams. */ public static void copyStream(InputStream fin, OutputStream fout) throws IOException { int bufsize = 4096; byte[] buf = null; for (int i = 0; i < 64; ++i) { if (i < 8) { bufsize *= 2; buf = new byte[bufsize]; } int size = 0; int len = 0; do { len = fin.read(buf, size, bufsize - size); if (len >= 0) size += len; else { fout.write(buf, 0, size); return; } } while (size < bufsize); fout.write(buf); } throw new IOException("too much data"); } }
ClassPathList tail = new ClassPathList(cp, null); ClassPathList list = pathList; if (list == null) pathList = tail; else { while (list.next != null) list = list.next; list.next = tail; } return cp;
1,909
85
1,994
669
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtMember.java
Cache
visibleFrom
class Cache extends CtMember { @Override protected void extendToString(StringBuffer buffer) {} @Override public boolean hasAnnotation(String clz) { return false; } @Override public Object getAnnotation(Class<?> clz) throws ClassNotFoundException { return null; } @Override public Object[] getAnnotations() throws ClassNotFoundException { return null; } @Override public byte[] getAttribute(String name) { return null; } @Override public Object[] getAvailableAnnotations() { return null; } @Override public int getModifiers() { return 0; } @Override public String getName() { return null; } @Override public String getSignature() { return null; } @Override public void setAttribute(String name, byte[] data) {} @Override public void setModifiers(int mod) {} @Override public String getGenericSignature() { return null; } @Override public void setGenericSignature(String sig) {} private CtMember methodTail; private CtMember consTail; // constructor tail private CtMember fieldTail; Cache(CtClassType decl) { super(decl); methodTail = this; consTail = this; fieldTail = this; fieldTail.next = this; } CtMember methodHead() { return this; } CtMember lastMethod() { return methodTail; } CtMember consHead() { return methodTail; } // may include a static initializer CtMember lastCons() { return consTail; } CtMember fieldHead() { return consTail; } CtMember lastField() { return fieldTail; } void addMethod(CtMember method) { method.next = methodTail.next; methodTail.next = method; if (methodTail == consTail) { consTail = method; if (methodTail == fieldTail) fieldTail = method; } methodTail = method; } /* Both constructors and a class initializer. */ void addConstructor(CtMember cons) { cons.next = consTail.next; consTail.next = cons; if (consTail == fieldTail) fieldTail = cons; consTail = cons; } void addField(CtMember field) { field.next = this; // or fieldTail.next fieldTail.next = field; fieldTail = field; } static int count(CtMember head, CtMember tail) { int n = 0; while (head != tail) { n++; head = head.next; } return n; } void remove(CtMember mem) { CtMember m = this; CtMember node; while ((node = m.next) != this) { if (node == mem) { m.next = node.next; if (node == methodTail) methodTail = m; if (node == consTail) consTail = m; if (node == fieldTail) fieldTail = m; break; } m = m.next; } } } protected CtMember(CtClass clazz) { declaringClass = clazz; next = null; } final CtMember next() { return next; } /** * This method is invoked when setName() or replaceClassName() * in CtClass is called. * * @see CtMethod#nameReplaced() */ void nameReplaced() {} @Override public String toString() { StringBuffer buffer = new StringBuffer(getClass().getName()); buffer.append("@"); buffer.append(Integer.toHexString(hashCode())); buffer.append("["); buffer.append(Modifier.toString(getModifiers())); extendToString(buffer); buffer.append("]"); return buffer.toString(); } /** * Invoked by {@link #toString()} to add to the buffer and provide the * complete value. Subclasses should invoke this method, adding a * space before each token. The modifiers for the member are * provided first; subclasses should provide additional data such * as return type, field or method name, etc. */ protected abstract void extendToString(StringBuffer buffer); /** * Returns the class that declares this member. */ public CtClass getDeclaringClass() { return declaringClass; } /** * Returns true if this member is accessible from the given class. */ public boolean visibleFrom(CtClass clazz) {<FILL_FUNCTION_BODY>
int mod = getModifiers(); if (Modifier.isPublic(mod)) return true; else if (Modifier.isPrivate(mod)) return clazz == declaringClass; else { // package or protected String declName = declaringClass.getPackageName(); String fromName = clazz.getPackageName(); boolean visible; if (declName == null) visible = fromName == null; else visible = declName.equals(fromName); if (!visible && Modifier.isProtected(mod)) return clazz.subclassOf(declaringClass); return visible; }
1,253
166
1,419
670
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtNewClass.java
CtNewClass
inheritAllConstructors
class CtNewClass extends CtClassType { /* true if the class is an interface. */ protected boolean hasConstructor; CtNewClass(String name, ClassPool cp, boolean isInterface, CtClass superclass) { super(name, cp); wasChanged = true; String superName; if (isInterface || superclass == null) superName = null; else superName = superclass.getName(); classfile = new ClassFile(isInterface, name, superName); if (isInterface && superclass != null) classfile.setInterfaces(new String[] { superclass.getName() }); setModifiers(Modifier.setPublic(getModifiers())); hasConstructor = isInterface; } @Override protected void extendToString(StringBuffer buffer) { if (hasConstructor) buffer.append("hasConstructor "); super.extendToString(buffer); } @Override public void addConstructor(CtConstructor c) throws CannotCompileException { hasConstructor = true; super.addConstructor(c); } @Override public void toBytecode(DataOutputStream out) throws CannotCompileException, IOException { if (!hasConstructor) try { inheritAllConstructors(); hasConstructor = true; } catch (NotFoundException e) { throw new CannotCompileException(e); } super.toBytecode(out); } /** * Adds constructors inhrited from the super class. * * <p>After this method is called, the class inherits all the * constructors from the super class. The added constructor * calls the super's constructor with the same signature. */ public void inheritAllConstructors() throws CannotCompileException, NotFoundException {<FILL_FUNCTION_BODY>} private boolean isInheritable(int mod, CtClass superclazz) { if (Modifier.isPrivate(mod)) return false; if (Modifier.isPackage(mod)) { String pname = getPackageName(); String pname2 = superclazz.getPackageName(); if (pname == null) return pname2 == null; return pname.equals(pname2); } return true; } }
CtClass superclazz; CtConstructor[] cs; superclazz = getSuperclass(); cs = superclazz.getDeclaredConstructors(); int n = 0; for (int i = 0; i < cs.length; ++i) { CtConstructor c = cs[i]; int mod = c.getModifiers(); if (isInheritable(mod, superclazz)) { CtConstructor cons = CtNewConstructor.make(c.getParameterTypes(), c.getExceptionTypes(), this); cons.setModifiers(mod & (Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE)); addConstructor(cons); ++n; } } if (n < 1) throw new CannotCompileException( "no inheritable constructor in " + superclazz.getName());
607
233
840
671
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtNewWrappedConstructor.java
CtNewWrappedConstructor
wrapped
class CtNewWrappedConstructor extends CtNewWrappedMethod { private static final int PASS_NONE = CtNewConstructor.PASS_NONE; // private static final int PASS_ARRAY = CtNewConstructor.PASS_ARRAY; private static final int PASS_PARAMS = CtNewConstructor.PASS_PARAMS; public static CtConstructor wrapped(CtClass[] parameterTypes, CtClass[] exceptionTypes, int howToCallSuper, CtMethod body, ConstParameter constParam, CtClass declaring) throws CannotCompileException {<FILL_FUNCTION_BODY>} protected static Bytecode makeBody(CtClass declaring, ClassFile classfile, int howToCallSuper, CtMethod wrappedBody, CtClass[] parameters, ConstParameter cparam) throws CannotCompileException { int stacksize, stacksize2; int superclazz = classfile.getSuperclassId(); Bytecode code = new Bytecode(classfile.getConstPool(), 0, 0); code.setMaxLocals(false, parameters, 0); code.addAload(0); if (howToCallSuper == PASS_NONE) { stacksize = 1; code.addInvokespecial(superclazz, "<init>", "()V"); } else if (howToCallSuper == PASS_PARAMS) { stacksize = code.addLoadParameters(parameters, 1) + 1; code.addInvokespecial(superclazz, "<init>", Descriptor.ofConstructor(parameters)); } else { stacksize = compileParameterList(code, parameters, 1); String desc; if (cparam == null) { stacksize2 = 2; desc = ConstParameter.defaultConstDescriptor(); } else { stacksize2 = cparam.compile(code) + 2; desc = cparam.constDescriptor(); } if (stacksize < stacksize2) stacksize = stacksize2; code.addInvokespecial(superclazz, "<init>", desc); } if (wrappedBody == null) code.add(Bytecode.RETURN); else { stacksize2 = makeBody0(declaring, classfile, wrappedBody, false, parameters, CtClass.voidType, cparam, code); if (stacksize < stacksize2) stacksize = stacksize2; } code.setMaxStack(stacksize); return code; } }
try { CtConstructor cons = new CtConstructor(parameterTypes, declaring); cons.setExceptionTypes(exceptionTypes); Bytecode code = makeBody(declaring, declaring.getClassFile2(), howToCallSuper, body, parameterTypes, constParam); cons.getMethodInfo2().setCodeAttribute(code.toCodeAttribute()); // a stack map table is not needed. return cons; } catch (NotFoundException e) { throw new CannotCompileException(e); }
659
134
793
672
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/CtNewWrappedMethod.java
CtNewWrappedMethod
addBodyMethod
class CtNewWrappedMethod { private static final String addedWrappedMethod = "_added_m$"; public static CtMethod wrapped(CtClass returnType, String mname, CtClass[] parameterTypes, CtClass[] exceptionTypes, CtMethod body, ConstParameter constParam, CtClass declaring) throws CannotCompileException { CtMethod mt = new CtMethod(returnType, mname, parameterTypes, declaring); mt.setModifiers(body.getModifiers()); try { mt.setExceptionTypes(exceptionTypes); } catch (NotFoundException e) { throw new CannotCompileException(e); } Bytecode code = makeBody(declaring, declaring.getClassFile2(), body, parameterTypes, returnType, constParam); MethodInfo minfo = mt.getMethodInfo2(); minfo.setCodeAttribute(code.toCodeAttribute()); // a stack map has been already created. return mt; } static Bytecode makeBody(CtClass clazz, ClassFile classfile, CtMethod wrappedBody, CtClass[] parameters, CtClass returnType, ConstParameter cparam) throws CannotCompileException { boolean isStatic = Modifier.isStatic(wrappedBody.getModifiers()); Bytecode code = new Bytecode(classfile.getConstPool(), 0, 0); int stacksize = makeBody0(clazz, classfile, wrappedBody, isStatic, parameters, returnType, cparam, code); code.setMaxStack(stacksize); code.setMaxLocals(isStatic, parameters, 0); return code; } /* The generated method body does not need a stack map table * because it does not contain a branch instruction. */ protected static int makeBody0(CtClass clazz, ClassFile classfile, CtMethod wrappedBody, boolean isStatic, CtClass[] parameters, CtClass returnType, ConstParameter cparam, Bytecode code) throws CannotCompileException { if (!(clazz instanceof CtClassType)) throw new CannotCompileException("bad declaring class" + clazz.getName()); if (!isStatic) code.addAload(0); int stacksize = compileParameterList(code, parameters, (isStatic ? 0 : 1)); int stacksize2; String desc; if (cparam == null) { stacksize2 = 0; desc = ConstParameter.defaultDescriptor(); } else { stacksize2 = cparam.compile(code); desc = cparam.descriptor(); } checkSignature(wrappedBody, desc); String bodyname; try { bodyname = addBodyMethod((CtClassType)clazz, classfile, wrappedBody); /* if an exception is thrown below, the method added above * should be removed. (future work :<) */ } catch (BadBytecode e) { throw new CannotCompileException(e); } if (isStatic) code.addInvokestatic(Bytecode.THIS, bodyname, desc); else code.addInvokespecial(Bytecode.THIS, bodyname, desc); compileReturn(code, returnType); // consumes 2 stack entries if (stacksize < stacksize2 + 2) stacksize = stacksize2 + 2; return stacksize; } private static void checkSignature(CtMethod wrappedBody, String descriptor) throws CannotCompileException { if (!descriptor.equals(wrappedBody.getMethodInfo2().getDescriptor())) throw new CannotCompileException( "wrapped method with a bad signature: " + wrappedBody.getDeclaringClass().getName() + '.' + wrappedBody.getName()); } private static String addBodyMethod(CtClassType clazz, ClassFile classfile, CtMethod src) throws BadBytecode, CannotCompileException {<FILL_FUNCTION_BODY>} /* compileParameterList() returns the stack size used * by the produced code. * * @param regno the index of the local variable in which * the first argument is received. * (0: static method, 1: regular method.) */ static int compileParameterList(Bytecode code, CtClass[] params, int regno) { return JvstCodeGen.compileParameterList(code, params, regno); } /* * The produced codes cosume 1 or 2 stack entries. */ private static void compileReturn(Bytecode code, CtClass type) { if (type.isPrimitive()) { CtPrimitiveType pt = (CtPrimitiveType)type; if (pt != CtClass.voidType) { String wrapper = pt.getWrapperName(); code.addCheckcast(wrapper); code.addInvokevirtual(wrapper, pt.getGetMethodName(), pt.getGetMethodDescriptor()); } code.addOpcode(pt.getReturnOp()); } else { code.addCheckcast(type); code.addOpcode(Bytecode.ARETURN); } } }
Map<CtMethod,String> bodies = clazz.getHiddenMethods(); String bodyname = bodies.get(src); if (bodyname == null) { do { bodyname = addedWrappedMethod + clazz.getUniqueNumber(); } while (classfile.getMethod(bodyname) != null); ClassMap map = new ClassMap(); map.put(src.getDeclaringClass().getName(), clazz.getName()); MethodInfo body = new MethodInfo(classfile.getConstPool(), bodyname, src.getMethodInfo2(), map); int acc = body.getAccessFlags(); body.setAccessFlags(AccessFlag.setPrivate(acc)); body.addAttribute(new SyntheticAttribute(classfile.getConstPool())); // a stack map is copied. rebuilding it is not needed. classfile.addMethod(body); bodies.put(src, bodyname); CtMember.Cache cache = clazz.hasMemberCache(); if (cache != null) cache.addMethod(new CtMethod(body, clazz)); } return bodyname;
1,370
285
1,655
673
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/LoaderClassPath.java
LoaderClassPath
find
class LoaderClassPath implements ClassPath { private Reference<ClassLoader> clref; /** * Creates a search path representing a class loader. */ public LoaderClassPath(ClassLoader cl) { clref = new WeakReference<ClassLoader>(cl); } @Override public String toString() { return clref.get() == null ? "<null>" : clref.get().toString(); } /** * Obtains a class file from the class loader. * This method calls <code>getResourceAsStream(String)</code> * on the class loader. */ @Override public InputStream openClassfile(String classname) throws NotFoundException { String cname = classname.replace('.', '/') + ".class"; ClassLoader cl = clref.get(); if (cl == null) return null; // not found InputStream is = cl.getResourceAsStream(cname); return is; } /** * Obtains the URL of the specified class file. * This method calls <code>getResource(String)</code> * on the class loader. * * @return null if the class file could not be found. */ @Override public URL find(String classname) {<FILL_FUNCTION_BODY>} }
String cname = classname.replace('.', '/') + ".class"; ClassLoader cl = clref.get(); if (cl == null) return null; // not found URL url = cl.getResource(cname); return url;
349
67
416
674
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/Modifier.java
Modifier
isPackage
class Modifier { public static final int PUBLIC = AccessFlag.PUBLIC; public static final int PRIVATE = AccessFlag.PRIVATE; public static final int PROTECTED = AccessFlag.PROTECTED; public static final int STATIC = AccessFlag.STATIC; public static final int FINAL = AccessFlag.FINAL; public static final int SYNCHRONIZED = AccessFlag.SYNCHRONIZED; public static final int VOLATILE = AccessFlag.VOLATILE; public static final int VARARGS = AccessFlag.VARARGS; public static final int TRANSIENT = AccessFlag.TRANSIENT; public static final int NATIVE = AccessFlag.NATIVE; public static final int INTERFACE = AccessFlag.INTERFACE; public static final int ABSTRACT = AccessFlag.ABSTRACT; public static final int STRICT = AccessFlag.STRICT; public static final int ANNOTATION = AccessFlag.ANNOTATION; public static final int ENUM = AccessFlag.ENUM; /** * Returns true if the modifiers include the <code>public</code> * modifier. */ public static boolean isPublic(int mod) { return (mod & PUBLIC) != 0; } /** * Returns true if the modifiers include the <code>private</code> * modifier. */ public static boolean isPrivate(int mod) { return (mod & PRIVATE) != 0; } /** * Returns true if the modifiers include the <code>protected</code> * modifier. */ public static boolean isProtected(int mod) { return (mod & PROTECTED) != 0; } /** * Returns true if the modifiers do not include either * <code>public</code>, <code>protected</code>, or <code>private</code>. */ public static boolean isPackage(int mod) {<FILL_FUNCTION_BODY>} /** * Returns true if the modifiers include the <code>static</code> * modifier. */ public static boolean isStatic(int mod) { return (mod & STATIC) != 0; } /** * Returns true if the modifiers include the <code>final</code> * modifier. */ public static boolean isFinal(int mod) { return (mod & FINAL) != 0; } /** * Returns true if the modifiers include the <code>synchronized</code> * modifier. */ public static boolean isSynchronized(int mod) { return (mod & SYNCHRONIZED) != 0; } /** * Returns true if the modifiers include the <code>volatile</code> * modifier. */ public static boolean isVolatile(int mod) { return (mod & VOLATILE) != 0; } /** * Returns true if the modifiers include the <code>transient</code> * modifier. */ public static boolean isTransient(int mod) { return (mod & TRANSIENT) != 0; } /** * Returns true if the modifiers include the <code>native</code> * modifier. */ public static boolean isNative(int mod) { return (mod & NATIVE) != 0; } /** * Returns true if the modifiers include the <code>interface</code> * modifier. */ public static boolean isInterface(int mod) { return (mod & INTERFACE) != 0; } /** * Returns true if the modifiers include the <code>annotation</code> * modifier. * * @since 3.2 */ public static boolean isAnnotation(int mod) { return (mod & ANNOTATION) != 0; } /** * Returns true if the modifiers include the <code>enum</code> * modifier. * * @since 3.2 */ public static boolean isEnum(int mod) { return (mod & ENUM) != 0; } /** * Returns true if the modifiers include the <code>abstract</code> * modifier. */ public static boolean isAbstract(int mod) { return (mod & ABSTRACT) != 0; } /** * Returns true if the modifiers include the <code>strictfp</code> * modifier. */ public static boolean isStrict(int mod) { return (mod & STRICT) != 0; } /** * Returns true if the modifiers include the <code>varargs</code> * (variable number of arguments) modifier. */ public static boolean isVarArgs(int mod) { return (mod & VARARGS) != 0; } /** * Truns the public bit on. The protected and private bits are * cleared. */ public static int setPublic(int mod) { return (mod & ~(PRIVATE | PROTECTED)) | PUBLIC; } /** * Truns the protected bit on. The protected and public bits are * cleared. */ public static int setProtected(int mod) { return (mod & ~(PRIVATE | PUBLIC)) | PROTECTED; } /** * Truns the private bit on. The protected and private bits are * cleared. */ public static int setPrivate(int mod) { return (mod & ~(PROTECTED | PUBLIC)) | PRIVATE; } /** * Clears the public, protected, and private bits. */ public static int setPackage(int mod) { return (mod & ~(PROTECTED | PUBLIC | PRIVATE)); } /** * Clears a specified bit in <code>mod</code>. */ public static int clear(int mod, int clearBit) { return mod & ~clearBit; } /** * Return a string describing the access modifier flags in * the specified modifier. * * @param mod modifier flags. */ public static String toString(int mod) { return java.lang.reflect.Modifier.toString(mod); } }
return (mod & (PUBLIC | PRIVATE | PROTECTED)) == 0;
1,695
26
1,721
675
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/SerialVersionUID.java
SerialVersionUID
calculateDefault
class SerialVersionUID { /** * Adds serialVersionUID if one does not already exist. Call this before * modifying a class to maintain serialization compatability. */ public static void setSerialVersionUID(CtClass clazz) throws CannotCompileException, NotFoundException { // check for pre-existing field. try { clazz.getDeclaredField("serialVersionUID"); return; } catch (NotFoundException e) {} // check if the class is serializable. if (!isSerializable(clazz)) return; // add field with default value. CtField field = new CtField(CtClass.longType, "serialVersionUID", clazz); field.setModifiers(Modifier.PRIVATE | Modifier.STATIC | Modifier.FINAL); clazz.addField(field, calculateDefault(clazz) + "L"); } /** * Does the class implement Serializable? */ private static boolean isSerializable(CtClass clazz) throws NotFoundException { ClassPool pool = clazz.getClassPool(); return clazz.subtypeOf(pool.get("java.io.Serializable")); } /** * Calculate default value. See Java Serialization Specification, Stream * Unique Identifiers. * * @since 3.20 */ public static long calculateDefault(CtClass clazz) throws CannotCompileException {<FILL_FUNCTION_BODY>} private static String javaName(CtClass clazz) { return Descriptor.toJavaName(Descriptor.toJvmName(clazz)); } private static String javaName(String name) { return Descriptor.toJavaName(Descriptor.toJvmName(name)); } }
try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); DataOutputStream out = new DataOutputStream(bout); ClassFile classFile = clazz.getClassFile(); // class name. String javaName = javaName(clazz); out.writeUTF(javaName); CtMethod[] methods = clazz.getDeclaredMethods(); // class modifiers. int classMods = clazz.getModifiers(); if ((classMods & Modifier.INTERFACE) != 0) if (methods.length > 0) classMods = classMods | Modifier.ABSTRACT; else classMods = classMods & ~Modifier.ABSTRACT; out.writeInt(classMods); // interfaces. String[] interfaces = classFile.getInterfaces(); for (int i = 0; i < interfaces.length; i++) interfaces[i] = javaName(interfaces[i]); Arrays.sort(interfaces); for (int i = 0; i < interfaces.length; i++) out.writeUTF(interfaces[i]); // fields. CtField[] fields = clazz.getDeclaredFields(); Arrays.sort(fields, new Comparator<CtField>() { @Override public int compare(CtField field1, CtField field2) { return field1.getName().compareTo(field2.getName()); } }); for (int i = 0; i < fields.length; i++) { CtField field = fields[i]; int mods = field.getModifiers(); if (((mods & Modifier.PRIVATE) == 0) || ((mods & (Modifier.STATIC | Modifier.TRANSIENT)) == 0)) { out.writeUTF(field.getName()); out.writeInt(mods); out.writeUTF(field.getFieldInfo2().getDescriptor()); } } // static initializer. if (classFile.getStaticInitializer() != null) { out.writeUTF("<clinit>"); out.writeInt(Modifier.STATIC); out.writeUTF("()V"); } // constructors. CtConstructor[] constructors = clazz.getDeclaredConstructors(); Arrays.sort(constructors, new Comparator<CtConstructor>() { @Override public int compare(CtConstructor c1, CtConstructor c2) { return c1.getMethodInfo2().getDescriptor().compareTo( c2.getMethodInfo2().getDescriptor()); } }); for (int i = 0; i < constructors.length; i++) { CtConstructor constructor = constructors[i]; int mods = constructor.getModifiers(); if ((mods & Modifier.PRIVATE) == 0) { out.writeUTF("<init>"); out.writeInt(mods); out.writeUTF(constructor.getMethodInfo2() .getDescriptor().replace('/', '.')); } } // methods. Arrays.sort(methods, new Comparator<CtMethod>() { @Override public int compare(CtMethod m1, CtMethod m2) { int value = m1.getName().compareTo(m2.getName()); if (value == 0) value = m1.getMethodInfo2().getDescriptor() .compareTo(m2.getMethodInfo2().getDescriptor()); return value; } }); for (int i = 0; i < methods.length; i++) { CtMethod method = methods[i]; int mods = method.getModifiers() & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED | Modifier.STATIC | Modifier.FINAL | Modifier.SYNCHRONIZED | Modifier.NATIVE | Modifier.ABSTRACT | Modifier.STRICT); if ((mods & Modifier.PRIVATE) == 0) { out.writeUTF(method.getName()); out.writeInt(mods); out.writeUTF(method.getMethodInfo2() .getDescriptor().replace('/', '.')); } } // calculate hash. out.flush(); MessageDigest digest = MessageDigest.getInstance("SHA"); byte[] digested = digest.digest(bout.toByteArray()); long hash = 0; for (int i = Math.min(digested.length, 8) - 1; i >= 0; i--) hash = (hash << 8) | (digested[i] & 0xFF); return hash; } catch (IOException e) { throw new CannotCompileException(e); } catch (NoSuchAlgorithmException e) { throw new CannotCompileException(e); }
476
1,264
1,740
676
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/URLClassPath.java
URLClassPath
fetchClass
class URLClassPath implements ClassPath { protected String hostname; protected int port; protected String directory; protected String packageName; /** * Creates a search path specified with URL (http). * * <p>This search path is used only if a requested * class name starts with the name specified by <code>packageName</code>. * If <code>packageName</code> is "org.javassist." and a requested class is * "org.javassist.test.Main", then the given URL is used for loading that class. * The <code>URLClassPath</code> obtains a class file from: * * <pre>http://www.javassist.org:80/java/classes/org/javassist/test/Main.class * </pre> * * <p>Here, we assume that <code>host</code> is "www.javassist.org", * <code>port</code> is 80, and <code>directory</code> is "/java/classes/". * * <p>If <code>packageName</code> is <code>null</code>, the URL is used * for loading any class. * * @param host host name * @param port port number * @param directory directory name ending with "/". * It can be "/" (root directory). * It must start with "/". * @param packageName package name. It must end with "." (dot). */ public URLClassPath(String host, int port, String directory, String packageName) { hostname = host; this.port = port; this.directory = directory; this.packageName = packageName; } @Override public String toString() { return hostname + ":" + port + directory; } /** * Opens a class file with http. * * @return null if the class file could not be found. */ @Override public InputStream openClassfile(String classname) { try { URLConnection con = openClassfile0(classname); if (con != null) return con.getInputStream(); } catch (IOException e) {} return null; // not found } private URLConnection openClassfile0(String classname) throws IOException { if (packageName == null || classname.startsWith(packageName)) { String jarname = directory + classname.replace('.', '/') + ".class"; return fetchClass0(hostname, port, jarname); } return null; // not found } /** * Returns the URL. * * @return null if the class file could not be obtained. */ @Override public URL find(String classname) { try { URLConnection con = openClassfile0(classname); InputStream is = con.getInputStream(); if (is != null) { is.close(); return con.getURL(); } } catch (IOException e) {} return null; } /** * Reads a class file on an http server. * * @param host host name * @param port port number * @param directory directory name ending with "/". * It can be "/" (root directory). * It must start with "/". * @param classname fully-qualified class name */ public static byte[] fetchClass(String host, int port, String directory, String classname) throws IOException {<FILL_FUNCTION_BODY>} private static URLConnection fetchClass0(String host, int port, String filename) throws IOException { URL url; try { url = new URL("http", host, port, filename); } catch (MalformedURLException e) { // should never reache here. throw new IOException("invalid URL?"); } URLConnection con = url.openConnection(); con.connect(); return con; } }
byte[] b; URLConnection con = fetchClass0(host, port, directory + classname.replace('.', '/') + ".class"); int size = con.getContentLength(); InputStream s = con.getInputStream(); try { if (size <= 0) b = ClassPoolTail.readStream(s); else { b = new byte[size]; int len = 0; do { int n = s.read(b, len, size - len); if (n < 0) throw new IOException("the stream was closed: " + classname); len += n; } while (len < size); } } finally { s.close(); } return b;
1,060
196
1,256
677
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/AccessFlag.java
AccessFlag
isPackage
class AccessFlag { public static final int PUBLIC = 0x0001; public static final int PRIVATE = 0x0002; public static final int PROTECTED = 0x0004; public static final int STATIC = 0x0008; public static final int FINAL = 0x0010; public static final int SYNCHRONIZED = 0x0020; public static final int VOLATILE = 0x0040; public static final int BRIDGE = 0x0040; // for method_info public static final int TRANSIENT = 0x0080; public static final int VARARGS = 0x0080; // for method_info public static final int NATIVE = 0x0100; public static final int INTERFACE = 0x0200; public static final int ABSTRACT = 0x0400; public static final int STRICT = 0x0800; public static final int SYNTHETIC = 0x1000; public static final int ANNOTATION = 0x2000; public static final int ENUM = 0x4000; public static final int MANDATED = 0x8000; public static final int SUPER = 0x0020; public static final int MODULE = 0x8000; // Note: 0x0020 is assigned to both ACC_SUPER and ACC_SYNCHRONIZED // although java.lang.reflect.Modifier does not recognize ACC_SUPER. /** * Turns the public bit on. The protected and private bits are * cleared. */ public static int setPublic(int accflags) { return (accflags & ~(PRIVATE | PROTECTED)) | PUBLIC; } /** * Turns the protected bit on. The protected and public bits are * cleared. */ public static int setProtected(int accflags) { return (accflags & ~(PRIVATE | PUBLIC)) | PROTECTED; } /** * Truns the private bit on. The protected and private bits are * cleared. */ public static int setPrivate(int accflags) { return (accflags & ~(PROTECTED | PUBLIC)) | PRIVATE; } /** * Clears the public, protected, and private bits. */ public static int setPackage(int accflags) { return (accflags & ~(PROTECTED | PUBLIC | PRIVATE)); } /** * Returns true if the access flags include the public bit. */ public static boolean isPublic(int accflags) { return (accflags & PUBLIC) != 0; } /** * Returns true if the access flags include the protected bit. */ public static boolean isProtected(int accflags) { return (accflags & PROTECTED) != 0; } /** * Returns true if the access flags include the private bit. */ public static boolean isPrivate(int accflags) { return (accflags & PRIVATE) != 0; } /** * Returns true if the access flags include neither public, protected, * or private. */ public static boolean isPackage(int accflags) {<FILL_FUNCTION_BODY>} /** * Clears a specified bit in <code>accflags</code>. */ public static int clear(int accflags, int clearBit) { return accflags & ~clearBit; } /** * Converts a javassist.Modifier into * a javassist.bytecode.AccessFlag. * * @param modifier javassist.Modifier */ public static int of(int modifier) { return modifier; } /** * Converts a javassist.bytecode.AccessFlag * into a javassist.Modifier. * * @param accflags javassist.bytecode.Accessflag */ public static int toModifier(int accflags) { return accflags; } }
return (accflags & (PROTECTED | PUBLIC | PRIVATE)) == 0;
1,116
26
1,142
678
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/AnnotationDefaultAttribute.java
AnnotationDefaultAttribute
getDefaultValue
class AnnotationDefaultAttribute extends AttributeInfo { /** * The name of the <code>AnnotationDefault</code> attribute. */ public static final String tag = "AnnotationDefault"; /** * Constructs an <code>AnnotationDefault_attribute</code>. * * @param cp constant pool * @param info the contents of this attribute. It does not * include <code>attribute_name_index</code> or * <code>attribute_length</code>. */ public AnnotationDefaultAttribute(ConstPool cp, byte[] info) { super(cp, tag, info); } /** * Constructs an empty <code>AnnotationDefault_attribute</code>. * The default value can be set by <code>setDefaultValue()</code>. * * @param cp constant pool * @see #setDefaultValue(javassist.bytecode.annotation.MemberValue) */ public AnnotationDefaultAttribute(ConstPool cp) { this(cp, new byte[] { 0, 0 }); } /** * @param n the attribute name. */ AnnotationDefaultAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Copies this attribute and returns a new copy. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { AnnotationsAttribute.Copier copier = new AnnotationsAttribute.Copier(info, constPool, newCp, classnames); try { copier.memberValue(0); return new AnnotationDefaultAttribute(newCp, copier.close()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } /** * Obtains the default value represented by this attribute. */ public MemberValue getDefaultValue() {<FILL_FUNCTION_BODY>} /** * Changes the default value represented by this attribute. * * @param value the new value. * @see javassist.bytecode.annotation.Annotation#createMemberValue(ConstPool, CtClass) */ public void setDefaultValue(MemberValue value) { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationsWriter writer = new AnnotationsWriter(output, constPool); try { value.write(writer); writer.close(); } catch (IOException e) { throw new RuntimeException(e); // should never reach here. } set(output.toByteArray()); } /** * Returns a string representation of this object. */ @Override public String toString() { return getDefaultValue().toString(); } }
try { return new AnnotationsAttribute.Parser(info, constPool) .parseMemberValue(); } catch (Exception e) { throw new RuntimeException(e.toString()); }
732
54
786
679
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/BootstrapMethodsAttribute.java
BootstrapMethod
getMethods
class BootstrapMethod { /** * Constructs an element of <code>bootstrap_methods</code>. * * @param method <code>bootstrap_method_ref</code>. * @param args <code>bootstrap_arguments</code>. */ public BootstrapMethod(int method, int[] args) { methodRef = method; arguments = args; } /** * <code>bootstrap_method_ref</code>. * The value at this index must be a <code>CONSTANT_MethodHandle_info</code>. */ public int methodRef; /** * <code>bootstrap_arguments</code>. */ public int[] arguments; } BootstrapMethodsAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs a BootstrapMethods attribute. * * @param cp a constant pool table. * @param methods the contents. */ public BootstrapMethodsAttribute(ConstPool cp, BootstrapMethod[] methods) { super(cp, tag); int size = 2; for (int i = 0; i < methods.length; i++) size += 4 + methods[i].arguments.length * 2; byte[] data = new byte[size]; ByteArray.write16bit(methods.length, data, 0); // num_bootstrap_methods int pos = 2; for (int i = 0; i < methods.length; i++) { ByteArray.write16bit(methods[i].methodRef, data, pos); ByteArray.write16bit(methods[i].arguments.length, data, pos + 2); int[] args = methods[i].arguments; pos += 4; for (int k = 0; k < args.length; k++) { ByteArray.write16bit(args[k], data, pos); pos += 2; } } set(data); } /** * Obtains <code>bootstrap_methods</code> in this attribute. * * @return an array of <code>BootstrapMethod</code>. Since it * is a fresh copy, modifying the returned array does not * affect the original contents of this attribute. */ public BootstrapMethod[] getMethods() {<FILL_FUNCTION_BODY>
byte[] data = this.get(); int num = ByteArray.readU16bit(data, 0); BootstrapMethod[] methods = new BootstrapMethod[num]; int pos = 2; for (int i = 0; i < num; i++) { int ref = ByteArray.readU16bit(data, pos); int len = ByteArray.readU16bit(data, pos + 2); int[] args = new int[len]; pos += 4; for (int k = 0; k < len; k++) { args[k] = ByteArray.readU16bit(data, pos); pos += 2; } methods[i] = new BootstrapMethod(ref, args); } return methods;
628
198
826
680
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ByteArray.java
ByteArray
readS16bit
class ByteArray { /** * Reads an unsigned 16bit integer at the index. */ public static int readU16bit(byte[] code, int index) { return ((code[index] & 0xff) << 8) | (code[index + 1] & 0xff); } /** * Reads a signed 16bit integer at the index. */ public static int readS16bit(byte[] code, int index) {<FILL_FUNCTION_BODY>} /** * Writes a 16bit integer at the index. */ public static void write16bit(int value, byte[] code, int index) { code[index] = (byte)(value >>> 8); code[index + 1] = (byte)value; } /** * Reads a 32bit integer at the index. */ public static int read32bit(byte[] code, int index) { return (code[index] << 24) | ((code[index + 1] & 0xff) << 16) | ((code[index + 2] & 0xff) << 8) | (code[index + 3] & 0xff); } /** * Writes a 32bit integer at the index. */ public static void write32bit(int value, byte[] code, int index) { code[index] = (byte)(value >>> 24); code[index + 1] = (byte)(value >>> 16); code[index + 2] = (byte)(value >>> 8); code[index + 3] = (byte)value; } /** * Copies a 32bit integer. * * @param src the source byte array. * @param isrc the index into the source byte array. * @param dest the destination byte array. * @param idest the index into the destination byte array. */ static void copy32bit(byte[] src, int isrc, byte[] dest, int idest) { dest[idest] = src[isrc]; dest[idest + 1] = src[isrc + 1]; dest[idest + 2] = src[isrc + 2]; dest[idest + 3] = src[isrc + 3]; } }
return (code[index] << 8) | (code[index + 1] & 0xff);
603
28
631
681
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ByteStream.java
ByteStream
enlarge
class ByteStream extends OutputStream { private byte[] buf; private int count; public ByteStream() { this(32); } public ByteStream(int size) { buf = new byte[size]; count = 0; } public int getPos() { return count; } public int size() { return count; } public void writeBlank(int len) { enlarge(len); count += len; } @Override public void write(byte[] data) { write(data, 0, data.length); } @Override public void write(byte[] data, int off, int len) { enlarge(len); System.arraycopy(data, off, buf, count, len); count += len; } @Override public void write(int b) { enlarge(1); int oldCount = count; buf[oldCount] = (byte)b; count = oldCount + 1; } public void writeShort(int s) { enlarge(2); int oldCount = count; buf[oldCount] = (byte)(s >>> 8); buf[oldCount + 1] = (byte)s; count = oldCount + 2; } public void writeInt(int i) { enlarge(4); int oldCount = count; buf[oldCount] = (byte)(i >>> 24); buf[oldCount + 1] = (byte)(i >>> 16); buf[oldCount + 2] = (byte)(i >>> 8); buf[oldCount + 3] = (byte)i; count = oldCount + 4; } public void writeLong(long i) { enlarge(8); int oldCount = count; buf[oldCount] = (byte)(i >>> 56); buf[oldCount + 1] = (byte)(i >>> 48); buf[oldCount + 2] = (byte)(i >>> 40); buf[oldCount + 3] = (byte)(i >>> 32); buf[oldCount + 4] = (byte)(i >>> 24); buf[oldCount + 5] = (byte)(i >>> 16); buf[oldCount + 6] = (byte)(i >>> 8); buf[oldCount + 7] = (byte)i; count = oldCount + 8; } public void writeFloat(float v) { writeInt(Float.floatToIntBits(v)); } public void writeDouble(double v) { writeLong(Double.doubleToLongBits(v)); } public void writeUTF(String s) { int sLen = s.length(); int pos = count; enlarge(sLen + 2); byte[] buffer = buf; buffer[pos++] = (byte)(sLen >>> 8); buffer[pos++] = (byte)sLen; for (int i = 0; i < sLen; ++i) { char c = s.charAt(i); if (0x01 <= c && c <= 0x7f) buffer[pos++] = (byte)c; else { writeUTF2(s, sLen, i); return; } } count = pos; } private void writeUTF2(String s, int sLen, int offset) { int size = sLen; for (int i = offset; i < sLen; i++) { int c = s.charAt(i); if (c > 0x7ff) size += 2; // 3 bytes code else if (c == 0 || c > 0x7f) ++size; // 2 bytes code } if (size > 65535) throw new RuntimeException( "encoded string too long: " + sLen + size + " bytes"); enlarge(size + 2); int pos = count; byte[] buffer = buf; buffer[pos] = (byte)(size >>> 8); buffer[pos + 1] = (byte)size; pos += 2 + offset; for (int j = offset; j < sLen; ++j) { int c = s.charAt(j); if (0x01 <= c && c <= 0x7f) buffer[pos++] = (byte) c; else if (c > 0x07ff) { buffer[pos] = (byte)(0xe0 | ((c >> 12) & 0x0f)); buffer[pos + 1] = (byte)(0x80 | ((c >> 6) & 0x3f)); buffer[pos + 2] = (byte)(0x80 | (c & 0x3f)); pos += 3; } else { buffer[pos] = (byte)(0xc0 | ((c >> 6) & 0x1f)); buffer[pos + 1] = (byte)(0x80 | (c & 0x3f)); pos += 2; } } count = pos; } public void write(int pos, int value) { buf[pos] = (byte)value; } public void writeShort(int pos, int value) { buf[pos] = (byte)(value >>> 8); buf[pos + 1] = (byte)value; } public void writeInt(int pos, int value) { buf[pos] = (byte)(value >>> 24); buf[pos + 1] = (byte)(value >>> 16); buf[pos + 2] = (byte)(value >>> 8); buf[pos + 3] = (byte)value; } public byte[] toByteArray() { byte[] buf2 = new byte[count]; System.arraycopy(buf, 0, buf2, 0, count); return buf2; } public void writeTo(OutputStream out) throws IOException { out.write(buf, 0, count); } public void enlarge(int delta) {<FILL_FUNCTION_BODY>} }
int newCount = count + delta; if (newCount > buf.length) { int newLen = buf.length << 1; byte[] newBuf = new byte[newLen > newCount ? newLen : newCount]; System.arraycopy(buf, 0, newBuf, 0, count); buf = newBuf; }
1,601
89
1,690
682
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ClassFilePrinter.java
ClassFilePrinter
print
class ClassFilePrinter { /** * Prints the contents of a class file to the standard output stream. */ public static void print(ClassFile cf) { print(cf, new PrintWriter(System.out, true)); } /** * Prints the contents of a class file. */ public static void print(ClassFile cf, PrintWriter out) {<FILL_FUNCTION_BODY>} static void printAttributes(List<AttributeInfo> list, PrintWriter out, char kind) { if (list == null) return; for (AttributeInfo ai:list) { if (ai instanceof CodeAttribute) { CodeAttribute ca = (CodeAttribute)ai; out.println("attribute: " + ai.getName() + ": " + ai.getClass().getName()); out.println("max stack " + ca.getMaxStack() + ", max locals " + ca.getMaxLocals() + ", " + ca.getExceptionTable().size() + " catch blocks"); out.println("<code attribute begin>"); printAttributes(ca.getAttributes(), out, kind); out.println("<code attribute end>"); } else if (ai instanceof AnnotationsAttribute) { out.println("annnotation: " + ai.toString()); } else if (ai instanceof ParameterAnnotationsAttribute) { out.println("parameter annnotations: " + ai.toString()); } else if (ai instanceof StackMapTable) { out.println("<stack map table begin>"); StackMapTable.Printer.print((StackMapTable)ai, out); out.println("<stack map table end>"); } else if (ai instanceof StackMap) { out.println("<stack map begin>"); ((StackMap)ai).print(out); out.println("<stack map end>"); } else if (ai instanceof SignatureAttribute) { SignatureAttribute sa = (SignatureAttribute)ai; String sig = sa.getSignature(); out.println("signature: " + sig); try { String s; if (kind == 'c') s = SignatureAttribute.toClassSignature(sig).toString(); else if (kind == 'm') s = SignatureAttribute.toMethodSignature(sig).toString(); else s = SignatureAttribute.toFieldSignature(sig).toString(); out.println(" " + s); } catch (BadBytecode e) { out.println(" syntax error"); } } else out.println("attribute: " + ai.getName() + " (" + ai.get().length + " byte): " + ai.getClass().getName()); } } }
/* 0x0020 (SYNCHRONIZED) means ACC_SUPER if the modifiers * are of a class. */ int mod = AccessFlag.toModifier(cf.getAccessFlags() & ~AccessFlag.SYNCHRONIZED); out.println("major: " + cf.major + ", minor: " + cf.minor + " modifiers: " + Integer.toHexString(cf.getAccessFlags())); out.println(Modifier.toString(mod) + " class " + cf.getName() + " extends " + cf.getSuperclass()); String[] infs = cf.getInterfaces(); if (infs != null && infs.length > 0) { out.print(" implements "); out.print(infs[0]); for (int i = 1; i < infs.length; ++i) out.print(", " + infs[i]); out.println(); } out.println(); List<FieldInfo> fields = cf.getFields(); for (FieldInfo finfo:fields) { int acc = finfo.getAccessFlags(); out.println(Modifier.toString(AccessFlag.toModifier(acc)) + " " + finfo.getName() + "\t" + finfo.getDescriptor()); printAttributes(finfo.getAttributes(), out, 'f'); } out.println(); List<MethodInfo> methods = cf.getMethods(); for (MethodInfo minfo:methods) { int acc = minfo.getAccessFlags(); out.println(Modifier.toString(AccessFlag.toModifier(acc)) + " " + minfo.getName() + "\t" + minfo.getDescriptor()); printAttributes(minfo.getAttributes(), out, 'm'); out.println(); } out.println(); printAttributes(cf.getAttributes(), out, 'c');
697
498
1,195
683
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ClassFileWriter.java
MethodWriter
writeThrows
class MethodWriter { protected ByteStream output; protected ConstPoolWriter constPool; private int methodCount; protected int codeIndex; protected int throwsIndex; protected int stackIndex; private int startPos; private boolean isAbstract; private int catchPos; private int catchCount; MethodWriter(ConstPoolWriter cp) { output = new ByteStream(256); constPool = cp; methodCount = 0; codeIndex = 0; throwsIndex = 0; stackIndex = 0; } /** * Starts Adding a new method. * * @param accessFlags access flags. * @param name the method name. * @param descriptor the method signature. * @param exceptions throws clause. It may be null. * The class names must be the JVM-internal * representations like <code>java/lang/Exception</code>. * @param aw attributes to the <code>Method_info</code>. */ public void begin(int accessFlags, String name, String descriptor, String[] exceptions, AttributeWriter aw) { int nameIndex = constPool.addUtf8Info(name); int descIndex = constPool.addUtf8Info(descriptor); int[] intfs; if (exceptions == null) intfs = null; else intfs = constPool.addClassInfo(exceptions); begin(accessFlags, nameIndex, descIndex, intfs, aw); } /** * Starts adding a new method. * * @param accessFlags access flags. * @param name the method name. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param descriptor the field type. an index indicating its <code>CONSTANT_Utf8_info</code>. * @param exceptions throws clause. indexes indicating <code>CONSTANT_Class_info</code>s. * It may be null. * @param aw attributes to the <code>Method_info</code>. */ public void begin(int accessFlags, int name, int descriptor, int[] exceptions, AttributeWriter aw) { ++methodCount; output.writeShort(accessFlags); output.writeShort(name); output.writeShort(descriptor); isAbstract = (accessFlags & AccessFlag.ABSTRACT) != 0; int attrCount = isAbstract ? 0 : 1; if (exceptions != null) ++attrCount; writeAttribute(output, aw, attrCount); if (exceptions != null) writeThrows(exceptions); if (!isAbstract) { if (codeIndex == 0) codeIndex = constPool.addUtf8Info(CodeAttribute.tag); startPos = output.getPos(); output.writeShort(codeIndex); output.writeBlank(12); // attribute_length, maxStack, maxLocals, code_lenth } catchPos = -1; catchCount = 0; } private void writeThrows(int[] exceptions) {<FILL_FUNCTION_BODY>} /** * Appends an 8bit value of bytecode. * * @see Opcode */ public void add(int b) { output.write(b); } /** * Appends a 16bit value of bytecode. */ public void add16(int b) { output.writeShort(b); } /** * Appends a 32bit value of bytecode. */ public void add32(int b) { output.writeInt(b); } /** * Appends a invokevirtual, inovkespecial, or invokestatic bytecode. * * @see Opcode */ public void addInvoke(int opcode, String targetClass, String methodName, String descriptor) { int target = constPool.addClassInfo(targetClass); int nt = constPool.addNameAndTypeInfo(methodName, descriptor); int method = constPool.addMethodrefInfo(target, nt); add(opcode); add16(method); } /** * Ends appending bytecode. */ public void codeEnd(int maxStack, int maxLocals) { if (!isAbstract) { output.writeShort(startPos + 6, maxStack); output.writeShort(startPos + 8, maxLocals); output.writeInt(startPos + 10, output.getPos() - startPos - 14); // code_length catchPos = output.getPos(); catchCount = 0; output.writeShort(0); // number of catch clauses } } /** * Appends an <code>exception_table</code> entry to the * <code>Code_attribute</code>. This method is available * only after the <code>codeEnd</code> method is called. * * @param catchType an index indicating a <code>CONSTANT_Class_info</code>. */ public void addCatch(int startPc, int endPc, int handlerPc, int catchType) { ++catchCount; output.writeShort(startPc); output.writeShort(endPc); output.writeShort(handlerPc); output.writeShort(catchType); } /** * Ends adding a new method. The <code>add</code> method must be * called before the <code>end</code> method is called. * * @param smap a stack map table. may be null. * @param aw attributes to the <code>Code_attribute</code>. * may be null. */ public void end(StackMapTable.Writer smap, AttributeWriter aw) { if (isAbstract) return; // exception_table_length output.writeShort(catchPos, catchCount); int attrCount = smap == null ? 0 : 1; writeAttribute(output, aw, attrCount); if (smap != null) { if (stackIndex == 0) stackIndex = constPool.addUtf8Info(StackMapTable.tag); output.writeShort(stackIndex); byte[] data = smap.toByteArray(); output.writeInt(data.length); output.write(data); } // Code attribute_length output.writeInt(startPos + 2, output.getPos() - startPos - 6); } /** * Returns the length of the bytecode that has been added so far. * * @return the length in bytes. * @since 3.19 */ public int size() { return output.getPos() - startPos - 14; } int numOfMethods() { return methodCount; } int dataSize() { return output.size(); } /** * Writes the added methods. */ void write(OutputStream out) throws IOException { output.writeTo(out); } }
if (throwsIndex == 0) throwsIndex = constPool.addUtf8Info(ExceptionsAttribute.tag); output.writeShort(throwsIndex); output.writeInt(exceptions.length * 2 + 2); output.writeShort(exceptions.length); for (int i = 0; i < exceptions.length; i++) output.writeShort(exceptions[i]);
1,871
102
1,973
684
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ConstantAttribute.java
ConstantAttribute
copy
class ConstantAttribute extends AttributeInfo { /** * The name of this attribute <code>"ConstantValue"</code>. */ public static final String tag = "ConstantValue"; ConstantAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs a ConstantValue attribute. * * @param cp a constant pool table. * @param index <code>constantvalue_index</code> * of <code>ConstantValue_attribute</code>. */ public ConstantAttribute(ConstPool cp, int index) { super(cp, tag); byte[] bvalue = new byte[2]; bvalue[0] = (byte)(index >>> 8); bvalue[1] = (byte)index; set(bvalue); } /** * Returns <code>constantvalue_index</code>. */ public int getConstantValue() { return ByteArray.readU16bit(get(), 0); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {<FILL_FUNCTION_BODY>} }
int index = getConstPool().copy(getConstantValue(), newCp, classnames); return new ConstantAttribute(newCp, index);
399
40
439
685
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/EnclosingMethodAttribute.java
EnclosingMethodAttribute
copy
class EnclosingMethodAttribute extends AttributeInfo { /** * The name of this attribute <code>"EnclosingMethod"</code>. */ public static final String tag = "EnclosingMethod"; EnclosingMethodAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs an EnclosingMethod attribute. * * @param cp a constant pool table. * @param className the name of the innermost enclosing class. * @param methodName the name of the enclosing method. * @param methodDesc the descriptor of the enclosing method. */ public EnclosingMethodAttribute(ConstPool cp, String className, String methodName, String methodDesc) { super(cp, tag); int ci = cp.addClassInfo(className); int ni = cp.addNameAndTypeInfo(methodName, methodDesc); byte[] bvalue = new byte[4]; bvalue[0] = (byte)(ci >>> 8); bvalue[1] = (byte)ci; bvalue[2] = (byte)(ni >>> 8); bvalue[3] = (byte)ni; set(bvalue); } /** * Constructs an EnclosingMethod attribute. * The value of <code>method_index</code> is set to 0. * * @param cp a constant pool table. * @param className the name of the innermost enclosing class. */ public EnclosingMethodAttribute(ConstPool cp, String className) { super(cp, tag); int ci = cp.addClassInfo(className); int ni = 0; byte[] bvalue = new byte[4]; bvalue[0] = (byte)(ci >>> 8); bvalue[1] = (byte)ci; bvalue[2] = (byte)(ni >>> 8); bvalue[3] = (byte)ni; set(bvalue); } /** * Returns the value of <code>class_index</code>. */ public int classIndex() { return ByteArray.readU16bit(get(), 0); } /** * Returns the value of <code>method_index</code>. */ public int methodIndex() { return ByteArray.readU16bit(get(), 2); } /** * Returns the name of the class specified by <code>class_index</code>. */ public String className() { return getConstPool().getClassInfo(classIndex()); } /** * Returns the method name specified by <code>method_index</code>. * If the method is a class initializer (static constructor), * {@link MethodInfo#nameClinit} is returned. */ public String methodName() { ConstPool cp = getConstPool(); int mi = methodIndex(); if (mi == 0) return MethodInfo.nameClinit; int ni = cp.getNameAndTypeName(mi); return cp.getUtf8Info(ni); } /** * Returns the method descriptor specified by <code>method_index</code>. */ public String methodDescriptor() { ConstPool cp = getConstPool(); int mi = methodIndex(); int ti = cp.getNameAndTypeDescriptor(mi); return cp.getUtf8Info(ti); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {<FILL_FUNCTION_BODY>} }
if (methodIndex() == 0) return new EnclosingMethodAttribute(newCp, className()); return new EnclosingMethodAttribute(newCp, className(), methodName(), methodDescriptor());
1,027
53
1,080
686
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ExceptionsAttribute.java
ExceptionsAttribute
setExceptions
class ExceptionsAttribute extends AttributeInfo { /** * The name of this attribute <code>"Exceptions"</code>. */ public static final String tag = "Exceptions"; ExceptionsAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs a copy of an exceptions attribute. * * @param cp constant pool table. * @param src source attribute. */ private ExceptionsAttribute(ConstPool cp, ExceptionsAttribute src, Map<String,String> classnames) { super(cp, tag); copyFrom(src, classnames); } /** * Constructs a new exceptions attribute. * * @param cp constant pool table. */ public ExceptionsAttribute(ConstPool cp) { super(cp, tag); byte[] data = new byte[2]; data[0] = data[1] = 0; // empty this.info = data; } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. It can be <code>null</code>. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { return new ExceptionsAttribute(newCp, this, classnames); } /** * Copies the contents from a source attribute. * Specified class names are replaced during the copy. * * @param srcAttr source Exceptions attribute * @param classnames pairs of replaced and substituted * class names. */ private void copyFrom(ExceptionsAttribute srcAttr, Map<String,String> classnames) { ConstPool srcCp = srcAttr.constPool; ConstPool destCp = this.constPool; byte[] src = srcAttr.info; int num = src.length; byte[] dest = new byte[num]; dest[0] = src[0]; dest[1] = src[1]; // the number of elements. for (int i = 2; i < num; i += 2) { int index = ByteArray.readU16bit(src, i); ByteArray.write16bit(srcCp.copy(index, destCp, classnames), dest, i); } this.info = dest; } /** * Returns <code>exception_index_table[]</code>. */ public int[] getExceptionIndexes() { byte[] blist = info; int n = blist.length; if (n <= 2) return null; int[] elist = new int[n / 2 - 1]; int k = 0; for (int j = 2; j < n; j += 2) elist[k++] = ((blist[j] & 0xff) << 8) | (blist[j + 1] & 0xff); return elist; } /** * Returns the names of exceptions that the method may throw. */ public String[] getExceptions() { byte[] blist = info; int n = blist.length; if (n <= 2) return null; String[] elist = new String[n / 2 - 1]; int k = 0; for (int j = 2; j < n; j += 2) { int index = ((blist[j] & 0xff) << 8) | (blist[j + 1] & 0xff); elist[k++] = constPool.getClassInfo(index); } return elist; } /** * Sets <code>exception_index_table[]</code>. */ public void setExceptionIndexes(int[] elist) { int n = elist.length; byte[] blist = new byte[n * 2 + 2]; ByteArray.write16bit(n, blist, 0); for (int i = 0; i < n; ++i) ByteArray.write16bit(elist[i], blist, i * 2 + 2); info = blist; } /** * Sets the names of exceptions that the method may throw. */ public void setExceptions(String[] elist) {<FILL_FUNCTION_BODY>} /** * Returns <code>number_of_exceptions</code>. */ public int tableLength() { return info.length / 2 - 1; } /** * Returns the value of <code>exception_index_table[nth]</code>. */ public int getException(int nth) { int index = nth * 2 + 2; // nth >= 0 return ((info[index] & 0xff) << 8) | (info[index + 1] & 0xff); } }
int n = elist.length; byte[] blist = new byte[n * 2 + 2]; ByteArray.write16bit(n, blist, 0); for (int i = 0; i < n; ++i) ByteArray.write16bit(constPool.addClassInfo(elist[i]), blist, i * 2 + 2); info = blist;
1,329
106
1,435
687
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/FieldInfo.java
FieldInfo
getConstantValue
class FieldInfo { ConstPool constPool; int accessFlags; int name; String cachedName; String cachedType; int descriptor; List<AttributeInfo> attribute; // may be null. private FieldInfo(ConstPool cp) { constPool = cp; accessFlags = 0; attribute = null; } /** * Constructs a <code>field_info</code> structure. * * @param cp a constant pool table * @param fieldName field name * @param desc field descriptor * * @see Descriptor */ public FieldInfo(ConstPool cp, String fieldName, String desc) { this(cp); name = cp.addUtf8Info(fieldName); cachedName = fieldName; descriptor = cp.addUtf8Info(desc); } FieldInfo(ConstPool cp, DataInputStream in) throws IOException { this(cp); read(in); } /** * Returns a string representation of the object. */ @Override public String toString() { return getName() + " " + getDescriptor(); } /** * Copies all constant pool items to a given new constant pool * and replaces the original items with the new ones. * This is used for garbage collecting the items of removed fields * and methods. * * @param cp the destination */ void compact(ConstPool cp) { name = cp.addUtf8Info(getName()); descriptor = cp.addUtf8Info(getDescriptor()); attribute = AttributeInfo.copyAll(attribute, cp); constPool = cp; } void prune(ConstPool cp) { List<AttributeInfo> newAttributes = new ArrayList<AttributeInfo>(); AttributeInfo invisibleAnnotations = getAttribute(AnnotationsAttribute.invisibleTag); if (invisibleAnnotations != null) { invisibleAnnotations = invisibleAnnotations.copy(cp, null); newAttributes.add(invisibleAnnotations); } AttributeInfo visibleAnnotations = getAttribute(AnnotationsAttribute.visibleTag); if (visibleAnnotations != null) { visibleAnnotations = visibleAnnotations.copy(cp, null); newAttributes.add(visibleAnnotations); } AttributeInfo signature = getAttribute(SignatureAttribute.tag); if (signature != null) { signature = signature.copy(cp, null); newAttributes.add(signature); } int index = getConstantValue(); if (index != 0) { index = constPool.copy(index, cp, null); newAttributes.add(new ConstantAttribute(cp, index)); } attribute = newAttributes; name = cp.addUtf8Info(getName()); descriptor = cp.addUtf8Info(getDescriptor()); constPool = cp; } /** * Returns the constant pool table used * by this <code>field_info</code>. */ public ConstPool getConstPool() { return constPool; } /** * Returns the field name. */ public String getName() { if (cachedName == null) cachedName = constPool.getUtf8Info(name); return cachedName; } /** * Sets the field name. */ public void setName(String newName) { name = constPool.addUtf8Info(newName); cachedName = newName; } /** * Returns the access flags. * * @see AccessFlag */ public int getAccessFlags() { return accessFlags; } /** * Sets the access flags. * * @see AccessFlag */ public void setAccessFlags(int acc) { accessFlags = acc; } /** * Returns the field descriptor. * * @see Descriptor */ public String getDescriptor() { return constPool.getUtf8Info(descriptor); } /** * Sets the field descriptor. * * @see Descriptor */ public void setDescriptor(String desc) { if (!desc.equals(getDescriptor())) descriptor = constPool.addUtf8Info(desc); } /** * Finds a ConstantValue attribute and returns the index into * the <code>constant_pool</code> table. * * @return 0 if a ConstantValue attribute is not found. */ public int getConstantValue() {<FILL_FUNCTION_BODY>} /** * Returns all the attributes. The returned <code>List</code> object * is shared with this object. If you add a new attribute to the list, * the attribute is also added to the field represented by this * object. If you remove an attribute from the list, it is also removed * from the field. * * @return a list of <code>AttributeInfo</code> objects. * @see AttributeInfo */ public List<AttributeInfo> getAttributes() { if (attribute == null) attribute = new ArrayList<AttributeInfo>(); return attribute; } /** * Returns the attribute with the specified name. * It returns null if the specified attribute is not found. * * <p>An attribute name can be obtained by, for example, * {@link AnnotationsAttribute#visibleTag} or * {@link AnnotationsAttribute#invisibleTag}. * </p> * * @param name attribute name * @see #getAttributes() */ public AttributeInfo getAttribute(String name) { return AttributeInfo.lookup(attribute, name); } /** * Removes an attribute with the specified name. * * @param name attribute name. * @return the removed attribute or null. * @since 3.21 */ public AttributeInfo removeAttribute(String name) { return AttributeInfo.remove(attribute, name); } /** * Appends an attribute. If there is already an attribute with * the same name, the new one substitutes for it. * * @see #getAttributes() */ public void addAttribute(AttributeInfo info) { if (attribute == null) attribute = new ArrayList<AttributeInfo>(); AttributeInfo.remove(attribute, info.getName()); attribute.add(info); } private void read(DataInputStream in) throws IOException { accessFlags = in.readUnsignedShort(); name = in.readUnsignedShort(); descriptor = in.readUnsignedShort(); int n = in.readUnsignedShort(); attribute = new ArrayList<AttributeInfo>(); for (int i = 0; i < n; ++i) attribute.add(AttributeInfo.read(constPool, in)); } void write(DataOutputStream out) throws IOException { out.writeShort(accessFlags); out.writeShort(name); out.writeShort(descriptor); if (attribute == null) out.writeShort(0); else { out.writeShort(attribute.size()); AttributeInfo.writeAll(attribute, out); } } }
if ((accessFlags & AccessFlag.STATIC) == 0) return 0; ConstantAttribute attr = (ConstantAttribute)getAttribute(ConstantAttribute.tag); if (attr == null) return 0; return attr.getConstantValue();
1,883
69
1,952
688
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/LineNumberAttribute.java
Pc
toNearPc
class Pc { /** * The index into the code array. */ public int index; /** * The line number. */ public int line; } /** * Returns the index into the code array at which the code for * the specified line (or the nearest line after the specified one) * begins. * * @param line the line number. * @return a pair of the index and the line number of the * bytecode at that index. */ public Pc toNearPc(int line) {<FILL_FUNCTION_BODY>
int n = tableLength(); int nearPc = 0; int distance = 0; if (n > 0) { distance = lineNumber(0) - line; nearPc = startPc(0); } for (int i = 1; i < n; ++i) { int d = lineNumber(i) - line; if ((d < 0 && d > distance) || (d >= 0 && (d < distance || distance < 0))) { distance = d; nearPc = startPc(i); } } Pc res = new Pc(); res.index = nearPc; res.line = line + distance; return res;
160
185
345
689
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/LongVector.java
LongVector
addElement
class LongVector { static final int ASIZE = 128; static final int ABITS = 7; // ASIZE = 2^ABITS static final int VSIZE = 8; private ConstInfo[][] objects; private int elements; public LongVector() { objects = new ConstInfo[VSIZE][]; elements = 0; } public LongVector(int initialSize) { int vsize = ((initialSize >> ABITS) & ~(VSIZE - 1)) + VSIZE; objects = new ConstInfo[vsize][]; elements = 0; } public int size() { return elements; } public int capacity() { return objects.length * ASIZE; } public ConstInfo elementAt(int i) { if (i < 0 || elements <= i) return null; return objects[i >> ABITS][i & (ASIZE - 1)]; } public void addElement(ConstInfo value) {<FILL_FUNCTION_BODY>} }
int nth = elements >> ABITS; int offset = elements & (ASIZE - 1); int len = objects.length; if (nth >= len) { ConstInfo[][] newObj = new ConstInfo[len + VSIZE][]; System.arraycopy(objects, 0, newObj, 0, len); objects = newObj; } if (objects[nth] == null) objects[nth] = new ConstInfo[ASIZE]; objects[nth][offset] = value; elements++;
267
146
413
690
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/MethodParametersAttribute.java
MethodParametersAttribute
copy
class MethodParametersAttribute extends AttributeInfo { /** * The name of this attribute <code>"MethodParameters"</code>. */ public static final String tag = "MethodParameters"; MethodParametersAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Constructs an attribute. * * @param cp a constant pool table. * @param names an array of parameter names. * The i-th element is the name of the i-th parameter. * @param flags an array of parameter access flags. */ public MethodParametersAttribute(ConstPool cp, String[] names, int[] flags) { super(cp, tag); byte[] data = new byte[names.length * 4 + 1]; data[0] = (byte)names.length; for (int i = 0; i < names.length; i++) { ByteArray.write16bit(cp.addUtf8Info(names[i]), data, i * 4 + 1); ByteArray.write16bit(flags[i], data, i * 4 + 3); } set(data); } /** * Returns <code>parameters_count</code>, which is the number of * parameters. */ public int size() { return info[0] & 0xff; } /** * Returns the value of <code>name_index</code> of the i-th element of <code>parameters</code>. * * @param i the position of the parameter. */ public int name(int i) { return ByteArray.readU16bit(info, i * 4 + 1); } /** * Returns the value of <code>access_flags</code> of the i-th element of <code>parameters</code>. * * @param i the position of the parameter. * @see AccessFlag */ public int accessFlags(int i) { return ByteArray.readU16bit(info, i * 4 + 3); } /** * Makes a copy. * * @param newCp the constant pool table used by the new copy. * @param classnames ignored. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) {<FILL_FUNCTION_BODY>} }
int s = size(); ConstPool cp = getConstPool(); String[] names = new String[s]; int[] flags = new int[s]; for (int i = 0; i < s; i++) { names[i] = cp.getUtf8Info(name(i)); flags[i] = accessFlags(i); } return new MethodParametersAttribute(newCp, names, flags);
641
110
751
691
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/NestHostAttribute.java
NestHostAttribute
copy
class NestHostAttribute extends AttributeInfo { /** * The name of this attribute <code>"NestHost"</code>. */ public static final String tag = "NestHost"; NestHostAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } private NestHostAttribute(ConstPool cp, int hostIndex) { super(cp, tag, new byte[2]); ByteArray.write16bit(hostIndex, get(), 0); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String, String> classnames) {<FILL_FUNCTION_BODY>} /** * Returns <code>host_class_index</code>. The constant pool entry * at this entry is a <code>CONSTANT_Class_info</code> structure. * @return the value of <code>host_class_index</code>. */ public int hostClassIndex() { return ByteArray.readU16bit(info, 0); } }
int hostIndex = ByteArray.readU16bit(get(), 0); int newHostIndex = getConstPool().copy(hostIndex, newCp, classnames); return new NestHostAttribute(newCp, newHostIndex);
363
63
426
692
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/NestMembersAttribute.java
NestMembersAttribute
copy
class NestMembersAttribute extends AttributeInfo { /** * The name of this attribute <code>"NestMembers"</code>. */ public static final String tag = "NestMembers"; NestMembersAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } private NestMembersAttribute(ConstPool cp, byte[] info) { super(cp, tag, info); } /** * Makes a copy. Class names are replaced according to the * given <code>Map</code> object. * * @param newCp the constant pool table used by the new copy. * @param classnames pairs of replaced and substituted * class names. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String, String> classnames) {<FILL_FUNCTION_BODY>} /** * Returns <code>number_of_classes</code>. * @return the number of the classes recorded in this attribute. */ public int numberOfClasses() { return ByteArray.readU16bit(info, 0); } /** Returns <code>classes[index]</code>. * * @param index the index into <code>classes</code>. * @return the value at the given index in the <code>classes</code> array. * It is an index into the constant pool. * The constant pool entry at the returned index is a * <code>CONSTANT_Class_info</code> structure. */ public int memberClass(int index) { return ByteArray.readU16bit(info, index * 2 + 2); } }
byte[] src = get(); byte[] dest = new byte[src.length]; ConstPool cp = getConstPool(); int n = ByteArray.readU16bit(src, 0); ByteArray.write16bit(n, dest, 0); for (int i = 0, j = 2; i < n; ++i, j += 2) { int index = ByteArray.readU16bit(src, j); int newIndex = cp.copy(index, newCp, classnames); ByteArray.write16bit(newIndex, dest, j); } return new NestMembersAttribute(newCp, dest);
454
170
624
693
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/ParameterAnnotationsAttribute.java
ParameterAnnotationsAttribute
getAnnotations
class ParameterAnnotationsAttribute extends AttributeInfo { /** * The name of the <code>RuntimeVisibleParameterAnnotations</code> * attribute. */ public static final String visibleTag = "RuntimeVisibleParameterAnnotations"; /** * The name of the <code>RuntimeInvisibleParameterAnnotations</code> * attribute. */ public static final String invisibleTag = "RuntimeInvisibleParameterAnnotations"; /** * Constructs * a <code>Runtime(In)VisibleParameterAnnotations_attribute</code>. * * @param cp constant pool * @param attrname attribute name (<code>visibleTag</code> or * <code>invisibleTag</code>). * @param info the contents of this attribute. It does not * include <code>attribute_name_index</code> or * <code>attribute_length</code>. */ public ParameterAnnotationsAttribute(ConstPool cp, String attrname, byte[] info) { super(cp, attrname, info); } /** * Constructs an empty * <code>Runtime(In)VisibleParameterAnnotations_attribute</code>. * A new annotation can be later added to the created attribute * by <code>setAnnotations()</code>. * * @param cp constant pool * @param attrname attribute name (<code>visibleTag</code> or * <code>invisibleTag</code>). * @see #setAnnotations(Annotation[][]) */ public ParameterAnnotationsAttribute(ConstPool cp, String attrname) { this(cp, attrname, new byte[] { 0 }); } /** * @param n the attribute name. */ ParameterAnnotationsAttribute(ConstPool cp, int n, DataInputStream in) throws IOException { super(cp, n, in); } /** * Returns <code>num_parameters</code>. */ public int numParameters() { return info[0] & 0xff; } /** * Copies this attribute and returns a new copy. */ @Override public AttributeInfo copy(ConstPool newCp, Map<String,String> classnames) { Copier copier = new Copier(info, constPool, newCp, classnames); try { copier.parameters(); return new ParameterAnnotationsAttribute(newCp, getName(), copier.close()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } /** * Parses the annotations and returns a data structure representing * that parsed annotations. Note that changes of the node values of the * returned tree are not reflected on the annotations represented by * this object unless the tree is copied back to this object by * <code>setAnnotations()</code>. * * @return Each element of the returned array represents an array of * annotations that are associated with each method parameter. * * @see #setAnnotations(Annotation[][]) */ public Annotation[][] getAnnotations() {<FILL_FUNCTION_BODY>} /** * Changes the annotations represented by this object according to * the given array of <code>Annotation</code> objects. * * @param params the data structure representing the * new annotations. Every element of this array * is an array of <code>Annotation</code> and * it represens annotations of each method parameter. */ public void setAnnotations(Annotation[][] params) { ByteArrayOutputStream output = new ByteArrayOutputStream(); AnnotationsWriter writer = new AnnotationsWriter(output, constPool); try { writer.numParameters(params.length); for (Annotation[] anno:params) { writer.numAnnotations(anno.length); for (int j = 0; j < anno.length; ++j) anno[j].write(writer); } writer.close(); } catch (IOException e) { throw new RuntimeException(e); // should never reach here. } set(output.toByteArray()); } /** * @param oldname a JVM class name. * @param newname a JVM class name. */ @Override void renameClass(String oldname, String newname) { Map<String,String> map = new HashMap<String,String>(); map.put(oldname, newname); renameClass(map); } @Override void renameClass(Map<String,String> classnames) { Renamer renamer = new Renamer(info, getConstPool(), classnames); try { renamer.parameters(); } catch (Exception e) { throw new RuntimeException(e); } } @Override void getRefClasses(Map<String,String> classnames) { renameClass(classnames); } /** * Returns a string representation of this object. */ @Override public String toString() { Annotation[][] aa = getAnnotations(); StringBuilder sbuf = new StringBuilder(); for (Annotation[] a : aa) { for (Annotation i : a) sbuf.append(i.toString()).append(" "); sbuf.append(", "); } return sbuf.toString().replaceAll(" (?=,)|, $",""); } }
try { return new Parser(info, constPool).parseParameters(); } catch (Exception e) { throw new RuntimeException(e.toString()); }
1,433
47
1,480
694
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/StackMap.java
SwitchShifter
locals
class SwitchShifter extends Walker { private int where, gap; public SwitchShifter(StackMap smt, int where, int gap) { super(smt); this.where = where; this.gap = gap; } @Override public int locals(int pos, int offset, int num) {<FILL_FUNCTION_BODY>} }
if (where == pos + offset) ByteArray.write16bit(offset - gap, info, pos - 4); else if (where == pos) ByteArray.write16bit(offset + gap, info, pos - 4); return super.locals(pos, offset, num);
100
79
179
695
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/StackMapTable.java
NewRemover
fullFrame
class NewRemover extends SimpleCopy { int posOfNew; public NewRemover(byte[] data, int pos) { super(data); posOfNew = pos; } @Override public void sameLocals(int pos, int offsetDelta, int stackTag, int stackData) { if (stackTag == UNINIT && stackData == posOfNew) super.sameFrame(pos, offsetDelta); else super.sameLocals(pos, offsetDelta, stackTag, stackData); } @Override public void fullFrame(int pos, int offsetDelta, int[] localTags, int[] localData, int[] stackTags, int[] stackData) {<FILL_FUNCTION_BODY>} }
int n = stackTags.length - 1; for (int i = 0; i < n; i++) if (stackTags[i] == UNINIT && stackData[i] == posOfNew && stackTags[i + 1] == UNINIT && stackData[i + 1] == posOfNew) { n++; int[] stackTags2 = new int[n - 2]; int[] stackData2 = new int[n - 2]; int k = 0; for (int j = 0; j < n; j++) if (j == i) j++; else { stackTags2[k] = stackTags[j]; stackData2[k++] = stackData[j]; } stackTags = stackTags2; stackData = stackData2; break; } super.fullFrame(pos, offsetDelta, localTags, localData, stackTags, stackData);
190
243
433
696
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/TypeAnnotationsAttribute.java
SubWalker
targetInfo
class SubWalker { byte[] info; SubWalker(byte[] attrInfo) { info = attrInfo; } final int targetInfo(int pos, int type) throws Exception {<FILL_FUNCTION_BODY>} void typeParameterTarget(int pos, int targetType, int typeParameterIndex) throws Exception {} void supertypeTarget(int pos, int superTypeIndex) throws Exception {} void typeParameterBoundTarget(int pos, int targetType, int typeParameterIndex, int boundIndex) throws Exception {} void emptyTarget(int pos, int targetType) throws Exception {} void formalParameterTarget(int pos, int formalParameterIndex) throws Exception {} void throwsTarget(int pos, int throwsTypeIndex) throws Exception {} int localvarTarget(int pos, int targetType, int tableLength) throws Exception { for (int i = 0; i < tableLength; i++) { int start = ByteArray.readU16bit(info, pos); int length = ByteArray.readU16bit(info, pos + 2); int index = ByteArray.readU16bit(info, pos + 4); localvarTarget(pos, targetType, start, length, index); pos += 6; } return pos; } void localvarTarget(int pos, int targetType, int startPc, int length, int index) throws Exception {} void catchTarget(int pos, int exceptionTableIndex) throws Exception {} void offsetTarget(int pos, int targetType, int offset) throws Exception {} void typeArgumentTarget(int pos, int targetType, int offset, int typeArgumentIndex) throws Exception {} final int typePath(int pos) throws Exception { int len = info[pos++] & 0xff; return typePath(pos, len); } int typePath(int pos, int pathLength) throws Exception { for (int i = 0; i < pathLength; i++) { int kind = info[pos] & 0xff; int index = info[pos + 1] & 0xff; typePath(pos, kind, index); pos += 2; } return pos; } void typePath(int pos, int typePathKind, int typeArgumentIndex) throws Exception {} }
switch (type) { case 0x00: case 0x01: { int index = info[pos] & 0xff; typeParameterTarget(pos, type, index); return pos + 1; } case 0x10: { int index = ByteArray.readU16bit(info, pos); supertypeTarget(pos, index); return pos + 2; } case 0x11: case 0x12: { int param = info[pos] & 0xff; int bound = info[pos + 1] & 0xff; typeParameterBoundTarget(pos, type, param, bound); return pos + 2; } case 0x13: case 0x14: case 0x15: emptyTarget(pos, type); return pos; case 0x16: { int index = info[pos] & 0xff; formalParameterTarget(pos, index); return pos + 1; } case 0x17: { int index = ByteArray.readU16bit(info, pos); throwsTarget(pos, index); return pos + 2; } case 0x40: case 0x41: { int len = ByteArray.readU16bit(info, pos); return localvarTarget(pos + 2, type, len); } case 0x42: { int index = ByteArray.readU16bit(info, pos); catchTarget(pos, index); return pos + 2; } case 0x43: case 0x44: case 0x45: case 0x46: { int offset = ByteArray.readU16bit(info, pos); offsetTarget(pos, type, offset); return pos + 2; } case 0x47: case 0x48: case 0x49: case 0x4a: case 0x4b: { int offset = ByteArray.readU16bit(info, pos); int index = info[pos + 2] & 0xff; typeArgumentTarget(pos, type, offset, index); return pos + 3; } default: throw new RuntimeException("invalid target type: " + type); }
588
611
1,199
697
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/ControlFlow.java
Node
toString
class Node { private Block block; private Node parent; private Node[] children; Node(Block b) { block = b; parent = null; } /** * Returns a <code>String</code> representation. */ @Override public String toString() {<FILL_FUNCTION_BODY>} /** * Returns the basic block indicated by this node. */ public Block block() { return block; } /** * Returns the parent of this node. */ public Node parent() { return parent; } /** * Returns the number of the children of this node. */ public int children() { return children.length; } /** * Returns the n-th child of this node. * * @param n an index in the array of children. */ public Node child(int n) { return children[n]; } /* * After executing this method, distance[] represents the post order of the tree nodes. * It also represents distances from the root; a bigger number represents a shorter * distance. parent is set to its parent in the depth first spanning tree. */ int makeDepth1stTree(Node caller, boolean[] visited, int counter, int[] distance, Access access) { int index = block.index; if (visited[index]) return counter; visited[index] = true; parent = caller; BasicBlock[] exits = access.exits(this); if (exits != null) for (int i = 0; i < exits.length; i++) { Node n = access.node(exits[i]); counter = n.makeDepth1stTree(this, visited, counter, distance, access); } distance[index] = counter++; return counter; } boolean makeDominatorTree(boolean[] visited, int[] distance, Access access) { int index = block.index; if (visited[index]) return false; visited[index] = true; boolean changed = false; BasicBlock[] exits = access.exits(this); if (exits != null) for (int i = 0; i < exits.length; i++) { Node n = access.node(exits[i]); if (n.makeDominatorTree(visited, distance, access)) changed = true; } BasicBlock[] entrances = access.entrances(this); if (entrances != null) for (int i = 0; i < entrances.length; i++) { if (parent != null) { Node n = getAncestor(parent, access.node(entrances[i]), distance); if (n != parent) { parent = n; changed = true; } } } return changed; } private static Node getAncestor(Node n1, Node n2, int[] distance) { while (n1 != n2) { if (distance[n1.block.index] < distance[n2.block.index]) n1 = n1.parent; else n2 = n2.parent; if (n1 == null || n2 == null) return null; } return n1; } private static void setChildren(Node[] all) { int size = all.length; int[] nchildren = new int[size]; for (int i = 0; i < size; i++) nchildren[i] = 0; for (int i = 0; i < size; i++) { Node p = all[i].parent; if (p != null) nchildren[p.block.index]++; } for (int i = 0; i < size; i++) all[i].children = new Node[nchildren[i]]; for (int i = 0; i < size; i++) nchildren[i] = 0; for (int i = 0; i < size; i++) { Node n = all[i]; Node p = n.parent; if (p != null) p.children[nchildren[p.block.index]++] = n; } } }
StringBuffer sbuf = new StringBuffer(); sbuf.append("Node[pos=").append(block().position()); sbuf.append(", parent="); sbuf.append(parent == null ? "*" : Integer.toString(parent.block().position())); sbuf.append(", children{"); for (int i = 0; i < children.length; i++) sbuf.append(children[i].block().position()).append(", "); sbuf.append("}]"); return sbuf.toString();
1,112
133
1,245
698
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/FramePrinter.java
FramePrinter
printLocals
class FramePrinter { private final PrintStream stream; /** * Constructs a bytecode printer. */ public FramePrinter(PrintStream stream) { this.stream = stream; } /** * Prints all the methods declared in the given class. */ public static void print(CtClass clazz, PrintStream stream) { (new FramePrinter(stream)).print(clazz); } /** * Prints all the methods declared in the given class. */ public void print(CtClass clazz) { CtMethod[] methods = clazz.getDeclaredMethods(); for (int i = 0; i < methods.length; i++) { print(methods[i]); } } private String getMethodString(CtMethod method) { try { return Modifier.toString(method.getModifiers()) + " " + method.getReturnType().getName() + " " + method.getName() + Descriptor.toString(method.getSignature()) + ";"; } catch (NotFoundException e) { throw new RuntimeException(e); } } /** * Prints the instructions and the frame states of the given method. */ public void print(CtMethod method) { stream.println("\n" + getMethodString(method)); MethodInfo info = method.getMethodInfo2(); ConstPool pool = info.getConstPool(); CodeAttribute code = info.getCodeAttribute(); if (code == null) return; Frame[] frames; try { frames = (new Analyzer()).analyze(method.getDeclaringClass(), info); } catch (BadBytecode e) { throw new RuntimeException(e); } int spacing = String.valueOf(code.getCodeLength()).length(); CodeIterator iterator = code.iterator(); while (iterator.hasNext()) { int pos; try { pos = iterator.next(); } catch (BadBytecode e) { throw new RuntimeException(e); } stream.println(pos + ": " + InstructionPrinter.instructionString(iterator, pos, pool)); addSpacing(spacing + 3); Frame frame = frames[pos]; if (frame == null) { stream.println("--DEAD CODE--"); continue; } printStack(frame); addSpacing(spacing + 3); printLocals(frame); } } private void printStack(Frame frame) { stream.print("stack ["); int top = frame.getTopIndex(); for (int i = 0; i <= top; i++) { if (i > 0) stream.print(", "); Type type = frame.getStack(i); stream.print(type); } stream.println("]"); } private void printLocals(Frame frame) {<FILL_FUNCTION_BODY>} private void addSpacing(int count) { while (count-- > 0) stream.print(' '); } }
stream.print("locals ["); int length = frame.localsLength(); for (int i = 0; i < length; i++) { if (i > 0) stream.print(", "); Type type = frame.getLocal(i); stream.print(type == null ? "empty" : type.toString()); } stream.println("]");
798
98
896
699
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/IntQueue.java
Entry
take
class Entry { private IntQueue.Entry next; private int value; private Entry(int value) { this.value = value; } } private IntQueue.Entry head; private IntQueue.Entry tail; void add(int value) { IntQueue.Entry entry = new Entry(value); if (tail != null) tail.next = entry; tail = entry; if (head == null) head = entry; } boolean isEmpty() { return head == null; } int take() {<FILL_FUNCTION_BODY>
if (head == null) throw new NoSuchElementException(); int value = head.value; head = head.next; if (head == null) tail = null; return value;
161
58
219
700
HotswapProjects_HotswapAgent
HotswapAgent/hotswap-agent-core/src/main/java/org/hotswap/agent/javassist/bytecode/analysis/MultiArrayType.java
MultiArrayType
toString
class MultiArrayType extends Type { private MultiType component; private int dims; public MultiArrayType(MultiType component, int dims) { super(null); this.component = component; this.dims = dims; } @Override public CtClass getCtClass() { CtClass clazz = component.getCtClass(); if (clazz == null) return null; ClassPool pool = clazz.getClassPool(); if (pool == null) pool = ClassPool.getDefault(); String name = arrayName(clazz.getName(), dims); try { return pool.get(name); } catch (NotFoundException e) { throw new RuntimeException(e); } } @Override boolean popChanged() { return component.popChanged(); } @Override public int getDimensions() { return dims; } @Override public Type getComponent() { return dims == 1 ? (Type)component : new MultiArrayType(component, dims - 1); } @Override public int getSize() { return 1; } @Override public boolean isArray() { return true; } @Override public boolean isAssignableFrom(Type type) { throw new UnsupportedOperationException("Not implemented"); } @Override public boolean isReference() { return true; } public boolean isAssignableTo(Type type) { if (eq(type.getCtClass(), Type.OBJECT.getCtClass())) return true; if (eq(type.getCtClass(), Type.CLONEABLE.getCtClass())) return true; if (eq(type.getCtClass(), Type.SERIALIZABLE.getCtClass())) return true; if (! type.isArray()) return false; Type typeRoot = getRootComponent(type); int typeDims = type.getDimensions(); if (typeDims > dims) return false; if (typeDims < dims) { if (eq(typeRoot.getCtClass(), Type.OBJECT.getCtClass())) return true; if (eq(typeRoot.getCtClass(), Type.CLONEABLE.getCtClass())) return true; if (eq(typeRoot.getCtClass(), Type.SERIALIZABLE.getCtClass())) return true; return false; } return component.isAssignableTo(typeRoot); } @Override public int hashCode() { return component.hashCode() + dims; } @Override public boolean equals(Object o) { if (! (o instanceof MultiArrayType)) return false; MultiArrayType multi = (MultiArrayType)o; return component.equals(multi.component) && dims == multi.dims; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
// follows the same detailed formating scheme as component return arrayName(component.toString(), dims);
805
28
833