This commit is contained in:
Phillip Webb
2015-01-14 14:49:23 -08:00
parent 9d823513c3
commit 3ea0f8d283
139 changed files with 652 additions and 733 deletions

View File

@@ -20,5 +20,7 @@ package org.springframework.cloud.netflix;
* @author Spencer Gibb
*/
public interface Constants {
String HYSTRIX_STREAM_NAME = "spring.cloud.hystrix.stream";
}

View File

@@ -56,6 +56,7 @@ public class ArchaiusAutoConfiguration {
private static final Logger logger = LoggerFactory
.getLogger(ArchaiusAutoConfiguration.class);
private static final AtomicBoolean initialized = new AtomicBoolean(false);
@Autowired
@@ -117,8 +118,8 @@ public class ArchaiusAutoConfiguration {
try {
config.addConfiguration(defaultURLConfig, URL_CONFIG_NAME);
}
catch (Throwable e) {
logger.error("Cannot create config from " + defaultURLConfig, e);
catch (Throwable ex) {
logger.error("Cannot create config from " + defaultURLConfig, ex);
}
// TODO: sys/env above urls?

View File

@@ -24,7 +24,6 @@ import com.netflix.config.ConfigurationManager;
/**
* @author Dave Syer
*
*/
public class ArchaiusDelegatingProxyUtils {

View File

@@ -31,7 +31,6 @@ import com.netflix.config.ConfigurationManager;
/**
* @author Dave Syer
*
*/
public class ArchaiusEndpoint extends AbstractEndpoint<Map<String, Object>> {

View File

@@ -34,7 +34,8 @@ import org.springframework.core.env.StandardEnvironment;
* @author Spencer Gibb
*/
public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration {
ConfigurableEnvironment environment;
private final ConfigurableEnvironment environment;
public ConfigurableEnvironmentConfiguration(ConfigurableEnvironment environment) {
this.environment = environment;
@@ -77,14 +78,8 @@ public class ConfigurableEnvironmentConfiguration extends AbstractConfiguration
private Map<String, PropertySource<?>> getPropertySources() {
Map<String, PropertySource<?>> map = new LinkedHashMap<>();
MutablePropertySources sources;
if (this.environment != null
&& this.environment instanceof ConfigurableEnvironment) {
sources = this.environment.getPropertySources();
}
else {
sources = new StandardEnvironment().getPropertySources();
}
MutablePropertySources sources = (this.environment != null ? this.environment
.getPropertySources() : new StandardEnvironment().getPropertySources());
for (PropertySource<?> source : sources) {
extract("", map, source);
}

View File

@@ -40,7 +40,6 @@ import com.netflix.discovery.DiscoveryClient;
* discovery.
*
* @author Dave Syer
*
*/
@ConditionalOnClass({ DiscoveryClient.class, ConfigServicePropertySourceLocator.class })
@ConditionalOnExpression("${spring.cloud.config.discovery.enabled:false}")
@@ -85,8 +84,8 @@ public class DiscoveryClientConfigServiceBootstrapConfiguration implements
}
this.config.setUri(url);
}
catch (Exception e) {
log.warn("Could not locate configserver via discovery", e);
catch (Exception ex) {
log.warn("Could not locate configserver via discovery", ex);
}
}

View File

@@ -30,8 +30,8 @@ import com.netflix.discovery.DiscoveryClient;
/**
* Extra configuration for config server if it happens to be a Eureka instance.
* @author Dave Syer
*
* @author Dave Syer
*/
@Configuration
@EnableConfigurationProperties

View File

@@ -31,14 +31,15 @@ import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.ServletWrappingController;
/**
* TODO: move to spring-boot? User: spencergibb Date: 4/24/14 Time: 9:13 PM
*/
public abstract class ServletWrappingEndpoint implements InitializingBean,
ApplicationContextAware, ServletContextAware, MvcEndpoint {
// TODO: move to spring-boot?
protected String path;
protected boolean sensitive;
protected boolean enabled = true;
protected final ServletWrappingController controller = new ServletWrappingController();
@@ -88,4 +89,5 @@ public abstract class ServletWrappingEndpoint implements InitializingBean,
public Class<? extends Endpoint<?>> getEndpointType() {
return null;
}
}

View File

@@ -53,11 +53,11 @@ import com.thoughtworks.xstream.mapper.Mapper;
* that isn't very useful when sitting behind a proxy).
*
* @author Dave Syer
*
*/
public class DataCenterAwareMarshallingStrategy implements MarshallingStrategy {
private TreeMarshallingStrategy delegate = new TreeMarshallingStrategy();
private ApplicationContext context;
public DataCenterAwareMarshallingStrategy(ApplicationContext context) {
@@ -104,6 +104,7 @@ public class DataCenterAwareMarshallingStrategy implements MarshallingStrategy {
private static class DataCenterAwareConverterLookup implements ConverterLookup {
private ConverterLookup delegate;
private ApplicationContext context;
public DataCenterAwareConverterLookup(ConverterLookup delegate,
@@ -147,6 +148,7 @@ public class DataCenterAwareMarshallingStrategy implements MarshallingStrategy {
@Slf4j
private static class SetVersionInterceptor implements MethodInterceptor {
private ApplicationContext context;
public SetVersionInterceptor(ApplicationContext context) {
@@ -164,6 +166,7 @@ public class DataCenterAwareMarshallingStrategy implements MarshallingStrategy {
}
return ret;
}
}
private static class DataCenterAwareConverter extends InstanceInfoConverter {

View File

@@ -39,4 +39,5 @@ public class DiscoveryManagerInitializer {
this.clientConfig);
}
}
}

View File

@@ -16,10 +16,6 @@
package org.springframework.cloud.netflix.eureka;
/**
* @author Spencer Gibb
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
@@ -37,7 +33,7 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
* well).
*
* @author Dave Syer
*
* @author Spencer Gibb
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@@ -45,4 +41,5 @@ import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@Inherited
@EnableDiscoveryClient
public @interface EnableEurekaClient {
}

View File

@@ -34,7 +34,6 @@ import com.netflix.discovery.converters.XmlXStream;
/**
* @author Dave Syer
*
*/
@Configuration
@EnableConfigurationProperties

View File

@@ -30,7 +30,6 @@ import com.netflix.discovery.EurekaClientConfig;
/**
* @author Dave Syer
*
*/
@Data
@ConfigurationProperties("eureka.client")
@@ -92,7 +91,6 @@ public class EurekaClientConfigBean implements EurekaClientConfig {
private int cacheRefreshExecutorExponentialBackOffBound = 10;
private Map<String, String> serviceUrl = new HashMap<String, String>();
{
this.serviceUrl.put(DEFAULT_ZONE, DEFAULT_URL);
}

View File

@@ -154,4 +154,5 @@ public class EurekaDiscoveryClient implements DiscoveryClient {
});
return Lists.newArrayList(instances);
}
}

View File

@@ -56,7 +56,6 @@ import com.netflix.discovery.shared.EurekaJerseyClient;
/**
* @author Dave Syer
*
*/
@Configuration
@EnableConfigurationProperties
@@ -105,8 +104,8 @@ public class EurekaDiscoveryClientConfiguration implements SmartLifecycle, Order
jerseyClient.destroyResources();
}
}
catch (Exception e) {
logger.error("Error closing DiscoveryClient.jerseyClient", e);
catch (Exception ex) {
logger.error("Error closing DiscoveryClient.jerseyClient", ex);
}
}
}
@@ -218,4 +217,5 @@ public class EurekaDiscoveryClientConfiguration implements SmartLifecycle, Order
return new EurekaHealthIndicator(eurekaDiscoveryClient, metrics, config);
}
}
}

View File

@@ -34,18 +34,17 @@ import com.netflix.discovery.shared.Applications;
/**
* @author Dave Syer
*
*/
public class EurekaHealthIndicator implements DiscoveryHealthIndicator {
private EurekaInstanceConfig instanceConfig;
private final DiscoveryClient discovery;
private MetricReader metrics;
private final MetricReader metrics;
private final EurekaInstanceConfig instanceConfig;
private int failCount = 0;
private DiscoveryClient discovery;
public EurekaHealthIndicator(DiscoveryClient discovery, MetricReader metrics,
EurekaInstanceConfig instanceConfig) {
super();

View File

@@ -38,7 +38,6 @@ import com.netflix.appinfo.UniqueIdentifier;
/**
* @author Dave Syer
*
*/
@Data
@ConfigurationProperties("eureka.instance")
@@ -120,8 +119,8 @@ public class EurekaInstanceConfigBean implements EurekaInstanceConfig {
info[0] = InetAddress.getLocalHost().getHostAddress();
info[1] = InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e) {
logger.error("Cannot get host info", e);
catch (UnknownHostException ex) {
logger.error("Cannot get host info", ex);
}
return info;
}
@@ -133,6 +132,7 @@ public class EurekaInstanceConfigBean implements EurekaInstanceConfig {
private final class IdentifyingDataCenterInfo implements DataCenterInfo,
UniqueIdentifier {
@Getter
@Setter
private Name name = Name.MyOwn;

View File

@@ -29,7 +29,6 @@ import com.netflix.eureka.EurekaServerConfig;
/**
* @author Dave Syer
*
*/
@Data
@ConfigurationProperties("eureka.server")
@@ -49,11 +48,6 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private boolean enableSelfPreservation = true;
@Override
public boolean shouldEnableSelfPreservation() {
return this.enableSelfPreservation;
}
private double renewalPercentThreshold = 0.85;
private int renewalThresholdUpdateIntervalMs = 10 * MINUTES;
@@ -92,11 +86,6 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private boolean disableDelta;
@Override
public boolean shouldDisableDelta() {
return this.disableDelta;
}
private long maxIdleThreadInMinutesAgeForStatusReplication = 10;
private int minThreadsForStatusReplication = 1;
@@ -107,11 +96,6 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private boolean syncWhenTimestampDiffers = true;
@Override
public boolean shouldSyncWhenTimestampDiffers() {
return this.syncWhenTimestampDiffers;
}
private int registrySyncRetries = 5;
private int maxElementsInPeerReplicationPool = 10000;
@@ -126,18 +110,8 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private boolean primeAwsReplicaConnections = true;
@Override
public boolean shouldPrimeAwsReplicaConnections() {
return this.primeAwsReplicaConnections;
}
private boolean disableDeltaForRemoteRegions;
@Override
public boolean shouldDisableDeltaForRemoteRegions() {
return this.disableDeltaForRemoteRegions;
}
private int remoteRegionConnectTimeoutMs = 1000;
private int remoteRegionReadTimeoutMs = 1000;
@@ -150,28 +124,12 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private boolean gZipContentFromRemoteRegion = true;
@Override
public boolean shouldGZipContentFromRemoteRegion() {
return this.gZipContentFromRemoteRegion;
}
private Map<String, String> remoteRegionUrlsWithName = new HashMap<String, String>();
private String[] remoteRegionUrls;
private Map<String, Set<String>> remoteRegionAppWhitelist;
@Override
public Set<String> getRemoteRegionAppWhitelist(String regionName) {
if (null == regionName) {
regionName = "global";
}
else {
regionName = regionName.trim().toLowerCase();
}
return this.remoteRegionAppWhitelist.get(regionName);
}
private int remoteRegionRegistryFetchInterval = 30;
private String remoteRegionTrustStore = "";
@@ -180,25 +138,8 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private boolean disableTransparentFallbackToOtherRegion;
@Override
public boolean disableTransparentFallbackToOtherRegion() {
return this.disableTransparentFallbackToOtherRegion;
}
private boolean batchReplication;
@Override
public boolean shouldBatchReplication() {
return this.batchReplication;
}
private boolean logIdentityHeaders = true;
@Override
public boolean shouldLogIdentityHeaders() {
return this.logIdentityHeaders;
}
private boolean rateLimiterEnabled = false;
private boolean rateLimiterThrottleStandardClients = false;
@@ -210,4 +151,58 @@ public class EurekaServerConfigBean implements EurekaServerConfig {
private int rateLimiterRegistryFetchAverageRate = 500;
private int rateLimiterFullFetchAverageRate = 100;
private boolean logIdentityHeaders = true;
@Override
public boolean shouldEnableSelfPreservation() {
return this.enableSelfPreservation;
}
@Override
public boolean shouldDisableDelta() {
return this.disableDelta;
}
@Override
public boolean shouldSyncWhenTimestampDiffers() {
return this.syncWhenTimestampDiffers;
}
@Override
public boolean shouldPrimeAwsReplicaConnections() {
return this.primeAwsReplicaConnections;
}
@Override
public boolean shouldDisableDeltaForRemoteRegions() {
return this.disableDeltaForRemoteRegions;
}
@Override
public boolean shouldGZipContentFromRemoteRegion() {
return this.gZipContentFromRemoteRegion;
}
@Override
public Set<String> getRemoteRegionAppWhitelist(String regionName) {
return this.remoteRegionAppWhitelist.get(regionName == null ? "global"
: regionName.trim().toLowerCase());
}
@Override
public boolean disableTransparentFallbackToOtherRegion() {
return this.disableTransparentFallbackToOtherRegion;
}
@Override
public boolean shouldBatchReplication() {
return this.batchReplication;
}
@Override
public boolean shouldLogIdentityHeaders() {
return this.logIdentityHeaders;
}
}

View File

@@ -39,13 +39,14 @@ import feign.Logger;
@ConditionalOnClass(Feign.class)
@AutoConfigureAfter(ArchaiusAutoConfiguration.class)
public class FeignAutoConfiguration {
@Bean
SpringDecoder feignDecoder() {
public SpringDecoder feignDecoder() {
return new SpringDecoder();
}
@Bean
SpringEncoder feignEncoder() {
public SpringEncoder feignEncoder() {
return new SpringEncoder();
}
@@ -68,4 +69,5 @@ public class FeignAutoConfiguration {
return new FeignRibbonClient(factory);
}
}
}

View File

@@ -29,6 +29,7 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FeignClient {
/**
* @return serviceId if loadbalance is true, url otherwise No need to prefix serviceId
* with http://
@@ -36,4 +37,5 @@ public @interface FeignClient {
String value();
boolean loadbalance() default true;
}

View File

@@ -29,7 +29,9 @@ import org.springframework.beans.factory.FactoryBean;
class FeignClientFactoryBean extends FeignConfiguration implements FactoryBean<Object> {
private boolean loadbalance;
private Class<?> type;
private String schemeName;
@Override
@@ -52,4 +54,5 @@ class FeignClientFactoryBean extends FeignConfiguration implements FactoryBean<O
public boolean isSingleton() {
return true;
}
}

View File

@@ -42,7 +42,6 @@ public @interface FeignClientScan {
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation
* declarations e.g.: {@code @ComponentScan("org.my.pkg")} instead of
* {@code @ComponentScan(basePackages="org.my.pkg")}.
*
* @return the array of 'basePackages'.
*/
String[] value() default {};
@@ -54,7 +53,6 @@ public @interface FeignClientScan {
* <p>
* Use {@link #basePackageClasses()} for a type-safe alternative to String-based
* package names.
*
* @return the array of 'basePackages'.
*/
String[] basePackages() default {};
@@ -65,7 +63,6 @@ public @interface FeignClientScan {
* <p>
* Consider creating a special no-op marker class or interface in each package that
* serves no purpose other than being referenced by this attribute.
*
* @return the array of 'basePackageClasses'.
*/
Class<?>[] basePackageClasses() default {};

View File

@@ -39,12 +39,13 @@ import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* @author Spencer Gibb patterned after Spring Integration
* IntegrationComponentScanRegistrar
* @author Spencer Gibb
*/
public class FeignClientScanRegistrar extends FeignConfiguration implements
ImportBeanDefinitionRegistrar, ResourceLoaderAware, BeanClassLoaderAware {
// patterned after Spring Integration IntegrationComponentScanRegistrar
private ResourceLoader resourceLoader;
private ClassLoader classLoader;
@@ -123,15 +124,16 @@ public class FeignClientScanRegistrar extends FeignConfiguration implements
FeignClientScanRegistrar.this.classLoader);
return !target.isAnnotation();
}
catch (Exception e) {
catch (Exception ex) {
this.logger.error("Could not load target class: "
+ beanDefinition.getMetadata().getClassName(), e);
+ beanDefinition.getMetadata().getClassName(), ex);
}
}
return true;
}
return false;
}
};
}

View File

@@ -36,6 +36,7 @@ import feign.ribbon.LoadBalancingTarget;
*/
@Configuration
public class FeignConfiguration {
@Autowired
ConfigurableEnvironmentConfiguration envConfig; // FIXME: howto enforce this?

View File

@@ -26,6 +26,7 @@ import org.springframework.http.HttpHeaders;
* @author Spencer Gibb
*/
public class FeignUtils {
static HttpHeaders getHttpHeaders(Map<String, Collection<String>> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
for (Map.Entry<String, Collection<String>> entry : headers.entrySet()) {
@@ -33,4 +34,5 @@ public class FeignUtils {
}
return httpHeaders;
}
}

View File

@@ -63,6 +63,7 @@ public class SpringDecoder implements Decoder {
}
private class FeignResponseAdapter implements ClientHttpResponse {
private final Response response;
private FeignResponseAdapter(Response response) {
@@ -89,8 +90,8 @@ public class SpringDecoder implements Decoder {
try {
this.response.body().close();
}
catch (IOException e) {
e.printStackTrace();
catch (IOException ex) {
ex.printStackTrace();
}
}
@@ -105,4 +106,5 @@ public class SpringDecoder implements Decoder {
}
}
}

View File

@@ -44,14 +44,12 @@ import static org.springframework.cloud.netflix.feign.FeignUtils.getHttpHeaders;
* @author Spencer Gibb
*/
public class SpringEncoder implements Encoder {
private static final Logger logger = LoggerFactory.getLogger(SpringEncoder.class);
@Autowired
Provider<HttpMessageConverters> messageConverters;
public SpringEncoder() {
}
@Override
public void encode(Object requestBody, RequestTemplate request)
throws EncodeException {
@@ -88,16 +86,16 @@ public class SpringEncoder implements Encoder {
HttpMessageConverter<Object> copy = (HttpMessageConverter<Object>) messageConverter;
copy.write(requestBody, requestContentType, outputMessage);
}
catch (IOException e) {
throw new EncodeException("Error converting request body", e);
catch (IOException ex) {
throw new EncodeException("Error converting request body", ex);
}
request.body(outputMessage.getOutputStream().toByteArray(),
Charsets.UTF_8); // TODO: set charset
return;
}
}
String message = "Could not write request: no suitable HttpMessageConverter found for request type ["
+ requestType.getName() + "]";
String message = "Could not write request: no suitable HttpMessageConverter "
+ "found for request type [" + requestType.getName() + "]";
if (requestContentType != null) {
message += " and content type [" + requestContentType + "]";
}
@@ -106,8 +104,10 @@ public class SpringEncoder implements Encoder {
}
private class FeignOutputMessage implements HttpOutputMessage {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
RequestTemplate request;
private final RequestTemplate request;
private FeignOutputMessage(RequestTemplate request) {
this.request = request;
@@ -126,5 +126,7 @@ public class SpringEncoder implements Encoder {
public ByteArrayOutputStream getOutputStream() {
return this.outputStream;
}
}
}

View File

@@ -37,8 +37,10 @@ import static feign.Util.emptyToNull;
* @author Spencer Gibb
*/
public class SpringMvcContract extends Contract.BaseContract {
static final String ACCEPT = "Accept";
static final String CONTENT_TYPE = "Content-Type";
private static final String ACCEPT = "Accept";
private static final String CONTENT_TYPE = "Content-Type";
@Override
protected void processAnnotationOnMethod(MethodMetadata data,
@@ -145,7 +147,10 @@ public class SpringMvcContract extends Contract.BaseContract {
data.template().header(name, header);
nameParam(data, name, paramIndex);
isHttpAnnotation = true;
}/*
}
// TODO
/*
* else if (annotationType == FormParam.class) { String name =
* FormParam.class.cast(parameterAnnotation).value();
* checkState(emptyToNull(name) != null,
@@ -163,13 +168,12 @@ public class SpringMvcContract extends Contract.BaseContract {
if (values == null) {
return false;
}
for (Collection<V> entry : values) {
if (entry.contains(search)) {
return true;
}
}
return false;
}
}

View File

@@ -41,17 +41,9 @@ import feign.Response;
*/
public class FeignRibbonClient implements Client {
private Client defaultClient = new Default(new Lazy<SSLSocketFactory>() {
@Override
public SSLSocketFactory get() {
return (SSLSocketFactory) SSLSocketFactory.getDefault();
}
}, new Lazy<HostnameVerifier>() {
@Override
public HostnameVerifier get() {
return HttpsURLConnection.getDefaultHostnameVerifier();
}
});
private Client defaultClient = new Default(new LazySSLSocketFactory(),
new LazyHostnameVerifier());
private SpringClientFactory factory;
public FeignRibbonClient(SpringClientFactory factory) {
@@ -61,7 +53,6 @@ public class FeignRibbonClient implements Client {
@Override
public Response execute(Request request, Request.Options options) throws IOException {
try {
URI asUri = URI.create(request.url());
String clientName = asUri.getHost();
URI uriWithoutSchemeAndPort = URI.create(request.url().replace(
@@ -70,13 +61,12 @@ public class FeignRibbonClient implements Client {
request, uriWithoutSchemeAndPort);
return lbClient(clientName).executeWithLoadBalancer(ribbonRequest)
.toResponse();
}
catch (ClientException e) {
if (e.getCause() instanceof IOException) {
throw IOException.class.cast(e.getCause());
catch (ClientException ex) {
if (ex.getCause() instanceof IOException) {
throw IOException.class.cast(ex.getCause());
}
throw Throwables.propagate(e);
throw Throwables.propagate(ex);
}
}
@@ -89,4 +79,23 @@ public class FeignRibbonClient implements Client {
public void setDefaultClient(Client defaultClient) {
this.defaultClient = defaultClient;
}
private static class LazySSLSocketFactory implements Lazy<SSLSocketFactory> {
@Override
public SSLSocketFactory get() {
return (SSLSocketFactory) SSLSocketFactory.getDefault();
}
}
private static class LazyHostnameVerifier implements Lazy<HostnameVerifier> {
@Override
public HostnameVerifier get() {
return HttpsURLConnection.getDefaultHostnameVerifier();
}
}
}

View File

@@ -41,8 +41,11 @@ public class RibbonLoadBalancer
AbstractLoadBalancerAwareClient<RibbonLoadBalancer.RibbonRequest, RibbonLoadBalancer.RibbonResponse> {
private final Client delegate;
private final int connectTimeout;
private final int readTimeout;
private final IClientConfig clientConfig;
public RibbonLoadBalancer(Client delegate, ILoadBalancer lb,
@@ -157,4 +160,5 @@ public class RibbonLoadBalancer
}
}
}

View File

@@ -16,10 +16,6 @@
package org.springframework.cloud.netflix.hystrix;
/**
* @author Spencer Gibb
*/
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
@@ -37,7 +33,7 @@ import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
* well).
*
* @author Dave Syer
*
* @author Spencer Gibb
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@@ -45,4 +41,5 @@ import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
@Inherited
@EnableCircuitBreaker
public @interface EnableHystrix {
}

View File

@@ -27,7 +27,8 @@ import org.springframework.context.annotation.Configuration;
import com.netflix.hystrix.Hystrix;
/**
* Auto configuration for Hystrix
* Auto configuration for Hystrix.
*
* @author Christian Dupuis
*/
@Configuration

View File

@@ -107,7 +107,7 @@ public class HystrixCircuitBreakerConfiguration {
addMetrics(map, "hystrix.");
}
}
catch (IOException e) {
catch (IOException ex) {
// ignore
}
}
@@ -190,4 +190,5 @@ public class HystrixCircuitBreakerConfiguration {
}
}
}

View File

@@ -37,7 +37,6 @@ import com.netflix.hystrix.HystrixCommandMetrics;
*/
public class HystrixHealthIndicator extends AbstractHealthIndicator {
/** Status code for open circuits */
private static final Status CIRCUIT_OPEN = new Status("CIRCUIT_OPEN");
@Override

View File

@@ -29,4 +29,5 @@ public class HystrixStreamEndpoint extends ServletWrappingEndpoint {
super(HystrixMetricsStreamServlet.class, "hystrixStream", "/hystrix.stream",
false, true);
}
}

View File

@@ -33,7 +33,8 @@ import org.springframework.web.client.RestTemplate;
import com.netflix.client.IClient;
/**
* Auto configuration for Ribbon (client side load balancing)
* Auto configuration for Ribbon (client side load balancing).
*
* @author Spencer Gibb
* @author Dave Syer
*/

View File

@@ -27,7 +27,6 @@ import org.springframework.context.annotation.Import;
/**
* @author Dave Syer
*
*/
@Configuration
@Import(RibbonClientConfigurationRegistrar.class)
@@ -35,9 +34,11 @@ import org.springframework.context.annotation.Import;
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RibbonClient {
String value() default "";
String name() default "";
Class<?>[] configuration() default {};
}

View File

@@ -37,7 +37,6 @@ import com.netflix.servo.monitor.Monitors;
/**
* @author Dave Syer
*
*/
@SuppressWarnings("deprecation")
@Configuration

View File

@@ -27,7 +27,6 @@ import org.springframework.util.StringUtils;
/**
* @author Dave Syer
*
*/
public class RibbonClientConfigurationRegistrar implements ImportBeanDefinitionRegistrar {

View File

@@ -21,13 +21,13 @@ import lombok.Data;
/**
* @author Dave Syer
*
*/
@Data
@AllArgsConstructor
public class RibbonClientSpecification {
private String name;
private Class<?>[] configuration;
}

View File

@@ -30,7 +30,6 @@ import org.springframework.context.annotation.Import;
* annotations on a single class (including in Java 7).
*
* @author Dave Syer
*
*/
@Configuration
@Retention(RetentionPolicy.RUNTIME)

View File

@@ -46,19 +46,34 @@ public class RibbonInterceptor implements ClientHttpRequestInterceptor {
String serviceName = originalUri.getHost();
return this.loadBalancer.execute(serviceName,
new LoadBalancerRequest<ClientHttpResponse>() {
@Override
public ClientHttpResponse apply(final ServiceInstance instance)
throws Exception {
HttpRequestWrapper wrapper = new HttpRequestWrapper(request) {
@Override
public URI getURI() {
URI uri = RibbonInterceptor.this.loadBalancer
.reconstructURI(instance, originalUri);
return uri;
}
};
return execution.execute(wrapper, body);
HttpRequest serviceRequest = new ServiceRequestWrapper(request,
instance);
return execution.execute(serviceRequest, body);
}
});
}
private class ServiceRequestWrapper extends HttpRequestWrapper {
private final ServiceInstance instance;
public ServiceRequestWrapper(HttpRequest request, ServiceInstance instance) {
super(request);
this.instance = instance;
}
@Override
public URI getURI() {
URI uri = RibbonInterceptor.this.loadBalancer.reconstructURI(this.instance,
getRequest().getURI());
return uri;
}
}
}

View File

@@ -68,14 +68,13 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
Stopwatch tracer = context.getExecuteTracer().start();
try {
T returnVal = request.apply(ribbonServer);
recordStats(context, tracer, serverStats, returnVal, null);
return returnVal;
}
catch (Exception e) {
recordStats(context, tracer, serverStats, null, e);
Throwables.propagate(e);
catch (Exception ex) {
recordStats(context, tracer, serverStats, null, ex);
Throwables.propagate(ex);
}
return null;
}
@@ -127,5 +126,7 @@ public class RibbonLoadBalancerClient implements LoadBalancerClient {
public int getPort() {
return this.server.getPort();
}
}
}

View File

@@ -61,4 +61,5 @@ public class RibbonLoadBalancerContext extends LoadBalancerContext {
long responseTime, RetryHandler errorHandler) {
super.noteRequestCompletion(stats, response, e, responseTime, errorHandler);
}
}

View File

@@ -43,11 +43,15 @@ import com.netflix.loadbalancer.ILoadBalancer;
* creates a Spring ApplicationContext per client name, and extracts the beans that it
* needs from there.
*
* @author Spencer Gibb
* @author Dave Syer
*/
public class SpringClientFactory implements DisposableBean, ApplicationContextAware {
private Map<String, AnnotationConfigApplicationContext> contexts = new ConcurrentHashMap<>();
private Map<String, RibbonClientSpecification> configurations = new ConcurrentHashMap<>();
private ApplicationContext parent;
@Override
@@ -72,7 +76,6 @@ public class SpringClientFactory implements DisposableBean, ApplicationContextAw
/**
* Get the rest client associated with the name.
*
* @throws RuntimeException if any error occurs
*/
public <C extends IClient<?, ?>> C getClient(String name, Class<C> clientClass) {
@@ -81,7 +84,6 @@ public class SpringClientFactory implements DisposableBean, ApplicationContextAw
/**
* Get the load balancer associated with the name.
*
* @throws RuntimeException if any error occurs
*/
public ILoadBalancer getLoadBalancer(String name) {
@@ -90,7 +92,6 @@ public class SpringClientFactory implements DisposableBean, ApplicationContextAw
/**
* Get the client config associated with the name.
*
* @throws RuntimeException if any error occurs
*/
public IClientConfig getClientConfig(String name) {
@@ -99,7 +100,6 @@ public class SpringClientFactory implements DisposableBean, ApplicationContextAw
/**
* Get the load balancer context associated with the name.
*
* @throws RuntimeException if any error occurs
*/
public RibbonLoadBalancerContext getLoadBalancerContext(String serviceId) {
@@ -169,7 +169,8 @@ public class SpringClientFactory implements DisposableBean, ApplicationContextAw
result = BeanUtils.instantiate(clazz);
}
}
catch (Throwable e) { // NOPMD
catch (Throwable ex) {
// NOPMD
}
}
context.getAutowireCapableBeanFactory().autowireBean(result);

View File

@@ -33,12 +33,13 @@ import com.netflix.niws.loadbalancer.DiscoveryEnabledServer;
/**
* @author Dave Syer
*
*/
public class DomainExtractingServerList implements ServerList<Server> {
private ServerList<Server> list;
private IClientConfig clientConfig;
private boolean approximateZoneFromHostname;
public DomainExtractingServerList(ServerList<Server> list,

View File

@@ -51,6 +51,7 @@ public class EurekaRibbonClientConfiguration {
private String serviceId = "client";
protected static final String VALUE_NOT_SET = "__not__set__";
protected static final String DEFAULT_NAMESPACE = "ribbon";
@Autowired(required = false)

View File

@@ -30,7 +30,6 @@ import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;
/**
* @author Dave Syer
*
*/
@Configuration
@EnableConfigurationProperties
@@ -40,4 +39,5 @@ import com.netflix.niws.loadbalancer.DiscoveryEnabledNIWSServerList;
@AutoConfigureAfter(RibbonAutoConfiguration.class)
@RibbonClients(defaultConfiguration = EurekaRibbonClientConfiguration.class)
public class RibbonEurekaAutoConfiguration {
}

View File

@@ -33,13 +33,13 @@ import com.netflix.loadbalancer.ZoneAffinityServerListFilter;
* the Eureka instance metadata).
*
* @author Dave Syer
*
* TODO: move out of ribbon.eureka package since it has nothing specific to eureka
*/
@Data
@EqualsAndHashCode(callSuper = false)
public class ZonePreferenceServerListFilter extends ZoneAffinityServerListFilter<Server> {
// TODO: move out of ribbon.eureka package since it has nothing specific to eureka
private String zone;
@Override

View File

@@ -95,6 +95,7 @@ public class ServoMetricCollector implements DisposableBean {
}
}
}
}
}

View File

@@ -48,4 +48,5 @@ public class ServoMetricsAutoConfiguration {
public ServoMetricCollector servoMetricCollector(MetricWriter metrics) {
return new ServoMetricCollector(metrics);
}
}

View File

@@ -41,4 +41,5 @@ import org.springframework.context.annotation.Import;
@Retention(RetentionPolicy.RUNTIME)
@Import(ZuulProxyConfiguration.class)
public @interface EnableZuulProxy {
}

View File

@@ -38,4 +38,5 @@ import org.springframework.context.annotation.Import;
@Documented
@Import(ZuulConfiguration.class)
public @interface EnableZuulServer {
}

View File

@@ -72,19 +72,15 @@ public class ProxyRouteLocator implements RouteLocator {
}
public Map<String, String> getRoutes() {
if (this.routes.get() == null) {
this.routes.set(locateRoutes());
}
Map<String, String> values = new LinkedHashMap<>();
for (String key : this.routes.get().keySet()) {
String url = key;
values.put(url, this.routes.get().get(key).getLocation());
}
return values;
}
public ProxyRouteSpec getMatchingRoute(String path) {
@@ -113,8 +109,8 @@ public class ProxyRouteLocator implements RouteLocator {
break;
}
}
return location == null ? null : new ProxyRouteSpec(id, targetPath, location,
prefix);
return (location == null ? null : new ProxyRouteSpec(id, targetPath, location,
prefix));
}
public void resetRoutes() {
@@ -122,12 +118,9 @@ public class ProxyRouteLocator implements RouteLocator {
}
protected LinkedHashMap<String, ZuulRoute> locateRoutes() {
LinkedHashMap<String, ZuulRoute> routesMap = new LinkedHashMap<>();
addConfiguredRoutes(routesMap);
routesMap.putAll(this.staticRoutes);
if (this.discovery != null) {
// Add routes for discovery services by default
List<String> services = this.discovery.getServices();
@@ -141,36 +134,28 @@ public class ProxyRouteLocator implements RouteLocator {
}
}
}
if (routesMap.get(DEFAULT_ROUTE) != null) {
ZuulRoute defaultRoute = routesMap.get(DEFAULT_ROUTE);
// Move the defaultServiceId to the end
routesMap.remove(DEFAULT_ROUTE);
routesMap.put(DEFAULT_ROUTE, defaultRoute);
}
LinkedHashMap<String, ZuulRoute> values = new LinkedHashMap<>();
for (Entry<String, ZuulRoute> entry : routesMap.entrySet()) {
String path = entry.getKey();
// Prepend with slash if not already present.
if (!path.startsWith("/")) {
path = "/" + path;
}
if (StringUtils.hasText(this.properties.getPrefix())) {
path = this.properties.getPrefix() + path;
if (!path.startsWith("/")) {
path = "/" + path;
}
}
values.put(path, entry.getValue());
}
return values;
}
protected void addConfiguredRoutes(Map<String, ZuulRoute> routes) {
@@ -187,23 +172,22 @@ public class ProxyRouteLocator implements RouteLocator {
public String getTargetPath(String matchingRoute, String requestURI) {
String path = getRoutes().get(matchingRoute);
if (path == null) {
path = requestURI;
}
else {
}
return path;
return (path != null ? path : requestURI);
}
@Data
@AllArgsConstructor
public static class ProxyRouteSpec {
private String id;
private String path;
private String location;
private String prefix;
}
}

View File

@@ -20,7 +20,6 @@ import java.util.Collection;
/**
* @author Dave Syer
*
*/
public interface RouteLocator {

View File

@@ -40,6 +40,7 @@ import org.springframework.web.bind.annotation.ResponseBody;
public class RoutesEndpoint implements MvcEndpoint, ApplicationEventPublisherAware {
private ProxyRouteLocator routes;
private ApplicationEventPublisher publisher;
@Override

View File

@@ -20,7 +20,6 @@ import org.springframework.context.ApplicationEvent;
/**
* @author Dave Syer
*
*/
@SuppressWarnings("serial")
public class RoutesRefreshedEvent extends ApplicationEvent {

View File

@@ -23,7 +23,6 @@ import org.springframework.cloud.netflix.zuul.ZuulProperties.ZuulRoute;
/**
* @author Dave Syer
*
*/
public class SimpleRouteLocator implements RouteLocator {

View File

@@ -63,6 +63,40 @@ public class ZuulConfiguration {
return new ZuulHandlerMapping(routes, zuulController());
}
@Bean
public ApplicationListener<ApplicationEvent> zuulRefreshRoutesListener() {
return new ZuulRefreshListener();
}
// pre filters
@Bean
public FormBodyWrapperFilter formBodyWrapperFilter() {
return new FormBodyWrapperFilter();
}
@Bean
public DebugFilter debugFilter() {
return new DebugFilter();
}
@Bean
public Servlet30WrapperFilter servlet30WrapperFilter() {
return new Servlet30WrapperFilter();
}
// post filters
@Bean
public SendResponseFilter sendResponseFilter() {
return new SendResponseFilter();
}
@Bean
public SendErrorFilter sendErrorFilter() {
return new SendErrorFilter();
}
@Configuration
protected static class ZuulFilterConfiguration {
@@ -76,11 +110,6 @@ public class ZuulConfiguration {
}
@Bean
public ApplicationListener<ApplicationEvent> zuulRefreshRoutesListener() {
return new ZuulRefreshListener();
}
private static class ZuulRefreshListener implements
ApplicationListener<ApplicationEvent> {
@@ -97,31 +126,4 @@ public class ZuulConfiguration {
}
// pre filters
@Bean
public FormBodyWrapperFilter formBodyWrapperFilter() {
return new FormBodyWrapperFilter();
}
@Bean
public DebugFilter debugFilter() {
return new DebugFilter();
}
@Bean
public Servlet30WrapperFilter servlet30WrapperFilter() {
return new Servlet30WrapperFilter();
}
// post filters
@Bean
public SendResponseFilter sendResponseFilter() {
return new SendResponseFilter();
}
@Bean
public SendErrorFilter sendErrorFilter() {
return new SendErrorFilter();
}
}

View File

@@ -47,4 +47,5 @@ public class ZuulController extends ServletWrappingController {
RequestContext.getCurrentContext().unset();
}
}
}

View File

@@ -29,9 +29,9 @@ import org.springframework.web.servlet.handler.AbstractUrlHandlerMapping;
*/
public class ZuulHandlerMapping extends AbstractUrlHandlerMapping {
private RouteLocator routeLocator;
private final RouteLocator routeLocator;
private ZuulController zuul;
private final ZuulController zuul;
@Autowired
public ZuulHandlerMapping(RouteLocator routeLocator, ZuulController zuul) {

View File

@@ -38,10 +38,15 @@ import org.springframework.util.StringUtils;
@Data
@ConfigurationProperties("zuul")
public class ZuulProperties {
private String prefix = "";
private boolean stripPrefix = true;
private Map<String, ZuulRoute> routes = new LinkedHashMap<String, ZuulRoute>();
private boolean addProxyHeaders = true;
private List<String> ignoredServices = new ArrayList<String>();
@PostConstruct
@@ -64,10 +69,15 @@ public class ZuulProperties {
@AllArgsConstructor
@NoArgsConstructor
public static class ZuulRoute {
private String id;
private String path;
private String serviceId;
private String url;
private boolean stripPrefix = true;
public ZuulRoute(String text) {
@@ -115,6 +125,7 @@ public class ZuulProperties {
path = path.replace("/*", "").replace("*", "");
return path;
}
}
}

View File

@@ -61,19 +61,6 @@ public class ZuulProxyConfiguration extends ZuulConfiguration {
return new ProxyRouteLocator(this.discovery, this.zuulProperties);
}
@Configuration
@ConditionalOnClass(Endpoint.class)
protected static class RoutesEndpointConfuguration {
@Autowired
private ProxyRouteLocator routeLocator;
@Bean
// @RefreshScope
public RoutesEndpoint zuulEndpoint() {
return new RoutesEndpoint(this.routeLocator);
}
}
// pre filters
@Bean
public PreDecorationFilter preDecorationFilter() {
@@ -106,6 +93,21 @@ public class ZuulProxyConfiguration extends ZuulConfiguration {
return new ZuulRefreshListener();
}
@Configuration
@ConditionalOnClass(Endpoint.class)
protected static class RoutesEndpointConfuguration {
@Autowired
private ProxyRouteLocator routeLocator;
@Bean
// @RefreshScope
public RoutesEndpoint zuulEndpoint() {
return new RoutesEndpoint(this.routeLocator);
}
}
private static class ZuulRefreshListener implements
ApplicationListener<ApplicationEvent> {

View File

@@ -40,7 +40,6 @@ import com.netflix.zuul.util.HTTPRequestUtils;
/**
* @author Dave Syer
*
*/
public class ProxyRequestHelper {
@@ -60,16 +59,12 @@ public class ProxyRequestHelper {
public MultiValueMap<String, String> buildZuulRequestQueryParams(
HttpServletRequest request) {
Map<String, List<String>> map = HTTPRequestUtils.getInstance().getQueryParams();
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
if (map == null) {
return params;
}
for (String key : map.keySet()) {
for (String value : map.get(key)) {
params.add(key, value);
}
@@ -79,9 +74,7 @@ public class ProxyRequestHelper {
public MultiValueMap<String, String> buildZuulRequestHeaders(
HttpServletRequest request) {
RequestContext context = RequestContext.getCurrentContext();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
Enumeration<?> headerNames = request.getHeaderNames();
if (headerNames != null) {
@@ -94,27 +87,21 @@ public class ProxyRequestHelper {
}
}
Map<String, String> zuulRequestHeaders = context.getZuulRequestHeaders();
for (String header : zuulRequestHeaders.keySet()) {
headers.set(header, zuulRequestHeaders.get(header));
}
headers.set("accept-encoding", "deflate, gzip");
return headers;
}
public void setResponse(int status, InputStream entity,
MultiValueMap<String, String> headers) throws IOException {
RequestContext context = RequestContext.getCurrentContext();
RequestContext.getCurrentContext().setResponseStatusCode(status);
if (entity != null) {
RequestContext.getCurrentContext().setResponseDataStream(entity);
}
boolean isOriginResponseGzipped = false;
if (headers.containsKey(CONTENT_ENCODING)) {
Collection<String> collection = headers.get(CONTENT_ENCODING);
for (String header : collection) {
@@ -125,23 +112,19 @@ public class ProxyRequestHelper {
}
}
context.setResponseGZipped(isOriginResponseGzipped);
for (Entry<String, List<String>> header : headers.entrySet()) {
RequestContext ctx = RequestContext.getCurrentContext();
String name = header.getKey();
for (String value : header.getValue()) {
ctx.addOriginResponseHeader(name, value);
if (name.equalsIgnoreCase("content-length")) {
ctx.setOriginContentLength(value);
}
if (isIncludedHeader(name)) {
ctx.addZuulResponseHeader(name, value);
}
}
}
}
public void addIgnoredHeaders(String... names) {
@@ -181,10 +164,8 @@ public class ProxyRequestHelper {
public Map<String, Object> debug(String verb, String uri,
MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
InputStream requestEntity) throws IOException {
Map<String, Object> info = new LinkedHashMap<String, Object>();
if (this.traces != null) {
RequestContext context = RequestContext.getCurrentContext();
StringBuilder query = new StringBuilder();
for (String param : params.keySet()) {
@@ -200,7 +181,6 @@ public class ProxyRequestHelper {
info.put("query", query.toString());
info.put("remote", true);
info.put("proxy", context.get("proxy"));
Map<String, Object> trace = new LinkedHashMap<String, Object>();
Map<String, Object> input = new LinkedHashMap<String, Object>();
trace.put("request", input);
@@ -213,7 +193,6 @@ public class ProxyRequestHelper {
}
input.put(entry.getKey(), value);
}
RequestContext ctx = RequestContext.getCurrentContext();
if (!ctx.isChunkedRequestBody()) {
if (requestEntity != null) {

View File

@@ -75,8 +75,8 @@ public class SendErrorFilter extends ZuulFilter {
}
}
}
catch (Exception e) {
Throwables.propagate(e);
catch (Exception ex) {
Throwables.propagate(ex);
}
return null;
}
@@ -84,4 +84,5 @@ public class SendErrorFilter extends ZuulFilter {
public void setErrorPath(String errorPath) {
this.errorPath = errorPath;
}
}

View File

@@ -35,17 +35,20 @@ import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.constants.ZuulHeaders;
import com.netflix.zuul.context.RequestContext;
/**
* @author Spencer Gibb
*/
public class SendResponseFilter extends ZuulFilter {
static DynamicBooleanProperty INCLUDE_DEBUG_HEADER = DynamicPropertyFactory
private static DynamicBooleanProperty INCLUDE_DEBUG_HEADER = DynamicPropertyFactory
.getInstance().getBooleanProperty(ZuulConstants.ZUUL_INCLUDE_DEBUG_HEADER,
false);
static DynamicIntProperty INITIAL_STREAM_BUFFER_SIZE = DynamicPropertyFactory
private static DynamicIntProperty INITIAL_STREAM_BUFFER_SIZE = DynamicPropertyFactory
.getInstance().getIntProperty(ZuulConstants.ZUUL_INITIAL_STREAM_BUFFER_SIZE,
1024);
static DynamicBooleanProperty SET_CONTENT_LENGTH = DynamicPropertyFactory
private static DynamicBooleanProperty SET_CONTENT_LENGTH = DynamicPropertyFactory
.getInstance().getBooleanProperty(ZuulConstants.ZUUL_SET_CONTENT_LENGTH,
false);
@@ -72,23 +75,20 @@ public class SendResponseFilter extends ZuulFilter {
addResponseHeaders();
writeResponse();
}
catch (Exception e) {
Throwables.propagate(e);
catch (Exception ex) {
Throwables.propagate(ex);
}
return null;
}
void writeResponse() throws Exception {
private void writeResponse() throws Exception {
RequestContext context = RequestContext.getCurrentContext();
// there is no body to send
if (context.getResponseBody() == null && context.getResponseDataStream() == null) {
return;
}
HttpServletResponse servletResponse = context.getResponse();
servletResponse.setCharacterEncoding("UTF-8");
OutputStream outStream = servletResponse.getOutputStream();
InputStream is = null;
try {
@@ -97,14 +97,12 @@ public class SendResponseFilter extends ZuulFilter {
writeResponse(new ByteArrayInputStream(body.getBytes()), outStream);
return;
}
boolean isGzipRequested = false;
final String requestEncoding = context.getRequest().getHeader(
ZuulHeaders.ACCEPT_ENCODING);
if (requestEncoding != null && requestEncoding.equals("gzip")) {
isGzipRequested = true;
}
is = context.getResponseDataStream();
InputStream inputStream = is;
if (is != null) {
@@ -116,14 +114,12 @@ public class SendResponseFilter extends ZuulFilter {
if (context.getResponseGZipped() && !isGzipRequested) {
try {
inputStream = new GZIPInputStream(is);
}
catch (java.util.zip.ZipException e) {
System.out
.println("gzip expected but not received assuming unencoded response"
+ RequestContext.getCurrentContext()
.getRequest().getRequestURL()
.toString());
catch (java.util.zip.ZipException ex) {
System.out.println("gzip expected but not "
+ "received assuming unencoded response"
+ RequestContext.getCurrentContext().getRequest()
.getRequestURL().toString());
inputStream = is;
}
}
@@ -133,19 +129,16 @@ public class SendResponseFilter extends ZuulFilter {
writeResponse(inputStream, outStream);
}
}
}
finally {
try {
if (is != null) {
is.close();
}
outStream.flush();
outStream.close();
}
catch (IOException e) {
catch (IOException ex) {
}
}
}
@@ -154,19 +147,18 @@ public class SendResponseFilter extends ZuulFilter {
byte[] bytes = new byte[INITIAL_STREAM_BUFFER_SIZE.get()];
int bytesRead = -1;
while ((bytesRead = zin.read(bytes)) != -1) {
// TODO
// if (Debug.debugRequest() && !Debug.debugRequestHeadersOnly()) {
// Debug.addRequestDebug("OUTBOUND: < " + new String(bytes, 0, bytesRead));
// }
try {
out.write(bytes, 0, bytesRead);
out.flush();
}
catch (IOException e) {
catch (IOException ex) {
// ignore
e.printStackTrace();
ex.printStackTrace();
}
// doubles buffer size if previous read filled it
if (bytesRead == bytes.length) {
bytes = new byte[bytes.length * 2];
@@ -178,7 +170,6 @@ public class SendResponseFilter extends ZuulFilter {
RequestContext context = RequestContext.getCurrentContext();
HttpServletResponse servletResponse = context.getResponse();
List<Pair<String, String>> zuulResponseHeaders = context.getZuulResponseHeaders();
@SuppressWarnings("unchecked")
List<String> rd = (List<String>) RequestContext.getCurrentContext().get(
"routingDebug");
@@ -191,16 +182,13 @@ public class SendResponseFilter extends ZuulFilter {
servletResponse.addHeader("X-Zuul-Debug-Header", debugHeader.toString());
}
}
if (zuulResponseHeaders != null) {
for (Pair<String, String> it : zuulResponseHeaders) {
servletResponse.addHeader(it.first(), it.second());
}
}
RequestContext ctx = RequestContext.getCurrentContext();
Integer contentLength = ctx.getOriginContentLength();
// Only inserts Content-Length if origin provides it and origin response is not
// gzipped
if (SET_CONTENT_LENGTH.get()) {

View File

@@ -25,11 +25,15 @@ import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
/**
* @author Spencer Gibb
*/
public class DebugFilter extends ZuulFilter {
static final DynamicBooleanProperty routingDebug = DynamicPropertyFactory
private static final DynamicBooleanProperty ROUTING_DEBUG = DynamicPropertyFactory
.getInstance().getBooleanProperty(ZuulConstants.ZUUL_DEBUG_REQUEST, false);
static final DynamicStringProperty debugParameter = DynamicPropertyFactory
private static final DynamicStringProperty DEBUG_PARAMETER = DynamicPropertyFactory
.getInstance().getStringProperty(ZuulConstants.ZUUL_DEBUG_PARAMETER, "debug");
@Override
@@ -45,11 +49,10 @@ public class DebugFilter extends ZuulFilter {
@Override
public boolean shouldFilter() {
HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
if ("true".equals(request.getParameter(debugParameter.get()))) {
if ("true".equals(request.getParameter(DEBUG_PARAMETER.get()))) {
return true;
}
return routingDebug.get();
return ROUTING_DEBUG.get();
}
@Override

View File

@@ -39,7 +39,8 @@ import com.netflix.zuul.http.ServletInputStreamWrapper;
* @author Spencer Gibb
*/
public class FormBodyWrapperFilter extends ZuulFilter {
protected Field requestField = null;
private Field requestField;
public FormBodyWrapperFilter() {
this.requestField = ReflectionUtils.findField(HttpServletRequestWrapper.class,
@@ -63,18 +64,16 @@ public class FormBodyWrapperFilter extends ZuulFilter {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String contentType = request.getContentType();
// Don't use this filter on GET method
if (contentType == null) {
return false;
}
// Only use this filter for MediaType : application/x-www-form-urlencoded
try {
return MediaType.APPLICATION_FORM_URLENCODED.includes(MediaType
.valueOf(contentType));
}
catch (InvalidMediaTypeException imte) {
catch (InvalidMediaTypeException ex) {
return false;
}
}
@@ -89,8 +88,8 @@ public class FormBodyWrapperFilter extends ZuulFilter {
.get(request);
this.requestField.set(request, new FormBodyRequestWrapper(wrapped));
}
catch (IllegalAccessException e) {
Throwables.propagate(e);
catch (IllegalAccessException ex) {
Throwables.propagate(ex);
}
}
else {
@@ -102,6 +101,7 @@ public class FormBodyWrapperFilter extends ZuulFilter {
private class FormBodyRequestWrapper extends HttpServletRequestWrapper {
private HttpServletRequest request;
private byte[] contentData;
public FormBodyRequestWrapper(HttpServletRequest request) {
@@ -145,4 +145,5 @@ public class FormBodyWrapperFilter extends ZuulFilter {
}
}
}

View File

@@ -32,6 +32,7 @@ import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
public class PreDecorationFilter extends ZuulFilter {
private static Logger LOG = LoggerFactory.getLogger(PreDecorationFilter.class);
private ProxyRouteLocator routeLocator;
@@ -61,20 +62,13 @@ public class PreDecorationFilter extends ZuulFilter {
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
final String requestURI = ctx.getRequest().getRequestURI();
ProxyRouteSpec route = this.routeLocator.getMatchingRoute(requestURI);
if (route != null) {
String location = route.getLocation();
if (location != null) {
ctx.put("requestURI", route.getPath());
ctx.put("proxy", route.getId());
if (location.startsWith("http:") || location.startsWith("https:")) {
ctx.setRouteHost(getUrl(location));
ctx.addOriginResponseHeader("X-Zuul-Service", location);
@@ -85,7 +79,6 @@ public class PreDecorationFilter extends ZuulFilter {
ctx.setRouteHost(null);
ctx.addOriginResponseHeader("X-Zuul-ServiceId", location);
}
if (this.properties.isAddProxyHeaders()) {
ctx.addZuulRequestHeader(
"X-Forwarded-Host",
@@ -108,8 +101,8 @@ public class PreDecorationFilter extends ZuulFilter {
try {
return new URL(target);
}
catch (MalformedURLException e) {
throw new IllegalStateException("Target URL is malformed", e);
catch (MalformedURLException ex) {
throw new IllegalStateException("Target URL is malformed", ex);
}
}
}

View File

@@ -42,6 +42,7 @@ import com.netflix.zuul.http.HttpServletRequestWrapper;
* @author Spencer Gibb
*/
public class Servlet30WrapperFilter extends ZuulFilter {
protected Field requestField = null;
public Servlet30WrapperFilter() {
@@ -74,8 +75,8 @@ public class Servlet30WrapperFilter extends ZuulFilter {
try {
request = (HttpServletRequest) this.requestField.get(request);
}
catch (IllegalAccessException e) {
Throwables.propagate(e);
catch (IllegalAccessException ex) {
Throwables.propagate(ex);
}
}
ctx.setRequest(new Servlet30RequestWrapper(request));
@@ -154,5 +155,7 @@ public class Servlet30WrapperFilter extends ZuulFilter {
public DispatcherType getDispatcherType() {
return this.request.getDispatcherType();
}
}
}

View File

@@ -27,10 +27,12 @@ import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpRequest.Builder;
import com.netflix.client.http.HttpRequest.Verb;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.DynamicIntProperty;
import com.netflix.config.DynamicPropertyFactory;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandProperties;
import com.netflix.hystrix.HystrixCommandProperties.ExecutionIsolationStrategy;
import com.netflix.niws.client.http.RestClient;
import com.netflix.zuul.constants.ZuulConstants;
import com.netflix.zuul.context.RequestContext;
@@ -45,10 +47,15 @@ import com.netflix.zuul.context.RequestContext;
public class RibbonCommand extends HystrixCommand<HttpResponse> {
private RestClient restClient;
private Verb verb;
private URI uri;
private MultivaluedMap<String, String> headers;
private MultivaluedMap<String, String> params;
private InputStream requestEntity;
public RibbonCommand(RestClient restClient, Verb verb, String uri,
@@ -62,25 +69,7 @@ public class RibbonCommand extends HystrixCommand<HttpResponse> {
MultivaluedMap<String, String> headers,
MultivaluedMap<String, String> params, InputStream requestEntity)
throws URISyntaxException {
super(
Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandKey))
.andCommandPropertiesDefaults(
// we want to default to semaphore-isolation since this wraps
// 2 others commands that are already thread isolated
HystrixCommandProperties
.Setter()
.withExecutionIsolationStrategy(
HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(
DynamicPropertyFactory
.getInstance()
.getIntProperty(
ZuulConstants.ZUUL_EUREKA
+ commandKey
+ ".semaphore.maxSemaphores",
100).get())));
super(getSetter(commandKey));
this.restClient = restClient;
this.verb = verb;
this.uri = new URI(uri);
@@ -89,39 +78,41 @@ public class RibbonCommand extends HystrixCommand<HttpResponse> {
this.requestEntity = requestEntity;
}
private static HystrixCommand.Setter getSetter(String commandKey) {
// we want to default to semaphore-isolation since this wraps
// 2 others commands that are already thread isolated
String name = ZuulConstants.ZUUL_EUREKA + commandKey + ".semaphore.maxSemaphores";
DynamicIntProperty value = DynamicPropertyFactory.getInstance().getIntProperty(
name, 100);
HystrixCommandProperties.Setter setter = HystrixCommandProperties.Setter()
.withExecutionIsolationStrategy(ExecutionIsolationStrategy.SEMAPHORE)
.withExecutionIsolationSemaphoreMaxConcurrentRequests(value.get());
return Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(commandKey))
.andCommandPropertiesDefaults(setter);
}
@Override
protected HttpResponse run() throws Exception {
try {
return forward();
}
catch (Exception e) {
throw e;
}
return forward();
}
private HttpResponse forward() throws Exception {
RequestContext context = RequestContext.getCurrentContext();
Builder builder = HttpRequest.newBuilder().verb(this.verb).uri(this.uri)
.entity(this.requestEntity);
for (String name : this.headers.keySet()) {
List<String> values = this.headers.get(name);
for (String value : values) {
builder.header(name, value);
}
}
for (String name : this.params.keySet()) {
List<String> values = this.params.get(name);
for (String value : values) {
builder.queryParams(name, value);
}
}
HttpRequest httpClientRequest = builder.build();
HttpResponse response = this.restClient
.executeWithLoadBalancer(httpClientRequest);
context.set("ribbonResponse", response);

View File

@@ -111,9 +111,9 @@ public class RibbonRoutingFilter extends ZuulFilter {
setResponse(response);
return response;
}
catch (Exception e) {
catch (Exception ex) {
context.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
context.set("error.exception", e);
context.set("error.exception", ex);
}
return null;
}
@@ -121,10 +121,8 @@ public class RibbonRoutingFilter extends ZuulFilter {
private HttpResponse forward(RestClient restClient, Verb verb, String uri,
MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
InputStream requestEntity) throws Exception {
Map<String, Object> info = this.helper.debug(verb.verb(), uri, headers, params,
requestEntity);
RibbonCommand command = new RibbonCommand(restClient, verb, uri,
convertHeaders(headers), convertHeaders(params), requestEntity);
try {
@@ -133,17 +131,17 @@ public class RibbonRoutingFilter extends ZuulFilter {
revertHeaders(response.getHeaders()));
return response;
}
catch (HystrixRuntimeException e) {
catch (HystrixRuntimeException ex) {
info.put("status", "500");
if (e.getFallbackException() != null
&& e.getFallbackException().getCause() != null
&& e.getFallbackException().getCause() instanceof ClientException) {
ClientException ex = (ClientException) e.getFallbackException()
if (ex.getFallbackException() != null
&& ex.getFallbackException().getCause() != null
&& ex.getFallbackException().getCause() instanceof ClientException) {
ClientException cause = (ClientException) ex.getFallbackException()
.getCause();
throw new ZuulException(ex, "Forwarding error", 500, ex.getErrorType()
.toString());
throw new ZuulException(cause, "Forwarding error", 500, cause
.getErrorType().toString());
}
throw new ZuulException(e, "Forwarding error", 500, e.getFailureType()
throw new ZuulException(ex, "Forwarding error", 500, ex.getFailureType()
.toString());
}
@@ -180,19 +178,18 @@ public class RibbonRoutingFilter extends ZuulFilter {
requestEntity = request.getInputStream();
}
}
catch (IOException e) {
LOG.error("Error during getRequestBody", e);
catch (IOException ex) {
LOG.error("Error during getRequestBody", ex);
}
return requestEntity;
}
Verb getVerb(HttpServletRequest request) {
private Verb getVerb(HttpServletRequest request) {
String sMethod = request.getMethod();
return getVerb(sMethod);
}
Verb getVerb(String sMethod) {
private Verb getVerb(String sMethod) {
if (sMethod == null) {
return Verb.GET;
}

View File

@@ -94,6 +94,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
private static final DynamicIntProperty SOCKET_TIMEOUT = DynamicPropertyFactory
.getInstance().getIntProperty(ZuulConstants.ZUUL_HOST_SOCKET_TIMEOUT_MILLIS,
10000);
private static final DynamicIntProperty CONNECTION_TIMEOUT = DynamicPropertyFactory
.getInstance().getIntProperty(ZuulConstants.ZUUL_HOST_CONNECT_TIMEOUT_MILLIS,
2000);
@@ -118,34 +119,13 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
}
hc.getConnectionManager().closeExpiredConnections();
}
catch (Throwable t) {
LOG.error("error closing expired connections", t);
catch (Throwable ex) {
LOG.error("error closing expired connections", ex);
}
}
}, 30000, 5000);
}
private static final ClientConnectionManager newConnectionManager() throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
registry.register(new Scheme("https", sf, 8443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
cm.setMaxTotal(Integer.parseInt(System.getProperty("zuul.max.host.connections",
"200")));
cm.setDefaultMaxPerRoute(Integer.parseInt(System.getProperty(
"zuul.max.host.connections", "20")));
return cm;
}
private ProxyRequestHelper helper;
public SimpleHostRoutingFilter() {
@@ -177,61 +157,6 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
&& RequestContext.getCurrentContext().sendZuulResponse();
}
private static final void loadClient() {
final HttpClient oldClient = CLIENT.get();
CLIENT.set(newClient());
if (oldClient != null) {
CONNECTION_MANAGER_TIMER.schedule(new TimerTask() {
@Override
public void run() {
try {
oldClient.getConnectionManager().shutdown();
}
catch (Throwable t) {
LOG.error("error shutting down old connection manager", t);
}
}
}, 30000);
}
}
private static final HttpClient newClient() {
// I could statically cache the connection manager but we will probably want to
// make some of its properties
// dynamic in the near future also
try {
DefaultHttpClient httpclient = new DefaultHttpClient(newConnectionManager());
HttpParams httpParams = httpclient.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
SOCKET_TIMEOUT.get());
httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
CONNECTION_TIMEOUT.get());
httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0,
false));
httpParams.setParameter(ClientPNames.COOKIE_POLICY,
org.apache.http.client.params.CookiePolicy.IGNORE_COOKIES);
httpclient.setRedirectStrategy(new org.apache.http.client.RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest httpRequest,
HttpResponse httpResponse, HttpContext httpContext) {
return false;
}
@Override
public org.apache.http.client.methods.HttpUriRequest getRedirect(
HttpRequest httpRequest, HttpResponse httpResponse,
HttpContext httpContext) {
return null;
}
});
return httpclient;
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Object run() {
RequestContext context = RequestContext.getCurrentContext();
@@ -254,9 +179,9 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
params, requestEntity);
setResponse(response);
}
catch (Exception e) {
catch (Exception ex) {
context.set("error.status_code", HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
context.set("error.exception", e);
context.set("error.exception", ex);
}
return null;
}
@@ -265,16 +190,12 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
HttpServletRequest request, MultiValueMap<String, String> headers,
MultiValueMap<String, String> params, InputStream requestEntity)
throws Exception {
Map<String, Object> info = this.helper.debug(verb, uri, headers, params,
requestEntity);
URL host = RequestContext.getCurrentContext().getRouteHost();
HttpHost httpHost = getHttpHost(host);
uri = StringUtils.cleanPath(host.getPath() + uri);
HttpRequest httpRequest;
switch (verb.toUpperCase()) {
case "POST":
HttpPost httpPost = new HttpPost(uri + getQueryString());
@@ -292,7 +213,6 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
httpRequest = new BasicHttpRequest(verb, uri + getQueryString());
LOG.debug(uri + getQueryString());
}
try {
httpRequest.setHeaders(convertHeaders(headers));
LOG.debug(httpHost.getHostName() + " " + httpHost.getPort() + " "
@@ -308,7 +228,6 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
// immediate deallocation of all system resources
// httpclient.getConnectionManager().shutdown();
}
}
private MultiValueMap<String, String> revertHeaders(Header[] headers) {
@@ -355,7 +274,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
try {
requestEntity = request.getInputStream();
}
catch (IOException e) {
catch (IOException ex) {
// no requestBody is ok.
}
return requestEntity;
@@ -372,14 +291,85 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
revertHeaders(response.getAllHeaders()));
}
private static ClientConnectionManager newConnectionManager() throws Exception {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
registry.register(new Scheme("https", sf, 8443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
cm.setMaxTotal(Integer.parseInt(System.getProperty("zuul.max.host.connections",
"200")));
cm.setDefaultMaxPerRoute(Integer.parseInt(System.getProperty(
"zuul.max.host.connections", "20")));
return cm;
}
private static void loadClient() {
final HttpClient oldClient = CLIENT.get();
CLIENT.set(newClient());
if (oldClient != null) {
CONNECTION_MANAGER_TIMER.schedule(new TimerTask() {
@Override
public void run() {
try {
oldClient.getConnectionManager().shutdown();
}
catch (Throwable ex) {
LOG.error("error shutting down old connection manager", ex);
}
}
}, 30000);
}
}
private static HttpClient newClient() {
// I could statically cache the connection manager but we will probably want to
// make some of its properties
// dynamic in the near future also
try {
DefaultHttpClient httpclient = new DefaultHttpClient(newConnectionManager());
HttpParams httpParams = httpclient.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,
SOCKET_TIMEOUT.get());
httpParams.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,
CONNECTION_TIMEOUT.get());
httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0,
false));
httpParams.setParameter(ClientPNames.COOKIE_POLICY,
org.apache.http.client.params.CookiePolicy.IGNORE_COOKIES);
httpclient.setRedirectStrategy(new org.apache.http.client.RedirectStrategy() {
@Override
public boolean isRedirected(HttpRequest httpRequest,
HttpResponse httpResponse, HttpContext httpContext) {
return false;
}
@Override
public org.apache.http.client.methods.HttpUriRequest getRedirect(
HttpRequest httpRequest, HttpResponse httpResponse,
HttpContext httpContext) {
return null;
}
});
return httpclient;
}
catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static class MySSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
@@ -394,8 +384,8 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
};
TrustManager[] tms = new TrustManager[1];
tms[0] = tm;
this.sslContext.init(null, tms, null);
@@ -412,5 +402,7 @@ public class SimpleHostRoutingFilter extends ZuulFilter {
public Socket createSocket() throws IOException {
return this.sslContext.getSocketFactory().createSocket();
}
}
}

View File

@@ -25,7 +25,6 @@ import static org.junit.Assert.assertNotNull;
/**
* @author Dave Syer
*
*/
public class ArchaiusAutoConfigurationTests {

View File

@@ -29,7 +29,6 @@ import static org.junit.Assert.assertTrue;
/**
* @author Dave Syer
*
*/
public class ArchaiusEndpointTests {

View File

@@ -31,7 +31,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
public class DiscoveryClientConfigServiceBootstrapConfigurationTests {

View File

@@ -31,7 +31,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
public class EurekaClientConfigServerAutoConfigurationTests {

View File

@@ -32,7 +32,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
public class EurekaClientConfigBeanTests {

View File

@@ -33,7 +33,6 @@ import static org.springframework.boot.test.EnvironmentTestUtils.addEnvironment;
/**
* @author Dave Syer
*
*/
public class EurekaInstanceConfigBeanTests {

View File

@@ -59,6 +59,37 @@ public class SpringDecoderTests extends FeignConfiguration {
return feign().target(TestClient.class, "http://localhost:" + this.port);
}
@Test
public void testSimpleType() {
Hello hello = testClient().getHello();
assertNotNull("hello was null", hello);
assertEquals("first hello didn't match", new Hello("hello world 1"), hello);
}
@Test
public void testUserParameterizedTypeDecode() {
List<Hello> hellos = testClient().getHellos();
assertNotNull("hellos was null", hellos);
assertEquals("hellos was not the right size", 2, hellos.size());
assertEquals("first hello didn't match", new Hello("hello world 1"),
hellos.get(0));
}
@Test
public void testSimpleParameterizedTypeDecode() {
List<String> hellos = testClient().getHelloStrings();
assertNotNull("hellos was null", hellos);
assertEquals("hellos was not the right size", 2, hellos.size());
assertEquals("first hello didn't match", "hello world 1", hellos.get(0));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Hello {
private String message;
}
protected static interface TestClient {
@RequestMapping(method = RequestMethod.GET, value = "/hello")
public Hello getHello();
@@ -103,34 +134,4 @@ public class SpringDecoderTests extends FeignConfiguration {
}
}
@Test
public void testSimpleType() {
Hello hello = testClient().getHello();
assertNotNull("hello was null", hello);
assertEquals("first hello didn't match", new Hello("hello world 1"), hello);
}
@Test
public void testUserParameterizedTypeDecode() {
List<Hello> hellos = testClient().getHellos();
assertNotNull("hellos was null", hellos);
assertEquals("hellos was not the right size", 2, hellos.size());
assertEquals("first hello didn't match", new Hello("hello world 1"),
hellos.get(0));
}
@Test
public void testSimpleParameterizedTypeDecode() {
List<String> hellos = testClient().getHelloStrings();
assertNotNull("hellos was null", hellos);
assertEquals("hellos was not the right size", 2, hellos.size());
assertEquals("first hello didn't match", "hello world 1", hellos.get(0));
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Hello {
private String message;
}
}

View File

@@ -21,7 +21,6 @@ import org.springframework.boot.builder.SpringApplicationBuilder;
/**
* @author Dave Syer
*
*/
public class HystrixConfigurationTests {

View File

@@ -135,4 +135,5 @@ class HystrixOnlyApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixOnlyApplication.class, args);
}
}

View File

@@ -22,7 +22,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
public class HystrixStreamEndpointTests {

View File

@@ -34,7 +34,6 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
/**
* @author Dave Syer
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)

View File

@@ -39,7 +39,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)

View File

@@ -41,7 +41,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)

View File

@@ -84,7 +84,8 @@ public class RibbonInterceptorTests {
}
protected static class MyClient implements LoadBalancerClient {
ServiceInstance instance;
private ServiceInstance instance;
public MyClient(ServiceInstance instance) {
this.instance = instance;
@@ -100,8 +101,8 @@ public class RibbonInterceptorTests {
try {
return request.apply(this.instance);
}
catch (Exception e) {
Throwables.propagate(e);
catch (Exception ex) {
Throwables.propagate(ex);
}
return null;
}
@@ -111,5 +112,7 @@ public class RibbonInterceptorTests {
return UriComponentsBuilder.fromUri(original).host(instance.getHost())
.port(instance.getPort()).build().toUri();
}
}
}

View File

@@ -47,16 +47,16 @@ import static org.mockito.Mockito.when;
public class RibbonLoadBalancerClientTests {
@Mock
SpringClientFactory clientFactory;
private SpringClientFactory clientFactory;
@Mock
BaseLoadBalancer loadBalancer;
private BaseLoadBalancer loadBalancer;
@Mock
LoadBalancerStats loadBalancerStats;
private LoadBalancerStats loadBalancerStats;
@Mock
ServerStats serverStats;
private ServerStats serverStats;
@Before
public void init() {
@@ -88,7 +88,6 @@ public class RibbonLoadBalancerClientTests {
public void testExecute() {
final RibbonServer server = getRibbonServer();
RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(server);
final String returnVal = "myval";
Object actualReturn = client.execute(server.getServiceId(),
new LoadBalancerRequest<Object>() {
@@ -98,9 +97,7 @@ public class RibbonLoadBalancerClientTests {
return returnVal;
}
});
verifyServerStats();
assertEquals("retVal was wrong", returnVal, actualReturn);
}
@@ -108,7 +105,6 @@ public class RibbonLoadBalancerClientTests {
public void testExecuteException() {
final RibbonServer ribbonServer = getRibbonServer();
RibbonLoadBalancerClient client = getRibbonLoadBalancerClient(ribbonServer);
try {
client.execute(ribbonServer.getServiceId(),
new LoadBalancerRequest<Object>() {
@@ -120,10 +116,9 @@ public class RibbonLoadBalancerClientTests {
});
fail("Should have thrown exception");
}
catch (Exception e) {
assertNotNull(e);
catch (Exception ex) {
assertNotNull(ex);
}
verifyServerStats();
}
@@ -156,7 +151,6 @@ public class RibbonLoadBalancerClientTests {
this.serverStats);
when(this.clientFactory.getLoadBalancer(this.loadBalancer.getName())).thenReturn(
this.loadBalancer);
return new RibbonLoadBalancerClient(this.clientFactory);
}
}

View File

@@ -41,20 +41,22 @@ import static org.mockito.Mockito.when;
public class DomainExtractingServerListTests {
static final String IP_ADDR = "10.0.0.2";
static final int PORT = 8080;
static final String ZONE = "myzone.mydomain.com";
static final String HOST_NAME = "myHostName." + ZONE;
static final String INSTANCE_ID = "myInstanceId";
@Test
public void testDomainExtractingServer() {
DomainExtractingServerList serverList = getDomainExtractingServerList(
new DefaultClientConfigImpl(), true);
List<Server> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
DomainExtractingServer des = assertDomainExtractingServer(servers, ZONE);
assertEquals("hostPort was wrong", HOST_NAME + ":" + PORT, des.getHostPort());
}
@@ -63,11 +65,9 @@ public class DomainExtractingServerListTests {
public void testDomainExtractingServerDontApproximateZone() {
DomainExtractingServerList serverList = getDomainExtractingServerList(
new DefaultClientConfigImpl(), false);
List<Server> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
DomainExtractingServer des = assertDomainExtractingServer(servers, null);
assertEquals("hostPort was wrong", HOST_NAME + ":" + PORT, des.getHostPort());
}
@@ -89,11 +89,9 @@ public class DomainExtractingServerListTests {
config.setProperty(CommonClientConfigKey.UseIPAddrForServer, true);
DomainExtractingServerList serverList = getDomainExtractingServerList(config,
true);
List<Server> servers = serverList.getInitialListOfServers();
assertNotNull("servers was null", servers);
assertEquals("servers was not size 1", 1, servers.size());
DomainExtractingServer des = assertDomainExtractingServer(servers, ZONE);
assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort());
}
@@ -104,20 +102,16 @@ public class DomainExtractingServerListTests {
@SuppressWarnings("unchecked")
ServerList<Server> originalServerList = mock(ServerList.class);
InstanceInfo instanceInfo = mock(InstanceInfo.class);
when(server.getInstanceInfo()).thenReturn(instanceInfo);
when(server.getHost()).thenReturn(HOST_NAME);
when(instanceInfo.getMetadata()).thenReturn(
ImmutableMap.<String, String> builder().put("instanceId", INSTANCE_ID)
.build());
when(instanceInfo.getHostName()).thenReturn(HOST_NAME);
when(instanceInfo.getIPAddr()).thenReturn(IP_ADDR);
when(instanceInfo.getPort()).thenReturn(PORT);
when(originalServerList.getInitialListOfServers()).thenReturn(
Arrays.<Server> asList(server));
return new DomainExtractingServerList(originalServerList, config,
approximateZoneFromHostname);
}

View File

@@ -36,7 +36,6 @@ import static org.springframework.cloud.netflix.ribbon.eureka.EurekaRibbonClient
/**
* @author Dave Syer
*
*/
public class EurekaRibbonClientConfigurationTests {
@@ -68,22 +67,15 @@ public class EurekaRibbonClientConfigurationTests {
EurekaClientConfigBean client = new EurekaClientConfigBean();
EurekaRibbonClientConfiguration preprocessor = new EurekaRibbonClientConfiguration(
client, "myService");
String serviceId = "myService";
String suffix = "mySuffix";
String value = "myValue";
DynamicStringProperty property = preprocessor.getProperty(preprocessor.getKey(
serviceId, suffix));
assertEquals("property doesn't have default value", VALUE_NOT_SET, property.get());
preprocessor.setProp(serviceId, suffix, value);
assertEquals("property has wrong value", value, property.get());
preprocessor.setProp(serviceId, suffix, value);
assertEquals("property has wrong value", value, property.get());
}

View File

@@ -38,7 +38,6 @@ import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
/**
* @author Dave Syer
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestConfiguration.class)
@@ -62,6 +61,7 @@ public class EurekaRibbonClientPreprocessorIntegrationTests {
ArchaiusAutoConfiguration.class, RibbonAutoConfiguration.class,
EurekaClientAutoConfiguration.class, RibbonEurekaAutoConfiguration.class })
protected static class TestConfiguration {
}
}

View File

@@ -29,7 +29,6 @@ import static org.junit.Assert.assertEquals;
/**
* @author Dave Syer
*
*/
public class ZonePreferenceServerListFilterTests {

View File

@@ -116,6 +116,7 @@ class FormZuulProxyApplication {
@Bean
public ZuulFilter sampleFilter() {
return new ZuulFilter() {
@Override
public String filterType() {
return "pre";
@@ -135,6 +136,7 @@ class FormZuulProxyApplication {
public int filterOrder() {
return 0;
}
};
}
@@ -147,6 +149,7 @@ class FormZuulProxyApplication {
// Load balancer with fixed server list for "simple" pointing to localhost
@Configuration
class FormRibbonClientConfiguration {
@Bean
public ILoadBalancer ribbonLoadBalancer(EurekaInstanceConfig instance) {
BaseLoadBalancer balancer = new BaseLoadBalancer();
@@ -154,4 +157,5 @@ class FormRibbonClientConfiguration {
.getNonSecurePort())));
return balancer;
}
}

View File

@@ -42,14 +42,16 @@ import static org.mockito.MockitoAnnotations.initMocks;
public class ProxyRouteLocatorTests {
public static final String IGNOREDSERVICE = "ignoredservice";
public static final String ASERVICE = "aservice";
public static final String MYSERVICE = "myservice";
@Mock
ConfigurableEnvironment env;
private ConfigurableEnvironment env;
@Mock
DiscoveryClient discovery;
private DiscoveryClient discovery;
private ZuulProperties properties = new ZuulProperties();
@@ -143,9 +145,7 @@ public class ProxyRouteLocatorTests {
this.properties);
this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/" + ASERVICE + "/**"));
this.properties.init();
Map<String, String> routesMap = routeLocator.getRoutes();
assertNotNull("routesMap was null", routesMap);
assertFalse("routesMap was empty", routesMap.isEmpty());
assertMapping(routesMap, ASERVICE);
@@ -169,9 +169,7 @@ public class ProxyRouteLocatorTests {
this.properties);
this.properties.getRoutes().put(ASERVICE,
new ZuulRoute("/" + ASERVICE + "/**", "http://" + ASERVICE));
Map<String, String> routesMap = routeLocator.getRoutes();
assertNotNull("routesMap was null", routesMap);
assertFalse("routesMap was empty", routesMap.isEmpty());
assertMapping(routesMap, "http://" + ASERVICE, ASERVICE);
@@ -182,9 +180,7 @@ public class ProxyRouteLocatorTests {
ProxyRouteLocator routeLocator = new ProxyRouteLocator(this.discovery,
this.properties);
this.properties.getRoutes().put(ASERVICE, new ZuulRoute("/**", ASERVICE));
Map<String, String> routesMap = routeLocator.getRoutes();
assertNotNull("routesMap was null", routesMap);
assertFalse("routesMap was empty", routesMap.isEmpty());
assertDefaultMapping(routesMap, ASERVICE);
@@ -196,9 +192,7 @@ public class ProxyRouteLocatorTests {
this.properties);
this.properties.getRoutes().put(ASERVICE,
new ZuulRoute("/**", "http://" + ASERVICE));
Map<String, String> routesMap = routeLocator.getRoutes();
assertNotNull("routesMap was null", routesMap);
assertFalse("routesMap was empty", routesMap.isEmpty());
assertDefaultMapping(routesMap, "http://" + ASERVICE);
@@ -221,11 +215,8 @@ public class ProxyRouteLocatorTests {
public void testAutoRoutes() {
ProxyRouteLocator routeLocator = new ProxyRouteLocator(this.discovery,
this.properties);
when(this.discovery.getServices()).thenReturn(Lists.newArrayList(MYSERVICE));
Map<String, String> routesMap = routeLocator.getRoutes();
assertNotNull("routesMap was null", routesMap);
assertFalse("routesMap was empty", routesMap.isEmpty());
assertMapping(routesMap, MYSERVICE);
@@ -233,17 +224,13 @@ public class ProxyRouteLocatorTests {
@Test
public void testAutoRoutesCanBeOverridden() {
this.properties.getRoutes()
.put(MYSERVICE,
new ZuulRoute("/" + MYSERVICE + "/**", "http://example.com/"
+ MYSERVICE));
ZuulRoute route = new ZuulRoute("/" + MYSERVICE + "/**", "http://example.com/"
+ MYSERVICE);
this.properties.getRoutes().put(MYSERVICE, route);
ProxyRouteLocator routeLocator = new ProxyRouteLocator(this.discovery,
this.properties);
when(this.discovery.getServices()).thenReturn(Lists.newArrayList(MYSERVICE));
Map<String, String> routesMap = routeLocator.getRoutes();
assertNotNull("routesMap was null", routesMap);
assertFalse("routesMap was empty", routesMap.isEmpty());
assertMapping(routesMap, "http://example.com/" + MYSERVICE, MYSERVICE);

View File

@@ -115,6 +115,7 @@ public class SampleZuulProxyApplicationTests {
assertEquals(HttpStatus.OK, result.getStatusCode());
assertEquals("Gotten!", result.getBody());
}
}
// Don't use @SpringBootApplication because we don't want to component scan
@@ -186,6 +187,7 @@ class SampleZuulProxyApplication {
// Load balancer with fixed server list for "simple" pointing to localhost
@Configuration
class SimpleRibbonClientConfiguration {
@Bean
public ILoadBalancer ribbonLoadBalancer(EurekaInstanceConfig instance) {
BaseLoadBalancer balancer = new BaseLoadBalancer();
@@ -193,10 +195,12 @@ class SimpleRibbonClientConfiguration {
.getNonSecurePort())));
return balancer;
}
}
@Configuration
class AnotherRibbonClientConfiguration {
@Bean
public ILoadBalancer ribbonLoadBalancer(EurekaInstanceConfig instance) {
BaseLoadBalancer balancer = new BaseLoadBalancer();
@@ -204,4 +208,5 @@ class AnotherRibbonClientConfiguration {
.getNonSecurePort())));
return balancer;
}
}

View File

@@ -43,7 +43,6 @@ public class SendErrorFilterTests {
@Test
public void runsNormally() {
SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest());
assertTrue("shouldFilter returned false", filter.shouldFilter());
filter.run();
}
@@ -62,7 +61,6 @@ public class SendErrorFilterTests {
@Test
public void noRequestDispatcher() {
SendErrorFilter filter = createSendErrorFilter(mock(HttpServletRequest.class));
assertTrue("shouldFilter returned false", filter.shouldFilter());
filter.run();
}
@@ -70,7 +68,6 @@ public class SendErrorFilterTests {
@Test
public void doesNotRunTwice() {
SendErrorFilter filter = createSendErrorFilter(new MockHttpServletRequest());
assertTrue("shouldFilter returned false", filter.shouldFilter());
filter.run();
assertFalse("shouldFilter returned true", filter.shouldFilter());

View File

@@ -35,7 +35,6 @@ import static org.mockito.MockitoAnnotations.initMocks;
/**
* @author Dave Syer
*
*/
public class PreDecorationFilterTests {

View File

@@ -57,14 +57,10 @@ public class EurekaController {
@RequestMapping(method = RequestMethod.GET)
public String status(HttpServletRequest request, Map<String, Object> model) {
populateBase(request, model);
populateApps(model);
StatusInfo statusInfo = new StatusResource().getStatusInfo();
model.put("statusInfo", statusInfo);
populateInstanceInfo(model, statusInfo);
return "eureka/status";
}
@@ -72,7 +68,6 @@ public class EurekaController {
public String lastn(HttpServletRequest request, Map<String, Object> model) {
populateBase(request, model);
PeerAwareInstanceRegistry registery = PeerAwareInstanceRegistry.getInstance();
ArrayList<Map<String, Object>> lastNCanceled = new ArrayList<>();
List<Pair<Long, String>> list = registery.getLastNCanceledInstances();
for (Pair<Long, String> entry : list) {
@@ -80,7 +75,6 @@ public class EurekaController {
.longValue()));
}
model.put("lastNCanceled", lastNCanceled);
list = registery.getLastNRegisteredInstances();
ArrayList<Map<String, Object>> lastNRegistered = new ArrayList<>();
for (Pair<Long, String> entry : list) {
@@ -88,7 +82,6 @@ public class EurekaController {
.longValue()));
}
model.put("lastNRegistered", lastNRegistered);
return "eureka/lastn";
}
@@ -104,9 +97,7 @@ public class EurekaController {
model.put("basePath", "/");
model.put("dashboardPath", this.dashboardPath.equals("/") ? ""
: this.dashboardPath);
populateHeader(model);
populateNavbar(request, model);
}
@@ -120,7 +111,6 @@ public class EurekaController {
model.put("registry", PeerAwareInstanceRegistry.getInstance());
model.put("isBelowRenewThresold", PeerAwareInstanceRegistry.getInstance()
.isBelowRenewThresold() == 1);
DataCenterInfo info = ApplicationInfoManager.getInstance().getInfo()
.getDataCenterInfo();
if (info.getName() == DataCenterInfo.Name.Amazon) {
@@ -143,7 +133,7 @@ public class EurekaController {
String href = node.getServiceUrl();
replicas.put(uri.getHost(), href);
}
catch (Exception e) {
catch (Exception ex) {
// ignore?
}
}
@@ -153,18 +143,14 @@ public class EurekaController {
private void populateApps(Map<String, Object> model) {
List<com.netflix.discovery.shared.Application> sortedApplications = PeerAwareInstanceRegistry
.getInstance().getSortedApplications();
ArrayList<Map<String, Object>> apps = new ArrayList<>();
for (Application app : sortedApplications) {
LinkedHashMap<String, Object> appData = new LinkedHashMap<>();
apps.add(appData);
appData.put("name", app.getName());
Map<String, Integer> amiCounts = new HashMap<>();
Map<InstanceInfo.InstanceStatus, List<Pair<String, String>>> instancesByStatus = new HashMap<>();
Map<String, Integer> zoneCounts = new HashMap<>();
for (InstanceInfo info : app.getInstances()) {
String id = info.getId();
String url = info.getStatusPageUrl();
@@ -176,7 +162,6 @@ public class EurekaController {
ami = dcInfo.get(AmazonInfo.MetaDataKey.amiId);
zone = dcInfo.get(AmazonInfo.MetaDataKey.availabilityZone);
}
Integer count = amiCounts.get(ami);
if (count != null) {
amiCounts.put(ami, Integer.valueOf(count.intValue() + 1));
@@ -184,7 +169,6 @@ public class EurekaController {
else {
amiCounts.put(ami, Integer.valueOf(1));
}
count = zoneCounts.get(zone);
if (count != null) {
zoneCounts.put(zone, Integer.valueOf(count.intValue() + 1));
@@ -193,35 +177,31 @@ public class EurekaController {
zoneCounts.put(zone, Integer.valueOf(1));
}
List<Pair<String, String>> list = instancesByStatus.get(status);
if (list == null) {
list = new ArrayList<>();
instancesByStatus.put(status, list);
}
list.add(new Pair<>(id, url));
}
appData.put("amiCounts", amiCounts.entrySet());
appData.put("zoneCounts", zoneCounts.entrySet());
ArrayList<Map<String, Object>> instanceInfos = new ArrayList<>();
appData.put("instanceInfos", instanceInfos);
for (Iterator<Map.Entry<InstanceInfo.InstanceStatus, List<Pair<String, String>>>> iter = instancesByStatus
.entrySet().iterator(); iter.hasNext();) {
Map.Entry<InstanceInfo.InstanceStatus, List<Pair<String, String>>> entry = iter
.next();
List<Pair<String, String>> value = entry.getValue();
InstanceInfo.InstanceStatus status = entry.getKey();
LinkedHashMap<String, Object> instanceData = new LinkedHashMap<>();
instanceInfos.add(instanceData);
instanceData.put("status", entry.getKey());
ArrayList<Map<String, Object>> instances = new ArrayList<>();
instanceData.put("instances", instances);
instanceData.put("isNotUp", status != InstanceInfo.InstanceStatus.UP);
// TODO
/*
* if(status != InstanceInfo.InstanceStatus.UP){
* buf.append("<font color=red size=+1><b>"); }
@@ -248,13 +228,11 @@ public class EurekaController {
}
// out.println("<td>" + buf.toString() + "</td></tr>");
}
model.put("apps", apps);
}
private void populateInstanceInfo(Map<String, Object> model, StatusInfo statusInfo) {
InstanceInfo instanceInfo = statusInfo.getInstanceInfo();
Map<String, String> instanceMap = new HashMap<>();
instanceMap.put("ipAddr", instanceInfo.getIPAddr());
instanceMap.put("status", instanceInfo.getStatus().toString());
@@ -270,7 +248,6 @@ public class EurekaController {
instanceMap.put("instance-type",
info.get(AmazonInfo.MetaDataKey.instanceType));
}
model.put("instanceInfo", instanceMap);
}
}

View File

@@ -22,8 +22,8 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Configuration properties for the Eureka dashboard (UI).
* @author Dave Syer
*
* @author Dave Syer
*/
@ConfigurationProperties("eureka.dashboard")
@Data
@@ -35,7 +35,7 @@ public class EurekaDashboardProperties {
private String path = "/";
/**
* FLag to enable the Eureka dashboard. Default true.
* Flag to enable the Eureka dashboard. Default true.
*/
private boolean enabled = true;

View File

@@ -34,9 +34,7 @@ import com.google.common.collect.Lists;
import com.sun.jersey.spi.container.servlet.ServletContainer;
/**
*
* @author Gunnar Hillert
*
*/
@Configuration
@Import(EurekaServerInitializerConfiguration.class)
@@ -72,4 +70,5 @@ public class EurekaServerConfiguration extends WebMvcConfigurerAdapter {
bean.setOrder(Ordered.LOWEST_PRECEDENCE - 10);
return bean;
}
}

Some files were not shown because too many files have changed in this diff Show More