proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthCheckHandler.java
EurekaHealthCheckHandler
getOrder
class EurekaHealthCheckHandler implements HealthCheckHandler, ApplicationContextAware, InitializingBean, Ordered, Lifecycle { private static final Map<Status, InstanceInfo.InstanceStatus> STATUS_MAPPING = new HashMap<>() { { put(Status.UNKNOWN, InstanceStatus.UNKNOWN); put(Status.OUT_OF_SERVICE, InstanceStatus.DOWN); put(Status.DOWN, InstanceStatus.DOWN); put(Status.UP, InstanceStatus.UP); } }; private final StatusAggregator statusAggregator; private ApplicationContext applicationContext; private final Map<String, HealthContributor> healthContributors = new HashMap<>(); /** * {@code true} until the context is stopped. */ private boolean running = true; private final Map<String, ReactiveHealthContributor> reactiveHealthContributors = new HashMap<>(); public EurekaHealthCheckHandler(StatusAggregator statusAggregator) { this.statusAggregator = statusAggregator; Assert.notNull(statusAggregator, "StatusAggregator must not be null"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } @Override public void afterPropertiesSet() { populateHealthContributors(applicationContext.getBeansOfType(HealthContributor.class)); reactiveHealthContributors.putAll(applicationContext.getBeansOfType(ReactiveHealthContributor.class)); } void populateHealthContributors(Map<String, HealthContributor> healthContributors) { for (Map.Entry<String, HealthContributor> entry : healthContributors.entrySet()) { // ignore EurekaHealthIndicator and flatten the rest of the composite // otherwise there is a never ending cycle of down. See gh-643 if (entry.getValue() instanceof DiscoveryCompositeHealthContributor indicator) { indicator.getIndicators().forEach((name, discoveryHealthIndicator) -> { if (!(discoveryHealthIndicator instanceof EurekaHealthIndicator)) { this.healthContributors.put(name, (HealthIndicator) discoveryHealthIndicator::health); } }); } else { this.healthContributors.put(entry.getKey(), entry.getValue()); } } } @Override public InstanceStatus getStatus(InstanceStatus instanceStatus) { if (running) { return getHealthStatus(); } else { // Return nothing if the context is not running, so the status held by the // InstanceInfo remains unchanged. // See gh-1571 return null; } } protected InstanceStatus getHealthStatus() { Status status = getStatus(statusAggregator); return mapToInstanceStatus(status); } protected Status getStatus(StatusAggregator statusAggregator) { Set<Status> statusSet = new HashSet<>(); for (HealthContributor contributor : healthContributors.values()) { processContributor(statusSet, contributor); } for (ReactiveHealthContributor contributor : reactiveHealthContributors.values()) { processContributor(statusSet, contributor); } return statusAggregator.getAggregateStatus(statusSet); } private void processContributor(Set<Status> statusSet, HealthContributor contributor) { if (contributor instanceof CompositeHealthContributor) { for (NamedContributor<HealthContributor> contrib : (CompositeHealthContributor) contributor) { processContributor(statusSet, contrib.getContributor()); } } else if (contributor instanceof HealthIndicator) { statusSet.add(((HealthIndicator) contributor).health().getStatus()); } } private void processContributor(Set<Status> statusSet, ReactiveHealthContributor contributor) { if (contributor instanceof CompositeReactiveHealthContributor) { for (NamedContributor<ReactiveHealthContributor> contrib : (CompositeReactiveHealthContributor) contributor) { processContributor(statusSet, contrib.getContributor()); } } else if (contributor instanceof ReactiveHealthIndicator) { Health health = ((ReactiveHealthIndicator) contributor).health().block(); if (health != null) { statusSet.add(health.getStatus()); } } } protected InstanceStatus mapToInstanceStatus(Status status) { if (!STATUS_MAPPING.containsKey(status)) { return InstanceStatus.UNKNOWN; } return STATUS_MAPPING.get(status); } @Override public int getOrder() {<FILL_FUNCTION_BODY>} @Override public void start() { running = true; } @Override public void stop() { running = false; } @Override public boolean isRunning() { return true; } }
// registered with a high order priority so the close() method is invoked early // and *BEFORE* EurekaAutoServiceRegistration // (must be in effect when the registration is closed and the eureka replication // triggered -> health check handler is // consulted at that moment) return Ordered.HIGHEST_PRECEDENCE;
1,317
91
1,408
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaHealthIndicator.java
EurekaHealthIndicator
health
class EurekaHealthIndicator implements DiscoveryHealthIndicator { private final EurekaClient eurekaClient; private final EurekaInstanceConfig instanceConfig; private final EurekaClientConfig clientConfig; public EurekaHealthIndicator(EurekaClient eurekaClient, EurekaInstanceConfig instanceConfig, EurekaClientConfig clientConfig) { super(); this.eurekaClient = eurekaClient; this.instanceConfig = instanceConfig; this.clientConfig = clientConfig; } @Override public String getName() { return "eureka"; } @Override public Health health() {<FILL_FUNCTION_BODY>} private Status getStatus(Builder builder) { Status status = new Status(this.eurekaClient.getInstanceRemoteStatus().toString(), "Remote status from Eureka server"); DiscoveryClient discoveryClient = getDiscoveryClient(); if (discoveryClient != null && clientConfig.shouldFetchRegistry()) { long lastFetch = discoveryClient.getLastSuccessfulRegistryFetchTimePeriod(); if (lastFetch < 0) { status = new Status("UP", "Eureka discovery client has not yet successfully connected to a Eureka server"); } else if (lastFetch > clientConfig.getRegistryFetchIntervalSeconds() * 2000) { status = new Status("UP", "Eureka discovery client is reporting failures to connect to a Eureka server"); builder.withDetail("renewalPeriod", instanceConfig.getLeaseRenewalIntervalInSeconds()); builder.withDetail("failCount", lastFetch / clientConfig.getRegistryFetchIntervalSeconds()); } } return status; } private DiscoveryClient getDiscoveryClient() { DiscoveryClient discoveryClient = null; if (AopUtils.isAopProxy(eurekaClient)) { discoveryClient = ProxyUtils.getTargetObject(eurekaClient); } else if (eurekaClient instanceof DiscoveryClient) { discoveryClient = (DiscoveryClient) eurekaClient; } return discoveryClient; } private Map<String, Object> getApplications() { Applications applications = this.eurekaClient.getApplications(); if (applications == null) { return Collections.emptyMap(); } Map<String, Object> result = new HashMap<>(); for (Application application : applications.getRegisteredApplications()) { if (!application.getInstances().isEmpty()) { result.put(application.getName(), application.getInstances().size()); } } return result; } }
Builder builder = Health.unknown(); Status status = getStatus(builder); return builder.status(status).withDetail("applications", getApplications()).build();
689
44
733
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/EurekaServiceInstance.java
EurekaServiceInstance
equals
class EurekaServiceInstance implements ServiceInstance { private final InstanceInfo instance; public EurekaServiceInstance(InstanceInfo instance) { Assert.notNull(instance, "Service instance required"); this.instance = instance; } public InstanceInfo getInstanceInfo() { return instance; } @Override public String getInstanceId() { return this.instance.getId(); } @Override public String getServiceId() { return this.instance.getAppName(); } @Override public String getHost() { return this.instance.getHostName(); } @Override public int getPort() { if (isSecure()) { return this.instance.getSecurePort(); } return this.instance.getPort(); } @Override public boolean isSecure() { // assume if secure is enabled, that is the default return this.instance.isPortEnabled(SECURE); } @Override public URI getUri() { return DefaultServiceInstance.getUri(this); } @Override public Map<String, String> getMetadata() { return this.instance.getMetadata(); } @Override public String getScheme() { return getUri().getScheme(); } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(this.instance); } @Override public String toString() { return new ToStringCreator(this).append("instance", instance).toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EurekaServiceInstance that = (EurekaServiceInstance) o; return Objects.equals(this.instance, that.instance);
401
82
483
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/InstanceInfoFactory.java
InstanceInfoFactory
create
class InstanceInfoFactory { private static final Log log = LogFactory.getLog(InstanceInfoFactory.class); public InstanceInfo create(EurekaInstanceConfig config) {<FILL_FUNCTION_BODY>} }
LeaseInfo.Builder leaseInfoBuilder = LeaseInfo.Builder.newBuilder() .setRenewalIntervalInSecs(config.getLeaseRenewalIntervalInSeconds()) .setDurationInSecs(config.getLeaseExpirationDurationInSeconds()); // Builder the instance information to be registered with eureka // server InstanceInfo.Builder builder = InstanceInfo.Builder.newBuilder(); String namespace = config.getNamespace(); if (!namespace.endsWith(".")) { namespace = namespace + "."; } builder.setNamespace(namespace).setAppName(config.getAppname()).setInstanceId(config.getInstanceId()) .setAppGroupName(config.getAppGroupName()).setDataCenterInfo(config.getDataCenterInfo()) .setIPAddr(config.getIpAddress()).setHostName(config.getHostName(false)) .setPort(config.getNonSecurePort()) .enablePort(InstanceInfo.PortType.UNSECURE, config.isNonSecurePortEnabled()) .setSecurePort(config.getSecurePort()) .enablePort(InstanceInfo.PortType.SECURE, config.getSecurePortEnabled()) .setVIPAddress(config.getVirtualHostName()).setSecureVIPAddress(config.getSecureVirtualHostName()) .setHomePageUrl(config.getHomePageUrlPath(), config.getHomePageUrl()) .setStatusPageUrl(config.getStatusPageUrlPath(), config.getStatusPageUrl()) .setHealthCheckUrls(config.getHealthCheckUrlPath(), config.getHealthCheckUrl(), config.getSecureHealthCheckUrl()) .setASGName(config.getASGName()); // Start off with the STARTING state to avoid traffic if (!config.isInstanceEnabledOnit()) { InstanceInfo.InstanceStatus initialStatus = InstanceInfo.InstanceStatus.STARTING; if (log.isInfoEnabled()) { log.info("Setting initial instance status as: " + initialStatus); } builder.setStatus(initialStatus); } else { if (log.isInfoEnabled()) { log.info("Setting initial instance status as: " + InstanceInfo.InstanceStatus.UP + ". This may be too early for the instance to advertise itself as available. " + "You would instead want to control this via a healthcheck handler."); } } // Add any user-specific metadata information for (Map.Entry<String, String> mapEntry : config.getMetadataMap().entrySet()) { String key = mapEntry.getKey(); String value = mapEntry.getValue(); // only add the metadata if the value is present if (value != null && !value.isEmpty()) { builder.add(key, value); } } InstanceInfo instanceInfo = builder.build(); instanceInfo.setLeaseInfo(leaseInfoBuilder.build()); return instanceInfo;
58
744
802
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/RestTemplateTimeoutProperties.java
RestTemplateTimeoutProperties
equals
class RestTemplateTimeoutProperties { /** * Default values are set to 180000, in keeping with {@link RequestConfig} and * {@link SocketConfig} defaults. */ private int connectTimeout = 3 * 60 * 1000; private int connectRequestTimeout = 3 * 60 * 1000; private int socketTimeout = 3 * 60 * 1000; public int getConnectTimeout() { return connectTimeout; } public int getConnectRequestTimeout() { return connectRequestTimeout; } public int getSocketTimeout() { return socketTimeout; } public void setConnectTimeout(int connectTimeout) { this.connectTimeout = connectTimeout; } public void setConnectRequestTimeout(int connectRequestTimeout) { this.connectRequestTimeout = connectRequestTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(connectTimeout, connectRequestTimeout, socketTimeout); } @Override public String toString() { return "RestTemplateTimeoutProperties{" + ", connectTimeout=" + connectTimeout + ", connectRequestTimeout=" + connectRequestTimeout + ", socketTimeout=" + socketTimeout + '}'; } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RestTemplateTimeoutProperties that = (RestTemplateTimeoutProperties) o; return connectTimeout == that.connectTimeout && connectRequestTimeout == that.connectRequestTimeout && socketTimeout == that.socketTimeout;
354
97
451
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/DiscoveryClientOptionalArgsConfiguration.java
DiscoveryClientOptionalArgsConfiguration
setupTLS
class DiscoveryClientOptionalArgsConfiguration { protected static final Log logger = LogFactory.getLog(DiscoveryClientOptionalArgsConfiguration.class); @Bean @ConfigurationProperties("eureka.client.tls") public TlsProperties tlsProperties() { return new TlsProperties(); } @Bean @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") @ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient") @ConditionalOnMissingBean(value = { AbstractDiscoveryClientOptionalArgs.class }, search = SearchStrategy.CURRENT) @ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", matchIfMissing = true, havingValue = "false") public RestTemplateDiscoveryClientOptionalArgs restTemplateDiscoveryClientOptionalArgs(TlsProperties tlsProperties, EurekaClientHttpRequestFactorySupplier eurekaClientHttpRequestFactorySupplier, ObjectProvider<RestTemplateBuilder> restTemplateBuilders) throws GeneralSecurityException, IOException { logger.info("Eureka HTTP Client uses RestTemplate."); RestTemplateDiscoveryClientOptionalArgs result = new RestTemplateDiscoveryClientOptionalArgs( eurekaClientHttpRequestFactorySupplier, restTemplateBuilders::getIfAvailable); setupTLS(result, tlsProperties); return result; } @Bean @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") @ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient") @ConditionalOnMissingBean(value = { TransportClientFactories.class }, search = SearchStrategy.CURRENT) @ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", matchIfMissing = true, havingValue = "false") public RestTemplateTransportClientFactories restTemplateTransportClientFactories( RestTemplateDiscoveryClientOptionalArgs optionalArgs) { return new RestTemplateTransportClientFactories(optionalArgs); } @Bean @ConditionalOnMissingBean @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") EurekaClientHttpRequestFactorySupplier defaultEurekaClientHttpRequestFactorySupplier( RestTemplateTimeoutProperties restTemplateTimeoutProperties) { return new DefaultEurekaClientHttpRequestFactorySupplier(restTemplateTimeoutProperties); } private static void setupTLS(AbstractDiscoveryClientOptionalArgs<?> args, TlsProperties properties) throws GeneralSecurityException, IOException {<FILL_FUNCTION_BODY>} @Configuration(proxyBeanMethods = false) @ConditionalOnClass(name = "org.glassfish.jersey.client.JerseyClient") @ConditionalOnBean(value = AbstractDiscoveryClientOptionalArgs.class, search = SearchStrategy.CURRENT) static class DiscoveryClientOptionalArgsTlsConfiguration { DiscoveryClientOptionalArgsTlsConfiguration(TlsProperties tlsProperties, AbstractDiscoveryClientOptionalArgs optionalArgs) throws GeneralSecurityException, IOException { logger.info("Eureka HTTP Client uses Jersey"); setupTLS(optionalArgs, tlsProperties); } } @ConditionalOnMissingClass("org.glassfish.jersey.client.JerseyClient") @ConditionalOnClass(name = "org.springframework.web.reactive.function.client.WebClient") @ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", havingValue = "true") protected static class WebClientConfiguration { @Autowired private TlsProperties tlsProperties; @Bean @ConditionalOnMissingBean( value = { AbstractDiscoveryClientOptionalArgs.class, RestTemplateDiscoveryClientOptionalArgs.class }, search = SearchStrategy.CURRENT) public WebClientDiscoveryClientOptionalArgs webClientDiscoveryClientOptionalArgs( ObjectProvider<WebClient.Builder> builder) throws GeneralSecurityException, IOException { logger.info("Eureka HTTP Client uses WebClient."); WebClientDiscoveryClientOptionalArgs result = new WebClientDiscoveryClientOptionalArgs( builder::getIfAvailable); setupTLS(result, tlsProperties); return result; } @Bean @ConditionalOnMissingBean(value = TransportClientFactories.class, search = SearchStrategy.CURRENT) public WebClientTransportClientFactories webClientTransportClientFactories( ObjectProvider<WebClient.Builder> builder) { return new WebClientTransportClientFactories(builder::getIfAvailable); } } @Configuration @ConditionalOnMissingClass({ "org.glassfish.jersey.client.JerseyClient", "org.springframework.web.reactive.function.client.WebClient" }) @ConditionalOnProperty(prefix = "eureka.client", name = "webclient.enabled", havingValue = "true") protected static class WebClientNotFoundConfiguration { public WebClientNotFoundConfiguration() { throw new IllegalStateException( "eureka.client.webclient.enabled is true, " + "but WebClient is not on the classpath. Please add " + "spring-boot-starter-webflux as a dependency."); } } }
if (properties.isEnabled()) { SSLContextFactory factory = new SSLContextFactory(properties); args.setSSLContext(factory.createSSLContext()); }
1,292
46
1,338
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaClientConfigServerAutoConfiguration.java
EurekaClientConfigServerAutoConfiguration
init
class EurekaClientConfigServerAutoConfiguration { @Autowired(required = false) private EurekaInstanceConfig instance; @Autowired private Environment env; @PostConstruct public void init() {<FILL_FUNCTION_BODY>} }
if (this.instance == null) { return; } String prefix = this.env.getProperty("spring.cloud.config.server.prefix"); if (StringUtils.hasText(prefix) && !StringUtils.hasText(this.instance.getMetadataMap().get("configPath"))) { this.instance.getMetadataMap().put("configPath", prefix); }
68
98
166
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaConfigServerBootstrapper.java
EurekaConfigServerBootstrapper
initialize
class EurekaConfigServerBootstrapper implements BootstrapRegistryInitializer { @Override public void initialize(BootstrapRegistry registry) {<FILL_FUNCTION_BODY>} private static PropertyResolver getPropertyResolver(BootstrapContext context) { return context.getOrElseSupply(PropertyResolver.class, () -> new PropertyResolver(context.get(Binder.class), context.getOrElse(BindHandler.class, null))); } public static Boolean getDiscoveryEnabled(BootstrapContext bootstrapContext) { PropertyResolver propertyResolver = getPropertyResolver(bootstrapContext); return propertyResolver.get(ConfigClientProperties.CONFIG_DISCOVERY_ENABLED, Boolean.class, false) && propertyResolver.get("eureka.client.enabled", Boolean.class, true) && propertyResolver.get("spring.cloud.discovery.enabled", Boolean.class, true); } }
if (!ClassUtils.isPresent("org.springframework.cloud.config.client.ConfigServerInstanceProvider", null)) { return; } registry.registerIfAbsent(EurekaClientConfigBean.class, context -> { if (!getDiscoveryEnabled(context)) { return null; } PropertyResolver propertyResolver = getPropertyResolver(context); return propertyResolver.resolveConfigurationProperties(EurekaClientConfigBean.PREFIX, EurekaClientConfigBean.class, EurekaClientConfigBean::new); }); registry.registerIfAbsent(ConfigServerInstanceProvider.Function.class, context -> { if (!getDiscoveryEnabled(context)) { return (id) -> Collections.emptyList(); } EurekaClientConfigBean config = context.get(EurekaClientConfigBean.class); EurekaHttpClient httpClient = new RestTemplateTransportClientFactory( context.getOrElse(TlsProperties.class, null), context.getOrElse(EurekaClientHttpRequestFactorySupplier.class, new DefaultEurekaClientHttpRequestFactorySupplier())).newClient( HostnameBasedUrlRandomizer.randomEndpoint(config, getPropertyResolver(context))); return new EurekaConfigServerInstanceProvider(httpClient, config)::getInstances; });
223
342
565
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/EurekaConfigServerInstanceProvider.java
EurekaConfigServerInstanceProvider
getInstances
class EurekaConfigServerInstanceProvider { private final Log log; private final EurekaHttpClient client; private final EurekaClientConfig config; public EurekaConfigServerInstanceProvider(EurekaHttpClient client, EurekaClientConfig config) { this(LogFactory.getLog(EurekaConfigServerInstanceProvider.class), client, config); } public EurekaConfigServerInstanceProvider(Log log, EurekaHttpClient client, EurekaClientConfig config) { this.log = log; this.client = client; this.config = config; } public List<ServiceInstance> getInstances(String serviceId) {<FILL_FUNCTION_BODY>} private boolean isSuccessful(EurekaHttpResponse<Applications> response) { HttpStatus httpStatus = HttpStatus.resolve(response.getStatusCode()); return httpStatus != null && httpStatus.is2xxSuccessful(); } }
if (log.isDebugEnabled()) { log.debug("eurekaConfigServerInstanceProvider finding instances for " + serviceId); } String remoteRegionsStr = config.fetchRegistryForRemoteRegions(); String[] remoteRegions = remoteRegionsStr == null ? null : remoteRegionsStr.split(","); EurekaHttpResponse<Applications> response = config.getRegistryRefreshSingleVipAddress() == null ? client.getApplications(remoteRegions) : client.getVip(config.getRegistryRefreshSingleVipAddress(), remoteRegions); List<ServiceInstance> instances = new ArrayList<>(); if (!isSuccessful(response) || response.getEntity() == null) { return instances; } Applications applications = response.getEntity(); applications.shuffleInstances(config.shouldFilterOnlyUpInstances()); List<InstanceInfo> infos = applications.getInstancesByVirtualHostName(serviceId); for (InstanceInfo info : infos) { instances.add(new EurekaServiceInstance(info)); } if (log.isDebugEnabled()) { log.debug("eurekaConfigServerInstanceProvider found " + infos.size() + " instance(s) for " + serviceId + ", " + instances); } return instances;
237
338
575
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/config/HostnameBasedUrlRandomizer.java
HostnameBasedUrlRandomizer
randomEndpoint
class HostnameBasedUrlRandomizer implements EndpointUtils.ServiceUrlRandomizer { private static final String EUREKA_INSTANCE_HOSTNAME = "eureka.instance.hostname"; private final String hostname; HostnameBasedUrlRandomizer(String hostname) { this.hostname = hostname; } @Override public void randomize(List<String> urlList) { int listSize = 0; if (urlList != null) { listSize = urlList.size(); } if (!StringUtils.hasText(hostname) || listSize == 0) { return; } // Find the hashcode of the instance hostname and use it to find an entry // and then arrange the rest of the entries after this entry. int instanceHashcode = hostname.hashCode(); if (instanceHashcode < 0) { instanceHashcode = instanceHashcode * -1; } int backupInstance = instanceHashcode % listSize; for (int i = 0; i < backupInstance; i++) { String zone = urlList.remove(0); urlList.add(zone); } } public static String getEurekaUrl(EurekaClientConfig config, String hostname) { List<String> urls = EndpointUtils.getDiscoveryServiceUrls(config, EurekaClientConfigBean.DEFAULT_ZONE, new HostnameBasedUrlRandomizer(hostname)); return urls.get(0); } public static DefaultEndpoint randomEndpoint(EurekaClientConfig config, Environment env) { String hostname = env.getProperty(EUREKA_INSTANCE_HOSTNAME); return new DefaultEndpoint(getEurekaUrl(config, hostname)); } public static DefaultEndpoint randomEndpoint(EurekaClientConfig config, Binder binder) {<FILL_FUNCTION_BODY>} public static DefaultEndpoint randomEndpoint(EurekaClientConfig config, PropertyResolver propertyResolver) { String hostname = propertyResolver.get(EUREKA_INSTANCE_HOSTNAME, String.class, null); return new DefaultEndpoint(getEurekaUrl(config, hostname)); } }
String hostname = binder.bind(EUREKA_INSTANCE_HOSTNAME, String.class).orElseGet(() -> null); return new DefaultEndpoint(getEurekaUrl(config, hostname));
547
57
604
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/DefaultEurekaClientHttpRequestFactorySupplier.java
DefaultEurekaClientHttpRequestFactorySupplier
get
class DefaultEurekaClientHttpRequestFactorySupplier implements EurekaClientHttpRequestFactorySupplier { private final RestTemplateTimeoutProperties restTemplateTimeoutProperties; /** * @deprecated in favour of * {@link DefaultEurekaClientHttpRequestFactorySupplier#DefaultEurekaClientHttpRequestFactorySupplier(RestTemplateTimeoutProperties)} */ @Deprecated public DefaultEurekaClientHttpRequestFactorySupplier() { this.restTemplateTimeoutProperties = new RestTemplateTimeoutProperties(); } public DefaultEurekaClientHttpRequestFactorySupplier(RestTemplateTimeoutProperties restTemplateTimeoutProperties) { this.restTemplateTimeoutProperties = restTemplateTimeoutProperties; } @Override public ClientHttpRequestFactory get(SSLContext sslContext, @Nullable HostnameVerifier hostnameVerifier) {<FILL_FUNCTION_BODY>} private HttpClientConnectionManager buildConnectionManager(SSLContext sslContext, HostnameVerifier hostnameVerifier, RestTemplateTimeoutProperties restTemplateTimeoutProperties) { PoolingHttpClientConnectionManagerBuilder connectionManagerBuilder = PoolingHttpClientConnectionManagerBuilder .create(); SSLConnectionSocketFactoryBuilder sslConnectionSocketFactoryBuilder = SSLConnectionSocketFactoryBuilder .create(); if (sslContext != null) { sslConnectionSocketFactoryBuilder.setSslContext(sslContext); } if (hostnameVerifier != null) { sslConnectionSocketFactoryBuilder.setHostnameVerifier(hostnameVerifier); } connectionManagerBuilder.setSSLSocketFactory(sslConnectionSocketFactoryBuilder.build()); if (restTemplateTimeoutProperties != null) { connectionManagerBuilder.setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(Timeout.of(restTemplateTimeoutProperties.getSocketTimeout(), TimeUnit.MILLISECONDS)) .build()); } return connectionManagerBuilder.build(); } private RequestConfig buildRequestConfig() { return RequestConfig.custom() .setConnectTimeout(Timeout.of(restTemplateTimeoutProperties.getConnectTimeout(), TimeUnit.MILLISECONDS)) .setConnectionRequestTimeout( Timeout.of(restTemplateTimeoutProperties.getConnectRequestTimeout(), TimeUnit.MILLISECONDS)) .build(); } }
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); if (sslContext != null || hostnameVerifier != null || restTemplateTimeoutProperties != null) { httpClientBuilder.setConnectionManager( buildConnectionManager(sslContext, hostnameVerifier, restTemplateTimeoutProperties)); } if (restTemplateTimeoutProperties != null) { httpClientBuilder.setDefaultRequestConfig(buildRequestConfig()); } CloseableHttpClient httpClient = httpClientBuilder.build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(); requestFactory.setHttpClient(httpClient); return requestFactory;
546
170
716
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/RestTemplateEurekaHttpClient.java
RestTemplateEurekaHttpClient
register
class RestTemplateEurekaHttpClient implements EurekaHttpClient { private final RestTemplate restTemplate; private String serviceUrl; public RestTemplateEurekaHttpClient(RestTemplate restTemplate, String serviceUrl) { this.restTemplate = restTemplate; this.serviceUrl = serviceUrl; if (!serviceUrl.endsWith("/")) { this.serviceUrl = this.serviceUrl + "/"; } } public String getServiceUrl() { return this.serviceUrl; } public RestTemplate getRestTemplate() { return restTemplate; } @Override public EurekaHttpResponse<Void> register(InstanceInfo info) {<FILL_FUNCTION_BODY>} @Override public EurekaHttpResponse<Void> cancel(String appName, String id) { String urlPath = serviceUrl + "apps/" + appName + '/' + id; ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.DELETE, null, Void.class); return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = serviceUrl + "apps/" + appName + '/' + id + "?status=" + info.getStatus().toString() + "&lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString() + (overriddenStatus != null ? "&overriddenstatus=" + overriddenStatus.name() : ""); ResponseEntity<InstanceInfo> response = restTemplate.exchange(urlPath, HttpMethod.PUT, null, InstanceInfo.class); EurekaHttpResponseBuilder<InstanceInfo> eurekaResponseBuilder = anEurekaHttpResponse( response.getStatusCode().value(), InstanceInfo.class).headers(headersOf(response)); if (response.hasBody()) { eurekaResponseBuilder.entity(response.getBody()); } return eurekaResponseBuilder.build(); } @Override public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) { String urlPath = serviceUrl + "apps/" + appName + '/' + id + "/status?value=" + newStatus.name() + "&lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString(); ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.PUT, null, Void.class); return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) { String urlPath = serviceUrl + "apps/" + appName + '/' + id + "/status?lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString(); ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.DELETE, null, Void.class); return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<Applications> getApplications(String... regions) { return getApplicationsInternal("apps/", regions); } private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath, String[] regions) { String url = serviceUrl + urlPath; if (regions != null && regions.length > 0) { url = url + (urlPath.contains("?") ? "&" : "?") + "regions=" + StringUtil.join(regions); } ResponseEntity<EurekaApplications> response = restTemplate.exchange(url, HttpMethod.GET, null, EurekaApplications.class); return anEurekaHttpResponse(response.getStatusCode().value(), response.getStatusCode().value() == HttpStatus.OK.value() && response.hasBody() ? (Applications) response.getBody() : null).headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<Applications> getDelta(String... regions) { return getApplicationsInternal("apps/delta", regions); } @Override public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) { return getApplicationsInternal("vips/" + vipAddress, regions); } @Override public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) { return getApplicationsInternal("svips/" + secureVipAddress, regions); } @Override public EurekaHttpResponse<Application> getApplication(String appName) { String urlPath = serviceUrl + "apps/" + appName; ResponseEntity<Application> response = restTemplate.exchange(urlPath, HttpMethod.GET, null, Application.class); Application application = response.getStatusCode().value() == HttpStatus.OK.value() && response.hasBody() ? response.getBody() : null; return anEurekaHttpResponse(response.getStatusCode().value(), application).headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) { return getInstanceInternal("apps/" + appName + '/' + id); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String id) { return getInstanceInternal("instances/" + id); } private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) { urlPath = serviceUrl + urlPath; ResponseEntity<InstanceInfo> response = restTemplate.exchange(urlPath, HttpMethod.GET, null, InstanceInfo.class); return anEurekaHttpResponse(response.getStatusCode().value(), response.getStatusCode().value() == HttpStatus.OK.value() && response.hasBody() ? response.getBody() : null).headers(headersOf(response)).build(); } @Override public void shutdown() { // Nothing to do } private static Map<String, String> headersOf(ResponseEntity<?> response) { HttpHeaders httpHeaders = response.getHeaders(); if (httpHeaders == null || httpHeaders.isEmpty()) { return Collections.emptyMap(); } Map<String, String> headers = new HashMap<>(); for (Entry<String, List<String>> entry : httpHeaders.entrySet()) { if (!entry.getValue().isEmpty()) { headers.put(entry.getKey(), entry.getValue().get(0)); } } return headers; } }
String urlPath = serviceUrl + "apps/" + info.getAppName(); HttpHeaders headers = new HttpHeaders(); headers.add(HttpHeaders.ACCEPT_ENCODING, "gzip"); headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE); ResponseEntity<Void> response = restTemplate.exchange(urlPath, HttpMethod.POST, new HttpEntity<>(info, headers), Void.class); return anEurekaHttpResponse(response.getStatusCode().value()).headers(headersOf(response)).build();
1,755
153
1,908
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientEurekaHttpClient.java
WebClientEurekaHttpClient
statusUpdate
class WebClientEurekaHttpClient implements EurekaHttpClient { private WebClient webClient; public WebClientEurekaHttpClient(WebClient webClient) { this.webClient = webClient; } @Override public EurekaHttpResponse<Void> register(InstanceInfo info) { return webClient.post().uri("apps/" + info.getAppName()).body(BodyInserters.fromValue(info)) .header(HttpHeaders.ACCEPT_ENCODING, "gzip") .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).retrieve() .onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity().map(this::eurekaHttpResponse) .block(); } @Override public EurekaHttpResponse<Void> cancel(String appName, String id) { return webClient.delete().uri("apps/" + appName + '/' + id).retrieve() .onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity().map(this::eurekaHttpResponse) .block(); } @Override public EurekaHttpResponse<InstanceInfo> sendHeartBeat(String appName, String id, InstanceInfo info, InstanceStatus overriddenStatus) { String urlPath = "apps/" + appName + '/' + id + "?status=" + info.getStatus().toString() + "&lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString() + (overriddenStatus != null ? "&overriddenstatus=" + overriddenStatus.name() : ""); ResponseEntity<InstanceInfo> response = webClient.put().uri(urlPath) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve() .onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(InstanceInfo.class).block(); EurekaHttpResponseBuilder<InstanceInfo> builder = anEurekaHttpResponse(statusCodeValueOf(response), InstanceInfo.class).headers(headersOf(response)); InstanceInfo entity = response.getBody(); if (entity != null) { builder.entity(entity); } return builder.build(); } @Override public EurekaHttpResponse<Void> statusUpdate(String appName, String id, InstanceStatus newStatus, InstanceInfo info) {<FILL_FUNCTION_BODY>} @Override public EurekaHttpResponse<Void> deleteStatusOverride(String appName, String id, InstanceInfo info) { String urlPath = "apps/" + appName + '/' + id + "/status?lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString(); return webClient.delete().uri(urlPath).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .retrieve().onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity() .map(this::eurekaHttpResponse).block(); } @Override public EurekaHttpResponse<Applications> getApplications(String... regions) { return getApplicationsInternal("apps/", regions); } private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath, String[] regions) { String url = urlPath; if (regions != null && regions.length > 0) { url = url + (urlPath.contains("?") ? "&" : "?") + "regions=" + StringUtil.join(regions); } ResponseEntity<Applications> response = webClient.get().uri(url) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve() .onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(Applications.class).block(); int statusCode = statusCodeValueOf(response); Applications body = response.getBody(); return anEurekaHttpResponse(statusCode, statusCode == HttpStatus.OK.value() && body != null ? body : null) .headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<Applications> getDelta(String... regions) { return getApplicationsInternal("apps/delta", regions); } @Override public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) { return getApplicationsInternal("vips/" + vipAddress, regions); } @Override public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) { return getApplicationsInternal("svips/" + secureVipAddress, regions); } @Override public EurekaHttpResponse<Application> getApplication(String appName) { ResponseEntity<Application> response = webClient.get().uri("apps/" + appName) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve() .onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(Application.class).block(); int statusCode = statusCodeValueOf(response); Application body = response.getBody(); Application application = statusCode == HttpStatus.OK.value() && body != null ? body : null; return anEurekaHttpResponse(statusCode, application).headers(headersOf(response)).build(); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String appName, String id) { return getInstanceInternal("apps/" + appName + '/' + id); } @Override public EurekaHttpResponse<InstanceInfo> getInstance(String id) { return getInstanceInternal("instances/" + id); } private EurekaHttpResponse<InstanceInfo> getInstanceInternal(String urlPath) { ResponseEntity<InstanceInfo> response = webClient.get().uri(urlPath) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).retrieve() .onStatus(HttpStatusCode::isError, this::ignoreError).toEntity(InstanceInfo.class).block(); int statusCode = statusCodeValueOf(response); InstanceInfo body = response.getBody(); return anEurekaHttpResponse(statusCode, statusCode == HttpStatus.OK.value() && body != null ? body : null) .headers(headersOf(response)).build(); } @Override public void shutdown() { // Nothing to do } public WebClient getWebClient() { return this.webClient; } private Mono<? extends Throwable> ignoreError(ClientResponse response) { return Mono.empty(); } private static Map<String, String> headersOf(ResponseEntity<?> response) { return response.getHeaders().toSingleValueMap(); } private int statusCodeValueOf(ResponseEntity<?> response) { return response.getStatusCode().value(); } private EurekaHttpResponse<Void> eurekaHttpResponse(ResponseEntity<?> response) { return anEurekaHttpResponse(statusCodeValueOf(response)).headers(headersOf(response)).build(); } }
String urlPath = "apps/" + appName + '/' + id + "/status?value=" + newStatus.name() + "&lastDirtyTimestamp=" + info.getLastDirtyTimestamp().toString(); return webClient.put().uri(urlPath).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .retrieve().onStatus(HttpStatusCode::isError, this::ignoreError).toBodilessEntity() .map(this::eurekaHttpResponse).block();
1,874
133
2,007
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/http/WebClientTransportClientFactory.java
WebClientTransportClientFactory
http4XxErrorExchangeFilterFunction
class WebClientTransportClientFactory implements TransportClientFactory { private final Supplier<WebClient.Builder> builderSupplier; public WebClientTransportClientFactory(Supplier<WebClient.Builder> builderSupplier) { this.builderSupplier = builderSupplier; } @Override public EurekaHttpClient newClient(EurekaEndpoint endpoint) { // we want a copy to modify. Don't change the original WebClient.Builder builder = this.builderSupplier.get().clone(); setUrl(builder, endpoint.getServiceUrl()); setCodecs(builder); builder.filter(http4XxErrorExchangeFilterFunction()); return new WebClientEurekaHttpClient(builder.build()); } private WebClient.Builder setUrl(WebClient.Builder builder, String serviceUrl) { String url = UriComponentsBuilder.fromUriString(serviceUrl).userInfo(null).toUriString(); try { URI serviceURI = new URI(serviceUrl); if (serviceURI.getUserInfo() != null) { String[] credentials = serviceURI.getUserInfo().split(":"); if (credentials.length == 2) { builder.filter(ExchangeFilterFunctions.basicAuthentication(credentials[0], credentials[1])); } } } catch (URISyntaxException ignore) { } return builder.baseUrl(url); } private static BeanSerializerModifier createJsonSerializerModifier() { return new BeanSerializerModifier() { @Override public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) { if (beanDesc.getBeanClass().isAssignableFrom(InstanceInfo.class)) { return new InstanceInfoJsonBeanSerializer((BeanSerializerBase) serializer, false); } return serializer; } }; } private void setCodecs(WebClient.Builder builder) { ObjectMapper objectMapper = objectMapper(); builder.codecs(configurer -> { ClientCodecConfigurer.ClientDefaultCodecs defaults = configurer.defaultCodecs(); defaults.jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON)); defaults.jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON)); }); } /** * Provides the serialization configurations required by the Eureka Server. JSON * content exchanged with eureka requires a root node matching the entity being * serialized or deserialized. Achieved with * {@link SerializationFeature#WRAP_ROOT_VALUE} and * {@link DeserializationFeature#UNWRAP_ROOT_VALUE}. * {@link PropertyNamingStrategies.SnakeCaseStrategy} is applied to the underlying * {@link ObjectMapper}. * @return a {@link ObjectMapper} object */ private ObjectMapper objectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE); SimpleModule jsonModule = new SimpleModule(); jsonModule.setSerializerModifier(createJsonSerializerModifier()); objectMapper.registerModule(jsonModule); objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); objectMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class); objectMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class); return objectMapper; } // Skip over 4xx http errors private ExchangeFilterFunction http4XxErrorExchangeFilterFunction() {<FILL_FUNCTION_BODY>} @Override public void shutdown() { } }
return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> { // literally 400 pass the tests, not 4xxClientError if (clientResponse.statusCode().value() == 400) { ClientResponse newResponse = clientResponse.mutate().statusCode(HttpStatus.OK).build(); newResponse.body((clientHttpResponse, context) -> clientHttpResponse.getBody()); return Mono.just(newResponse); } if (clientResponse.statusCode().equals(HttpStatus.NOT_FOUND)) { ClientResponse newResponse = clientResponse.mutate().statusCode(clientResponse.statusCode()) // ignore body on 404 for heartbeat, see gh-4145 .body(Flux.empty()).build(); return Mono.just(newResponse); } return Mono.just(clientResponse); });
985
222
1,207
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/loadbalancer/EurekaLoadBalancerClientConfiguration.java
EurekaLoadBalancerClientConfiguration
getZoneFromEureka
class EurekaLoadBalancerClientConfiguration { private static final Log LOG = LogFactory.getLog(EurekaLoadBalancerClientConfiguration.class); private final EurekaClientConfig clientConfig; private final EurekaInstanceConfig eurekaConfig; private final LoadBalancerZoneConfig zoneConfig; private final EurekaLoadBalancerProperties eurekaLoadBalancerProperties; public EurekaLoadBalancerClientConfiguration(@Autowired(required = false) EurekaClientConfig clientConfig, @Autowired(required = false) EurekaInstanceConfig eurekaInstanceConfig, LoadBalancerZoneConfig zoneConfig, EurekaLoadBalancerProperties eurekaLoadBalancerProperties) { this.clientConfig = clientConfig; this.eurekaConfig = eurekaInstanceConfig; this.zoneConfig = zoneConfig; this.eurekaLoadBalancerProperties = eurekaLoadBalancerProperties; } @PostConstruct public void postprocess() { if (StringUtils.hasText(zoneConfig.getZone())) { return; } String zone = getZoneFromEureka(); if (StringUtils.hasText(zone)) { if (LOG.isDebugEnabled()) { LOG.debug("Setting the value of '" + LOADBALANCER_ZONE + "' to " + zone); } zoneConfig.setZone(zone); } } private String getZoneFromEureka() {<FILL_FUNCTION_BODY>} }
String zone; boolean approximateZoneFromHostname = eurekaLoadBalancerProperties.isApproximateZoneFromHostname(); if (approximateZoneFromHostname && eurekaConfig != null) { return ZoneUtils.extractApproximateZone(this.eurekaConfig.getHostName(false)); } else { zone = eurekaConfig == null ? null : eurekaConfig.getMetadataMap().get("zone"); if (!StringUtils.hasText(zone) && clientConfig != null) { String[] zones = clientConfig.getAvailabilityZones(clientConfig.getRegion()); // Pick the first one from the regions we want to connect to zone = zones != null && zones.length > 0 ? zones[0] : null; } return zone; }
375
207
582
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/DefaultManagementMetadataProvider.java
DefaultManagementMetadataProvider
constructValidUrl
class DefaultManagementMetadataProvider implements ManagementMetadataProvider { private static final int RANDOM_PORT = 0; private static final Log log = LogFactory.getLog(DefaultManagementMetadataProvider.class); @Override public ManagementMetadata get(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, String managementContextPath, Integer managementPort) { if (isRandom(managementPort)) { return null; } if (managementPort == null && isRandom(serverPort)) { return null; } String healthCheckUrl = getHealthCheckUrl(instance, serverPort, serverContextPath, managementContextPath, managementPort, false); String statusPageUrl = getStatusPageUrl(instance, serverPort, serverContextPath, managementContextPath, managementPort); ManagementMetadata metadata = new ManagementMetadata(healthCheckUrl, statusPageUrl, managementPort == null ? serverPort : managementPort); if (instance.isSecurePortEnabled()) { metadata.setSecureHealthCheckUrl(getHealthCheckUrl(instance, serverPort, serverContextPath, managementContextPath, managementPort, true)); } return metadata; } private boolean isRandom(Integer port) { return port != null && port == RANDOM_PORT; } protected String getHealthCheckUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, String managementContextPath, Integer managementPort, boolean isSecure) { String healthCheckUrlPath = instance.getHealthCheckUrlPath(); String healthCheckUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath, managementPort, healthCheckUrlPath, isSecure); log.debug("Constructed eureka meta-data healthcheckUrl: " + healthCheckUrl); return healthCheckUrl; } public String getStatusPageUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, String managementContextPath, Integer managementPort) { String statusPageUrlPath = instance.getStatusPageUrlPath(); String statusPageUrl = getUrl(instance, serverPort, serverContextPath, managementContextPath, managementPort, statusPageUrlPath, false); log.debug("Constructed eureka meta-data statusPageUrl: " + statusPageUrl); return statusPageUrl; } private String getUrl(EurekaInstanceConfigBean instance, int serverPort, String serverContextPath, String managementContextPath, Integer managementPort, String urlPath, boolean isSecure) { managementContextPath = refineManagementContextPath(serverContextPath, managementContextPath, managementPort); if (managementPort == null) { managementPort = serverPort; } String scheme = isSecure ? "https" : "http"; return constructValidUrl(scheme, instance.getHostname(), managementPort, managementContextPath, urlPath); } private String refineManagementContextPath(String serverContextPath, String managementContextPath, Integer managementPort) { // management context path is relative to server context path when no management // port is set if (managementContextPath != null && managementPort == null) { return serverContextPath + managementContextPath; } if (managementContextPath != null) { return managementContextPath; } if (managementPort != null) { return "/"; } return serverContextPath; } private String constructValidUrl(String scheme, String hostname, int port, String contextPath, String statusPath) {<FILL_FUNCTION_BODY>} private String refinedStatusPath(String statusPath, String contextPath) { if (statusPath.startsWith(contextPath) && !"/".equals(contextPath)) { statusPath = StringUtils.replace(statusPath, contextPath, ""); } return StringUtils.trimLeadingCharacter(statusPath, '/'); } private String getErrorMessage(String scheme, String hostname, int port, String contextPath, String statusPath) { return String.format( "Failed to construct url for scheme: %s, hostName: %s port: %s contextPath: %s statusPath: %s", scheme, hostname, port, contextPath, statusPath); } }
try { if (!contextPath.endsWith("/")) { contextPath = contextPath + "/"; } String refinedContextPath = '/' + StringUtils.trimLeadingCharacter(contextPath, '/'); URL base = new URL(scheme, hostname, port, refinedContextPath); String refinedStatusPath = refinedStatusPath(statusPath, contextPath); return new URL(base, refinedStatusPath).toString(); } catch (MalformedURLException e) { String message = getErrorMessage(scheme, hostname, port, contextPath, statusPath); throw new IllegalStateException(message, e); }
1,044
161
1,205
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/metadata/ManagementMetadata.java
ManagementMetadata
equals
class ManagementMetadata { private final String healthCheckUrl; private final String statusPageUrl; private final Integer managementPort; private String secureHealthCheckUrl; public ManagementMetadata(String healthCheckUrl, String statusPageUrl, Integer managementPort) { this.healthCheckUrl = healthCheckUrl; this.statusPageUrl = statusPageUrl; this.managementPort = managementPort; this.secureHealthCheckUrl = null; } public String getHealthCheckUrl() { return healthCheckUrl; } public String getStatusPageUrl() { return statusPageUrl; } public Integer getManagementPort() { return managementPort; } public String getSecureHealthCheckUrl() { return secureHealthCheckUrl; } public void setSecureHealthCheckUrl(String secureHealthCheckUrl) { this.secureHealthCheckUrl = secureHealthCheckUrl; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(healthCheckUrl, statusPageUrl, managementPort); } @Override public String toString() { final StringBuilder sb = new StringBuilder("ManagementMetadata{"); sb.append("healthCheckUrl='").append(healthCheckUrl).append('\''); sb.append(", statusPageUrl='").append(statusPageUrl).append('\''); sb.append(", managementPort=").append(managementPort); sb.append('}'); return sb.toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ManagementMetadata that = (ManagementMetadata) o; return Objects.equals(healthCheckUrl, that.healthCheckUrl) && Objects.equals(statusPageUrl, that.statusPageUrl) && Objects.equals(managementPort, that.managementPort);
388
110
498
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/reactive/EurekaReactiveDiscoveryClient.java
EurekaReactiveDiscoveryClient
getServices
class EurekaReactiveDiscoveryClient implements ReactiveDiscoveryClient { private final EurekaClient eurekaClient; private final EurekaClientConfig clientConfig; public EurekaReactiveDiscoveryClient(EurekaClient eurekaClient, EurekaClientConfig clientConfig) { this.eurekaClient = eurekaClient; this.clientConfig = clientConfig; } @Override public String description() { return "Spring Cloud Eureka Reactive Discovery Client"; } @Override public Flux<ServiceInstance> getInstances(String serviceId) { return Flux.defer(() -> Flux.fromIterable(eurekaClient.getInstancesByVipAddress(serviceId, false))) .map(EurekaServiceInstance::new); } @Override public Flux<String> getServices() {<FILL_FUNCTION_BODY>} @Override public int getOrder() { return clientConfig instanceof Ordered ? ((Ordered) clientConfig).getOrder() : ReactiveDiscoveryClient.DEFAULT_ORDER; } }
return Flux.defer(() -> Mono.justOrEmpty(eurekaClient.getApplications())) .flatMapIterable(Applications::getRegisteredApplications) .filter(application -> !application.getInstances().isEmpty()).map(Application::getName) .map(String::toLowerCase);
274
81
355
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaAutoServiceRegistration.java
EurekaAutoServiceRegistration
start
class EurekaAutoServiceRegistration implements AutoServiceRegistration, SmartLifecycle, Ordered, SmartApplicationListener { private static final Log log = LogFactory.getLog(EurekaAutoServiceRegistration.class); private final AtomicBoolean running = new AtomicBoolean(false); private final int order = 0; private final AtomicInteger port = new AtomicInteger(0); private final ApplicationContext context; private final EurekaServiceRegistry serviceRegistry; private final EurekaRegistration registration; public EurekaAutoServiceRegistration(ApplicationContext context, EurekaServiceRegistry serviceRegistry, EurekaRegistration registration) { this.context = context; this.serviceRegistry = serviceRegistry; this.registration = registration; } @Override public void start() {<FILL_FUNCTION_BODY>} @Override public void stop() { serviceRegistry.deregister(registration); running.set(false); } @Override public boolean isRunning() { return running.get(); } @Override public int getPhase() { return 0; } @Override public boolean isAutoStartup() { return true; } @Override public void stop(Runnable callback) { stop(); callback.run(); } @Override public int getOrder() { return order; } @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return WebServerInitializedEvent.class.isAssignableFrom(eventType) || ContextClosedEvent.class.isAssignableFrom(eventType); } @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof WebServerInitializedEvent) { onApplicationEvent((WebServerInitializedEvent) event); } else if (event instanceof ContextClosedEvent) { onApplicationEvent((ContextClosedEvent) event); } } public void onApplicationEvent(WebServerInitializedEvent event) { // TODO: take SSL into account String contextName = event.getApplicationContext().getServerNamespace(); if (contextName == null || !contextName.equals("management")) { int localPort = event.getWebServer().getPort(); if (port.get() == 0) { log.info("Updating port to " + localPort); port.compareAndSet(0, localPort); start(); } } } public void onApplicationEvent(ContextClosedEvent event) { if (event.getApplicationContext() == context) { stop(); } } }
// only set the port if the nonSecurePort or securePort is 0 and port != 0 if (port.get() != 0) { if (registration.getNonSecurePort() == 0) { registration.setNonSecurePort(port.get()); } if (registration.getSecurePort() == 0 && registration.isSecure()) { registration.setSecurePort(port.get()); } } // only initialize if nonSecurePort is greater than 0 and it isn't already running // because of containerPortInitializer below if (!running.get() && registration.getNonSecurePort() > 0) { context.publishEvent(new InstancePreRegisteredEvent(this, registration)); serviceRegistry.register(registration); context.publishEvent(new InstanceRegisteredEvent<>(this, registration.getInstanceConfig())); running.set(true); }
667
244
911
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaRegistration.java
Builder
build
class Builder { private final CloudEurekaInstanceConfig instanceConfig; private ApplicationInfoManager applicationInfoManager; private EurekaClient eurekaClient; private ObjectProvider<HealthCheckHandler> healthCheckHandler; private EurekaClientConfig clientConfig; private ApplicationEventPublisher publisher; private TransportClientFactories<?> transportClientFactories; Builder(CloudEurekaInstanceConfig instanceConfig) { this.instanceConfig = instanceConfig; } public Builder with(ApplicationInfoManager applicationInfoManager) { this.applicationInfoManager = applicationInfoManager; return this; } public Builder with(EurekaClient eurekaClient) { this.eurekaClient = eurekaClient; return this; } public Builder with(ObjectProvider<HealthCheckHandler> healthCheckHandler) { this.healthCheckHandler = healthCheckHandler; return this; } public Builder with(TransportClientFactories<?> transportClientFactories) { this.transportClientFactories = transportClientFactories; return this; } public Builder with(EurekaClientConfig clientConfig, ApplicationEventPublisher publisher) { this.clientConfig = clientConfig; this.publisher = publisher; return this; } public EurekaRegistration build() {<FILL_FUNCTION_BODY>} }
Assert.notNull(instanceConfig, "instanceConfig may not be null"); if (this.applicationInfoManager == null) { InstanceInfo instanceInfo = new InstanceInfoFactory().create(this.instanceConfig); this.applicationInfoManager = new ApplicationInfoManager(this.instanceConfig, instanceInfo); } if (this.eurekaClient == null) { Assert.notNull(this.clientConfig, "if eurekaClient is null, EurekaClientConfig may not be null"); Assert.notNull(this.publisher, "if eurekaClient is null, ApplicationEventPublisher may not be null"); Assert.notNull(this.transportClientFactories, "if eurekaClient is null, TransportClientFactories may not be null"); this.eurekaClient = new CloudEurekaClient(this.applicationInfoManager, this.clientConfig, this.transportClientFactories, this.publisher); } return new EurekaRegistration(instanceConfig, eurekaClient, applicationInfoManager, healthCheckHandler);
355
264
619
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/serviceregistry/EurekaServiceRegistry.java
EurekaServiceRegistry
deregister
class EurekaServiceRegistry implements ServiceRegistry<EurekaRegistration> { private static final Log log = LogFactory.getLog(EurekaServiceRegistry.class); private EurekaInstanceConfigBean eurekaInstanceConfigBean; public EurekaServiceRegistry() { } public EurekaServiceRegistry(EurekaInstanceConfigBean eurekaInstanceConfigBean) { this.eurekaInstanceConfigBean = eurekaInstanceConfigBean; } @Override public void register(EurekaRegistration reg) { if (eurekaInstanceConfigBean != null && eurekaInstanceConfigBean.isAsyncClientInitialization()) { if (log.isDebugEnabled()) { log.debug("Initializing client asynchronously..."); } ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(() -> { maybeInitializeClient(reg); if (log.isDebugEnabled()) { log.debug("Asynchronous client initialization done."); } }); } else { maybeInitializeClient(reg); } if (log.isInfoEnabled()) { log.info("Registering application " + reg.getApplicationInfoManager().getInfo().getAppName() + " with eureka with status " + reg.getInstanceConfig().getInitialStatus()); } reg.getApplicationInfoManager().setInstanceStatus(reg.getInstanceConfig().getInitialStatus()); reg.getHealthCheckHandler() .ifAvailable(healthCheckHandler -> reg.getEurekaClient().registerHealthCheck(healthCheckHandler)); } private void maybeInitializeClient(EurekaRegistration reg) { // force initialization of possibly scoped proxies reg.getApplicationInfoManager().getInfo(); reg.getEurekaClient().getApplications(); } @Override public void deregister(EurekaRegistration reg) {<FILL_FUNCTION_BODY>} @Override public void setStatus(EurekaRegistration registration, String status) { InstanceInfo info = registration.getApplicationInfoManager().getInfo(); // TODO: howto deal with delete properly? if ("CANCEL_OVERRIDE".equalsIgnoreCase(status)) { registration.getEurekaClient().cancelOverrideStatus(info); return; } // TODO: howto deal with status types across discovery systems? InstanceInfo.InstanceStatus newStatus = InstanceInfo.InstanceStatus.toEnum(status); registration.getEurekaClient().setStatus(newStatus, info); } @SuppressWarnings("unchecked") @Override public Object getStatus(EurekaRegistration registration) { String appname = registration.getApplicationInfoManager().getInfo().getAppName(); String instanceId = registration.getApplicationInfoManager().getInfo().getId(); InstanceInfo info = registration.getEurekaClient().getInstanceInfo(appname, instanceId); HashMap<String, Object> status = new HashMap<>(); if (info != null) { status.put("status", info.getStatus().toString()); status.put("overriddenStatus", info.getOverriddenStatus().toString()); } else { status.put("status", UNKNOWN.toString()); } return status; } public void close() { } }
if (reg.getApplicationInfoManager().getInfo() != null) { if (log.isInfoEnabled()) { log.info("Unregistering application " + reg.getApplicationInfoManager().getInfo().getAppName() + " with eureka with status DOWN"); } reg.getApplicationInfoManager().setInstanceStatus(InstanceInfo.InstanceStatus.DOWN); // shutdown of eureka client should happen with EurekaRegistration.close() // auto registration will create a bean which will be properly disposed // manual registrations will need to call close() }
851
151
1,002
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-client/src/main/java/org/springframework/cloud/netflix/eureka/support/ZoneUtils.java
ZoneUtils
extractApproximateZone
class ZoneUtils { private ZoneUtils() { throw new AssertionError("Must not instantiate utility class."); } /** * Approximates Eureka zones from a host name. This method approximates the zone to be * everything after the first "." in the host name. * @param host The host name to extract the host name from * @return The approximate zone */ public static String extractApproximateZone(String host) {<FILL_FUNCTION_BODY>} }
String[] split = StringUtils.split(host, "."); return split == null ? host : split[1];
126
31
157
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/CloudJacksonJson.java
CloudJacksonJson
updateIfNeeded
class CloudJacksonJson extends LegacyJacksonJson { protected final CloudJacksonCodec codec = new CloudJacksonCodec(); public CloudJacksonCodec getCodec() { return codec; } @Override public String codecName() { return getCodecName(LegacyJacksonJson.class); } @Override public <T> String encode(T object) { return this.codec.writeToString(object); } @Override public <T> void encode(T object, OutputStream outputStream) throws IOException { this.codec.writeTo(object, outputStream); } @Override public <T> T decode(String textValue, Class<T> type) throws IOException { return this.codec.readValue(type, textValue); } @Override public <T> T decode(InputStream inputStream, Class<T> type) throws IOException { return this.codec.readValue(type, inputStream); } static InstanceInfo updateIfNeeded(final InstanceInfo info) {<FILL_FUNCTION_BODY>} static class CloudJacksonCodec extends EurekaJacksonCodec { private static final Version VERSION = new Version(1, 1, 0, null, null, null); @SuppressWarnings("deprecation") CloudJacksonCodec() { super(); ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); SimpleModule module = new SimpleModule("eureka1.x", VERSION); module.addSerializer(DataCenterInfo.class, new DataCenterInfoSerializer()); module.addSerializer(InstanceInfo.class, new CloudInstanceInfoSerializer()); module.addSerializer(Application.class, new ApplicationSerializer()); module.addSerializer(Applications.class, new ApplicationsSerializer(this.getVersionDeltaKey(), this.getAppHashCodeKey())); // TODO: Watch if this causes problems // module.addDeserializer(DataCenterInfo.class, // new DataCenterInfoDeserializer()); module.addDeserializer(LeaseInfo.class, new LeaseInfoDeserializer()); module.addDeserializer(InstanceInfo.class, new CloudInstanceInfoDeserializer(mapper)); module.addDeserializer(Application.class, new ApplicationDeserializer(mapper)); module.addDeserializer(Applications.class, new ApplicationsDeserializer(mapper, this.getVersionDeltaKey(), this.getAppHashCodeKey())); mapper.registerModule(module); HashMap<Class<?>, Supplier<ObjectReader>> readers = new HashMap<>(); readers.put(InstanceInfo.class, () -> mapper.reader().withType(InstanceInfo.class).withRootName("instance")); readers.put(Application.class, () -> mapper.reader().withType(Application.class).withRootName("application")); readers.put(Applications.class, () -> mapper.reader().withType(Applications.class).withRootName("applications")); setField("objectReaderByClass", readers); HashMap<Class<?>, ObjectWriter> writers = new HashMap<>(); writers.put(InstanceInfo.class, mapper.writer().withType(InstanceInfo.class).withRootName("instance")); writers.put(Application.class, mapper.writer().withType(Application.class).withRootName("application")); writers.put(Applications.class, mapper.writer().withType(Applications.class).withRootName("applications")); setField("objectWriterByClass", writers); setField("mapper", mapper); } void setField(String name, Object value) { Field field = ReflectionUtils.findField(EurekaJacksonCodec.class, name); ReflectionUtils.makeAccessible(field); ReflectionUtils.setField(field, this, value); } } static class CloudInstanceInfoSerializer extends InstanceInfoSerializer { @Override public void serialize(final InstanceInfo info, JsonGenerator jgen, SerializerProvider provider) throws IOException { InstanceInfo updated = updateIfNeeded(info); super.serialize(updated, jgen, provider); } } static class CloudInstanceInfoDeserializer extends InstanceInfoDeserializer { protected CloudInstanceInfoDeserializer(ObjectMapper mapper) { super(mapper); } @Override public InstanceInfo deserialize(JsonParser jp, DeserializationContext context) throws IOException { InstanceInfo info = super.deserialize(jp, context); InstanceInfo updated = updateIfNeeded(info); return updated; } } }
if (info.getInstanceId() == null && info.getMetadata() != null) { String instanceId = info.getMetadata().get("instanceId"); if (StringUtils.hasText(instanceId)) { // backwards compatibility for Angel if (StringUtils.hasText(info.getHostName()) && !instanceId.startsWith(info.getHostName())) { instanceId = info.getHostName() + ":" + instanceId; } return new InstanceInfo.Builder(info).setInstanceId(instanceId).build(); } } return info;
1,238
148
1,386
<methods>public void <init>() ,public java.lang.String codecName() ,public T decode(java.lang.String, Class<T>) throws java.io.IOException,public T decode(java.io.InputStream, Class<T>) throws java.io.IOException,public java.lang.String encode(T) throws java.io.IOException,public void encode(T, java.io.OutputStream) throws java.io.IOException,public boolean support(jakarta.ws.rs.core.MediaType) <variables>protected final com.netflix.discovery.converters.EurekaJacksonCodec codec
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaDashboardProperties.java
EurekaDashboardProperties
toString
class EurekaDashboardProperties { /** * The path to the Eureka dashboard (relative to the servlet path). Defaults to "/". */ private String path = "/"; /** * Flag to enable the Eureka dashboard. Default true. */ private boolean enabled = true; public String getPath() { return path; } public void setPath(String path) { this.path = path; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EurekaDashboardProperties that = (EurekaDashboardProperties) o; return enabled == that.enabled && Objects.equals(path, that.path); } @Override public int hashCode() { return Objects.hash(path, enabled); } @Override public String toString() {<FILL_FUNCTION_BODY>} }
final StringBuilder sb = new StringBuilder("EurekaDashboardProperties{"); sb.append("path='").append(path).append('\''); sb.append(", enabled=").append(enabled); sb.append('}'); return sb.toString();
303
74
377
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaProperties.java
EurekaProperties
equals
class EurekaProperties { /** * Eureka environment. Defaults to "test". */ private String environment = "test"; /** * Eureka datacenter. Defaults to "default". */ private String datacenter = "default"; public String getEnvironment() { return environment; } public void setEnvironment(String environment) { this.environment = environment; } public String getDatacenter() { return datacenter; } public void setDatacenter(String datacenter) { this.datacenter = datacenter; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(environment, datacenter); } @Override public String toString() { final StringBuilder sb = new StringBuilder("EurekaProperties{"); sb.append("environment='").append(environment).append('\''); sb.append(", datacenter=").append(datacenter); sb.append('}'); return sb.toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EurekaProperties that = (EurekaProperties) o; return Objects.equals(datacenter, that.datacenter) && Objects.equals(environment, that.environment);
291
94
385
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerBootstrap.java
EurekaServerBootstrap
initEurekaServerContext
class EurekaServerBootstrap { private static final Log log = LogFactory.getLog(EurekaServerBootstrap.class); protected EurekaServerConfig eurekaServerConfig; protected ApplicationInfoManager applicationInfoManager; protected EurekaClientConfig eurekaClientConfig; protected PeerAwareInstanceRegistry registry; protected volatile EurekaServerContext serverContext; protected volatile AwsBinder awsBinder; public EurekaServerBootstrap(ApplicationInfoManager applicationInfoManager, EurekaClientConfig eurekaClientConfig, EurekaServerConfig eurekaServerConfig, PeerAwareInstanceRegistry registry, EurekaServerContext serverContext) { this.applicationInfoManager = applicationInfoManager; this.eurekaClientConfig = eurekaClientConfig; this.eurekaServerConfig = eurekaServerConfig; this.registry = registry; this.serverContext = serverContext; } public void contextInitialized(ServletContext context) { try { initEurekaServerContext(); context.setAttribute(EurekaServerContext.class.getName(), this.serverContext); } catch (Throwable e) { log.error("Cannot bootstrap eureka server :", e); throw new RuntimeException("Cannot bootstrap eureka server :", e); } } public void contextDestroyed(ServletContext context) { try { log.info("Shutting down Eureka Server.."); context.removeAttribute(EurekaServerContext.class.getName()); destroyEurekaServerContext(); destroyEurekaEnvironment(); } catch (Throwable e) { log.error("Error shutting down eureka", e); } log.info("Eureka Service is now shutdown..."); } protected void initEurekaServerContext() throws Exception {<FILL_FUNCTION_BODY>} /** * Server context shutdown hook. Override for custom logic * @throws Exception - calling {@link AwsBinder#shutdown()} or * {@link EurekaServerContext#shutdown()} may result in an exception */ protected void destroyEurekaServerContext() throws Exception { EurekaMonitors.shutdown(); if (this.awsBinder != null) { this.awsBinder.shutdown(); } if (this.serverContext != null) { this.serverContext.shutdown(); } } /** * Users can override to clean up the environment themselves. * @throws Exception - shutting down Eureka servers may result in an exception */ protected void destroyEurekaEnvironment() throws Exception { } protected boolean isAws(InstanceInfo selfInstanceInfo) { boolean result = DataCenterInfo.Name.Amazon == selfInstanceInfo.getDataCenterInfo().getName(); log.info("isAws returned " + result); return result; } }
// For backward compatibility JsonXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH); XmlXStream.getInstance().registerConverter(new V1AwareInstanceInfoConverter(), XStream.PRIORITY_VERY_HIGH); if (isAws(this.applicationInfoManager.getInfo())) { this.awsBinder = new AwsBinderDelegate(this.eurekaServerConfig, this.eurekaClientConfig, this.registry, this.applicationInfoManager); this.awsBinder.start(); } EurekaServerContextHolder.initialize(this.serverContext); log.info("Initialized server context"); // Copy registry from neighboring eureka node int registryCount = this.registry.syncUp(); this.registry.openForTraffic(this.applicationInfoManager, registryCount); // Register all monitoring statistics. EurekaMonitors.registerAllStats();
760
256
1,016
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/EurekaServerInitializerConfiguration.java
EurekaServerInitializerConfiguration
start
class EurekaServerInitializerConfiguration implements ServletContextAware, SmartLifecycle, Ordered { private static final Log log = LogFactory.getLog(EurekaServerInitializerConfiguration.class); @Autowired private EurekaServerConfig eurekaServerConfig; private ServletContext servletContext; @Autowired private ApplicationContext applicationContext; @Autowired private EurekaServerBootstrap eurekaServerBootstrap; private boolean running; private final int order = 1; @Override public void setServletContext(ServletContext servletContext) { this.servletContext = servletContext; } @Override public void start() {<FILL_FUNCTION_BODY>} private EurekaServerConfig getEurekaServerConfig() { return this.eurekaServerConfig; } private void publish(ApplicationEvent event) { this.applicationContext.publishEvent(event); } @Override public void stop() { this.running = false; eurekaServerBootstrap.contextDestroyed(this.servletContext); } @Override public boolean isRunning() { return this.running; } @Override public int getPhase() { return 0; } @Override public boolean isAutoStartup() { return true; } @Override public int getOrder() { return this.order; } }
new Thread(() -> { try { // TODO: is this class even needed now? eurekaServerBootstrap.contextInitialized(EurekaServerInitializerConfiguration.this.servletContext); log.info("Started Eureka Server"); publish(new EurekaRegistryAvailableEvent(getEurekaServerConfig())); EurekaServerInitializerConfiguration.this.running = true; publish(new EurekaServerStartedEvent(getEurekaServerConfig())); } catch (Exception ex) { // Help! log.error("Could not initialize Eureka servlet context", ex); } }).start();
360
177
537
<no_super_class>
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/InstanceRegistry.java
InstanceRegistry
handleRenewal
class InstanceRegistry extends PeerAwareInstanceRegistryImpl implements ApplicationContextAware { private static final Log log = LogFactory.getLog(InstanceRegistry.class); private ApplicationContext ctxt; private final int defaultOpenForTrafficCount; public InstanceRegistry(EurekaServerConfig serverConfig, EurekaClientConfig clientConfig, ServerCodecs serverCodecs, EurekaClient eurekaClient, EurekaServerHttpClientFactory eurekaServerHttpClientFactory, int expectedNumberOfClientsSendingRenews, int defaultOpenForTrafficCount) { super(serverConfig, clientConfig, serverCodecs, eurekaClient, eurekaServerHttpClientFactory); this.expectedNumberOfClientsSendingRenews = expectedNumberOfClientsSendingRenews; this.defaultOpenForTrafficCount = defaultOpenForTrafficCount; } @Override public void setApplicationContext(ApplicationContext context) throws BeansException { this.ctxt = context; } /** * If * {@link PeerAwareInstanceRegistryImpl#openForTraffic(ApplicationInfoManager, int)} * is called with a zero argument, it means that leases are not automatically * cancelled if the instance hasn't sent any renewals recently. This happens for a * standalone server. It seems like a bad default, so we set it to the smallest * non-zero value we can, so that any instances that subsequently register can bump up * the threshold. */ @Override public void openForTraffic(ApplicationInfoManager applicationInfoManager, int count) { super.openForTraffic(applicationInfoManager, count == 0 ? this.defaultOpenForTrafficCount : count); } @Override public void register(InstanceInfo info, int leaseDuration, boolean isReplication) { super.register(info, leaseDuration, isReplication); handleRegistration(info, leaseDuration, isReplication); } @Override public void register(final InstanceInfo info, final boolean isReplication) { super.register(info, isReplication); handleRegistration(info, resolveInstanceLeaseDuration(info), isReplication); } @Override public boolean cancel(String appName, String serverId, boolean isReplication) { final boolean cancelled = super.cancel(appName, serverId, isReplication); if (cancelled) { handleCancelation(appName, serverId, isReplication); } return cancelled; } @Override public boolean renew(final String appName, final String serverId, boolean isReplication) { final boolean renewed = super.renew(appName, serverId, isReplication); if (renewed) { handleRenewal(appName, serverId, isReplication); } return renewed; } @Override protected boolean internalCancel(String appName, String id, boolean isReplication) { final boolean cancelled = super.internalCancel(appName, id, isReplication); if (cancelled) { handleCancelation(appName, id, isReplication); } return cancelled; } private void handleCancelation(String appName, String id, boolean isReplication) { log("cancelled " + appName + ", serverId " + id + ", isReplication " + isReplication); publishEvent(new EurekaInstanceCanceledEvent(this, appName, id, isReplication)); } private void handleRegistration(InstanceInfo info, int leaseDuration, boolean isReplication) { log("registered " + info.getAppName() + ", vip " + info.getVIPAddress() + ", leaseDuration " + leaseDuration + ", isReplication " + isReplication); publishEvent(new EurekaInstanceRegisteredEvent(this, info, leaseDuration, isReplication)); } private void handleRenewal(final String appName, final String serverId, boolean isReplication) {<FILL_FUNCTION_BODY>} private void log(String message) { if (log.isDebugEnabled()) { log.debug(message); } } private void publishEvent(ApplicationEvent applicationEvent) { this.ctxt.publishEvent(applicationEvent); } private int resolveInstanceLeaseDuration(final InstanceInfo info) { int leaseDuration = Lease.DEFAULT_DURATION_IN_SECS; if (info.getLeaseInfo() != null && info.getLeaseInfo().getDurationInSecs() > 0) { leaseDuration = info.getLeaseInfo().getDurationInSecs(); } return leaseDuration; } }
log("renewed " + appName + ", serverId " + serverId + ", isReplication " + isReplication); final Application application = getApplication(appName); if (application != null) { final InstanceInfo instanceInfo = application.getByInstanceId(serverId); if (instanceInfo != null) { publishEvent(new EurekaInstanceRenewedEvent(this, appName, serverId, instanceInfo, isReplication)); } }
1,172
127
1,299
<methods>public void <init>(com.netflix.eureka.EurekaServerConfig, com.netflix.discovery.EurekaClientConfig, com.netflix.eureka.resources.ServerCodecs, com.netflix.discovery.EurekaClient, com.netflix.eureka.transport.EurekaServerHttpClientFactory) ,public boolean cancel(java.lang.String, java.lang.String, boolean) ,public boolean deleteStatusOverride(java.lang.String, java.lang.String, com.netflix.appinfo.InstanceInfo.InstanceStatus, java.lang.String, boolean) ,public long getLocalRegistrySize() ,public com.netflix.appinfo.InstanceInfo getNextServerFromEureka(java.lang.String, boolean) ,public long getNumOfReplicationsInLastMin() ,public List<com.netflix.eureka.cluster.PeerEurekaNode> getReplicaNodes() ,public List<com.netflix.discovery.shared.Application> getSortedApplications() ,public void init(com.netflix.eureka.cluster.PeerEurekaNodes) throws java.lang.Exception,public int isBelowRenewThresold() ,public boolean isLeaseExpirationEnabled() ,public int isLeaseExpirationEnabledMetric() ,public boolean isRegisterable(com.netflix.appinfo.InstanceInfo) ,public boolean isSelfPreservationModeEnabled() ,public int isSelfPreservationModeEnabledMetric() ,public void openForTraffic(com.netflix.appinfo.ApplicationInfoManager, int) ,public void register(com.netflix.appinfo.InstanceInfo, boolean) ,public boolean renew(java.lang.String, java.lang.String, boolean) ,public boolean shouldAllowAccess() ,public boolean shouldAllowAccess(boolean) ,public int shouldAllowAccessMetric() ,public void shutdown() ,public void statusUpdate(java.lang.String, com.netflix.eureka.resources.ASGResource.ASGStatus, boolean) ,public boolean statusUpdate(java.lang.String, java.lang.String, com.netflix.appinfo.InstanceInfo.InstanceStatus, java.lang.String, boolean) ,public int syncUp() <variables>private static final Comparator<com.netflix.discovery.shared.Application> APP_COMPARATOR,private static final int PRIME_PEER_NODES_RETRY_MS,private static final java.lang.String US_EAST_1,protected final com.netflix.discovery.EurekaClient eurekaClient,private final com.netflix.eureka.registry.rule.InstanceStatusOverrideRule instanceStatusOverrideRule,private static final org.slf4j.Logger logger,private final com.netflix.eureka.util.MeasuredRate numberOfReplicationsLastMin,protected volatile com.netflix.eureka.cluster.PeerEurekaNodes peerEurekaNodes,private boolean peerInstancesTransferEmptyOnStartup,private long startupTime,private java.util.Timer timer
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceCanceledEvent.java
EurekaInstanceCanceledEvent
equals
class EurekaInstanceCanceledEvent extends ApplicationEvent { private String appName; private String serverId; private boolean replication; public EurekaInstanceCanceledEvent(Object source, String appName, String serverId, boolean replication) { super(source); this.appName = appName; this.serverId = serverId; this.replication = replication; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public boolean isReplication() { return replication; } public void setReplication(boolean replication) { this.replication = replication; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(appName, serverId, replication); } @Override public String toString() { return new StringBuilder("EurekaInstanceCanceledEvent{").append("appName='").append(appName).append("', ") .append("serverId='").append(serverId).append("', ").append("replication=").append(replication) .append("}").toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EurekaInstanceCanceledEvent that = (EurekaInstanceCanceledEvent) o; return this.replication == that.replication && Objects.equals(this.appName, that.appName) && Objects.equals(this.serverId, that.serverId);
362
116
478
<methods>public void <init>(java.lang.Object) ,public void <init>(java.lang.Object, java.time.Clock) ,public final long getTimestamp() <variables>private static final long serialVersionUID,private final long timestamp
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRegisteredEvent.java
EurekaInstanceRegisteredEvent
equals
class EurekaInstanceRegisteredEvent extends ApplicationEvent { private InstanceInfo instanceInfo; private int leaseDuration; private boolean replication; public EurekaInstanceRegisteredEvent(Object source, InstanceInfo instanceInfo, int leaseDuration, boolean replication) { super(source); this.instanceInfo = instanceInfo; this.leaseDuration = leaseDuration; this.replication = replication; } public InstanceInfo getInstanceInfo() { return instanceInfo; } public void setInstanceInfo(InstanceInfo instanceInfo) { this.instanceInfo = instanceInfo; } public int getLeaseDuration() { return leaseDuration; } public void setLeaseDuration(int leaseDuration) { this.leaseDuration = leaseDuration; } public boolean isReplication() { return replication; } public void setReplication(boolean replication) { this.replication = replication; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(instanceInfo, leaseDuration, replication); } @Override public String toString() { return new StringBuilder("EurekaInstanceRegisteredEvent{").append("instanceInfo=").append(instanceInfo) .append(", ").append("leaseDuration=").append(leaseDuration).append(", ").append("replication=") .append(replication).append("}").toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EurekaInstanceRegisteredEvent that = (EurekaInstanceRegisteredEvent) o; return this.leaseDuration == that.leaseDuration && this.replication == that.replication && Objects.equals(this.instanceInfo, that.instanceInfo);
373
110
483
<methods>public void <init>(java.lang.Object) ,public void <init>(java.lang.Object, java.time.Clock) ,public final long getTimestamp() <variables>private static final long serialVersionUID,private final long timestamp
spring-cloud_spring-cloud-netflix
spring-cloud-netflix/spring-cloud-netflix-eureka-server/src/main/java/org/springframework/cloud/netflix/eureka/server/event/EurekaInstanceRenewedEvent.java
EurekaInstanceRenewedEvent
equals
class EurekaInstanceRenewedEvent extends ApplicationEvent { private String appName; private String serverId; private InstanceInfo instanceInfo; private boolean replication; public EurekaInstanceRenewedEvent(Object source, String appName, String serverId, InstanceInfo instanceInfo, boolean replication) { super(source); this.appName = appName; this.serverId = serverId; this.instanceInfo = instanceInfo; this.replication = replication; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getServerId() { return serverId; } public void setServerId(String serverId) { this.serverId = serverId; } public InstanceInfo getInstanceInfo() { return instanceInfo; } public void setInstanceInfo(InstanceInfo instanceInfo) { this.instanceInfo = instanceInfo; } public boolean isReplication() { return replication; } public void setReplication(boolean replication) { this.replication = replication; } @Override public boolean equals(Object o) {<FILL_FUNCTION_BODY>} @Override public int hashCode() { return Objects.hash(appName, serverId, instanceInfo, replication); } @Override public String toString() { return new StringBuilder("EurekaInstanceRenewedEvent{").append("appName='").append(appName).append("', ") .append("serverId='").append(serverId).append("', ").append("instanceInfo=").append(instanceInfo) .append(", ").append("replication=").append(replication).append("}").toString(); } }
if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } EurekaInstanceRenewedEvent that = (EurekaInstanceRenewedEvent) o; return Objects.equals(appName, that.appName) && Objects.equals(serverId, that.serverId) && Objects.equals(instanceInfo, that.instanceInfo) && replication == that.replication;
460
128
588
<methods>public void <init>(java.lang.Object) ,public void <init>(java.lang.Object, java.time.Clock) ,public final long getTimestamp() <variables>private static final long serialVersionUID,private final long timestamp
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-autowired/src/main/java/com/xcs/spring/AutowiredApplication.java
AutowiredApplication
main
class AutowiredApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyController controller = context.getBean(MyController.class); controller.showService();
34
47
81
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-componentScan/src/main/java/com/xcs/spring/ComponentScanApplication.java
ComponentScanApplication
main
class ComponentScanApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println("beanName = " + beanDefinitionName); }
33
61
94
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-conditional/src/main/java/com/xcs/spring/bean/ConditionBeanApplication.java
ConditionBeanApplication
main
class ConditionBeanApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
System.setProperty("enable.bean","false"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyBeanConfiguration.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println("beanDefinitionName = " + beanDefinitionName); }
33
76
109
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-conditional/src/main/java/com/xcs/spring/configuration/ConditionConfigurationApplication.java
ConditionConfigurationApplication
main
class ConditionConfigurationApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
System.setProperty("enable.config","false"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfigConfiguration.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println("beanDefinitionName = " + beanDefinitionName); }
33
76
109
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-conditional/src/main/java/com/xcs/spring/custom/ConditionCustomApplication.java
ConditionCustomApplication
main
class ConditionCustomApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
System.setProperty("enable.custom","false"); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyCustomConfiguration.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println("beanDefinitionName = " + beanDefinitionName); }
33
76
109
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-configuration/src/main/java/com/xcs/spring/ConfigurationApplication.java
ConfigurationApplication
main
class ConfigurationApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyConfiguration configuration = context.getBean(MyConfiguration.class); System.out.println(configuration.myBean()); System.out.println(configuration.myBean());
32
67
99
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-import/src/main/java/com/xcs/spring/ImportApplication.java
ImportApplication
main
class ImportApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println("beanName = " + beanDefinitionName); }
32
61
93
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-lazy/src/main/java/com/xcs/spring/LazyApplication.java
LazyApplication
main
class LazyApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
System.out.println("启动 Spring ApplicationContext..."); AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); System.out.println("启动完成 Spring ApplicationContext..."); System.out.println("获取MyService..."); MyService myService = context.getBean(MyService.class); System.out.println("调用show方法..."); myService.show();
33
106
139
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-propertySource/src/main/java/com/xcs/spring/PropertySourceApplication.java
PropertySourceApplication
main
class PropertySourceApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); System.out.println("apiVersion = " + context.getEnvironment().getProperty("apiVersion")); System.out.println("kind = " + context.getEnvironment().getProperty("kind"));
33
70
103
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-annotation/spring-annotation-value/src/main/java/com/xcs/spring/service/MyService.java
MyService
afterPropertiesSet
class MyService implements InitializingBean { /** * 直接注入值 */ @Value("Some String Value") private String someString; /** * 从属性文件中注入值方式 */ @Value("${app.name}") private String appName; /** * 使用默认值方式 */ @Value("${app.description:我是默认值}") private String appDescription; /** * 注入列表和属性 */ @Value("#{'${app.servers}'.split(',')}") private List<String> servers; /** * 使用Spring的SpEL */ @Value("#{${app.val1} + ${app.val2}}") private int sumOfValues; @Value("${myapp.names[0]}") private String firstName; @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} }
System.out.println("直接注入值: " + someString); System.out.println("从属性文件中注入值: " + appName); System.out.println("使用默认值: " + appDescription); System.out.println("注入列表和属性: " + servers); System.out.println("使用Spring的SpEL: " + sumOfValues); System.out.println("firstName: " + firstName);
264
118
382
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-afterReturningAdvice/src/main/java/com/xcs/spring/AfterReturningAdviceDemo.java
AfterReturningAdviceDemo
main
class AfterReturningAdviceDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂&创建目标对象 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 创建通知 proxyFactory.addAdvice(new MyAfterReturningAdvice()); // 获取代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 调用代理对象的方法 proxy.doSomething();
37
93
130
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-afterReturningAdvice/src/main/java/com/xcs/spring/MyAfterReturningAdvice.java
MyAfterReturningAdvice
afterReturning
class MyAfterReturningAdvice implements AfterReturningAdvice { @Override public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {<FILL_FUNCTION_BODY>} }
System.out.println("After method " + method.getName() + " is called, returned value: " + returnValue);
60
32
92
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-introductionInterceptor/src/main/java/com/xcs/spring/IntroductionInterceptorDemo.java
IntroductionInterceptorDemo
main
class IntroductionInterceptorDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂&创建目标对象 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 强制私用CGLIB proxyFactory.setProxyTargetClass(true); // 创建通知 proxyFactory.addAdvisor(new DefaultIntroductionAdvisor(new MyMonitoringIntroductionAdvice(), MyMonitoringCapable.class)); // 创建代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 调用代理对象的方法 proxy.doSomething(); // 开始监控 ((MyMonitoringCapable) proxy).toggleMonitoring(); // 再次调用代理对象的方法 proxy.doSomething();
36
170
206
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-introductionInterceptor/src/main/java/com/xcs/spring/MyMonitoringIntroductionAdvice.java
MyMonitoringIntroductionAdvice
doProceed
class MyMonitoringIntroductionAdvice extends DelegatingIntroductionInterceptor implements MyMonitoringCapable { private boolean active = false; public void setActive(boolean active) { this.active = active; } @Override public void toggleMonitoring() { setActive(true); } // 当被监控的方法被调用时,如果监控处于激活状态,则输出日志 @Override protected Object doProceed(MethodInvocation mi) throws Throwable {<FILL_FUNCTION_BODY>} }
if (this.active) { System.out.println("开启监控..."); long startTime = System.currentTimeMillis(); Object result = super.doProceed(mi); long endTime = System.currentTimeMillis(); System.out.println(mi.getClass().getName() + "." + mi.getMethod().getName() + " 耗费时间:" + (endTime - startTime) + " 毫秒"); System.out.println("结束监控..."); return result; } return super.doProceed(mi);
140
143
283
<methods>public void <init>(java.lang.Object) ,public java.lang.Object invoke(org.aopalliance.intercept.MethodInvocation) throws java.lang.Throwable<variables>private java.lang.Object delegate
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-methodBeforeAdvice/src/main/java/com/xcs/spring/MethodBeforeAdviceDemo.java
MethodBeforeAdviceDemo
main
class MethodBeforeAdviceDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂&创建目标对象 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 创建通知 proxyFactory.addAdvice(new MyMethodBeforeAdvice()); // 获取代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 调用代理对象的方法 proxy.doSomething();
36
92
128
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-methodBeforeAdvice/src/main/java/com/xcs/spring/MyMethodBeforeAdvice.java
MyMethodBeforeAdvice
before
class MyMethodBeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method method, Object[] args, Object target) throws Throwable {<FILL_FUNCTION_BODY>} }
System.out.println("Before method " + method.getName() + " is called.");
52
24
76
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-methodInterceptor/src/main/java/com/xcs/spring/MethodInterceptorDemo.java
MethodInterceptorDemo
main
class MethodInterceptorDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂&创建目标对象 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 创建通知 proxyFactory.addAdvice(new MyMethodInterceptor()); // 获取代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 调用代理对象的方法 proxy.doSomething();
36
92
128
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-methodInterceptor/src/main/java/com/xcs/spring/MyMethodInterceptor.java
MyMethodInterceptor
invoke
class MyMethodInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
// 在方法调用之前执行的逻辑 System.out.println("Method " + invocation.getMethod().getName() + " is called."); // 调用原始方法 Object result = invocation.proceed(); // 在方法调用之后执行的逻辑 System.out.println("Method " + invocation.getMethod().getName() + " returns " + result); return result;
48
102
150
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-throwsAdvice/src/main/java/com/xcs/spring/MyService.java
MyService
doSomethingException
class MyService { public void doSomethingException() {<FILL_FUNCTION_BODY>} }
System.out.println("Doing something exception..."); int i = 1 / 0;
29
27
56
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advice-throwsAdvice/src/main/java/com/xcs/spring/ThrowsAdviceDemo.java
ThrowsAdviceDemo
main
class ThrowsAdviceDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂&创建目标对象 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 创建通知 proxyFactory.addAdvice(new MyThrowsAdvice()); // 获取代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 调用代理对象的方法 proxy.doSomethingException();
36
93
129
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advisor/src/main/java/com/xcs/spring/AdvisorDemo.java
AdvisorDemo
main
class AdvisorDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 添加Advisor proxyFactory.addAdvisor(new MyCustomAdvisor()); // 获取代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 调用方法 proxy.foo(); // 会触发通知 proxy.bar(); // 不会触发通知
34
106
140
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advisorAdapter/src/main/java/com/xcs/spring/AdvisorAdapterDemo.java
AdvisorAdapterDemo
main
class AdvisorAdapterDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 注册自定义适配器 GlobalAdvisorAdapterRegistry.getInstance().registerAdvisorAdapter(new NullReturningAdviceAdapter()); // 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 添加Advisor proxyFactory.addAdvice(new MyNullReturningAdvice()); // 获取代理对象 MyService proxy = (MyService) proxyFactory.getProxy(); // 不会触发通知 System.out.println("foo return value : " + proxy.foo()); // 换行 System.out.println(); // 会触发通知 System.out.println("bar return value : " + proxy.bar());
35
177
212
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advisorAdapter/src/main/java/com/xcs/spring/MyNullReturningAdvice.java
MyNullReturningAdvice
nullReturning
class MyNullReturningAdvice implements NullReturningAdvice { @Override public Object nullReturning(Method method, Object[] args, Object target) throws Throwable {<FILL_FUNCTION_BODY>} }
System.out.println("Null Returning method " + method.getName() + " is called."); return "hello default value";
57
34
91
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advisorAdapter/src/main/java/com/xcs/spring/NullReturningAdviceInterceptor.java
NullReturningAdviceInterceptor
invoke
class NullReturningAdviceInterceptor implements MethodInterceptor, AfterAdvice { /** 空返回通知 */ private final NullReturningAdvice advice; /** * 构造一个空返回通知拦截器。 * @param advice 空返回通知 */ public NullReturningAdviceInterceptor(NullReturningAdvice advice) { Assert.notNull(advice, "Advice must not be null"); this.advice = advice; } /** * 在方法执行后拦截,检查返回值是否为空,并根据情况执行空返回通知的逻辑。 * @param mi 方法调用信息 * @return 方法执行结果,如果返回值为空,则根据空返回通知执行后的返回值 * @throws Throwable 如果方法调用过程中发生异常,则抛出异常 */ @Override public Object invoke(MethodInvocation mi) throws Throwable {<FILL_FUNCTION_BODY>} }
// 执行方法调用,获取返回值 Object retVal = mi.proceed(); // 如果返回值为空,则根据空返回通知执行后的返回值 if (retVal == null) { retVal = this.advice.nullReturning(mi.getMethod(), mi.getArguments(), mi.getThis()); } return retVal;
257
97
354
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advisorAdapterRegistry/src/main/java/com/xcs/spring/AdvisorAdapterRegistryDemo.java
AdvisorAdapterRegistryDemo
main
class AdvisorAdapterRegistryDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建默认的Advisor适配器注册表实例 DefaultAdvisorAdapterRegistry registry = new DefaultAdvisorAdapterRegistry(); // 包装给定的MyMethodBeforeAdvice为Advisor Advisor advisor = registry.wrap(new MyMethodBeforeAdvice()); // 获取Advisor中的拦截器数组 MethodInterceptor[] interceptors = registry.getInterceptors(advisor); // 输出拦截器信息 for (MethodInterceptor interceptor : interceptors) { System.out.println("interceptor = " + interceptor); }
36
159
195
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-advisorChainFactory/src/main/java/com/xcs/spring/AdvisorChainFactoryDemo.java
AdvisorChainFactoryDemo
main
class AdvisorChainFactoryDemo { public static void main(String[] args) throws NoSuchMethodException {<FILL_FUNCTION_BODY>} }
// 创建AOP配置对象 AdvisedSupport config = new AdvisedSupport(); // 添加前置通知 config.addAdvice(new MyMethodBeforeAdvice()); // 添加后置返回通知 config.addAdvice(new MyAfterReturningAdvice()); // 设置目标类 Class<MyService> targetClass = MyService.class; // 获取目标方法 Method method = targetClass.getDeclaredMethod("doSomething"); // 创建默认的Advisor链工厂实例 DefaultAdvisorChainFactory chainFactory = new DefaultAdvisorChainFactory(); // 获取Advisor链 List<Object> chain = chainFactory.getInterceptorsAndDynamicInterceptionAdvice(config, method, targetClass); // 打印Advisor链中的拦截器 chain.forEach(System.out::println);
41
218
259
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-annotationAwareAspectJAutoProxyCreator/src/main/java/com/xcs/spring/AnnotationAwareAspectJAutoProxyCreatorDemo.java
AnnotationAwareAspectJAutoProxyCreatorDemo
main
class AnnotationAwareAspectJAutoProxyCreatorDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建一个默认的 Bean 工厂 AnnotationConfigApplicationContext beanFactory = new AnnotationConfigApplicationContext(); // 注册AnnotationAwareAspectJAutoProxyCreator作为Bean,用于自动创建切面代理 beanFactory.registerBeanDefinition("internalAutoProxyCreator", new RootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class)); // 注册应用程序配置类 beanFactory.register(AppConfig.class); // 刷新应用程序上下文 beanFactory.refresh(); // 从容器中获取MyService bean MyService myService = beanFactory.getBean(MyService.class); // 调用MyService的方法 myService.doSomething();
43
177
220
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-aopProxy/src/main/java/com/xcs/spring/AopProxyDemo.java
AopProxyDemo
cglibProxy
class AopProxyDemo { public static void main(String[] args) throws Exception { // cglibProxy(); jdkProxy(); } /** * cglib代理 * * @throws Exception */ private static void cglibProxy() throws Exception {<FILL_FUNCTION_BODY>} /** * Jdk代理 * * @throws Exception */ private static void jdkProxy() throws Exception { // 创建AdvisedSupport对象,用于配置AOP代理 AdvisedSupport advisedSupport = new AdvisedSupport(); // 设置目标对象 advisedSupport.setTarget(new MyServiceImpl()); // 设置目标对象实现的接口 advisedSupport.setInterfaces(MyService.class); // 添加拦截器 advisedSupport.addAdvice(new MyMethodInterceptor()); // 获取JdkDynamicAopProxy的Class对象 Class<?> jdkClass = Class.forName("org.springframework.aop.framework.JdkDynamicAopProxy"); // 获取JdkDynamicAopProxy的构造方法 Constructor<?> constructor = jdkClass.getConstructor(AdvisedSupport.class); constructor.setAccessible(true); // 使用构造方法创建JdkDynamicAopProxy实例 AopProxy aopProxy = (AopProxy) constructor.newInstance(advisedSupport); // 调用getProxy方法创建代理对象 MyService myService = (MyService) aopProxy.getProxy(); // 输出代理对象的信息 System.out.println("JDK Class = " + myService.getClass()); // 调用代理对象的方法 myService.doSomething(); } }
// 创建AdvisedSupport对象,用于配置AOP代理 AdvisedSupport advisedSupport = new AdvisedSupport(); // 设置目标对象 advisedSupport.setTarget(new MyServiceImpl()); // 添加拦截器 advisedSupport.addAdvice(new MyMethodInterceptor()); // 获取CglibAopProxy的Class对象 Class<?> cglibClass = Class.forName("org.springframework.aop.framework.CglibAopProxy"); // 获取CglibAopProxy的构造方法 Constructor<?> constructor = cglibClass.getConstructor(AdvisedSupport.class); constructor.setAccessible(true); // 使用构造方法创建CglibAopProxy实例 AopProxy aopProxy = (AopProxy) constructor.newInstance(advisedSupport); // 调用getProxy方法创建代理对象 MyService myService = (MyService) aopProxy.getProxy(); // 输出代理对象的信息 System.out.println("Cglib Class = " + myService.getClass()); // 调用代理对象的方法 myService.doSomething();
438
292
730
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-aopProxy/src/main/java/com/xcs/spring/MyMethodInterceptor.java
MyMethodInterceptor
invoke
class MyMethodInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable {<FILL_FUNCTION_BODY>} }
// 在方法调用之前执行的逻辑 System.out.println("Before " + invocation.getMethod().getName()); // 调用原始方法 Object result = invocation.proceed(); // 在方法调用之后执行的逻辑 System.out.println("After " + invocation.getMethod().getName()); return result;
48
90
138
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-aopProxyFactory/src/main/java/com/xcs/spring/AopProxyFactoryDemo.java
AopProxyFactoryDemo
cglibProxy
class AopProxyFactoryDemo { public static void main(String[] args) { // 分别演示 JDK 动态代理和 CGLIB 代理 jdkProxy(); cglibProxy(); } /** * JDK 动态代理示例 */ private static void jdkProxy() { // 创建 AdvisedSupport 对象,用于配置 AOP 代理 AdvisedSupport advisedSupport = new AdvisedSupport(); // 设置目标对象 advisedSupport.setTarget(new MyServiceImpl()); // 设置目标对象的类 advisedSupport.setTargetClass(MyService.class); // 创建 DefaultAopProxyFactory 实例 AopProxyFactory aopProxyFactory = new DefaultAopProxyFactory(); // 创建 JDK 动态代理对象 MyService myService = (MyService) aopProxyFactory.createAopProxy(advisedSupport).getProxy(); // 打印生成的代理类 System.out.println("jdkProxy = " + myService.getClass()); } /** * CGLIB 代理示例 */ private static void cglibProxy() {<FILL_FUNCTION_BODY>} }
// 创建 AdvisedSupport 对象,用于配置 AOP 代理 AdvisedSupport advisedSupport = new AdvisedSupport(); // 设置目标对象 advisedSupport.setTarget(new MyServiceImpl()); // 创建 DefaultAopProxyFactory 实例 AopProxyFactory aopProxyFactory = new DefaultAopProxyFactory(); // 创建 CGLIB 代理对象 MyService myService = (MyService) aopProxyFactory.createAopProxy(advisedSupport).getProxy(); // 打印生成的代理类 System.out.println("cglibProxy = " + myService.getClass());
301
154
455
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-aspectInstanceFactory/src/main/java/com/xcs/spring/AspectInstanceFactoryDemo.java
AspectInstanceFactoryDemo
main
class AspectInstanceFactoryDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 使用 SimpleAspectInstanceFactory 创建切面实例 SimpleAspectInstanceFactory sAif = new SimpleAspectInstanceFactory(MyAspect.class); System.out.println("SimpleAspectInstanceFactory (1): " + sAif.getAspectInstance()); System.out.println("SimpleAspectInstanceFactory (2): " + sAif.getAspectInstance()); // 使用 SingletonAspectInstanceFactory 创建单例切面实例 SingletonAspectInstanceFactory singletonAif = new SingletonAspectInstanceFactory(new MyAspect()); System.out.println("SingletonAspectInstanceFactory (1): " + singletonAif.getAspectInstance()); System.out.println("SingletonAspectInstanceFactory (2): " + singletonAif.getAspectInstance()); // 创建一个 DefaultListableBeanFactory 实例,用于注册和管理 bean DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // 注册一个名为 "myAspect" 的单例 bean,类型为 MyAspect beanFactory.registerSingleton("myAspect", new MyAspect()); // 创建一个切面工厂的 BeanDefinition RootBeanDefinition aspectFactoryDef = new RootBeanDefinition(SimpleBeanFactoryAwareAspectInstanceFactory.class); // 设置切面工厂的属性 aspectBeanName 为 "myAspect" aspectFactoryDef.getPropertyValues().add("aspectBeanName", "myAspect"); // 设置切面工厂为合成的,即不对外暴露 aspectFactoryDef.setSynthetic(true); // 注册名为 "simpleBeanFactoryAwareAspectInstanceFactory" 的 bean,并使用切面工厂的 BeanDefinition beanFactory.registerBeanDefinition("simpleBeanFactoryAwareAspectInstanceFactory", aspectFactoryDef); // 从 BeanFactory 中获取 SimpleBeanFactoryAwareAspectInstanceFactory 的实例 SimpleBeanFactoryAwareAspectInstanceFactory simpleBeanFactoryAwareAif = beanFactory.getBean(SimpleBeanFactoryAwareAspectInstanceFactory.class); System.out.println("SimpleBeanFactoryAwareAspectInstanceFactory (1): " + simpleBeanFactoryAwareAif.getAspectInstance()); System.out.println("SimpleBeanFactoryAwareAspectInstanceFactory (2): " + simpleBeanFactoryAwareAif.getAspectInstance());
36
578
614
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-aspectJAdvisorFactory/src/main/java/com/xcs/spring/AspectJAdvisorFactoryDemo.java
AspectJAdvisorFactoryDemo
main
class AspectJAdvisorFactoryDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建一个默认的 Bean 工厂 DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // 在 Bean 工厂中注册一个名为 "myAspect" 的单例 Bean,类型为 MyAspect beanFactory.registerSingleton("myAspect", new MyAspect()); // 创建一个 Aspect 实例工厂,用于实例化切面 MetadataAwareAspectInstanceFactory factory = new BeanFactoryAspectInstanceFactory(beanFactory, "myAspect"); // 创建 ReflectiveAspectJAdvisorFactory 实例,用于创建 Advisor ReflectiveAspectJAdvisorFactory aspectJAdvisorFactory = new ReflectiveAspectJAdvisorFactory(beanFactory); // 获取所有注解式 AspectJ 方法的 Advisors List<Advisor> advisors = aspectJAdvisorFactory.getAdvisors(factory); // 打印 Advisors advisors.forEach(System.out::println);
39
251
290
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-beanFactoryAdvisorRetrievalHelper/src/main/java/com/xcs/spring/BeanFactoryAdvisorRetrievalHelperDemo.java
BeanFactoryAdvisorRetrievalHelperDemo
main
class BeanFactoryAdvisorRetrievalHelperDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建一个默认的 Bean 工厂 DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // 向 Bean 工厂注册一个名为 "myAspect" 的 Advisor beanFactory.registerSingleton("myAspect", new MyAdvisor()); // 创建 BeanFactoryAdvisorRetrievalHelper 实例,并传入 Bean 工厂 BeanFactoryAdvisorRetrievalHelper helper = new BeanFactoryAdvisorRetrievalHelper(beanFactory); // 获取 Bean 工厂中的 Advisor 列表 List<Advisor> advisors = helper.findAdvisorBeans(); // 打印 Advisors advisors.forEach(System.out::println);
42
186
228
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-beanFactoryAspectJAdvisorsBuilder/src/main/java/com/xcs/spring/BeanFactoryAspectJAdvisorsBuilderDemo.java
BeanFactoryAspectJAdvisorsBuilderDemo
main
class BeanFactoryAspectJAdvisorsBuilderDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建一个默认的 Bean 工厂 DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // 在 Bean 工厂中注册一个名为 "myAspect" 的单例 Bean,类型为 MyAspect beanFactory.registerSingleton("myAspect", new MyAspect()); // 创建 BeanFactoryAspectJAdvisorsBuilder 实例,并传入 Bean 工厂和 ReflectiveAspectJAdvisorFactory 实例 BeanFactoryAspectJAdvisorsBuilder builder = new BeanFactoryAspectJAdvisorsBuilder(beanFactory, new ReflectiveAspectJAdvisorFactory(beanFactory)); // 构建 AspectJ Advisors List<Advisor> advisors = builder.buildAspectJAdvisors(); // 打印 Advisors advisors.forEach(System.out::println);
42
219
261
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-cglibProxy/src/main/java/com/xcs/spring/CglibProxyDemo.java
CglibProxyDemo
main
class CglibProxyDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建 Enhancer 对象,用于生成代理类 Enhancer enhancer = new Enhancer(); // 设置目标对象的父类 enhancer.setSuperclass(MyServiceImpl.class); // 设置回调拦截器 enhancer.setCallback(new MyMethodInterceptor()); // 创建代理对象 MyService proxyObject = (MyService) enhancer.create(); // 输出代理对象的类名 System.out.println("ProxyObject = " + proxyObject.getClass()); // 调用代理对象的方法 proxyObject.doSomething();
36
152
188
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-cglibProxy/src/main/java/com/xcs/spring/MyMethodInterceptor.java
MyMethodInterceptor
intercept
class MyMethodInterceptor implements MethodInterceptor { @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {<FILL_FUNCTION_BODY>} }
System.out.println("Before invoking method: " + method.getName()); Object result = methodProxy.invokeSuper(obj, args); System.out.println("After invoking method: " + method.getName()); return result;
58
61
119
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-classFilter/src/main/java/com/xcs/spring/ClassFilterDemo.java
ClassFilterDemo
main
class ClassFilterDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建 AnnotationClassFilter 实例,匹配带有 MyAnnotation 注解的类 ClassFilter filter1 = new AnnotationClassFilter(MyAnnotation.class); System.out.println("AnnotationClassFilter 是否匹配 MyService 类:" + filter1.matches(MyService.class)); // 创建 TypePatternClassFilter 实例,匹配指定类名的类 ClassFilter filter2 = new TypePatternClassFilter("com.xcs.spring.MyService"); System.out.println("TypePatternClassFilter 是否匹配 MyService 类:" + filter2.matches(MyService.class)); // 创建 RootClassFilter 实例,匹配指定类的根类 ClassFilter filter3 = new RootClassFilter(MyService.class); System.out.println("RootClassFilter 是否匹配 MySubService 的根类:" + filter3.matches(MySubService.class)); // 创建 AspectJExpressionPointcut 实例,根据 AspectJ 表达式匹配类和方法 AspectJExpressionPointcut filter4 = new AspectJExpressionPointcut(); filter4.setExpression("execution(* com.xcs.spring.MyService.*(..))"); System.out.println("AspectJExpressionPointcut 是否匹配 MyService 类:" + filter4.matches(MyService.class));
33
341
374
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-enableAspectJAutoProxy/src/main/java/com/xcs/spring/EnableAspectJAutoProxyDemo.java
EnableAspectJAutoProxyDemo
main
class EnableAspectJAutoProxyDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建基于注解的应用上下文 AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); // 从应用上下文中获取FooService bean FooService fooService = context.getBean(FooService.class); // 调用FooService的方法 fooService.foo();
38
86
124
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-enableLoadTimeWeaving/src/main/java/com/xcs/spring/EnableLoadTimeWeavingDemo.java
EnableLoadTimeWeavingDemo
main
class EnableLoadTimeWeavingDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); FooService fooService = context.getBean(FooService.class); fooService.foo(); // 换行 System.out.println(); FooService fooService1 = new FooService(); fooService1.foo();
37
86
123
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-enableLoadTimeWeaving/src/main/java/com/xcs/spring/MyLTWAspect.java
MyLTWAspect
around
class MyLTWAspect { @Around("ltwPointcut()") public Object around(ProceedingJoinPoint pjp) throws Throwable {<FILL_FUNCTION_BODY>} @Pointcut("execution(public * com.xcs.spring.FooService.*(..))") public void ltwPointcut(){} }
// 在方法调用之前执行的逻辑 System.out.println("Method " + pjp.getSignature().getName() + " is called."); // 调用原始方法 Object result = pjp.proceed(); // 在方法调用之后执行的逻辑 System.out.println("Method " + pjp.getSignature().getName() + " returns " + result); return result;
91
105
196
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-jdkProxy/src/main/java/com/xcs/spring/JdkProxyDemo.java
JdkProxyDemo
main
class JdkProxyDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建目标对象 MyService target = new MyServiceImpl(); // 获取目标对象的类对象 Class clz = target.getClass(); // 创建代理对象,并指定目标对象的类加载器、实现的接口以及调用处理器 MyService proxyObject = (MyService) Proxy.newProxyInstance(clz.getClassLoader(), clz.getInterfaces(), new MyInvocationHandler(target)); // 打印代理对象的类信息 System.out.println("ProxyObject = " + proxyObject.getClass()); // 通过代理对象调用方法,实际上会调用 MyInvocationHandler 中的 invoke 方法 proxyObject.doSomething();
35
172
207
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-jdkProxy/src/main/java/com/xcs/spring/MyInvocationHandler.java
MyInvocationHandler
invoke
class MyInvocationHandler implements InvocationHandler { private Object target; public MyInvocationHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {<FILL_FUNCTION_BODY>} }
System.out.println("Before method execution"); Object result = method.invoke(target, args); System.out.println("After method execution"); return result;
82
45
127
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-metadataAwareAspectInstanceFactory/src/main/java/com/xcs/spring/MetadataAwareAspectInstanceFactoryDemo.java
MetadataAwareAspectInstanceFactoryDemo
main
class MetadataAwareAspectInstanceFactoryDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 使用 SimpleMetadataAwareAspectInstanceFactory 实例化切面 SimpleMetadataAwareAspectInstanceFactory simpleMetadataAwareAif = new SimpleMetadataAwareAspectInstanceFactory(MyAspect.class, "myAspect"); System.out.println("SimpleMetadataAwareAspectInstanceFactory (1) = " + simpleMetadataAwareAif.getAspectInstance()); System.out.println("SimpleMetadataAwareAspectInstanceFactory (2) = " + simpleMetadataAwareAif.getAspectInstance()); System.out.println("SimpleMetadataAwareAspectInstanceFactory AspectMetadata = " + JSONUtil.toJsonStr(simpleMetadataAwareAif.getAspectMetadata())); System.out.println(); // 使用 SingletonMetadataAwareAspectInstanceFactory 实例化切面 SingletonMetadataAwareAspectInstanceFactory singletonMetadataAwareAif = new SingletonMetadataAwareAspectInstanceFactory(new MyAspect(), "myAspect"); System.out.println("SingletonMetadataAwareAspectInstanceFactory (1) = " + singletonMetadataAwareAif.getAspectInstance()); System.out.println("SingletonMetadataAwareAspectInstanceFactory (2) = " + singletonMetadataAwareAif.getAspectInstance()); System.out.println("SimpleMetadataAwareAspectInstanceFactory AspectMetadata = " + JSONUtil.toJsonStr(singletonMetadataAwareAif.getAspectMetadata())); System.out.println(); // 使用 BeanFactoryAspectInstanceFactory 实例化切面 DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerSingleton("myAspect", new MyAspect()); BeanFactoryAspectInstanceFactory banFactoryAif = new BeanFactoryAspectInstanceFactory(beanFactory, "myAspect"); System.out.println("BeanFactoryAspectInstanceFactory (1) = " + banFactoryAif.getAspectInstance()); System.out.println("BeanFactoryAspectInstanceFactory (2) = " + banFactoryAif.getAspectInstance()); System.out.println("SimpleMetadataAwareAspectInstanceFactory AspectMetadata = " + JSONUtil.toJsonStr(banFactoryAif.getAspectMetadata())); System.out.println(); // 使用 LazySingletonAspectInstanceFactoryDecorator 实例化切面 LazySingletonAspectInstanceFactoryDecorator lazySingletonAifD = new LazySingletonAspectInstanceFactoryDecorator(banFactoryAif); System.out.println("LazySingletonAspectInstanceFactoryDecorator (1) = " + lazySingletonAifD.getAspectInstance()); System.out.println("LazySingletonAspectInstanceFactoryDecorator (2) = " + lazySingletonAifD.getAspectInstance()); System.out.println("LazySingletonAspectInstanceFactoryDecorator AspectCreationMutex = " + lazySingletonAifD.getAspectCreationMutex()); System.out.println("LazySingletonAspectInstanceFactoryDecorator AspectMetadata = " + JSONUtil.toJsonStr(lazySingletonAifD.getAspectMetadata())); System.out.println();
40
783
823
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-methodMatcher/src/main/java/com/xcs/spring/MethodMatcherDemo.java
MethodMatcherDemo
main
class MethodMatcherDemo { public static void main(String[] args) throws Exception {<FILL_FUNCTION_BODY>} }
// 使用 AnnotationMethodMatcher 检查是否具有特定注解 AnnotationMethodMatcher methodMatcher = new AnnotationMethodMatcher(MyAnnotation.class); System.out.println("方法是否具有特定注解: " + methodMatcher.matches(MyService.class.getDeclaredMethod("myMethod"), MyService.class)); // 使用 AspectJExpressionPointcut 基于 AspectJ 表达式匹配方法 AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression("execution(* com.xcs.spring.MyService.*(..))"); System.out.println("方法是否匹配 AspectJ 表达式: " + pointcut.matches(MyService.class.getDeclaredMethod("myMethod"), MyService.class)); // 使用 NameMatchMethodPointcut 基于方法名称匹配方法 NameMatchMethodPointcut pointcut2 = new NameMatchMethodPointcut(); pointcut2.setMappedName("myMethod"); System.out.println("方法是否匹配指定名称: " + pointcut2.matches(MyService.class.getDeclaredMethod("myMethod"), MyService.class)); // 使用 JdkRegexpMethodPointcut 基于正则表达式匹配方法 JdkRegexpMethodPointcut pointcut3 = new JdkRegexpMethodPointcut(); pointcut3.setPattern(".*my.*"); System.out.println("方法是否匹配正则表达式: " + pointcut3.matches(MyService.class.getDeclaredMethod("myMethod"), MyService.class));
37
401
438
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-pointcut/src/main/java/com/xcs/spring/MyCustomPointcut.java
MyCustomPointcut
getMethodMatcher
class MyCustomPointcut implements Pointcut { @Override public ClassFilter getClassFilter() { // 匹配所有类 return clazz -> true; } @Override public MethodMatcher getMethodMatcher() {<FILL_FUNCTION_BODY>} }
return new MethodMatcher() { @Override public boolean matches(Method method, Class<?> targetClass) { // 匹配所有以 "get" 开头的方法 return method.getName().startsWith("get"); } @Override public boolean isRuntime() { // 是否需要在运行时动态匹配 return false; } @Override public boolean matches(Method method, Class<?> targetClass, Object... args) { // 运行时匹配,这里不需要,所以简单返回 false return false; } };
76
151
227
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-pointcut/src/main/java/com/xcs/spring/PointcutDemo.java
PointcutDemo
aspectJExpressionPointcut
class PointcutDemo { public static void main(String[] args) { customPointcut(); } /** * 自定义 Pointcut 最佳实践 */ private static void customPointcut() { // 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(new MyBean()); // 添加切面:使用自定义的切入点和通知构建默认切面 proxyFactory.addAdvisor(new DefaultPointcutAdvisor(new MyCustomPointcut(), new MyCustomAdvice())); // 获取代理对象 MyBean myBean = (MyBean) proxyFactory.getProxy(); // 使用代理对象调用方法 myBean.getName(); // 将被通知拦截 myBean.getAge(); // 将被通知拦截 myBean.setName(); // 不会被通知拦截 } /** * AspectJExpressionPointcut最佳实践 */ private static void aspectJExpressionPointcut() {<FILL_FUNCTION_BODY>} /** * AnnotationMatchingPointcut 最佳实践 */ private static void annotationMatchingPointcut() { // 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(new MyBean()); // 添加切面:使用AnnotationMatchingPointcut切入点和通知构建默认切面 proxyFactory.addAdvisor(new DefaultPointcutAdvisor(new AnnotationMatchingPointcut(MyAnnotation.class, false), new MyCustomAdvice())); // 获取代理对象 MyBean myBean = (MyBean) proxyFactory.getProxy(); // 使用代理对象调用方法 myBean.getName(); // 将被通知拦截 myBean.getAge(); // 将被通知拦截 myBean.setName(); // 将被通知拦截 } /** * AspectJExpressionPointcut最佳实践 */ private static void nameMatchMethodPointcut() { // 创建方法名匹配切入点 NameMatchMethodPointcut pointcut = new NameMatchMethodPointcut(); pointcut.addMethodName("getAge"); // 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(new MyBean()); // 添加切面:使用自定义的切入点和通知构建默认切面 proxyFactory.addAdvisor(new DefaultPointcutAdvisor(pointcut, new MyCustomAdvice())); // 获取代理对象 MyBean myBean = (MyBean) proxyFactory.getProxy(); // 使用代理对象调用方法 myBean.getName(); // 不会被通知拦截 myBean.getAge(); // 将被通知拦截 myBean.setName(); // 不会被通知拦截 } }
// 创建 AspectJ 表达式切入点 AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut(); pointcut.setExpression("execution(* *.getName())"); // 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(new MyBean()); // 添加切面:使用自定义的切入点和通知构建默认切面 proxyFactory.addAdvisor(new DefaultPointcutAdvisor(pointcut, new MyCustomAdvice())); // 获取代理对象 MyBean myBean = (MyBean) proxyFactory.getProxy(); // 使用代理对象调用方法 myBean.getName(); // 将被通知拦截 myBean.getAge(); // 不会被通知拦截 myBean.setName(); // 不会被通知拦截
704
210
914
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-proxyFactory/src/main/java/com/xcs/spring/MyMethodBeforeAdvice.java
MyMethodBeforeAdvice
before
class MyMethodBeforeAdvice implements MethodBeforeAdvice { @Override public void before(Method method, Object[] args, Object target) throws Throwable {<FILL_FUNCTION_BODY>} }
System.out.println("Before method " + method.getName() + " is called.");
52
24
76
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-proxyFactory/src/main/java/com/xcs/spring/ProxyFactoryDemo.java
ProxyFactoryDemo
main
class ProxyFactoryDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂&创建目标对象 ProxyFactory proxyFactory = new ProxyFactory(new MyService()); // 创建通知 proxyFactory.addAdvice(new MyMethodBeforeAdvice()); // 获取代理对象 Object proxy = proxyFactory.getProxy(); // 调用代理对象的方法 System.out.println("proxy = " + proxy.getClass());
35
97
132
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-targetSource/src/main/java/com/xcs/spring/ConnectionPoolTargetSource.java
ConnectionPoolTargetSource
initializeConnectionPool
class ConnectionPoolTargetSource implements TargetSource { /** * 连接池 */ private final BlockingQueue<MyConnection> connectionPool; /** * 构造函数,初始化连接池。 * * @param poolSize 连接池大小 */ public ConnectionPoolTargetSource(int poolSize) { this.connectionPool = new ArrayBlockingQueue<>(poolSize); initializeConnectionPool(poolSize); } /** * 初始化连接池,填充连接对象。 * * @param poolSize 连接池大小 */ private void initializeConnectionPool(int poolSize) {<FILL_FUNCTION_BODY>} /** * 获取目标类的类型。 * * @return 目标类的类型 */ @Override public Class<?> getTargetClass() { return MyConnection.class; } /** * 判断目标对象是否是静态的。 * * @return 如果目标对象是静态的,则返回true,否则返回false */ @Override public boolean isStatic() { return false; } /** * 获取连接对象。 * * @return 连接对象 * @throws Exception 如果获取连接对象时发生异常 */ @Override public Object getTarget() throws Exception { return connectionPool.take(); } /** * 释放连接对象。 * * @param target 待释放的连接对象 * @throws Exception 如果释放连接对象时发生异常 */ @Override public void releaseTarget(Object target) throws Exception { if (target instanceof MyConnection) { connectionPool.offer((MyConnection) target); } } }
for (int i = 0; i < poolSize; i++) { MyConnection connection = new MyConnection("Connection" + i); connectionPool.offer(connection); }
455
49
504
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-targetSource/src/main/java/com/xcs/spring/MyConnection.java
MyConnection
toString
class MyConnection { private String name; public MyConnection(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() {<FILL_FUNCTION_BODY>} }
return "MyConnection{" + "name='" + name + '\'' + '}';
101
28
129
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aop/spring-aop-targetSource/src/main/java/com/xcs/spring/TargetSourceDemo.java
TargetSourceDemo
main
class TargetSourceDemo { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
// 创建代理工厂 ProxyFactory proxyFactory = new ProxyFactory(); // 设置目标源为连接池目标源,连接池大小为3 proxyFactory.setTargetSource(new ConnectionPoolTargetSource(3)); // 获取代理对象 MyConnection proxy = (MyConnection) proxyFactory.getProxy(); // 调用10次方法 for (int i = 0; i < 10; i++) { System.out.println("MyConnection Name = " + proxy.getName()); }
34
131
165
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-applicationEventPublisherAware/src/main/java/com/xcs/spring/ApplicationEventPublisherAwareApplication.java
ApplicationEventPublisherAwareApplication
main
class ApplicationEventPublisherAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyApplicationEventPublisherAware publisherAware = context.getBean(MyApplicationEventPublisherAware.class); publisherAware.publish("hello world");
37
64
101
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-applicationStartupAware/src/main/java/com/xcs/spring/ApplicationStartupAwareApplication.java
ApplicationStartupAwareApplication
main
class ApplicationStartupAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); context.setApplicationStartup(new BufferingApplicationStartup(100)); context.register(MyConfiguration.class); context.refresh(); context.close();
36
63
99
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-applicationStartupAware/src/main/java/com/xcs/spring/config/MyApplicationStartupAware.java
MyApplicationStartupAware
afterPropertiesSet
class MyApplicationStartupAware implements ApplicationStartupAware, InitializingBean { private ApplicationStartup applicationStartup; @Override public void setApplicationStartup(ApplicationStartup applicationStartup) { this.applicationStartup = applicationStartup; } @Override public void afterPropertiesSet() throws Exception {<FILL_FUNCTION_BODY>} }
StartupStep step1 = applicationStartup.start("MyApplicationStartupAware Logic Step 1"); // 自定义逻辑 Thread.sleep(200); step1.tag("status", "done").end(); StartupStep step2 = applicationStartup.start("MyApplicationStartupAware Logic Step 2"); // 自定义逻辑 Thread.sleep(300); step2.tag("status", "done").end();
97
120
217
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanClassLoaderAware/src/main/java/com/xcs/spring/BeanClassLoaderAwareApplication.java
BeanClassLoaderAwareApplication
main
class BeanClassLoaderAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyBeanClassLoaderAware myBeanClassLoaderAware = context.getBean(MyBeanClassLoaderAware.class); myBeanClassLoaderAware.loadAndExecute();
37
66
103
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanClassLoaderAware/src/main/java/com/xcs/spring/config/MyBeanClassLoaderAware.java
MyBeanClassLoaderAware
loadAndExecute
class MyBeanClassLoaderAware implements BeanClassLoaderAware { private ClassLoader classLoader; @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } public void loadAndExecute() {<FILL_FUNCTION_BODY>} }
try { Class<?> clazz = classLoader.loadClass("com.xcs.spring.service.UserServiceImpl"); UserServiceImpl instance = (UserServiceImpl) clazz.getDeclaredConstructor().newInstance(); System.out.println("UserInfo = " + instance.getUserInfo()); } catch (Exception e) { e.printStackTrace(); }
82
97
179
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanFactoryAware/src/main/java/com/xcs/spring/BeanFactoryAwareApplication.java
BeanFactoryAwareApplication
main
class BeanFactoryAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); UserService userService = context.getBean(UserService.class); userService.validateUser("root", "123456");
36
59
95
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanFactoryAware/src/main/java/com/xcs/spring/service/UserService.java
UserService
validateUser
class UserService implements BeanFactoryAware, InitializingBean { private BeanFactory beanFactory; private UserValidator userValidator; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } @Override public void afterPropertiesSet() throws Exception { if (someConfigurationMethod()) { userValidator = beanFactory.getBean("simpleUserValidator", UserValidator.class); } else { userValidator = beanFactory.getBean("complexUserValidator", UserValidator.class); } } public void validateUser(String username, String password) {<FILL_FUNCTION_BODY>} private boolean someConfigurationMethod() { return true; } }
boolean success = userValidator.validate(username, password); if (success){ System.out.println("验证账号密码成功"); }else{ System.out.println("验证账号密码失败"); }
192
63
255
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanFactoryAware/src/main/java/com/xcs/spring/validate/ComplexUserValidator.java
ComplexUserValidator
validate
class ComplexUserValidator implements UserValidator { @Override public boolean validate(String username, String password) {<FILL_FUNCTION_BODY>} }
System.out.println("使用ComplexUserValidator"); return username != null && username.length() > 5 && password != null && password.length() > 8;
41
44
85
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanFactoryAware/src/main/java/com/xcs/spring/validate/SimpleUserValidator.java
SimpleUserValidator
validate
class SimpleUserValidator implements UserValidator { @Override public boolean validate(String username, String password) {<FILL_FUNCTION_BODY>} }
System.out.println("使用SimpleUserValidator"); return username != null && password != null;
40
29
69
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-beanNameAware/src/main/java/com/xcs/spring/service/MyBasePayService.java
MyBasePayService
destroy
class MyBasePayService implements BeanNameAware, InitializingBean, DisposableBean { private String beanName; @Override public void setBeanName(String beanName) { this.beanName = beanName; } @Override public void afterPropertiesSet() throws Exception { System.out.println("Module " + beanName + " has been registered."); } @Override public void destroy() throws Exception {<FILL_FUNCTION_BODY>} }
System.out.println("Module " + beanName + " has been unregistered.");
127
24
151
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-embeddedValueResolverAware/src/main/java/com/xcs/spring/EmbeddedValueResolverAwareApplication.java
EmbeddedValueResolverAwareApplication
main
class EmbeddedValueResolverAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyEmbeddedValueResolverAware resolverAware = context.getBean(MyEmbeddedValueResolverAware.class); resolverAware.resolve();
38
66
104
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-embeddedValueResolverAware/src/main/java/com/xcs/spring/config/MyEmbeddedValueResolverAware.java
MyEmbeddedValueResolverAware
resolve
class MyEmbeddedValueResolverAware implements EmbeddedValueResolverAware { private StringValueResolver stringValueResolver; @Override public void setEmbeddedValueResolver(StringValueResolver resolver) { this.stringValueResolver = resolver; } public void resolve() {<FILL_FUNCTION_BODY>} }
String resolvedValue = stringValueResolver.resolveStringValue("Hello, ${user.name:xcs}! Today is #{T(java.time.LocalDate).now().toString()}"); System.out.println(resolvedValue);
91
59
150
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-environmentAware/src/main/java/com/xcs/spring/EnvironmentAwareApplication.java
EnvironmentAwareApplication
main
class EnvironmentAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyEnvironmentAware environmentAware = context.getBean(MyEnvironmentAware.class); System.out.println("AppProperty = " + environmentAware.getAppProperty());
34
67
101
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-importAware/src/main/java/com/xcs/spring/ImportAwareApplication.java
ImportAwareApplication
main
class ImportAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); String customBean = context.getBean(String.class); System.out.println(customBean);
34
50
84
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-importAware/src/main/java/com/xcs/spring/config/MyImportAware.java
MyImportAware
setImportMetadata
class MyImportAware implements ImportAware { private AnnotationAttributes enableXcs; @Override public void setImportMetadata(AnnotationMetadata importMetadata) {<FILL_FUNCTION_BODY>} @Bean public String customBean() { return "This is a custom bean!"; } }
this.enableXcs = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableXcs.class.getName(), false)); if (this.enableXcs == null) { throw new IllegalArgumentException( "@EnableXcs is not present on importing class " + importMetadata.getClassName()); }
82
83
165
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-messageSourceAware/src/main/java/com/xcs/spring/MessageSourceAwareApplication.java
MessageSourceAwareApplication
main
class MessageSourceAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyMessageSourceAware messageSourceAware = context.getBean(MyMessageSourceAware.class); messageSourceAware.getMessage();
35
58
93
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-resourceLoaderAware/src/main/java/com/xcs/spring/ResourceLoaderAwareApplication.java
ResourceLoaderAwareApplication
main
class ResourceLoaderAwareApplication { public static void main(String[] args) {<FILL_FUNCTION_BODY>} }
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfiguration.class); MyResourceLoaderAware resourceLoaderAware = context.getBean(MyResourceLoaderAware.class); resourceLoaderAware.getResource("classpath:xcs.txt");
35
67
102
<no_super_class>
xuchengsheng_spring-reading
spring-reading/spring-aware/spring-aware-resourceLoaderAware/src/main/java/com/xcs/spring/config/MyResourceLoaderAware.java
MyResourceLoaderAware
getResource
class MyResourceLoaderAware implements ResourceLoaderAware { private ResourceLoader resourceLoader; @Override public void setResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public void getResource(String location){<FILL_FUNCTION_BODY>} }
try { Resource resource = resourceLoader.getResource(location); System.out.println("Resource content: " + new String(FileCopyUtils.copyToByteArray(resource.getInputStream()))); } catch (IOException e) { e.printStackTrace(); }
79
71
150
<no_super_class>